entities listlengths 1 8.61k | max_stars_repo_path stringlengths 7 172 | max_stars_repo_name stringlengths 5 89 | max_stars_count int64 0 82k | content stringlengths 14 1.05M | id stringlengths 2 6 | new_content stringlengths 15 1.05M | modified bool 1 class | references stringlengths 29 1.05M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": "erDone = (event_data, cb) ->\n console.log 'wonk jones', \"tx:#{event_data.event.transactionHash}:done\"\n ",
"end": 1727,
"score": 0.8221942186355591,
"start": 1722,
"tag": "NAME",
"value": "jones"
}
] | services/engine.coffee | brynwaldwick/blockwoods | 0 | somata = require 'somata'
config = require '../config'
client = new somata.Client
random = (l=8) ->
getRandomIntInclusive = (min, max) ->
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
ContractsService = client.bindRemote 'blockwoods:contracts'
handleSpin = (event_data, cb) ->
result = getRandomIntInclusive 0, 37
console.log result
# TODO: submit result to wheel contract
{bettor} = event_data
ContractsService 'sendSpinResult', bettor, result, (err, resp) ->
service.publish "spins:#{bettor}:result"
service.publish "tx:#{event_data.event.transactionHash}:done", {n: result, outcome_tx: resp}
cb null, resp
rouletteSpinDone = (event_data, cb) ->
{bettor, result} = event_data
service.publish "tx:#{event_data.event.transactionHash}:done", {bettor, result}
handleRouletteEvent = (event_data, cb) ->
if event_data.kind == 'spin'
handleSpin event_data, (err, resp) ->
console.log err, resp
else
rouletteSpinDone event_data, (err, resp) ->
console.log err, resp
handlePullSlot = (event_data, cb) ->
s_1 = getRandomIntInclusive 0, 9
s_2 = getRandomIntInclusive 0, 9
s_3 = getRandomIntInclusive 0, 9
# TODO: submit result to wheel contract
{bettor} = event_data
ContractsService 'didPullSlot', bettor, s_1, s_2, s_3, (err, resp) ->
console.log 'ill handle this', event_data
service.publish "pulls:#{bettor}:result"
service.publish "tx:#{event_data.event.transactionHash}:done", {s_1, s_2, s_3, outcome_tx: resp}
cb null, success: true
pullLeverDone = (event_data, cb) ->
console.log 'wonk jones', "tx:#{event_data.event.transactionHash}:done"
service.publish "tx:#{event_data.event.transactionHash}:done", event_data, cb
service = new somata.Service 'blockwoods:engine', {
handleSpin
handlePullSlot
handleRouletteEvent
pullLeverDone
} | 161944 | somata = require 'somata'
config = require '../config'
client = new somata.Client
random = (l=8) ->
getRandomIntInclusive = (min, max) ->
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
ContractsService = client.bindRemote 'blockwoods:contracts'
handleSpin = (event_data, cb) ->
result = getRandomIntInclusive 0, 37
console.log result
# TODO: submit result to wheel contract
{bettor} = event_data
ContractsService 'sendSpinResult', bettor, result, (err, resp) ->
service.publish "spins:#{bettor}:result"
service.publish "tx:#{event_data.event.transactionHash}:done", {n: result, outcome_tx: resp}
cb null, resp
rouletteSpinDone = (event_data, cb) ->
{bettor, result} = event_data
service.publish "tx:#{event_data.event.transactionHash}:done", {bettor, result}
handleRouletteEvent = (event_data, cb) ->
if event_data.kind == 'spin'
handleSpin event_data, (err, resp) ->
console.log err, resp
else
rouletteSpinDone event_data, (err, resp) ->
console.log err, resp
handlePullSlot = (event_data, cb) ->
s_1 = getRandomIntInclusive 0, 9
s_2 = getRandomIntInclusive 0, 9
s_3 = getRandomIntInclusive 0, 9
# TODO: submit result to wheel contract
{bettor} = event_data
ContractsService 'didPullSlot', bettor, s_1, s_2, s_3, (err, resp) ->
console.log 'ill handle this', event_data
service.publish "pulls:#{bettor}:result"
service.publish "tx:#{event_data.event.transactionHash}:done", {s_1, s_2, s_3, outcome_tx: resp}
cb null, success: true
pullLeverDone = (event_data, cb) ->
console.log 'wonk <NAME>', "tx:#{event_data.event.transactionHash}:done"
service.publish "tx:#{event_data.event.transactionHash}:done", event_data, cb
service = new somata.Service 'blockwoods:engine', {
handleSpin
handlePullSlot
handleRouletteEvent
pullLeverDone
} | true | somata = require 'somata'
config = require '../config'
client = new somata.Client
random = (l=8) ->
getRandomIntInclusive = (min, max) ->
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
ContractsService = client.bindRemote 'blockwoods:contracts'
handleSpin = (event_data, cb) ->
result = getRandomIntInclusive 0, 37
console.log result
# TODO: submit result to wheel contract
{bettor} = event_data
ContractsService 'sendSpinResult', bettor, result, (err, resp) ->
service.publish "spins:#{bettor}:result"
service.publish "tx:#{event_data.event.transactionHash}:done", {n: result, outcome_tx: resp}
cb null, resp
rouletteSpinDone = (event_data, cb) ->
{bettor, result} = event_data
service.publish "tx:#{event_data.event.transactionHash}:done", {bettor, result}
handleRouletteEvent = (event_data, cb) ->
if event_data.kind == 'spin'
handleSpin event_data, (err, resp) ->
console.log err, resp
else
rouletteSpinDone event_data, (err, resp) ->
console.log err, resp
handlePullSlot = (event_data, cb) ->
s_1 = getRandomIntInclusive 0, 9
s_2 = getRandomIntInclusive 0, 9
s_3 = getRandomIntInclusive 0, 9
# TODO: submit result to wheel contract
{bettor} = event_data
ContractsService 'didPullSlot', bettor, s_1, s_2, s_3, (err, resp) ->
console.log 'ill handle this', event_data
service.publish "pulls:#{bettor}:result"
service.publish "tx:#{event_data.event.transactionHash}:done", {s_1, s_2, s_3, outcome_tx: resp}
cb null, success: true
pullLeverDone = (event_data, cb) ->
console.log 'wonk PI:NAME:<NAME>END_PI', "tx:#{event_data.event.transactionHash}:done"
service.publish "tx:#{event_data.event.transactionHash}:done", event_data, cb
service = new somata.Service 'blockwoods:engine', {
handleSpin
handlePullSlot
handleRouletteEvent
pullLeverDone
} |
[
{
"context": "ndemand.com/\n#\n# Author:\n# Symphony Integration by Vinay Mistry (mistryvinay)\n#\nEntities = require('html-entities",
"end": 1014,
"score": 0.9998853802680969,
"start": 1002,
"tag": "NAME",
"value": "Vinay Mistry"
},
{
"context": "# Author:\n# Symphony Integration by... | src/scripts/marketdata.coffee | Mohannrajk/Github-raj | 0 | #
#
#
# Copyright 2016 Symphony Communication Services, LLC
#
# Licensed to Symphony Communication Services, LLC under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#
# Description
# Listen for cash tags and look up market data at Barcharts OnDemand http://barchartondemand.com/
#
# Author:
# Symphony Integration by Vinay Mistry (mistryvinay)
#
Entities = require('html-entities').XmlEntities
entities = new Entities()
apikey = process.env.HUBOT_BARCHARTS_API_KEY
_lookupPrice = (robot, msg, ticker) ->
robot.http("http://marketdata.websol.barchart.com/getQuote.json?key=#{apikey}&symbols=#{ticker}")
.header('Accept', 'application/json')
.get() (err, res, body) ->
if err
msg.send "Failed to look up #{ticker}"
else
try
json = JSON.parse(body)
msg.send {
format: 'MESSAGEML'
text: "<messageML><cash tag=\"#{json.results[0].symbol}\"/> @ <b>#{json.results[0].lastPrice}</b> #{json.results[0].netChange} (#{json.results[0].percentChange}%) <br/>Open: #{json.results[0].open} High: #{json.results[0].high} Low: #{json.results[0].low} Close: #{json.results[0].close}</messageML>"
}
catch error
msg.send "Failed to look up $#{ticker}"
module.exports = (robot) ->
robot.hear /<cash tag=".*"\/>/i, (msg) ->
regex = /(?:<cash tag=["'])([^"']+)(?:["']\/>)/gi
while match = regex.exec msg.match
_lookupPrice(robot, msg, match[1])
| 164461 | #
#
#
# Copyright 2016 Symphony Communication Services, LLC
#
# Licensed to Symphony Communication Services, LLC under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#
# Description
# Listen for cash tags and look up market data at Barcharts OnDemand http://barchartondemand.com/
#
# Author:
# Symphony Integration by <NAME> (mistryvinay)
#
Entities = require('html-entities').XmlEntities
entities = new Entities()
apikey = process.env.HUBOT_BARCHARTS_API_KEY
_lookupPrice = (robot, msg, ticker) ->
robot.http("http://marketdata.websol.barchart.com/getQuote.json?key=#{apikey}&symbols=#{ticker}")
.header('Accept', 'application/json')
.get() (err, res, body) ->
if err
msg.send "Failed to look up #{ticker}"
else
try
json = JSON.parse(body)
msg.send {
format: 'MESSAGEML'
text: "<messageML><cash tag=\"#{json.results[0].symbol}\"/> @ <b>#{json.results[0].lastPrice}</b> #{json.results[0].netChange} (#{json.results[0].percentChange}%) <br/>Open: #{json.results[0].open} High: #{json.results[0].high} Low: #{json.results[0].low} Close: #{json.results[0].close}</messageML>"
}
catch error
msg.send "Failed to look up $#{ticker}"
module.exports = (robot) ->
robot.hear /<cash tag=".*"\/>/i, (msg) ->
regex = /(?:<cash tag=["'])([^"']+)(?:["']\/>)/gi
while match = regex.exec msg.match
_lookupPrice(robot, msg, match[1])
| true | #
#
#
# Copyright 2016 Symphony Communication Services, LLC
#
# Licensed to Symphony Communication Services, LLC under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#
# Description
# Listen for cash tags and look up market data at Barcharts OnDemand http://barchartondemand.com/
#
# Author:
# Symphony Integration by PI:NAME:<NAME>END_PI (mistryvinay)
#
Entities = require('html-entities').XmlEntities
entities = new Entities()
apikey = process.env.HUBOT_BARCHARTS_API_KEY
_lookupPrice = (robot, msg, ticker) ->
robot.http("http://marketdata.websol.barchart.com/getQuote.json?key=#{apikey}&symbols=#{ticker}")
.header('Accept', 'application/json')
.get() (err, res, body) ->
if err
msg.send "Failed to look up #{ticker}"
else
try
json = JSON.parse(body)
msg.send {
format: 'MESSAGEML'
text: "<messageML><cash tag=\"#{json.results[0].symbol}\"/> @ <b>#{json.results[0].lastPrice}</b> #{json.results[0].netChange} (#{json.results[0].percentChange}%) <br/>Open: #{json.results[0].open} High: #{json.results[0].high} Low: #{json.results[0].low} Close: #{json.results[0].close}</messageML>"
}
catch error
msg.send "Failed to look up $#{ticker}"
module.exports = (robot) ->
robot.hear /<cash tag=".*"\/>/i, (msg) ->
regex = /(?:<cash tag=["'])([^"']+)(?:["']\/>)/gi
while match = regex.exec msg.match
_lookupPrice(robot, msg, match[1])
|
[
{
"context": " # no params\n }, deps)\n {\n insertedId: aliceId\n } = await db.Users.insertOne(\n emails:",
"end": 762,
"score": 0.5817345380783081,
"start": 757,
"tag": "NAME",
"value": "alice"
},
{
"context": "rs.insertOne(\n emails: [\n { address: '... | test/MaintainHealth.test.coffee | DenisGorbachev/talloc | 0 | import moment from 'moment'
import { MongoClient } from 'mongodb'
import MaintainHealth from '../src/Functor/MaintainHealth'
import { perms } from '../src/helpers'
import { complete } from '../src/test_helpers'
describe 'MaintainHealth', ->
connection = null
db = null
beforeAll ->
connection = await MongoClient.connect(global.__MONGO_URI__, { useNewUrlParser: true })
db = await connection.db(global.__MONGO_DB_NAME__)
db.Users = db.collection('Users')
db.Acts = db.collection('Acts')
afterAll ->
await db.close()
await connection.close()
it 'should return the task', ->
deps = { db, now: new Date('2019-07-26T00:00:00Z') }
functor = new MaintainHealth({
# no params
}, deps)
{
insertedId: aliceId
} = await db.Users.insertOne(
emails: [
{ address: 'alice@example.com', verified: true }
]
)
alice = await db.Users.findOne({ _id: aliceId })
task = await functor.getNextTask(alice)
expect(task).toMatchObject(
type: 'CreateAct',
context:
blueprint:
type: 'MorningExercise'
title: "Do morning exercises"
)
await db.Acts.insertOne(
type: 'MorningExercise'
userId: alice._id
createdAt: moment(deps.now).subtract(2, 'days').toDate()
)
task = await functor.getNextTask(alice)
expect(task).toMatchObject(
type: 'CreateAct',
context:
blueprint:
type: 'MorningExercise'
title: "Do morning exercises"
)
await complete(task, deps)
task = await functor.getNextTask(alice)
expect(task).toBeUndefined()
# Jest requires `describe` callback to return undefined
return undefined
| 90499 | import moment from 'moment'
import { MongoClient } from 'mongodb'
import MaintainHealth from '../src/Functor/MaintainHealth'
import { perms } from '../src/helpers'
import { complete } from '../src/test_helpers'
describe 'MaintainHealth', ->
connection = null
db = null
beforeAll ->
connection = await MongoClient.connect(global.__MONGO_URI__, { useNewUrlParser: true })
db = await connection.db(global.__MONGO_DB_NAME__)
db.Users = db.collection('Users')
db.Acts = db.collection('Acts')
afterAll ->
await db.close()
await connection.close()
it 'should return the task', ->
deps = { db, now: new Date('2019-07-26T00:00:00Z') }
functor = new MaintainHealth({
# no params
}, deps)
{
insertedId: <NAME>Id
} = await db.Users.insertOne(
emails: [
{ address: '<EMAIL>', verified: true }
]
)
alice = await db.Users.findOne({ _id: <NAME>Id })
task = await functor.getNextTask(alice)
expect(task).toMatchObject(
type: 'CreateAct',
context:
blueprint:
type: 'MorningExercise'
title: "Do morning exercises"
)
await db.Acts.insertOne(
type: 'MorningExercise'
userId: alice._id
createdAt: moment(deps.now).subtract(2, 'days').toDate()
)
task = await functor.getNextTask(alice)
expect(task).toMatchObject(
type: 'CreateAct',
context:
blueprint:
type: 'MorningExercise'
title: "Do morning exercises"
)
await complete(task, deps)
task = await functor.getNextTask(alice)
expect(task).toBeUndefined()
# Jest requires `describe` callback to return undefined
return undefined
| true | import moment from 'moment'
import { MongoClient } from 'mongodb'
import MaintainHealth from '../src/Functor/MaintainHealth'
import { perms } from '../src/helpers'
import { complete } from '../src/test_helpers'
describe 'MaintainHealth', ->
connection = null
db = null
beforeAll ->
connection = await MongoClient.connect(global.__MONGO_URI__, { useNewUrlParser: true })
db = await connection.db(global.__MONGO_DB_NAME__)
db.Users = db.collection('Users')
db.Acts = db.collection('Acts')
afterAll ->
await db.close()
await connection.close()
it 'should return the task', ->
deps = { db, now: new Date('2019-07-26T00:00:00Z') }
functor = new MaintainHealth({
# no params
}, deps)
{
insertedId: PI:NAME:<NAME>END_PIId
} = await db.Users.insertOne(
emails: [
{ address: 'PI:EMAIL:<EMAIL>END_PI', verified: true }
]
)
alice = await db.Users.findOne({ _id: PI:NAME:<NAME>END_PIId })
task = await functor.getNextTask(alice)
expect(task).toMatchObject(
type: 'CreateAct',
context:
blueprint:
type: 'MorningExercise'
title: "Do morning exercises"
)
await db.Acts.insertOne(
type: 'MorningExercise'
userId: alice._id
createdAt: moment(deps.now).subtract(2, 'days').toDate()
)
task = await functor.getNextTask(alice)
expect(task).toMatchObject(
type: 'CreateAct',
context:
blueprint:
type: 'MorningExercise'
title: "Do morning exercises"
)
await complete(task, deps)
task = await functor.getNextTask(alice)
expect(task).toBeUndefined()
# Jest requires `describe` callback to return undefined
return undefined
|
[
{
"context": "rter.addImporter 'slack', Importer.Slack,\n\tname: 'Slack'\n\tmimeType: 'application/zip'\n",
"end": 59,
"score": 0.5989934206008911,
"start": 54,
"tag": "NAME",
"value": "Slack"
}
] | packages/rocketchat-importer-slack/main.coffee | kumarpradeephk/mychatapp | 2 | Importer.addImporter 'slack', Importer.Slack,
name: 'Slack'
mimeType: 'application/zip'
| 150189 | Importer.addImporter 'slack', Importer.Slack,
name: '<NAME>'
mimeType: 'application/zip'
| true | Importer.addImporter 'slack', Importer.Slack,
name: 'PI:NAME:<NAME>END_PI'
mimeType: 'application/zip'
|
[
{
"context": "ular Expression for URL validation\n #\n # Author: Diego Perini\n # Updated: 2010/12/05\n # License: MIT\n #\n # ",
"end": 135,
"score": 0.9998819231987,
"start": 123,
"tag": "NAME",
"value": "Diego Perini"
},
{
"context": "5\n # License: MIT\n #\n # Copyright ... | src/common/validators/url.coffee | SteefTheBeef/angular-validate | 0 | angular.module('slick-angular-validation')
.factory 'url', () ->
# Regular Expression for URL validation
#
# Author: Diego Perini
# Updated: 2010/12/05
# License: MIT
#
# Copyright (c) 2010-2013 Diego Perini (http://www.iport.it)
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
urlRegex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/i
{
link: (scope, ctrl) ->
ctrl.$validators.url = (modelValue, viewValue) ->
if ctrl.$isEmpty(modelValue) then return true
urlRegex.test(viewValue)
return
} | 209156 | angular.module('slick-angular-validation')
.factory 'url', () ->
# Regular Expression for URL validation
#
# Author: <NAME>
# Updated: 2010/12/05
# License: MIT
#
# Copyright (c) 2010-2013 <NAME> (http://www.iport.it)
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
urlRegex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/i
{
link: (scope, ctrl) ->
ctrl.$validators.url = (modelValue, viewValue) ->
if ctrl.$isEmpty(modelValue) then return true
urlRegex.test(viewValue)
return
} | true | angular.module('slick-angular-validation')
.factory 'url', () ->
# Regular Expression for URL validation
#
# Author: PI:NAME:<NAME>END_PI
# Updated: 2010/12/05
# License: MIT
#
# Copyright (c) 2010-2013 PI:NAME:<NAME>END_PI (http://www.iport.it)
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
urlRegex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/i
{
link: (scope, ctrl) ->
ctrl.$validators.url = (modelValue, viewValue) ->
if ctrl.$isEmpty(modelValue) then return true
urlRegex.test(viewValue)
return
} |
[
{
"context": "a href=\"http://a.com/1.html\">1</a><a href=\"mailto:a@b.com\">2</a>' )\n .should.eql [ 'http://a.com/1.h",
"end": 5436,
"score": 0.999899685382843,
"start": 5429,
"tag": "EMAIL",
"value": "a@b.com"
}
] | test/lib/linkTest.coffee | marufsiddiqui/huntsman | 1 |
link = require( '../../lib/link' );
should = require 'should'
describe 'normaliser', ->
describe 'validation', ->
it 'should throw if uri is invalid', ->
(-> link.normaliser( '' ) ).should.throw 'invalid uri';
(-> link.normaliser( null ) ).should.throw 'invalid uri';
(-> link.normaliser( undefined ) ).should.throw 'invalid uri';
(-> link.normaliser( {} ) ).should.throw 'invalid uri';
(-> link.normaliser( [] ) ).should.throw 'invalid uri';
(-> link.normaliser( 'a' ) ).should.not.throw();
describe 'transformations', ->
it 'should remove trailing slashes', ->
link.normaliser( '/' ).should.eql ''
link.normaliser( 'http://a.com/foo' ).should.eql 'http://a.com/foo' # no trailing slash
link.normaliser( 'http://a.com/foo/#bingo' ).should.eql 'http://a.com/foo#bingo'
link.normaliser( 'http://a.com/foo/#bingo/' ).should.eql 'http://a.com/foo#bingo'
link.normaliser( 'http://a.com/foo/?bing=bang' ).should.eql 'http://a.com/foo?bing=bang'
link.normaliser( 'http://a.com/foo/?bing=bang#moo' ).should.eql 'http://a.com/foo?bing=bang#moo'
link.normaliser( 'http://a.com/foo/bar/' ).should.eql 'http://a.com/foo/bar'
describe 'resolver', ->
describe 'validation', ->
it 'should throw if uri is invalid', ->
(-> link.resolver( '' ) ).should.throw 'invalid uri';
(-> link.resolver( null ) ).should.throw 'invalid uri';
(-> link.resolver( undefined ) ).should.throw 'invalid uri';
(-> link.resolver( {} ) ).should.throw 'invalid uri';
(-> link.resolver( [] ) ).should.throw 'invalid uri';
(-> link.resolver( 'a' ) ).should.not.throw();
describe 'absolute / relative urls', ->
it 'should not convert relative url to absolute urls if base url not provided', ->
link.resolver( '/1.html' ).should.eql '/1.html'
it 'should not convert absolute urls if base url not provided', ->
link.resolver( 'http://www.example.com/1.html' ).should.eql 'http://www.example.com/1.html'
it 'should convert relative url to absolute urls when base url is provided', ->
link.resolver( '/1.html', 'http://example.com/' ).should.eql 'http://example.com/1.html'
link.resolver( '1.html', 'http://example.com/a' ).should.eql 'http://example.com/1.html'
link.resolver( '1.html', 'http://example.com/a/' ).should.eql 'http://example.com/a/1.html'
it 'should not convert domains for absolute urls when a base url is provided', ->
link.resolver( 'http://example.com/1.html', 'http://foo.com/' ).should.eql 'http://example.com/1.html'
it 'should resolve parent directory references', ->
link.resolver( '../2.html', 'http://example.com/a/1.html' ).should.eql 'http://example.com/2.html'
describe 'extractor', ->
describe 'source parsing', ->
it 'should accept single and double quote attributes', ->
link.extractor( 'http://example.com/', '<a href="/1.html">1</a>'+"<a href='/2.html'>2</a>" )
.should.eql [ 'http://example.com/1.html', 'http://example.com/2.html' ]
describe 'search & refine patterns', ->
describe 'default patterns', ->
it 'should only refine anchor links', ->
link.extractor( 'http://example.com/', '<script src="/1.js">1</script><a href="/2.html">2</a>' )
.should.eql [ 'http://example.com/2.html' ]
it 'should parse correctly when tag has preceding arguments', ->
link.extractor( 'http://example.com/', '<a id="myid" href="/1.html">1</a>' )
.should.eql [ 'http://example.com/1.html' ]
it 'should parse correctly when tag has succeeding arguments', ->
link.extractor( 'http://example.com/', '<a href="/1.html" id="myid">1</a>' )
.should.eql [ 'http://example.com/1.html' ]
describe 'should be overridable', ->
it 'should allow script tags src to be extracted', ->
link.extractor( 'http://example.com/', '<script src="/1.js#foo">1</script><a href="/2.html">2</a>', {
pattern: {
search: /script([^>]+)src\s*=\s*['"]([^"']+)/gi, # extract script tags and allow fragment hash
refine: /['"]([^"']+)/ # allow fragment hash
}
})
.should.eql [ 'http://example.com/1.js#foo' ]
it 'should allow both script & anchor tags to be extracted', ->
link.extractor( 'http://example.com/', '<script src="/1.js#foo">1</script><a href="/2.html">2</a>', {
pattern: {
search: /(a([^>]+)href|script([^>]+)src)\s?=\s?['"]([^"'#]+)/gi, # anchor or script tags
}
})
.should.eql [ 'http://example.com/1.js', 'http://example.com/2.html' ]
describe 'filter pattern', ->
describe 'default pattern', ->
it 'should not filter by domain (or apply any filtering)', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.html">2</a>' )
.should.eql [ 'http://a.com/1.html', 'http://b.com/2.html' ]
describe 'should be overridable', ->
it 'should allow domain filtering', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.html">2</a>', {
pattern: {
filter: 'http://a.com'
}
})
.should.eql [ 'http://a.com/1.html' ]
it 'should filter non http(s) uris by default', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="mailto:a@b.com">2</a>' )
.should.eql [ 'http://a.com/1.html' ]
it 'should allow filtering out certain file extension using a lookahead', ->
link.extractor( null, '<a href="http://a.com/1.mp3">1</a><a href="http://a.com/2.pdf">2</a>', {
pattern: {
filter: /^https?:\/\/.*(?!\.(pdf|png|jpg|gif|zip))....$/
}
})
.should.eql [ 'http://a.com/1.mp3' ]
it 'should allow filtering out all uris with three letter extensions', ->
link.extractor( null, '<a href="http://a.com/1.mp3">1</a><a href="http://a.com/2">2</a>', {
pattern: {
filter: /^https?:\/\/.*(?!\.\w{3})....$/
}
})
.should.eql [ 'http://a.com/2' ]
it 'should allow file extension filtering', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.jpg">2</a>', {
pattern: {
filter: /\.jpg|\.gif|\.png/ # images only
}
})
.should.eql [ 'http://b.com/2.jpg' ]
describe 'unique option', ->
it 'should default unique filtering to enabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>' )
.should.eql [ 'http://a.com/1.html' ]
it 'should allow unique filtering to be disabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>', {
unique: false
})
.should.eql [ 'http://a.com/1.html', 'http://a.com/1.html' ]
it 'should allow unique filtering to be enabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>', {
unique: true
})
.should.eql [ 'http://a.com/1.html' ]
describe 'custom link resolver', ->
it 'should be able to override resolver', ->
link.extractor( 'http://a.com', '<a href="1.html">1</a>', {
resolver: ( url, baseUri ) -> return url # just return the url without modification
pattern: filter: /.*/ # allow any uri
})
.should.eql [ '1.html' ]
describe 'custom link normaliser', ->
it 'should be able to override normaliser', ->
link.extractor( 'http://a.com', '<a href="1.html">1</a>', {
normaliser: ( url ) -> return url.replace /\.\w*$/, '' # remove file extension
})
.should.eql [ 'http://a.com/1' ] | 164955 |
link = require( '../../lib/link' );
should = require 'should'
describe 'normaliser', ->
describe 'validation', ->
it 'should throw if uri is invalid', ->
(-> link.normaliser( '' ) ).should.throw 'invalid uri';
(-> link.normaliser( null ) ).should.throw 'invalid uri';
(-> link.normaliser( undefined ) ).should.throw 'invalid uri';
(-> link.normaliser( {} ) ).should.throw 'invalid uri';
(-> link.normaliser( [] ) ).should.throw 'invalid uri';
(-> link.normaliser( 'a' ) ).should.not.throw();
describe 'transformations', ->
it 'should remove trailing slashes', ->
link.normaliser( '/' ).should.eql ''
link.normaliser( 'http://a.com/foo' ).should.eql 'http://a.com/foo' # no trailing slash
link.normaliser( 'http://a.com/foo/#bingo' ).should.eql 'http://a.com/foo#bingo'
link.normaliser( 'http://a.com/foo/#bingo/' ).should.eql 'http://a.com/foo#bingo'
link.normaliser( 'http://a.com/foo/?bing=bang' ).should.eql 'http://a.com/foo?bing=bang'
link.normaliser( 'http://a.com/foo/?bing=bang#moo' ).should.eql 'http://a.com/foo?bing=bang#moo'
link.normaliser( 'http://a.com/foo/bar/' ).should.eql 'http://a.com/foo/bar'
describe 'resolver', ->
describe 'validation', ->
it 'should throw if uri is invalid', ->
(-> link.resolver( '' ) ).should.throw 'invalid uri';
(-> link.resolver( null ) ).should.throw 'invalid uri';
(-> link.resolver( undefined ) ).should.throw 'invalid uri';
(-> link.resolver( {} ) ).should.throw 'invalid uri';
(-> link.resolver( [] ) ).should.throw 'invalid uri';
(-> link.resolver( 'a' ) ).should.not.throw();
describe 'absolute / relative urls', ->
it 'should not convert relative url to absolute urls if base url not provided', ->
link.resolver( '/1.html' ).should.eql '/1.html'
it 'should not convert absolute urls if base url not provided', ->
link.resolver( 'http://www.example.com/1.html' ).should.eql 'http://www.example.com/1.html'
it 'should convert relative url to absolute urls when base url is provided', ->
link.resolver( '/1.html', 'http://example.com/' ).should.eql 'http://example.com/1.html'
link.resolver( '1.html', 'http://example.com/a' ).should.eql 'http://example.com/1.html'
link.resolver( '1.html', 'http://example.com/a/' ).should.eql 'http://example.com/a/1.html'
it 'should not convert domains for absolute urls when a base url is provided', ->
link.resolver( 'http://example.com/1.html', 'http://foo.com/' ).should.eql 'http://example.com/1.html'
it 'should resolve parent directory references', ->
link.resolver( '../2.html', 'http://example.com/a/1.html' ).should.eql 'http://example.com/2.html'
describe 'extractor', ->
describe 'source parsing', ->
it 'should accept single and double quote attributes', ->
link.extractor( 'http://example.com/', '<a href="/1.html">1</a>'+"<a href='/2.html'>2</a>" )
.should.eql [ 'http://example.com/1.html', 'http://example.com/2.html' ]
describe 'search & refine patterns', ->
describe 'default patterns', ->
it 'should only refine anchor links', ->
link.extractor( 'http://example.com/', '<script src="/1.js">1</script><a href="/2.html">2</a>' )
.should.eql [ 'http://example.com/2.html' ]
it 'should parse correctly when tag has preceding arguments', ->
link.extractor( 'http://example.com/', '<a id="myid" href="/1.html">1</a>' )
.should.eql [ 'http://example.com/1.html' ]
it 'should parse correctly when tag has succeeding arguments', ->
link.extractor( 'http://example.com/', '<a href="/1.html" id="myid">1</a>' )
.should.eql [ 'http://example.com/1.html' ]
describe 'should be overridable', ->
it 'should allow script tags src to be extracted', ->
link.extractor( 'http://example.com/', '<script src="/1.js#foo">1</script><a href="/2.html">2</a>', {
pattern: {
search: /script([^>]+)src\s*=\s*['"]([^"']+)/gi, # extract script tags and allow fragment hash
refine: /['"]([^"']+)/ # allow fragment hash
}
})
.should.eql [ 'http://example.com/1.js#foo' ]
it 'should allow both script & anchor tags to be extracted', ->
link.extractor( 'http://example.com/', '<script src="/1.js#foo">1</script><a href="/2.html">2</a>', {
pattern: {
search: /(a([^>]+)href|script([^>]+)src)\s?=\s?['"]([^"'#]+)/gi, # anchor or script tags
}
})
.should.eql [ 'http://example.com/1.js', 'http://example.com/2.html' ]
describe 'filter pattern', ->
describe 'default pattern', ->
it 'should not filter by domain (or apply any filtering)', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.html">2</a>' )
.should.eql [ 'http://a.com/1.html', 'http://b.com/2.html' ]
describe 'should be overridable', ->
it 'should allow domain filtering', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.html">2</a>', {
pattern: {
filter: 'http://a.com'
}
})
.should.eql [ 'http://a.com/1.html' ]
it 'should filter non http(s) uris by default', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="mailto:<EMAIL>">2</a>' )
.should.eql [ 'http://a.com/1.html' ]
it 'should allow filtering out certain file extension using a lookahead', ->
link.extractor( null, '<a href="http://a.com/1.mp3">1</a><a href="http://a.com/2.pdf">2</a>', {
pattern: {
filter: /^https?:\/\/.*(?!\.(pdf|png|jpg|gif|zip))....$/
}
})
.should.eql [ 'http://a.com/1.mp3' ]
it 'should allow filtering out all uris with three letter extensions', ->
link.extractor( null, '<a href="http://a.com/1.mp3">1</a><a href="http://a.com/2">2</a>', {
pattern: {
filter: /^https?:\/\/.*(?!\.\w{3})....$/
}
})
.should.eql [ 'http://a.com/2' ]
it 'should allow file extension filtering', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.jpg">2</a>', {
pattern: {
filter: /\.jpg|\.gif|\.png/ # images only
}
})
.should.eql [ 'http://b.com/2.jpg' ]
describe 'unique option', ->
it 'should default unique filtering to enabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>' )
.should.eql [ 'http://a.com/1.html' ]
it 'should allow unique filtering to be disabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>', {
unique: false
})
.should.eql [ 'http://a.com/1.html', 'http://a.com/1.html' ]
it 'should allow unique filtering to be enabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>', {
unique: true
})
.should.eql [ 'http://a.com/1.html' ]
describe 'custom link resolver', ->
it 'should be able to override resolver', ->
link.extractor( 'http://a.com', '<a href="1.html">1</a>', {
resolver: ( url, baseUri ) -> return url # just return the url without modification
pattern: filter: /.*/ # allow any uri
})
.should.eql [ '1.html' ]
describe 'custom link normaliser', ->
it 'should be able to override normaliser', ->
link.extractor( 'http://a.com', '<a href="1.html">1</a>', {
normaliser: ( url ) -> return url.replace /\.\w*$/, '' # remove file extension
})
.should.eql [ 'http://a.com/1' ] | true |
link = require( '../../lib/link' );
should = require 'should'
describe 'normaliser', ->
describe 'validation', ->
it 'should throw if uri is invalid', ->
(-> link.normaliser( '' ) ).should.throw 'invalid uri';
(-> link.normaliser( null ) ).should.throw 'invalid uri';
(-> link.normaliser( undefined ) ).should.throw 'invalid uri';
(-> link.normaliser( {} ) ).should.throw 'invalid uri';
(-> link.normaliser( [] ) ).should.throw 'invalid uri';
(-> link.normaliser( 'a' ) ).should.not.throw();
describe 'transformations', ->
it 'should remove trailing slashes', ->
link.normaliser( '/' ).should.eql ''
link.normaliser( 'http://a.com/foo' ).should.eql 'http://a.com/foo' # no trailing slash
link.normaliser( 'http://a.com/foo/#bingo' ).should.eql 'http://a.com/foo#bingo'
link.normaliser( 'http://a.com/foo/#bingo/' ).should.eql 'http://a.com/foo#bingo'
link.normaliser( 'http://a.com/foo/?bing=bang' ).should.eql 'http://a.com/foo?bing=bang'
link.normaliser( 'http://a.com/foo/?bing=bang#moo' ).should.eql 'http://a.com/foo?bing=bang#moo'
link.normaliser( 'http://a.com/foo/bar/' ).should.eql 'http://a.com/foo/bar'
describe 'resolver', ->
describe 'validation', ->
it 'should throw if uri is invalid', ->
(-> link.resolver( '' ) ).should.throw 'invalid uri';
(-> link.resolver( null ) ).should.throw 'invalid uri';
(-> link.resolver( undefined ) ).should.throw 'invalid uri';
(-> link.resolver( {} ) ).should.throw 'invalid uri';
(-> link.resolver( [] ) ).should.throw 'invalid uri';
(-> link.resolver( 'a' ) ).should.not.throw();
describe 'absolute / relative urls', ->
it 'should not convert relative url to absolute urls if base url not provided', ->
link.resolver( '/1.html' ).should.eql '/1.html'
it 'should not convert absolute urls if base url not provided', ->
link.resolver( 'http://www.example.com/1.html' ).should.eql 'http://www.example.com/1.html'
it 'should convert relative url to absolute urls when base url is provided', ->
link.resolver( '/1.html', 'http://example.com/' ).should.eql 'http://example.com/1.html'
link.resolver( '1.html', 'http://example.com/a' ).should.eql 'http://example.com/1.html'
link.resolver( '1.html', 'http://example.com/a/' ).should.eql 'http://example.com/a/1.html'
it 'should not convert domains for absolute urls when a base url is provided', ->
link.resolver( 'http://example.com/1.html', 'http://foo.com/' ).should.eql 'http://example.com/1.html'
it 'should resolve parent directory references', ->
link.resolver( '../2.html', 'http://example.com/a/1.html' ).should.eql 'http://example.com/2.html'
describe 'extractor', ->
describe 'source parsing', ->
it 'should accept single and double quote attributes', ->
link.extractor( 'http://example.com/', '<a href="/1.html">1</a>'+"<a href='/2.html'>2</a>" )
.should.eql [ 'http://example.com/1.html', 'http://example.com/2.html' ]
describe 'search & refine patterns', ->
describe 'default patterns', ->
it 'should only refine anchor links', ->
link.extractor( 'http://example.com/', '<script src="/1.js">1</script><a href="/2.html">2</a>' )
.should.eql [ 'http://example.com/2.html' ]
it 'should parse correctly when tag has preceding arguments', ->
link.extractor( 'http://example.com/', '<a id="myid" href="/1.html">1</a>' )
.should.eql [ 'http://example.com/1.html' ]
it 'should parse correctly when tag has succeeding arguments', ->
link.extractor( 'http://example.com/', '<a href="/1.html" id="myid">1</a>' )
.should.eql [ 'http://example.com/1.html' ]
describe 'should be overridable', ->
it 'should allow script tags src to be extracted', ->
link.extractor( 'http://example.com/', '<script src="/1.js#foo">1</script><a href="/2.html">2</a>', {
pattern: {
search: /script([^>]+)src\s*=\s*['"]([^"']+)/gi, # extract script tags and allow fragment hash
refine: /['"]([^"']+)/ # allow fragment hash
}
})
.should.eql [ 'http://example.com/1.js#foo' ]
it 'should allow both script & anchor tags to be extracted', ->
link.extractor( 'http://example.com/', '<script src="/1.js#foo">1</script><a href="/2.html">2</a>', {
pattern: {
search: /(a([^>]+)href|script([^>]+)src)\s?=\s?['"]([^"'#]+)/gi, # anchor or script tags
}
})
.should.eql [ 'http://example.com/1.js', 'http://example.com/2.html' ]
describe 'filter pattern', ->
describe 'default pattern', ->
it 'should not filter by domain (or apply any filtering)', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.html">2</a>' )
.should.eql [ 'http://a.com/1.html', 'http://b.com/2.html' ]
describe 'should be overridable', ->
it 'should allow domain filtering', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.html">2</a>', {
pattern: {
filter: 'http://a.com'
}
})
.should.eql [ 'http://a.com/1.html' ]
it 'should filter non http(s) uris by default', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="mailto:PI:EMAIL:<EMAIL>END_PI">2</a>' )
.should.eql [ 'http://a.com/1.html' ]
it 'should allow filtering out certain file extension using a lookahead', ->
link.extractor( null, '<a href="http://a.com/1.mp3">1</a><a href="http://a.com/2.pdf">2</a>', {
pattern: {
filter: /^https?:\/\/.*(?!\.(pdf|png|jpg|gif|zip))....$/
}
})
.should.eql [ 'http://a.com/1.mp3' ]
it 'should allow filtering out all uris with three letter extensions', ->
link.extractor( null, '<a href="http://a.com/1.mp3">1</a><a href="http://a.com/2">2</a>', {
pattern: {
filter: /^https?:\/\/.*(?!\.\w{3})....$/
}
})
.should.eql [ 'http://a.com/2' ]
it 'should allow file extension filtering', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://b.com/2.jpg">2</a>', {
pattern: {
filter: /\.jpg|\.gif|\.png/ # images only
}
})
.should.eql [ 'http://b.com/2.jpg' ]
describe 'unique option', ->
it 'should default unique filtering to enabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>' )
.should.eql [ 'http://a.com/1.html' ]
it 'should allow unique filtering to be disabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>', {
unique: false
})
.should.eql [ 'http://a.com/1.html', 'http://a.com/1.html' ]
it 'should allow unique filtering to be enabled', ->
link.extractor( null, '<a href="http://a.com/1.html">1</a><a href="http://a.com/1.html">1</a>', {
unique: true
})
.should.eql [ 'http://a.com/1.html' ]
describe 'custom link resolver', ->
it 'should be able to override resolver', ->
link.extractor( 'http://a.com', '<a href="1.html">1</a>', {
resolver: ( url, baseUri ) -> return url # just return the url without modification
pattern: filter: /.*/ # allow any uri
})
.should.eql [ '1.html' ]
describe 'custom link normaliser', ->
it 'should be able to override normaliser', ->
link.extractor( 'http://a.com', '<a href="1.html">1</a>', {
normaliser: ( url ) -> return url.replace /\.\w*$/, '' # remove file extension
})
.should.eql [ 'http://a.com/1' ] |
[
{
"context": "SER_NUMID_NAME = 'fldUserNumId'\nUSER_PASS_NAME = 'fldUserPass'\nLOGIN_BUTTON_ID = 'loginbutton'\nSECURITY_CARD_ID",
"end": 89,
"score": 0.9993087649345398,
"start": 78,
"tag": "PASSWORD",
"value": "fldUserPass"
}
] | src/content_scripts/index.coffee | shizuku613/shinseibank-autologin-ext | 0 | USER_ID_NAME = 'fldUserID'
USER_NUMID_NAME = 'fldUserNumId'
USER_PASS_NAME = 'fldUserPass'
LOGIN_BUTTON_ID = 'loginbutton'
SECURITY_CARD_ID = 'main-left-securitycard'
SECURITY_CARD_POSITION_SEL = 'td > strong'
SECURITY_CARD_NAMES = ['fldGridChg1', 'fldGridChg2', 'fldGridChg3']
LAST_FIRST_STEP_DATE_KEY = 'lastFirstStepDate'
LAST_SECOND_STEP_DATE_KEY = 'lastSecondStepDate'
FIRST_STEP_INTERVAL_MS = 10 * 1000
SECOND_STEP_INTERVAL_MS = 10 * 1000
main = ->
chrome.runtime.sendMessage { }, (res) ->
return unless res
securityCard = byId(SECURITY_CARD_ID)
if securityCard
secondStep(res.userdata)
else
firstStep(res.userdata)
firstStep = (data) ->
console.log 'Start first step'
unless checkStepInterval(LAST_FIRST_STEP_DATE_KEY, FIRST_STEP_INTERVAL_MS)
return
setByName(USER_ID_NAME, data.userId)
setByName(USER_NUMID_NAME, data.userNumid)
setByName(USER_PASS_NAME, data.userPass)
byId(LOGIN_BUTTON_ID).click()
secondStep = (data) ->
console.log 'Start second step'
unless checkStepInterval(LAST_SECOND_STEP_DATE_KEY, SECOND_STEP_INTERVAL_MS)
return
positions = getSecurityCardPositions()
elems = SECURITY_CARD_NAMES.map(byName)
for position, i in positions
val = getSecurityCardValue(data, position)
# 正しく取得できていない場合は処理を中断
return if typeof val != 'string' or val.length != 1
elems[i].value = val
# ログイン
byId(LOGIN_BUTTON_ID).click()
checkStepInterval = (key, interval) ->
# 前回の操作からの時間を計算
lastStepDate = localStorage.getItem(key)
if lastStepDate
console.log 'Check last login date'
if new Date() - new Date(lastStepDate) < interval
console.log 'Skip step'
return false
localStorage.setItem(key, new Date().toUTCString())
return true
getSecurityCardPositions = ->
positions = []
elems = document.querySelectorAll(SECURITY_CARD_POSITION_SEL)
for elem in elems
positions.push(elem.textContent)
positions
getSecurityCardValue = (data, position) ->
data.securityCard[position]
byId = (id) ->
document.getElementById(id)
byName = (name) ->
document.querySelector('[name="' + name + '"]')
setByName = (name, val) ->
elem = byName(name)
elem.value = val if elem
start = ->
return main() if isReady()
return if isLoggedIn()
setTimeout start, 100
isReady = ->
byName(USER_ID_NAME) or byId(SECURITY_CARD_ID)
isLoggedIn = ->
document.getElementsByTagName('frameset').length > 0
start() | 68229 | USER_ID_NAME = 'fldUserID'
USER_NUMID_NAME = 'fldUserNumId'
USER_PASS_NAME = '<PASSWORD>'
LOGIN_BUTTON_ID = 'loginbutton'
SECURITY_CARD_ID = 'main-left-securitycard'
SECURITY_CARD_POSITION_SEL = 'td > strong'
SECURITY_CARD_NAMES = ['fldGridChg1', 'fldGridChg2', 'fldGridChg3']
LAST_FIRST_STEP_DATE_KEY = 'lastFirstStepDate'
LAST_SECOND_STEP_DATE_KEY = 'lastSecondStepDate'
FIRST_STEP_INTERVAL_MS = 10 * 1000
SECOND_STEP_INTERVAL_MS = 10 * 1000
main = ->
chrome.runtime.sendMessage { }, (res) ->
return unless res
securityCard = byId(SECURITY_CARD_ID)
if securityCard
secondStep(res.userdata)
else
firstStep(res.userdata)
firstStep = (data) ->
console.log 'Start first step'
unless checkStepInterval(LAST_FIRST_STEP_DATE_KEY, FIRST_STEP_INTERVAL_MS)
return
setByName(USER_ID_NAME, data.userId)
setByName(USER_NUMID_NAME, data.userNumid)
setByName(USER_PASS_NAME, data.userPass)
byId(LOGIN_BUTTON_ID).click()
secondStep = (data) ->
console.log 'Start second step'
unless checkStepInterval(LAST_SECOND_STEP_DATE_KEY, SECOND_STEP_INTERVAL_MS)
return
positions = getSecurityCardPositions()
elems = SECURITY_CARD_NAMES.map(byName)
for position, i in positions
val = getSecurityCardValue(data, position)
# 正しく取得できていない場合は処理を中断
return if typeof val != 'string' or val.length != 1
elems[i].value = val
# ログイン
byId(LOGIN_BUTTON_ID).click()
checkStepInterval = (key, interval) ->
# 前回の操作からの時間を計算
lastStepDate = localStorage.getItem(key)
if lastStepDate
console.log 'Check last login date'
if new Date() - new Date(lastStepDate) < interval
console.log 'Skip step'
return false
localStorage.setItem(key, new Date().toUTCString())
return true
getSecurityCardPositions = ->
positions = []
elems = document.querySelectorAll(SECURITY_CARD_POSITION_SEL)
for elem in elems
positions.push(elem.textContent)
positions
getSecurityCardValue = (data, position) ->
data.securityCard[position]
byId = (id) ->
document.getElementById(id)
byName = (name) ->
document.querySelector('[name="' + name + '"]')
setByName = (name, val) ->
elem = byName(name)
elem.value = val if elem
start = ->
return main() if isReady()
return if isLoggedIn()
setTimeout start, 100
isReady = ->
byName(USER_ID_NAME) or byId(SECURITY_CARD_ID)
isLoggedIn = ->
document.getElementsByTagName('frameset').length > 0
start() | true | USER_ID_NAME = 'fldUserID'
USER_NUMID_NAME = 'fldUserNumId'
USER_PASS_NAME = 'PI:PASSWORD:<PASSWORD>END_PI'
LOGIN_BUTTON_ID = 'loginbutton'
SECURITY_CARD_ID = 'main-left-securitycard'
SECURITY_CARD_POSITION_SEL = 'td > strong'
SECURITY_CARD_NAMES = ['fldGridChg1', 'fldGridChg2', 'fldGridChg3']
LAST_FIRST_STEP_DATE_KEY = 'lastFirstStepDate'
LAST_SECOND_STEP_DATE_KEY = 'lastSecondStepDate'
FIRST_STEP_INTERVAL_MS = 10 * 1000
SECOND_STEP_INTERVAL_MS = 10 * 1000
main = ->
chrome.runtime.sendMessage { }, (res) ->
return unless res
securityCard = byId(SECURITY_CARD_ID)
if securityCard
secondStep(res.userdata)
else
firstStep(res.userdata)
firstStep = (data) ->
console.log 'Start first step'
unless checkStepInterval(LAST_FIRST_STEP_DATE_KEY, FIRST_STEP_INTERVAL_MS)
return
setByName(USER_ID_NAME, data.userId)
setByName(USER_NUMID_NAME, data.userNumid)
setByName(USER_PASS_NAME, data.userPass)
byId(LOGIN_BUTTON_ID).click()
secondStep = (data) ->
console.log 'Start second step'
unless checkStepInterval(LAST_SECOND_STEP_DATE_KEY, SECOND_STEP_INTERVAL_MS)
return
positions = getSecurityCardPositions()
elems = SECURITY_CARD_NAMES.map(byName)
for position, i in positions
val = getSecurityCardValue(data, position)
# 正しく取得できていない場合は処理を中断
return if typeof val != 'string' or val.length != 1
elems[i].value = val
# ログイン
byId(LOGIN_BUTTON_ID).click()
checkStepInterval = (key, interval) ->
# 前回の操作からの時間を計算
lastStepDate = localStorage.getItem(key)
if lastStepDate
console.log 'Check last login date'
if new Date() - new Date(lastStepDate) < interval
console.log 'Skip step'
return false
localStorage.setItem(key, new Date().toUTCString())
return true
getSecurityCardPositions = ->
positions = []
elems = document.querySelectorAll(SECURITY_CARD_POSITION_SEL)
for elem in elems
positions.push(elem.textContent)
positions
getSecurityCardValue = (data, position) ->
data.securityCard[position]
byId = (id) ->
document.getElementById(id)
byName = (name) ->
document.querySelector('[name="' + name + '"]')
setByName = (name, val) ->
elem = byName(name)
elem.value = val if elem
start = ->
return main() if isReady()
return if isLoggedIn()
setTimeout start, 100
isReady = ->
byName(USER_ID_NAME) or byId(SECURITY_CARD_ID)
isLoggedIn = ->
document.getElementsByTagName('frameset').length > 0
start() |
[
{
"context": "est.expect 2\n lo = new vrs.LO(DEF_CTX, null, [\"Juergen\", \"Gmeiner\"])\n test.deepEqual new Buffer(\"Juer",
"end": 3948,
"score": 0.9998614192008972,
"start": 3941,
"tag": "NAME",
"value": "Juergen"
},
{
"context": "2\n lo = new vrs.LO(DEF_CTX, null, [\"Juer... | test/test_vrs.coffee | alwhiting/node-dicom | 57 | #! /usr/bin/env coffee
vrs = require "../lib/vrs"
b_1704 = new Buffer([0x17, 0x04])
b_deadbeef = new Buffer([0xDE, 0xAD, 0xBE, 0xEF])
exports.LittleEndianTest =
"test unpacking": (test) ->
test.expect 2
test.equal 0x0417, vrs.LITTLE_ENDIAN.unpack_uint16(b_1704)
test.deepEqual [0xADDE, 0xEFBE], vrs.LITTLE_ENDIAN.unpack_uint16s(b_deadbeef, 2)
test.done()
"test packing": (test) ->
test.expect 1
test.deepEqual b_deadbeef, vrs.LITTLE_ENDIAN.pack_uint16s([0xADDE, 0xEFBE])
test.done()
exports.BigEndianTest =
"test unpacking": (test) ->
test.expect 2
test.equal 0x1704, vrs.BIG_ENDIAN.unpack_uint16(b_1704)
test.deepEqual [0xDEAD, 0xBEEF], vrs.BIG_ENDIAN.unpack_uint16s(b_deadbeef, 2)
test.done()
"test packing": (test) ->
test.expect 1
test.deepEqual b_deadbeef, vrs.BIG_ENDIAN.pack_uint16s([0xDEAD, 0xBEEF])
test.done()
DEF_CTX = new vrs.Context({}, {})
exports.ATTest =
"test encoding": (test) ->
test.expect 2
at = new vrs.AT(DEF_CTX, null, [0x00100012, 0x0020001D])
expect = new Buffer([0x10, 0x00, 0x12, 0x00, 0x20, 0x00, 0x1D, 0x00])
test.deepEqual expect, at.buffer
at = new vrs.AT(DEF_CTX, null, [0xfffee000])
expect = new Buffer([0xfe, 0xff, 0x00, 0xe0])
test.deepEqual expect, at.buffer
test.done()
"test decoding": (test) ->
test.expect 1
input = new Buffer([0x10, 0x00, 0x12, 0x00, 0x20, 0x00, 0x1D, 0x00])
at = new vrs.AT(DEF_CTX, input)
test.deepEqual [0x00100012, 0x0020001D], at.values()
test.done()
exports.FDTest =
"test doubles": (test) ->
test.expect 1
_vals = [0.5, 1000.0]
fd = new vrs.FD(DEF_CTX, null, _vals)
# this relies on the fact that the values are not stored
# converting to buffer and converting back should be the same
test.deepEqual _vals, fd.values()
test.done()
exports.FLTest =
"test floats": (test) ->
test.expect 1
_vals = [0.5, 1000.0]
fl = new vrs.FL(DEF_CTX, null, _vals)
# this relies on the fact that the values are not stored
# converting to buffer and converting back should be the same
test.deepEqual _vals, fl.values()
test.done()
exports.SLTest =
"test encode": (test) ->
test.expect 1
sl = new vrs.SL(DEF_CTX, null, [0x01020304, 0x05060708])
test.deepEqual sl.buffer, new Buffer([4..1].concat([8..5]))
test.done()
"test decode": (test) ->
test.expect 1
sl = new vrs.SL(DEF_CTX, new Buffer([4..1].concat([8..5])))
test.deepEqual [0x01020304, 0x05060708], sl.values()
test.done()
exports.SSTest =
"test encode": (test) ->
test.expect 1
ss = new vrs.SS(DEF_CTX, null, [0x0102, 0x0506])
test.deepEqual ss.buffer, new Buffer([2..1].concat([6..5]))
test.done()
"test decode": (test) ->
test.expect 1
ss = new vrs.SS(DEF_CTX, new Buffer([2..1].concat([6..5])))
test.deepEqual [0x0102, 0x0506], ss.values()
test.done()
exports.ULTest =
"test encode": (test) ->
test.expect 1
ul = new vrs.UL(DEF_CTX, null, [0x01020304, 0x05060708])
test.deepEqual ul.buffer, new Buffer([4..1].concat([8..5]))
test.done()
"test decode": (test) ->
test.expect 1
ul = new vrs.UL(DEF_CTX, new Buffer([4..1].concat([8..5])))
test.deepEqual [0x01020304, 0x05060708], ul.values()
test.done()
exports.USTest =
"test encode": (test) ->
test.expect 1
us = new vrs.US(DEF_CTX, null, [0x0102, 0x0506])
test.deepEqual us.buffer, new Buffer([2..1].concat([6..5]))
test.done()
"test decode": (test) ->
test.expect 1
us = new vrs.US(DEF_CTX, new Buffer([2..1].concat([6..5])))
test.deepEqual [0x0102, 0x0506], us.values()
test.done()
#
# for string tests:
#
# * multi-values
# * no multi-values, e.g. LT with backslashes in there
# * space-padding
# * zero-padding (UI)
exports.StringMultiValuesTest =
"test multivalue": (test) ->
test.expect 2
lo = new vrs.LO(DEF_CTX, null, ["Juergen", "Gmeiner"])
test.deepEqual new Buffer("Juergen\\Gmeiner ", "binary"), lo.buffer
test.deepEqual ["Juergen", "Gmeiner"], lo.values()
test.done()
"test no multivalue": (test) ->
test.expect 2
st = new vrs.ST(DEF_CTX, null, ["Some text with \\ in there"])
test.deepEqual new Buffer("Some text with \\ in there ", "binary"), st.buffer
test.deepEqual ["Some text with \\ in there"], st.values()
test.done()
exports.StringPaddingTest =
"test space padding": (test) ->
test.expect 2
lo = new vrs.LO(DEF_CTX, null, ["ASD"])
test.deepEqual new Buffer("ASD ", "binary"), lo.buffer
test.deepEqual ["ASD"], lo.values()
test.done()
"test zerobyte padding": (test) ->
test.expect 2
lo = new vrs.UI(DEF_CTX, null, ["1.2"])
test.deepEqual new Buffer("1.2\x00", "binary"), lo.buffer
test.deepEqual ["1.2"], lo.values()
test.done()
#
# binary vrs should produce base64 encoded values ...
#
exports.OBTest =
"test base64 values": (test) ->
test.expect 1
ob = new vrs.OB(DEF_CTX, new Buffer("asdf"))
test.deepEqual ["YXNkZg=="], ob.values()
test.done()
#
# binary vrs should produce base64 encoded values ...
#
exports.ODTest =
"test base64 values": (test) ->
test.expect 1
od = new vrs.OD(DEF_CTX, new Buffer("asdfasdf"))
test.deepEqual ["YXNkZmFzZGY="], od.values()
test.done()
exports.PNTest =
"test single component group value": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, new Buffer("group1"))
test.deepEqual [{Alphabetic: "group1"}], pn.values()
test.done()
"test all component groups values": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, new Buffer("group1=group2=group3=x=y"))
test.deepEqual [{Alphabetic: "group1", Ideographic: "group2", Phonetic: "group3"}], pn.values()
test.done()
"test encode alphabetic": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, null, [{Alphabetic: "group1"}])
test.deepEqual new Buffer("group1"), pn.buffer
test.done()
"test encode all groups": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, null, [{Alphabetic: "group1", Ideographic: "group2", Phonetic: "group3", Xtra1: "x", Xtra2: "y"}])
test.deepEqual new Buffer("group1=group2=group3"), pn.buffer
test.done()
#
# IS and DS are encoded as strings, but represent numbers.
# They are numbers in the DICOM model.
#
exports.ISTest =
"test values": (test) ->
test.expect 3
_is = new vrs.IS(DEF_CTX, new Buffer("1\\2"))
_vals = _is.values()
test.deepEqual [1,2], _vals
test.equal 'number', typeof _vals[0]
test.equal 'number', typeof _vals[1]
test.done()
"test encode": (test) ->
test.expect 1
_is = new vrs.IS(DEF_CTX, null, [1,2])
test.deepEqual new Buffer("1\\2 "), _is.buffer
test.done()
| 165957 | #! /usr/bin/env coffee
vrs = require "../lib/vrs"
b_1704 = new Buffer([0x17, 0x04])
b_deadbeef = new Buffer([0xDE, 0xAD, 0xBE, 0xEF])
exports.LittleEndianTest =
"test unpacking": (test) ->
test.expect 2
test.equal 0x0417, vrs.LITTLE_ENDIAN.unpack_uint16(b_1704)
test.deepEqual [0xADDE, 0xEFBE], vrs.LITTLE_ENDIAN.unpack_uint16s(b_deadbeef, 2)
test.done()
"test packing": (test) ->
test.expect 1
test.deepEqual b_deadbeef, vrs.LITTLE_ENDIAN.pack_uint16s([0xADDE, 0xEFBE])
test.done()
exports.BigEndianTest =
"test unpacking": (test) ->
test.expect 2
test.equal 0x1704, vrs.BIG_ENDIAN.unpack_uint16(b_1704)
test.deepEqual [0xDEAD, 0xBEEF], vrs.BIG_ENDIAN.unpack_uint16s(b_deadbeef, 2)
test.done()
"test packing": (test) ->
test.expect 1
test.deepEqual b_deadbeef, vrs.BIG_ENDIAN.pack_uint16s([0xDEAD, 0xBEEF])
test.done()
DEF_CTX = new vrs.Context({}, {})
exports.ATTest =
"test encoding": (test) ->
test.expect 2
at = new vrs.AT(DEF_CTX, null, [0x00100012, 0x0020001D])
expect = new Buffer([0x10, 0x00, 0x12, 0x00, 0x20, 0x00, 0x1D, 0x00])
test.deepEqual expect, at.buffer
at = new vrs.AT(DEF_CTX, null, [0xfffee000])
expect = new Buffer([0xfe, 0xff, 0x00, 0xe0])
test.deepEqual expect, at.buffer
test.done()
"test decoding": (test) ->
test.expect 1
input = new Buffer([0x10, 0x00, 0x12, 0x00, 0x20, 0x00, 0x1D, 0x00])
at = new vrs.AT(DEF_CTX, input)
test.deepEqual [0x00100012, 0x0020001D], at.values()
test.done()
exports.FDTest =
"test doubles": (test) ->
test.expect 1
_vals = [0.5, 1000.0]
fd = new vrs.FD(DEF_CTX, null, _vals)
# this relies on the fact that the values are not stored
# converting to buffer and converting back should be the same
test.deepEqual _vals, fd.values()
test.done()
exports.FLTest =
"test floats": (test) ->
test.expect 1
_vals = [0.5, 1000.0]
fl = new vrs.FL(DEF_CTX, null, _vals)
# this relies on the fact that the values are not stored
# converting to buffer and converting back should be the same
test.deepEqual _vals, fl.values()
test.done()
exports.SLTest =
"test encode": (test) ->
test.expect 1
sl = new vrs.SL(DEF_CTX, null, [0x01020304, 0x05060708])
test.deepEqual sl.buffer, new Buffer([4..1].concat([8..5]))
test.done()
"test decode": (test) ->
test.expect 1
sl = new vrs.SL(DEF_CTX, new Buffer([4..1].concat([8..5])))
test.deepEqual [0x01020304, 0x05060708], sl.values()
test.done()
exports.SSTest =
"test encode": (test) ->
test.expect 1
ss = new vrs.SS(DEF_CTX, null, [0x0102, 0x0506])
test.deepEqual ss.buffer, new Buffer([2..1].concat([6..5]))
test.done()
"test decode": (test) ->
test.expect 1
ss = new vrs.SS(DEF_CTX, new Buffer([2..1].concat([6..5])))
test.deepEqual [0x0102, 0x0506], ss.values()
test.done()
exports.ULTest =
"test encode": (test) ->
test.expect 1
ul = new vrs.UL(DEF_CTX, null, [0x01020304, 0x05060708])
test.deepEqual ul.buffer, new Buffer([4..1].concat([8..5]))
test.done()
"test decode": (test) ->
test.expect 1
ul = new vrs.UL(DEF_CTX, new Buffer([4..1].concat([8..5])))
test.deepEqual [0x01020304, 0x05060708], ul.values()
test.done()
exports.USTest =
"test encode": (test) ->
test.expect 1
us = new vrs.US(DEF_CTX, null, [0x0102, 0x0506])
test.deepEqual us.buffer, new Buffer([2..1].concat([6..5]))
test.done()
"test decode": (test) ->
test.expect 1
us = new vrs.US(DEF_CTX, new Buffer([2..1].concat([6..5])))
test.deepEqual [0x0102, 0x0506], us.values()
test.done()
#
# for string tests:
#
# * multi-values
# * no multi-values, e.g. LT with backslashes in there
# * space-padding
# * zero-padding (UI)
exports.StringMultiValuesTest =
"test multivalue": (test) ->
test.expect 2
lo = new vrs.LO(DEF_CTX, null, ["<NAME>", "<NAME>"])
test.deepEqual new Buffer("<NAME> ", "binary"), lo.buffer
test.deepEqual ["<NAME>", "<NAME>"], lo.values()
test.done()
"test no multivalue": (test) ->
test.expect 2
st = new vrs.ST(DEF_CTX, null, ["Some text with \\ in there"])
test.deepEqual new Buffer("Some text with \\ in there ", "binary"), st.buffer
test.deepEqual ["Some text with \\ in there"], st.values()
test.done()
exports.StringPaddingTest =
"test space padding": (test) ->
test.expect 2
lo = new vrs.LO(DEF_CTX, null, ["ASD"])
test.deepEqual new Buffer("ASD ", "binary"), lo.buffer
test.deepEqual ["ASD"], lo.values()
test.done()
"test zerobyte padding": (test) ->
test.expect 2
lo = new vrs.UI(DEF_CTX, null, ["1.2"])
test.deepEqual new Buffer("1.2\x00", "binary"), lo.buffer
test.deepEqual ["1.2"], lo.values()
test.done()
#
# binary vrs should produce base64 encoded values ...
#
exports.OBTest =
"test base64 values": (test) ->
test.expect 1
ob = new vrs.OB(DEF_CTX, new Buffer("asdf"))
test.deepEqual ["YXNkZg=="], ob.values()
test.done()
#
# binary vrs should produce base64 encoded values ...
#
exports.ODTest =
"test base64 values": (test) ->
test.expect 1
od = new vrs.OD(DEF_CTX, new Buffer("asdfasdf"))
test.deepEqual ["YXNkZmFzZGY="], od.values()
test.done()
exports.PNTest =
"test single component group value": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, new Buffer("group1"))
test.deepEqual [{Alphabetic: "group1"}], pn.values()
test.done()
"test all component groups values": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, new Buffer("group1=group2=group3=x=y"))
test.deepEqual [{Alphabetic: "group1", Ideographic: "group2", Phonetic: "group3"}], pn.values()
test.done()
"test encode alphabetic": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, null, [{Alphabetic: "group1"}])
test.deepEqual new Buffer("group1"), pn.buffer
test.done()
"test encode all groups": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, null, [{Alphabetic: "group1", Ideographic: "group2", Phonetic: "group3", Xtra1: "x", Xtra2: "y"}])
test.deepEqual new Buffer("group1=group2=group3"), pn.buffer
test.done()
#
# IS and DS are encoded as strings, but represent numbers.
# They are numbers in the DICOM model.
#
exports.ISTest =
"test values": (test) ->
test.expect 3
_is = new vrs.IS(DEF_CTX, new Buffer("1\\2"))
_vals = _is.values()
test.deepEqual [1,2], _vals
test.equal 'number', typeof _vals[0]
test.equal 'number', typeof _vals[1]
test.done()
"test encode": (test) ->
test.expect 1
_is = new vrs.IS(DEF_CTX, null, [1,2])
test.deepEqual new Buffer("1\\2 "), _is.buffer
test.done()
| true | #! /usr/bin/env coffee
vrs = require "../lib/vrs"
b_1704 = new Buffer([0x17, 0x04])
b_deadbeef = new Buffer([0xDE, 0xAD, 0xBE, 0xEF])
exports.LittleEndianTest =
"test unpacking": (test) ->
test.expect 2
test.equal 0x0417, vrs.LITTLE_ENDIAN.unpack_uint16(b_1704)
test.deepEqual [0xADDE, 0xEFBE], vrs.LITTLE_ENDIAN.unpack_uint16s(b_deadbeef, 2)
test.done()
"test packing": (test) ->
test.expect 1
test.deepEqual b_deadbeef, vrs.LITTLE_ENDIAN.pack_uint16s([0xADDE, 0xEFBE])
test.done()
exports.BigEndianTest =
"test unpacking": (test) ->
test.expect 2
test.equal 0x1704, vrs.BIG_ENDIAN.unpack_uint16(b_1704)
test.deepEqual [0xDEAD, 0xBEEF], vrs.BIG_ENDIAN.unpack_uint16s(b_deadbeef, 2)
test.done()
"test packing": (test) ->
test.expect 1
test.deepEqual b_deadbeef, vrs.BIG_ENDIAN.pack_uint16s([0xDEAD, 0xBEEF])
test.done()
DEF_CTX = new vrs.Context({}, {})
exports.ATTest =
"test encoding": (test) ->
test.expect 2
at = new vrs.AT(DEF_CTX, null, [0x00100012, 0x0020001D])
expect = new Buffer([0x10, 0x00, 0x12, 0x00, 0x20, 0x00, 0x1D, 0x00])
test.deepEqual expect, at.buffer
at = new vrs.AT(DEF_CTX, null, [0xfffee000])
expect = new Buffer([0xfe, 0xff, 0x00, 0xe0])
test.deepEqual expect, at.buffer
test.done()
"test decoding": (test) ->
test.expect 1
input = new Buffer([0x10, 0x00, 0x12, 0x00, 0x20, 0x00, 0x1D, 0x00])
at = new vrs.AT(DEF_CTX, input)
test.deepEqual [0x00100012, 0x0020001D], at.values()
test.done()
exports.FDTest =
"test doubles": (test) ->
test.expect 1
_vals = [0.5, 1000.0]
fd = new vrs.FD(DEF_CTX, null, _vals)
# this relies on the fact that the values are not stored
# converting to buffer and converting back should be the same
test.deepEqual _vals, fd.values()
test.done()
exports.FLTest =
"test floats": (test) ->
test.expect 1
_vals = [0.5, 1000.0]
fl = new vrs.FL(DEF_CTX, null, _vals)
# this relies on the fact that the values are not stored
# converting to buffer and converting back should be the same
test.deepEqual _vals, fl.values()
test.done()
exports.SLTest =
"test encode": (test) ->
test.expect 1
sl = new vrs.SL(DEF_CTX, null, [0x01020304, 0x05060708])
test.deepEqual sl.buffer, new Buffer([4..1].concat([8..5]))
test.done()
"test decode": (test) ->
test.expect 1
sl = new vrs.SL(DEF_CTX, new Buffer([4..1].concat([8..5])))
test.deepEqual [0x01020304, 0x05060708], sl.values()
test.done()
exports.SSTest =
"test encode": (test) ->
test.expect 1
ss = new vrs.SS(DEF_CTX, null, [0x0102, 0x0506])
test.deepEqual ss.buffer, new Buffer([2..1].concat([6..5]))
test.done()
"test decode": (test) ->
test.expect 1
ss = new vrs.SS(DEF_CTX, new Buffer([2..1].concat([6..5])))
test.deepEqual [0x0102, 0x0506], ss.values()
test.done()
exports.ULTest =
"test encode": (test) ->
test.expect 1
ul = new vrs.UL(DEF_CTX, null, [0x01020304, 0x05060708])
test.deepEqual ul.buffer, new Buffer([4..1].concat([8..5]))
test.done()
"test decode": (test) ->
test.expect 1
ul = new vrs.UL(DEF_CTX, new Buffer([4..1].concat([8..5])))
test.deepEqual [0x01020304, 0x05060708], ul.values()
test.done()
exports.USTest =
"test encode": (test) ->
test.expect 1
us = new vrs.US(DEF_CTX, null, [0x0102, 0x0506])
test.deepEqual us.buffer, new Buffer([2..1].concat([6..5]))
test.done()
"test decode": (test) ->
test.expect 1
us = new vrs.US(DEF_CTX, new Buffer([2..1].concat([6..5])))
test.deepEqual [0x0102, 0x0506], us.values()
test.done()
#
# for string tests:
#
# * multi-values
# * no multi-values, e.g. LT with backslashes in there
# * space-padding
# * zero-padding (UI)
exports.StringMultiValuesTest =
"test multivalue": (test) ->
test.expect 2
lo = new vrs.LO(DEF_CTX, null, ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"])
test.deepEqual new Buffer("PI:NAME:<NAME>END_PI ", "binary"), lo.buffer
test.deepEqual ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"], lo.values()
test.done()
"test no multivalue": (test) ->
test.expect 2
st = new vrs.ST(DEF_CTX, null, ["Some text with \\ in there"])
test.deepEqual new Buffer("Some text with \\ in there ", "binary"), st.buffer
test.deepEqual ["Some text with \\ in there"], st.values()
test.done()
exports.StringPaddingTest =
"test space padding": (test) ->
test.expect 2
lo = new vrs.LO(DEF_CTX, null, ["ASD"])
test.deepEqual new Buffer("ASD ", "binary"), lo.buffer
test.deepEqual ["ASD"], lo.values()
test.done()
"test zerobyte padding": (test) ->
test.expect 2
lo = new vrs.UI(DEF_CTX, null, ["1.2"])
test.deepEqual new Buffer("1.2\x00", "binary"), lo.buffer
test.deepEqual ["1.2"], lo.values()
test.done()
#
# binary vrs should produce base64 encoded values ...
#
exports.OBTest =
"test base64 values": (test) ->
test.expect 1
ob = new vrs.OB(DEF_CTX, new Buffer("asdf"))
test.deepEqual ["YXNkZg=="], ob.values()
test.done()
#
# binary vrs should produce base64 encoded values ...
#
exports.ODTest =
"test base64 values": (test) ->
test.expect 1
od = new vrs.OD(DEF_CTX, new Buffer("asdfasdf"))
test.deepEqual ["YXNkZmFzZGY="], od.values()
test.done()
exports.PNTest =
"test single component group value": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, new Buffer("group1"))
test.deepEqual [{Alphabetic: "group1"}], pn.values()
test.done()
"test all component groups values": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, new Buffer("group1=group2=group3=x=y"))
test.deepEqual [{Alphabetic: "group1", Ideographic: "group2", Phonetic: "group3"}], pn.values()
test.done()
"test encode alphabetic": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, null, [{Alphabetic: "group1"}])
test.deepEqual new Buffer("group1"), pn.buffer
test.done()
"test encode all groups": (test) ->
test.expect 1
pn = new vrs.PN(DEF_CTX, null, [{Alphabetic: "group1", Ideographic: "group2", Phonetic: "group3", Xtra1: "x", Xtra2: "y"}])
test.deepEqual new Buffer("group1=group2=group3"), pn.buffer
test.done()
#
# IS and DS are encoded as strings, but represent numbers.
# They are numbers in the DICOM model.
#
exports.ISTest =
"test values": (test) ->
test.expect 3
_is = new vrs.IS(DEF_CTX, new Buffer("1\\2"))
_vals = _is.values()
test.deepEqual [1,2], _vals
test.equal 'number', typeof _vals[0]
test.equal 'number', typeof _vals[1]
test.done()
"test encode": (test) ->
test.expect 1
_is = new vrs.IS(DEF_CTX, null, [1,2])
test.deepEqual new Buffer("1\\2 "), _is.buffer
test.done()
|
[
{
"context": " EnvParser\"\n\n\tparser = new EnvParser(\"\"\"\n\t\t\tname = John\n\t\t\t\tlast = Deighan\n\t\t\tage = 68\n\t\t\ttown = Blacksbu",
"end": 1546,
"score": 0.9998501539230347,
"start": 1542,
"tag": "NAME",
"value": "John"
},
{
"context": "rser = new EnvParser(\"\"\"\n\t\t... | test/PLLParser.test.coffee | johndeighan/string-input | 0 | # PLLParser.test.coffee
import assert from 'assert'
import {
undef, error, warn, croak,
} from '@jdeighan/coffee-utils'
import {log} from '@jdeighan/coffee-utils/log'
import {setDebugging} from '@jdeighan/coffee-utils/debug'
import {UnitTester} from '@jdeighan/coffee-utils/test'
import {PLLParser} from '@jdeighan/string-input'
simple = new UnitTester()
# ---------------------------------------------------------------------------
class GatherTester extends UnitTester
transformValue: (oInput) ->
assert oInput instanceof PLLParser,
"oInput should be a PLLParser object"
return oInput.getAll()
normalize: (str) ->
return str
tester = new GatherTester()
# ---------------------------------------------------------------------------
tester.equal 31, new PLLParser("""
line 1
line 2
line 3
"""), [
[0, 1, 'line 1']
[0, 2, 'line 2']
[1, 3, 'line 3']
]
# ---------------------------------------------------------------------------
tester.equal 43, new PLLParser("""
line 1
line 2
line 3
"""), [
[0, 1, 'line 1']
[1, 2, 'line 2']
[2, 3, 'line 3']
]
# ---------------------------------------------------------------------------
# Test extending PLLParser
(() ->
class EnvParser extends PLLParser
mapNode: (line) ->
if (lMatches = line.match(///^
\s*
([A-Za-z]+)
\s*
=
\s*
([A-Za-z0-9]+)
\s*
$///))
[_, left, right] = lMatches
return [left, right]
else
croak "Bad line in EnvParser"
parser = new EnvParser("""
name = John
last = Deighan
age = 68
town = Blacksburg
""")
tree = parser.getTree()
simple.equal 84, tree, [
{ lineNum: 1, node: ['name','John'], body: [
{ lineNum: 2, node: ['last','Deighan'] }
]}
{ lineNum: 3, node: ['age','68'] },
{ lineNum: 4, node: ['town','Blacksburg'] },
]
)()
# ---------------------------------------------------------------------------
# Test extending PLLParser when mapNode() sometimes returns undef
(() ->
class EnvParser extends PLLParser
mapNode: (line) ->
if (lMatches = line.match(///^
\s*
([A-Za-z]+)
\s*
=
\s*
([A-Za-z0-9]+)
\s*
$///))
[_, left, right] = lMatches
if (left == 'name')
return undef
return right
else
croak "Bad line in EnvParser"
parser = new EnvParser("""
name = John
last = Deighan
age = 68
town = Blacksburg
""")
tree = parser.getTree()
simple.equal 127, tree, [
{ lineNum: 3, node: '68' },
{ lineNum: 4, node: 'Blacksburg' },
]
)()
| 122155 | # PLLParser.test.coffee
import assert from 'assert'
import {
undef, error, warn, croak,
} from '@jdeighan/coffee-utils'
import {log} from '@jdeighan/coffee-utils/log'
import {setDebugging} from '@jdeighan/coffee-utils/debug'
import {UnitTester} from '@jdeighan/coffee-utils/test'
import {PLLParser} from '@jdeighan/string-input'
simple = new UnitTester()
# ---------------------------------------------------------------------------
class GatherTester extends UnitTester
transformValue: (oInput) ->
assert oInput instanceof PLLParser,
"oInput should be a PLLParser object"
return oInput.getAll()
normalize: (str) ->
return str
tester = new GatherTester()
# ---------------------------------------------------------------------------
tester.equal 31, new PLLParser("""
line 1
line 2
line 3
"""), [
[0, 1, 'line 1']
[0, 2, 'line 2']
[1, 3, 'line 3']
]
# ---------------------------------------------------------------------------
tester.equal 43, new PLLParser("""
line 1
line 2
line 3
"""), [
[0, 1, 'line 1']
[1, 2, 'line 2']
[2, 3, 'line 3']
]
# ---------------------------------------------------------------------------
# Test extending PLLParser
(() ->
class EnvParser extends PLLParser
mapNode: (line) ->
if (lMatches = line.match(///^
\s*
([A-Za-z]+)
\s*
=
\s*
([A-Za-z0-9]+)
\s*
$///))
[_, left, right] = lMatches
return [left, right]
else
croak "Bad line in EnvParser"
parser = new EnvParser("""
name = <NAME>
last = <NAME>
age = 68
town = Blacksburg
""")
tree = parser.getTree()
simple.equal 84, tree, [
{ lineNum: 1, node: ['name','<NAME>'], body: [
{ lineNum: 2, node: ['last','<NAME>'] }
]}
{ lineNum: 3, node: ['age','68'] },
{ lineNum: 4, node: ['town','Blacksburg'] },
]
)()
# ---------------------------------------------------------------------------
# Test extending PLLParser when mapNode() sometimes returns undef
(() ->
class EnvParser extends PLLParser
mapNode: (line) ->
if (lMatches = line.match(///^
\s*
([A-Za-z]+)
\s*
=
\s*
([A-Za-z0-9]+)
\s*
$///))
[_, left, right] = lMatches
if (left == 'name')
return undef
return right
else
croak "Bad line in EnvParser"
parser = new EnvParser("""
name = <NAME>
last = <NAME>
age = 68
town = Blacksburg
""")
tree = parser.getTree()
simple.equal 127, tree, [
{ lineNum: 3, node: '68' },
{ lineNum: 4, node: 'Blacksburg' },
]
)()
| true | # PLLParser.test.coffee
import assert from 'assert'
import {
undef, error, warn, croak,
} from '@jdeighan/coffee-utils'
import {log} from '@jdeighan/coffee-utils/log'
import {setDebugging} from '@jdeighan/coffee-utils/debug'
import {UnitTester} from '@jdeighan/coffee-utils/test'
import {PLLParser} from '@jdeighan/string-input'
simple = new UnitTester()
# ---------------------------------------------------------------------------
class GatherTester extends UnitTester
transformValue: (oInput) ->
assert oInput instanceof PLLParser,
"oInput should be a PLLParser object"
return oInput.getAll()
normalize: (str) ->
return str
tester = new GatherTester()
# ---------------------------------------------------------------------------
tester.equal 31, new PLLParser("""
line 1
line 2
line 3
"""), [
[0, 1, 'line 1']
[0, 2, 'line 2']
[1, 3, 'line 3']
]
# ---------------------------------------------------------------------------
tester.equal 43, new PLLParser("""
line 1
line 2
line 3
"""), [
[0, 1, 'line 1']
[1, 2, 'line 2']
[2, 3, 'line 3']
]
# ---------------------------------------------------------------------------
# Test extending PLLParser
(() ->
class EnvParser extends PLLParser
mapNode: (line) ->
if (lMatches = line.match(///^
\s*
([A-Za-z]+)
\s*
=
\s*
([A-Za-z0-9]+)
\s*
$///))
[_, left, right] = lMatches
return [left, right]
else
croak "Bad line in EnvParser"
parser = new EnvParser("""
name = PI:NAME:<NAME>END_PI
last = PI:NAME:<NAME>END_PI
age = 68
town = Blacksburg
""")
tree = parser.getTree()
simple.equal 84, tree, [
{ lineNum: 1, node: ['name','PI:NAME:<NAME>END_PI'], body: [
{ lineNum: 2, node: ['last','PI:NAME:<NAME>END_PI'] }
]}
{ lineNum: 3, node: ['age','68'] },
{ lineNum: 4, node: ['town','Blacksburg'] },
]
)()
# ---------------------------------------------------------------------------
# Test extending PLLParser when mapNode() sometimes returns undef
(() ->
class EnvParser extends PLLParser
mapNode: (line) ->
if (lMatches = line.match(///^
\s*
([A-Za-z]+)
\s*
=
\s*
([A-Za-z0-9]+)
\s*
$///))
[_, left, right] = lMatches
if (left == 'name')
return undef
return right
else
croak "Bad line in EnvParser"
parser = new EnvParser("""
name = PI:NAME:<NAME>END_PI
last = PI:NAME:<NAME>END_PI
age = 68
town = Blacksburg
""")
tree = parser.getTree()
simple.equal 127, tree, [
{ lineNum: 3, node: '68' },
{ lineNum: 4, node: 'Blacksburg' },
]
)()
|
[
{
"context": "nfiguration:\n# None\n#\n# Command:\n#\n# Author:\n# Robert Carroll\n\nmoment = require 'moment'\n_ = require('underscor",
"end": 160,
"score": 0.9998610019683838,
"start": 146,
"tag": "NAME",
"value": "Robert Carroll"
},
{
"context": "s shuffle in Coffeescript http... | old_scripts/chat.coffee | robertocarroll/chatui | 0 | #### Description:
# Respond to custom answers
#
# Dependencies:
# redis-brain.coffee
#
# Configuration:
# None
#
# Command:
#
# Author:
# Robert Carroll
moment = require 'moment'
_ = require('underscore')
initial_question_bank = {
1: {question: "What's the quietest thing you can hear?", my_answer: '', answers: []},
2: {question: "What one word would you use to describe me?", my_answer: '', answers: []}
3: {question: "What makes me unique?", my_answer: '', answers: []}
}
# Varied response
response_to_answer = ["I see. ", "Interesting. "]
# Varied conjunction
conjunction = ["Here's another question for you. ", "Another question for you. "]
module.exports = (robot) ->
robot.brain.on 'loaded', =>
robot.logger.info "Loading knowledge"
robot.brain.data.questions ?= {}
if _.isUndefined(robot.brain.data.questions) then robot.brain.data.questions = initial_question_bank
question_bank = robot.brain.data.questions
current_question = null
question_ids = Object.keys(question_bank)
used_questions = []
# Fisher-Yates shuffle in Coffeescript https://gist.github.com/smrchy/3098096
shuffle = (a) ->
i = a.length
while --i > 0
j = ~~(Math.random() * (i + 1))
t = a[j]
a[j] = a[i]
a[i] = t
a
getQuestion = (cb) ->
shuffle (question_ids)
current_question = question_ids[0]
if _.isUndefined(current_question)
question_text = "Thanks for talking to me. "
else
used_questions.push current_question
question_ids = _.difference(question_ids, used_questions)
question_text = question_bank[current_question].question
cb question_text
robot.hear /talk/i, (msg) ->
getQuestion (question_text) ->
msg.send question_text
robot.hear /answer (.*)$/i, (msg) ->
answer = msg.match[1]
current_question_answers = question_bank[current_question].answers
current_question_answers.push answer
answers_without_current = current_question_answers.filter (exclude_current) -> exclude_current isnt answer
shuffled_answer = shuffle (answers_without_current)
getQuestion (question_text) ->
robot.logger.info robot.brain.data.questions
msg.send [msg.random response_to_answer] + [if shuffled_answer.length > 0 then 'Someone else told me ' + "'" + shuffled_answer[0] + "'. "] + question_text
robot.hear /reset/i, (msg) ->
question_bank = robot.brain.data.questions
current_question = null
question_ids = Object.keys(question_bank)
used_questions = []
msg.send "All the questions are back on the table."
| 102049 | #### Description:
# Respond to custom answers
#
# Dependencies:
# redis-brain.coffee
#
# Configuration:
# None
#
# Command:
#
# Author:
# <NAME>
moment = require 'moment'
_ = require('underscore')
initial_question_bank = {
1: {question: "What's the quietest thing you can hear?", my_answer: '', answers: []},
2: {question: "What one word would you use to describe me?", my_answer: '', answers: []}
3: {question: "What makes me unique?", my_answer: '', answers: []}
}
# Varied response
response_to_answer = ["I see. ", "Interesting. "]
# Varied conjunction
conjunction = ["Here's another question for you. ", "Another question for you. "]
module.exports = (robot) ->
robot.brain.on 'loaded', =>
robot.logger.info "Loading knowledge"
robot.brain.data.questions ?= {}
if _.isUndefined(robot.brain.data.questions) then robot.brain.data.questions = initial_question_bank
question_bank = robot.brain.data.questions
current_question = null
question_ids = Object.keys(question_bank)
used_questions = []
# Fisher-Yates shuffle in Coffeescript https://gist.github.com/smrchy/3098096
shuffle = (a) ->
i = a.length
while --i > 0
j = ~~(Math.random() * (i + 1))
t = a[j]
a[j] = a[i]
a[i] = t
a
getQuestion = (cb) ->
shuffle (question_ids)
current_question = question_ids[0]
if _.isUndefined(current_question)
question_text = "Thanks for talking to me. "
else
used_questions.push current_question
question_ids = _.difference(question_ids, used_questions)
question_text = question_bank[current_question].question
cb question_text
robot.hear /talk/i, (msg) ->
getQuestion (question_text) ->
msg.send question_text
robot.hear /answer (.*)$/i, (msg) ->
answer = msg.match[1]
current_question_answers = question_bank[current_question].answers
current_question_answers.push answer
answers_without_current = current_question_answers.filter (exclude_current) -> exclude_current isnt answer
shuffled_answer = shuffle (answers_without_current)
getQuestion (question_text) ->
robot.logger.info robot.brain.data.questions
msg.send [msg.random response_to_answer] + [if shuffled_answer.length > 0 then 'Someone else told me ' + "'" + shuffled_answer[0] + "'. "] + question_text
robot.hear /reset/i, (msg) ->
question_bank = robot.brain.data.questions
current_question = null
question_ids = Object.keys(question_bank)
used_questions = []
msg.send "All the questions are back on the table."
| true | #### Description:
# Respond to custom answers
#
# Dependencies:
# redis-brain.coffee
#
# Configuration:
# None
#
# Command:
#
# Author:
# PI:NAME:<NAME>END_PI
moment = require 'moment'
_ = require('underscore')
initial_question_bank = {
1: {question: "What's the quietest thing you can hear?", my_answer: '', answers: []},
2: {question: "What one word would you use to describe me?", my_answer: '', answers: []}
3: {question: "What makes me unique?", my_answer: '', answers: []}
}
# Varied response
response_to_answer = ["I see. ", "Interesting. "]
# Varied conjunction
conjunction = ["Here's another question for you. ", "Another question for you. "]
module.exports = (robot) ->
robot.brain.on 'loaded', =>
robot.logger.info "Loading knowledge"
robot.brain.data.questions ?= {}
if _.isUndefined(robot.brain.data.questions) then robot.brain.data.questions = initial_question_bank
question_bank = robot.brain.data.questions
current_question = null
question_ids = Object.keys(question_bank)
used_questions = []
# Fisher-Yates shuffle in Coffeescript https://gist.github.com/smrchy/3098096
shuffle = (a) ->
i = a.length
while --i > 0
j = ~~(Math.random() * (i + 1))
t = a[j]
a[j] = a[i]
a[i] = t
a
getQuestion = (cb) ->
shuffle (question_ids)
current_question = question_ids[0]
if _.isUndefined(current_question)
question_text = "Thanks for talking to me. "
else
used_questions.push current_question
question_ids = _.difference(question_ids, used_questions)
question_text = question_bank[current_question].question
cb question_text
robot.hear /talk/i, (msg) ->
getQuestion (question_text) ->
msg.send question_text
robot.hear /answer (.*)$/i, (msg) ->
answer = msg.match[1]
current_question_answers = question_bank[current_question].answers
current_question_answers.push answer
answers_without_current = current_question_answers.filter (exclude_current) -> exclude_current isnt answer
shuffled_answer = shuffle (answers_without_current)
getQuestion (question_text) ->
robot.logger.info robot.brain.data.questions
msg.send [msg.random response_to_answer] + [if shuffled_answer.length > 0 then 'Someone else told me ' + "'" + shuffled_answer[0] + "'. "] + question_text
robot.hear /reset/i, (msg) ->
question_bank = robot.brain.data.questions
current_question = null
question_ids = Object.keys(question_bank)
used_questions = []
msg.send "All the questions are back on the table."
|
[
{
"context": "\n# Notes:\n# Use at your own risk\n#\n# Author:\n# Prithvi Raju A <alluri.prithvi@gmail.com>\n\nmodule.exports = (rob",
"end": 589,
"score": 0.9998387694358826,
"start": 575,
"tag": "NAME",
"value": "Prithvi Raju A"
},
{
"context": " at your own risk\n#\n# Author:\... | scripts/log-everything.coffee | makekarma/hubot | 0 | # Description:
# Allows Hubot to record slack conversations in elastic search and query them
#
# Commands:
# hubot channel count <channel> - Retuns the number of messages logged in the database for a particular channel
# hubot channel mentions <phrase> - Returns logged messages containing the specified phrase
#
# Configuration:
# ELASTICSEARCH_HOST hostname of the elastic search cluster
# ELASTICSEARCH_PORT port of the elastic search cluster
# ELASTICSEARCH_INDEX elastic search index to used for archiving
#
# Notes:
# Use at your own risk
#
# Author:
# Prithvi Raju A <alluri.prithvi@gmail.com>
module.exports = (robot) ->
ELASTICSEARCH_HOST = "" # Replace with elastic search IP
if(process.env.ELASTICSEARCH_HOST?)
ELASTICSEARCH_HOST = "http://" + process.env.ELASTICSEARCH_HOST
ELASTICSEARCH_PORT = "80"
if(process.env.ELASTICSEARCH_PORT?)
ELASTICSEARCH_PORT = process.env.ELASTICSEARCH_PORT
ELASTICSEARCH_INDEX = "archive"
if(process.env.ELASTICSEARCH_INDEX?)
ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX
ELASTICSEARCH_CLUSTER = "#{ELASTICSEARCH_HOST}:#{ELASTICSEARCH_PORT}/elasticsearch"
# check status of elastic search end point
robot.hear /channel status/i, (res) ->
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_cat/indices?v")
.put(JSON.stringify(res.message)) (err, response, body) ->
if err
res.send("Something went terribly wrong: (#{err})")
else
res.send("Everything went well.")
# listen to everything
robot.hear /.*/i, (res) ->
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/#{res.message.room}/#{res.message.id}?pretty")
.put(JSON.stringify(res.message)) (err, response, body) ->
if err
res.send("Can not backup chat: (#{err})")
else
console.log("Logged message from #{res.message.user.name} in #{res.message.room} with id #{res.message.id}.")
# ask hubot how many messages are recorded for a particular channel
robot.respond /channel count (.*)/i, (res) ->
query = JSON.stringify({
"query": {
"match": {
"room": "#{res.match[1]}"
}
}
})
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_search?pretty")
.header('Content-Type', 'application/json')
.header('Accept', 'application/json')
.post(query) (err, response, body) ->
res.send(JSON.parse(body).hits.total)
console.log("Channel count command fired for channel #{res.match[1]}.")
# ask hubot to for messages containing a certain string
robot.respond /channel mentions (.*)/i, (res) ->
query = JSON.stringify({
"query": {
"match": {
"text": "#{res.match[1]}"
}
}
})
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_search?pretty")
.post(query) (err, response, body) ->
if err
res.send("Can not retrieve backups: (#{err})")
else
JSON.parse(body).hits.hits.map((hit) => res.send(hit._source.text))
| 40810 | # Description:
# Allows Hubot to record slack conversations in elastic search and query them
#
# Commands:
# hubot channel count <channel> - Retuns the number of messages logged in the database for a particular channel
# hubot channel mentions <phrase> - Returns logged messages containing the specified phrase
#
# Configuration:
# ELASTICSEARCH_HOST hostname of the elastic search cluster
# ELASTICSEARCH_PORT port of the elastic search cluster
# ELASTICSEARCH_INDEX elastic search index to used for archiving
#
# Notes:
# Use at your own risk
#
# Author:
# <NAME> <<EMAIL>>
module.exports = (robot) ->
ELASTICSEARCH_HOST = "" # Replace with elastic search IP
if(process.env.ELASTICSEARCH_HOST?)
ELASTICSEARCH_HOST = "http://" + process.env.ELASTICSEARCH_HOST
ELASTICSEARCH_PORT = "80"
if(process.env.ELASTICSEARCH_PORT?)
ELASTICSEARCH_PORT = process.env.ELASTICSEARCH_PORT
ELASTICSEARCH_INDEX = "archive"
if(process.env.ELASTICSEARCH_INDEX?)
ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX
ELASTICSEARCH_CLUSTER = "#{ELASTICSEARCH_HOST}:#{ELASTICSEARCH_PORT}/elasticsearch"
# check status of elastic search end point
robot.hear /channel status/i, (res) ->
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_cat/indices?v")
.put(JSON.stringify(res.message)) (err, response, body) ->
if err
res.send("Something went terribly wrong: (#{err})")
else
res.send("Everything went well.")
# listen to everything
robot.hear /.*/i, (res) ->
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/#{res.message.room}/#{res.message.id}?pretty")
.put(JSON.stringify(res.message)) (err, response, body) ->
if err
res.send("Can not backup chat: (#{err})")
else
console.log("Logged message from #{res.message.user.name} in #{res.message.room} with id #{res.message.id}.")
# ask hubot how many messages are recorded for a particular channel
robot.respond /channel count (.*)/i, (res) ->
query = JSON.stringify({
"query": {
"match": {
"room": "#{res.match[1]}"
}
}
})
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_search?pretty")
.header('Content-Type', 'application/json')
.header('Accept', 'application/json')
.post(query) (err, response, body) ->
res.send(JSON.parse(body).hits.total)
console.log("Channel count command fired for channel #{res.match[1]}.")
# ask hubot to for messages containing a certain string
robot.respond /channel mentions (.*)/i, (res) ->
query = JSON.stringify({
"query": {
"match": {
"text": "#{res.match[1]}"
}
}
})
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_search?pretty")
.post(query) (err, response, body) ->
if err
res.send("Can not retrieve backups: (#{err})")
else
JSON.parse(body).hits.hits.map((hit) => res.send(hit._source.text))
| true | # Description:
# Allows Hubot to record slack conversations in elastic search and query them
#
# Commands:
# hubot channel count <channel> - Retuns the number of messages logged in the database for a particular channel
# hubot channel mentions <phrase> - Returns logged messages containing the specified phrase
#
# Configuration:
# ELASTICSEARCH_HOST hostname of the elastic search cluster
# ELASTICSEARCH_PORT port of the elastic search cluster
# ELASTICSEARCH_INDEX elastic search index to used for archiving
#
# Notes:
# Use at your own risk
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
ELASTICSEARCH_HOST = "" # Replace with elastic search IP
if(process.env.ELASTICSEARCH_HOST?)
ELASTICSEARCH_HOST = "http://" + process.env.ELASTICSEARCH_HOST
ELASTICSEARCH_PORT = "80"
if(process.env.ELASTICSEARCH_PORT?)
ELASTICSEARCH_PORT = process.env.ELASTICSEARCH_PORT
ELASTICSEARCH_INDEX = "archive"
if(process.env.ELASTICSEARCH_INDEX?)
ELASTICSEARCH_INDEX = process.env.ELASTICSEARCH_INDEX
ELASTICSEARCH_CLUSTER = "#{ELASTICSEARCH_HOST}:#{ELASTICSEARCH_PORT}/elasticsearch"
# check status of elastic search end point
robot.hear /channel status/i, (res) ->
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_cat/indices?v")
.put(JSON.stringify(res.message)) (err, response, body) ->
if err
res.send("Something went terribly wrong: (#{err})")
else
res.send("Everything went well.")
# listen to everything
robot.hear /.*/i, (res) ->
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/#{res.message.room}/#{res.message.id}?pretty")
.put(JSON.stringify(res.message)) (err, response, body) ->
if err
res.send("Can not backup chat: (#{err})")
else
console.log("Logged message from #{res.message.user.name} in #{res.message.room} with id #{res.message.id}.")
# ask hubot how many messages are recorded for a particular channel
robot.respond /channel count (.*)/i, (res) ->
query = JSON.stringify({
"query": {
"match": {
"room": "#{res.match[1]}"
}
}
})
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_search?pretty")
.header('Content-Type', 'application/json')
.header('Accept', 'application/json')
.post(query) (err, response, body) ->
res.send(JSON.parse(body).hits.total)
console.log("Channel count command fired for channel #{res.match[1]}.")
# ask hubot to for messages containing a certain string
robot.respond /channel mentions (.*)/i, (res) ->
query = JSON.stringify({
"query": {
"match": {
"text": "#{res.match[1]}"
}
}
})
robot.http("#{ELASTICSEARCH_CLUSTER}/#{ELASTICSEARCH_INDEX}/_search?pretty")
.post(query) (err, response, body) ->
if err
res.send("Can not retrieve backups: (#{err})")
else
JSON.parse(body).hits.hits.map((hit) => res.send(hit._source.text))
|
[
{
"context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#",
"end": 166,
"score": 0.9888654947280884,
"start": 152,
"tag": "USERNAME",
"value": "programmfabrik"
},
{
"context": "revokeObjectURL(url)\n\n\n\t# htt... | src/base/CUI.coffee | programmfabrik/coffeescript-ui | 10 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# Base class for the Coffeescript UI system. It is used for
# Theme-Management as well as for basic event management tasks.
#
# @example Startup
#
marked = require('marked')
class CUI
@__readyFuncs = []
@__themes = []
@__ng__: true
@start: ->
trigger_viewport_resize = =>
# console.info("CUI: trigger viewport resize.")
CUI.Events.trigger
type: "viewport-resize"
CUI.Events.listen
type: "resize"
node: window
call: (ev, info) =>
# console.info("CUI: caught window resize event.")
if !CUI.browser.ie
trigger_viewport_resize()
else
CUI.scheduleCallback(ms: 500, call: trigger_viewport_resize)
return
CUI.Events.listen
type: "drop"
node: document.documentElement
call: (ev) ->
ev.preventDefault()
CUI.Events.listen
type: "keyup"
node: window
capture: true
call: (ev) =>
if ev.getKeyboard() == "C+U+I"
CUI.toaster(text: "CUI!")
if CUI.defaults.debug
if ev.getKeyboard() == "Alt+Shift+U"
@__toggleUIElements()
return
CUI.Events.listen
type: "keydown"
node: window
call: (ev) ->
if ev.getKeyboard() == "c+"
CUI.toaster(text: "CUI!")
# backspace acts as "BACK" in some browser, like FF
if ev.keyCode() == 8
for node in CUI.dom.elementsUntil(ev.getTarget(), null, document.documentElement)
if node.tagName in ["INPUT", "TEXTAREA"]
return
if node.getAttribute("contenteditable") == "true"
return
# console.info("swalloded BACKSPACE keydown event to prevent default")
ev.preventDefault()
return
document.body.scrollTop=0
icons = require('../scss/icons/icons.svg').default
CUI.Template.loadText(icons)
CUI.Template.load()
@chainedCall.apply(@, @__readyFuncs).always =>
@__ready = true
@
@getPathToScript: ->
if not @__pathToScript
scripts = document.getElementsByTagName('script')
cui_script = scripts[scripts.length - 1]
if m = cui_script.src.match("(.*/).*?\.js$")
@__pathToScript = m[1]
else
CUI.util.assert(@__pathToScript, "CUI", "Could not determine script path.")
@__pathToScript
@ready: (func) ->
if @__ready
return func.call(@)
@__readyFuncs.push(func)
@defaults:
FileUpload:
name:
"files[]"
debug: true
asserts: true
asserts_alert: 'js' # or 'cui' or 'off' or 'debugger'
class: {}
# Returns a resolved CUI.Promise.
@resolvedPromise: ->
dfr = new CUI.Deferred()
dfr.resolve.apply(dfr, arguments)
dfr.promise()
# Returns a rejected CUI.Promise.
@rejectedPromise: ->
dfr = new CUI.Deferred()
dfr.reject.apply(dfr, arguments)
dfr.promise()
# calls the as arguments passed functions in order
# of appearance. if a function returns
# a deferred or promise, the next function waits
# for that function to complete the promise
# if the argument is a value or a promise
# it is used the same way
# returns a promise which resolve when all
# functions resolve or the first doesnt
@chainedCall: ->
idx = 0
__this = @
# return a real array from arguments
get_args = (_arguments) ->
_args = []
for arg in _arguments
_args.push(arg)
_args
# mimic the behaviour of jQuery "when"
get_return_value = (_arguments) ->
_args = get_args(_arguments)
if _args.length == 0
return undefined
else if _args.length == 1
return _args[0]
else
return _args
args = get_args(arguments)
return_values = []
init_next = =>
if idx == args.length
dfr.resolve.apply(dfr, return_values)
return
if CUI.util.isFunction(args[idx])
if __this != CUI
ret = args[idx].call(__this)
else
ret = args[idx]()
else
ret = args[idx]
# console.debug "idx", idx, "ret", ret, "state:", ret?.state?()
idx++
if CUI.util.isPromise(ret)
ret
.done =>
return_values.push(get_return_value(arguments))
init_next()
.fail =>
return_values.push(get_return_value(arguments))
dfr.reject.apply(dfr, return_values)
else
return_values.push(ret)
init_next()
return
dfr = new CUI.Deferred()
init_next()
dfr.promise()
# Executes 'call' function in batches of 'chunk_size' for all the 'items'.
# It must be called with '.call(this, opts)'
@chunkWork: (_opts = {}) ->
opts = CUI.Element.readOpts _opts, "CUI.chunkWork",
items:
mandatory: true
check: (v) ->
CUI.util.isArray(v)
chunk_size:
mandatory: true
default: 10
check: (v) ->
v >= 1
timeout:
mandatory: true
default: 0
check: (v) ->
v >= -1
call:
mandatory: true
check: (v) ->
v instanceof Function
chunk_size = opts.chunk_size
timeout = opts.timeout
CUI.util.assert(@ != CUI, "CUI.chunkWork", "Cannot call CUI.chunkWork with 'this' not set to the caller.")
idx = 0
len = opts.items.length
next_chunk = =>
progress = (idx+1) + " - " + Math.min(len, idx+chunk_size) + " / " +len
# console.error "progress:", progress
dfr.notify
progress: progress
idx: idx
len: len
chunk_size: chunk_size
go_on = =>
if idx + chunk_size >= len
dfr.resolve()
else
idx = idx + chunk_size
if timeout == -1
next_chunk()
else
CUI.setTimeout
ms: timeout
call: next_chunk
return
ret = opts.call.call(@, opts.items.slice(idx, idx+opts.chunk_size), idx, len)
if ret == false
# interrupt this
dfr.reject()
return
if CUI.util.isPromise(ret)
ret.fail(dfr.reject).done(go_on)
else
go_on()
return
dfr = new CUI.Deferred()
CUI.setTimeout
ms: Math.min(0, timeout)
call: =>
if len > 0
next_chunk()
else
dfr.resolve()
return dfr.promise()
# returns a Deferred, the Deferred
# notifies the worker for each
# object
@chunkWorkOLD: (objects, chunkSize = 10, timeout = 0) ->
dfr = new CUI.Deferred()
idx = 0
do_next_chunk = =>
chunk = 0
while idx < objects.length and (chunk < chunkSize or chunkSize == 0)
if dfr.state() == "rejected"
return
# console.debug idx, chunk, chunkSize, dfr.state()
dfr.notify(objects[idx], idx)
if idx == objects.length-1
dfr.resolve()
return
idx++
chunk++
if idx < objects.length
CUI.setTimeout(do_next_chunk, timeout)
if objects.length == 0
CUI.setTimeout =>
if dfr.state() == "rejected"
return
dfr.resolve()
else
CUI.setTimeout(do_next_chunk)
dfr
# proxy methods
@proxyMethods: (target, source, methods) ->
# console.debug target, source, methods
for k in methods
target.prototype[k] = source.prototype[k]
@__timeouts = []
# list of function which we need to call if
# the timeouts counter changes
@__timeoutCallbacks = []
@__callTimeoutChangeCallbacks: ->
tracked = @countTimeouts()
for cb in @__timeoutCallbacks
cb(tracked)
return
@__removeTimeout: (timeout) ->
if CUI.util.removeFromArray(timeout, @__timeouts)
if timeout.track
@__callTimeoutChangeCallbacks()
return
@__getTimeoutById: (timeoutID, ignoreNotFound = false) ->
for timeout in @__timeouts
if timeout.id == timeoutID
return timeout
CUI.util.assert(ignoreNotFound, "CUI.__getTimeoutById", "Timeout ##{timeoutID} not found.")
null
@resetTimeout: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID)
CUI.util.assert(not timeout.__isRunning, "CUI.resetTimeout", "Timeout #{timeoutID} cannot be resetted while running.", timeout: timeout)
timeout.onReset?(timeout)
window.clearTimeout(timeout.real_id)
old_real_id = timeout.real_id
tid = @__startTimeout(timeout)
return tid
@registerTimeoutChangeCallback: (cb) ->
@__timeoutCallbacks.push(cb)
@setTimeout: (_func, ms=0, track) ->
if CUI.util.isPlainObject(_func)
ms = _func.ms or 0
track = _func.track
func = _func.call
onDone = _func.onDone
onReset = _func.onReset
else
func = _func
if CUI.util.isNull(track)
if ms == 0
track = false
else
track = true
CUI.util.assert(CUI.util.isFunction(func), "CUI.setTimeout", "Function needs to be a Function (opts.call)", parameter: _func)
timeout =
call: =>
timeout.__isRunning = true
func()
@__removeTimeout(timeout)
timeout.onDone?(timeout)
ms: ms
func: func # for debug purposes
track: track
onDone: onDone
onReset: onReset
@__timeouts.push(timeout)
if track and ms > 0
@__callTimeoutChangeCallbacks()
@__startTimeout(timeout)
@__scheduledCallbacks = []
# schedules to run a function after
# a timeout has occurred. does not schedule
# the same function a second time
# returns a deferred, which resolves when
# the callback is done
@scheduleCallback: (_opts) ->
opts = CUI.Element.readOpts _opts, "CUI.scheduleCallback",
call:
mandatory: true
check: Function
ms:
default: 0
check: (v) ->
CUI.util.isInteger(v) and v >= 0
track:
default: false
check: Boolean
idx = CUI.util.idxInArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
if idx > -1 and CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeoutID)
# don't schedule the same call while it is already running, schedule
# a new one
idx = -1
if idx == -1
idx = @__scheduledCallbacks.length
# console.debug "...schedule", idx
else
# function already scheduled
# console.info("scheduleCallback, already scheduled: ", @__scheduledCallbacks[idx].timeout, CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeout))
CUI.resetTimeout(@__scheduledCallbacks[idx].timeoutID)
return @__scheduledCallbacks[idx].promise
dfr = new CUI.Deferred()
timeoutID = CUI.setTimeout
ms: opts.ms
track: opts.track
call: =>
opts.call()
dfr.resolve()
cb = @__scheduledCallbacks[idx] =
call: opts.call
timeoutID: timeoutID
promise: dfr.promise()
# console.error "scheduleCallback", cb.timeoutID, opts.call
dfr.done =>
# remove this callback after we are done
CUI.util.removeFromArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
cb.promise
# call: function callback to cancel
# return: true if found, false if not
@scheduleCallbackCancel: (_opts) ->
opts = CUI.Element.readOpts _opts, "CUI.scheduleCallbackCancel",
call:
mandatory: true
check: Function
idx = CUI.util.idxInArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
if idx > -1 and not CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeoutID)
# console.error "cancel timeout...", @__scheduledCallbacks[idx].timeoutID
CUI.clearTimeout(@__scheduledCallbacks[idx].timeoutID)
@__scheduledCallbacks.splice(idx, 1)
return true
else
return false
@utf8ArrayBufferToString: (arrayBuffer) ->
out = []
array = new Uint8Array(arrayBuffer)
len = array.length
i = 0
while (i < len)
c = array[i++]
switch(c >> 4)
when 0, 1, 2, 3, 4, 5, 6, 7
# 0xxxxxxx
out.push(String.fromCharCode(c))
when 12, 13
# 110x xxxx 10xx xxxx
char2 = array[i++]
out.push(String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)))
when 14
# 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++]
char3 = array[i++]
out.push(String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)))
out.join("")
@__startTimeout: (timeout) ->
real_id = window.setTimeout(timeout.call, timeout.ms)
if not timeout.id
# first time we put the real id
timeout.id = real_id
timeout.real_id = real_id
# console.error "new timeout:", timeoutID, "ms:", ms, "current timeouts:", @__timeouts.length
timeout.id
@countTimeouts: ->
tracked = 0
for timeout in @__timeouts
if timeout.track
tracked++
tracked
@clearTimeout: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID, true) # ignore not found
if not timeout
return
window.clearTimeout(timeout.real_id)
@__removeTimeout(timeout)
timeout.id
@isTimeoutRunning: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID, true) # ignore not found
if not timeout?.__isRunning
false
else
true
@setInterval: (func, ms) ->
window.setInterval(func, ms)
@clearInterval: (interval) ->
window.clearInterval(interval)
# used to set a css-class while testing with webdriver. this way
# we can hide things on the screen that should not irritate our screenshot comparison
@startWebdriverTest: ->
a= "body"
CUI.dom.addClass(a, "cui-webdriver-test")
@getParameterByName: (name, search=document.location.search) ->
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]")
regex = new RegExp("[\\?&]" + name + "=([^&#]*)")
results = regex.exec(search)
if results == null
""
else
decodeURIComponent(results[1].replace(/\+/g, " "))
@setSessionStorage: (key, value) ->
@__setStorage("sessionStorage", key, value)
@getSessionStorage: (key = null) ->
@__getStorage("sessionStorage", key)
@clearSessionStorage: ->
@__clearStorage("sessionStorage")
@setLocalStorage: (key, value) ->
@__setStorage("localStorage", key, value)
@getLocalStorage: (key = null) ->
@__getStorage("localStorage", key)
@clearLocalStorage: ->
@__clearStorage("localStorage")
@__storage: localStorage: null, sessionStorage: null
@__setStorage: (skey, key, value) ->
data = @__getStorage(skey)
if value == undefined
delete(data[key])
else
data[key] = value
try
window[skey].setItem("CUI", JSON.stringify(data))
catch e
console.warn("CUI.__setStorage: Storage not available.", e)
@__storage[skey] = JSON.stringify(data)
data
@__getStorage: (skey, key = null) ->
try
data_json = window[skey].getItem("CUI")
catch e
console.warn("CUI.__getStorage: Storage not available.", e)
data_json = @__storage[skey]
if data_json
data = JSON.parse(data_json)
else
data = {}
if key != null
data[key]
else
data
@__clearStorage: (skey) ->
try
window[skey].removeItem("CUI")
catch e
console.warn("CUI.__clearStorage: Storage not available.", e)
@__storage[skey] = null
@encodeUrlData: (params, replacer = null, connect = "&", connect_pair = "=") ->
url = []
if replacer
if CUI.util.isFunction(replacer)
encode_func = replacer
else
encode_func = (v) -> CUI.util.stringMapReplace(v+"", replace_map)
else
encode_func = (v) -> encodeURIComponent(v)
for k, v of params
if CUI.util.isArray(v)
for _v in v
url.push(encode_func(k) + connect_pair + encode_func(_v))
else if not CUI.util.isEmpty(v)
url.push(encode_func(k) + connect_pair + encode_func(v))
else if v != undefined
url.push(encode_func(k))
url.join(connect)
# keep "," and ":" in url intact, encodeURI all other parts
@encodeURIComponentNicely: (str="") ->
s = []
for v, idx in (str+"").split(",")
if idx > 0
s.push(",")
for v2, idx2 in v.split(":")
if idx2 > 0
s.push(":")
s.push(encodeURIComponent(v2))
s.join("")
@decodeURIComponentNicely: (v) ->
decodeURIComponent(v)
@decodeUrlData: (url, replacer = null, connect = "&", connect_pair = "=", use_array=false) ->
params = {}
if replacer
if CUI.util.isFunction(replacer)
decode_func = replacer
else
decode_func = (v) -> CUI.util.stringMapReplace(v+"", replacer)
else
decode_func = (v) -> decodeURIComponent(v)
for part in url.split(connect)
if part.length == 0
continue
if part.indexOf(connect_pair) > -1
pair = part.split(connect_pair)
key = decode_func(pair[0])
value = decode_func(pair[1])
else
key = decode_func(part)
value = ""
if use_array
if not params[key]
params[key] = []
params[key].push(value)
else
params[key] = value
params
@decodeUrlDataArray: (url, replace_map = null, connect = "&", connect_pair = "=") ->
@decodeUrlData(url, replace_map, connect, connect_pair, true)
# Deprecated -> Use CUI.util
@mergeMap: (targetMap, mergeMap) ->
for k, v of mergeMap
if not targetMap.hasOwnProperty(k)
targetMap[k] = v
else if CUI.util.isPlainObject(targetMap[k]) and CUI.util.isPlainObject(v)
CUI.util.mergeMap(targetMap[k], v)
targetMap
# Deprecated -> Use CUI.util
@revertMap: (map) ->
map_reverted = {}
for k, v of map
map_reverted[v] = k
map_reverted
# Deprecated -> Use CUI.util
@stringMapReplace: (s, map) ->
regex = []
for key of map
if CUI.util.isEmpty(key)
continue
regex.push(key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"))
if regex.length > 0
s.replace(new RegExp(regex.join('|'),"g"), (word) -> map[word])
else
s
# Deprecated -> Use CUI.util
@isFunction: (v) ->
v and typeof(v) == "function"
# Deprecated -> Use CUI.util
@isPlainObject: (v) ->
v and typeof(v) == "object" and v.constructor?.prototype.hasOwnProperty("isPrototypeOf")
# Deprecated -> Use CUI.util
@isEmptyObject: (v) ->
for k of v
return false
return true
# Deprecated -> Use CUI.util
@isMap: (v) ->
@isPlainObject(v)
# Deprecated -> Use CUI.util
@isArray: (v) ->
Array.isArray(v)
# Deprecated -> Use CUI.util
@inArray: (value, array) ->
array.indexOf(value)
# Deprecated -> Use CUI.util
@isString: (s) ->
typeof(s) == "string"
@downloadData: (data, fileName) ->
blob = new Blob([data], type: "octet/stream")
if window.navigator.msSaveOrOpenBlob
window.navigator.msSaveOrOpenBlob(blob, fileName)
else
url = window.URL.createObjectURL(blob)
@__downloadDataElement.href = url
@__downloadDataElement.download = fileName
@__downloadDataElement.click()
window.URL.revokeObjectURL(url)
# https://gist.github.com/dperini/729294
@urlRegex: new RegExp(
"^" +
# protocol identifier
"(?:(?:(sftp|ftp|ftps|https|http))://|)" +
# user:pass authentication
"(?:(\\S+?)(?::(\\S*))?@)?" +
"((?:(?:" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 224.0.0.0
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host & domain name
"(?:[a-z0-9\\u00a1-\\uffff](?:|[a-z\\u00a1-\\uffff0-9-]*[a-z0-9\\u00a1-\\uffff])\\.)*" +
# last identifier
"(?:[a-z\\u00a1-\\uffff]{2,})" +
# hostname only
"|" +
"(?:[a-z0-9\\u00a1-\\uffff][a-z0-9-\\u00a1-\\uffff]*[a-z0-9\\u00a1-\\uffff])" +
"))|)" +
# port number
"(?::(\\d{2,5}))?" +
# resource path
"(?:([/?#]\\S*))?" +
"$", "i"
)
@evalCode: (code) ->
script = document.createElement("script")
script.text = code
document.head.appendChild(script).parentNode.removeChild(script)
@appendToUrl: (url, data) ->
for key, value of data
if value == undefined
continue
# add token to the url
if url.match(/\?/)
url += "&"
else
url += "?"
url += encodeURIComponent(key)+"="+encodeURIComponent(value)
url
@parseLocation: (url) ->
if not CUI.util.isFunction(url?.match) or url.length == 0
return null
match = url.match(@urlRegex)
if not match
return null
# console.debug "CUI.parseLocation:", url, match
p =
protocol: match[1] or ""
user: match[2] or ""
password: match[3] or ""
hostname: match[4] or ""
port: match[5] or ""
path: match[6] or ""
origin: ""
if p.hostname
if not p.protocol
p.protocol = "http"
p.origin = p.protocol+"://"+p.hostname
if p.port
p.origin += ":"+p.port
p.url = p.protocol+"://"
if p.user
p.url = p.url + p.user + ":" + p.password + "@"
p.url = p.url + p.hostname
if p.port
p.url = p.url + ":" + p.port
else
p.url = ""
if p.path.length > 0
_match = p.path.match(/(.*?)(|\?.*?)(|\#.*)$/)
p.pathname = _match[1]
p.search = _match[2]
if p.search == "?"
p.search = ""
p.fragment = _match[3]
else
p.search = ""
p.pathname = ""
p.fragment = ""
p.href = p.origin+p.path
p.hash = p.fragment
if p.login
p.auth = btoa(p.user+":"+p.password)
# url includes user+password
p.url = p.url + p.path
p
@escapeAttribute: (data) ->
if CUI.util.isNull(data) or !CUI.util.isString(data)
return ""
data = data.replace(/"/g, """).replace(/\'/g, "'")
data
@loadScript: (src) ->
deferred = new CUI.Deferred
script = CUI.dom.element("script", charset: "utf-8", src: src)
CUI.Events.listen
type: "load"
node: script
instance: script
call: (ev) =>
deferred.resolve(ev)
return
CUI.Events.listen
type: "error"
node: script
instance: script
call: (ev) =>
document.head.removeChild(script)
deferred.reject(ev)
return
deferred.always =>
CUI.Events.ignore(instance: script)
document.head.appendChild(script)
return deferred.promise()
# http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
@browser: (->
map =
opera: `(!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0`
firefox: `typeof InstallTrigger !== 'undefined'`
safari: `Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0`
ie: `/*@cc_on!@*/false || !!document.documentMode`
chrome: !!window.chrome and !!window.chrome.webstore
map.edge = not map.ie && !!window.StyleMedia
map.blink = (map.chrome or map.opera) && !!window.CSS
map
)()
@__toggleUIElements: ->
if @__uiHighlightDivs?.length > 0
for highlightDiv in @__uiHighlightDivs
CUI.dom.remove(highlightDiv)
delete @__uiHighlightDivs
return
@__uiHighlightDivs = []
uiElements = document.querySelectorAll("[ui]")
for uiElement in uiElements
div = CUI.dom.div()
@__uiHighlightDivs.push(div)
do(div, uiElement) =>
divRect = div.getBoundingClientRect();
uiElementRect = uiElement.getBoundingClientRect();
div.textContent = uiElement.getAttribute("ui")
CUI.dom.setStyle(div,
padding: "4px"
background: "yellow"
position: "absolute"
"white-space": "nowrap"
cursor: "pointer"
border: "solid 1.5px grey"
)
div.title = "Click to copy!"
span = CUI.dom.span()
span.textContent = " [X]"
CUI.dom.append(div, span)
CUI.dom.append(document.body, div)
borderStyle = CUI.dom.getStyle(uiElement).border
div.addEventListener('mouseenter', =>
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.hideElement(otherHighlightDiv)
CUI.dom.showElement(div)
CUI.dom.setStyle(uiElement, {border: "2px solid yellow"})
)
div.addEventListener('mouseleave', =>
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.showElement(otherHighlightDiv)
CUI.dom.setStyle(uiElement, {border: borderStyle})
)
div.addEventListener('click', =>
navigator.clipboard.writeText(uiElement.getAttribute("ui"))
)
span.addEventListener('click', =>
CUI.dom.remove(div)
CUI.util.removeFromArray(div, @__uiHighlightDivs)
CUI.dom.setStyle(uiElement, {border: borderStyle})
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.showElement(otherHighlightDiv)
return
)
top = uiElementRect.y + uiElementRect.height / 2 - divRect.height / 2
if top < 0
# Skip not visible elements.
CUI.dom.remove(div)
return
left = uiElementRect.x - divRect.width
if left <= 0
if uiElementRect.width > divRect.width
left = uiElementRect.x
else
left = uiElementRect.x + uiElementRect.width
CUI.dom.setStyle(div,
top: top
left: left
)
CUI.dom.setStyle(div, "zIndex": 5, "")
return
CUI.ready =>
for k of CUI.browser
if CUI.browser[k]
document.body.classList.add("cui-browser-"+k)
CUI.defaults.marked_opts =
renderer: new marked.Renderer()
gfm: true
tables: true
breaks: false
pedantic: false
smartLists: true
smartypants: false
# initialize a markdown renderer
marked.setOptions(CUI.defaults.marked_opts)
nodes = CUI.dom.htmlToNodes("<!-- CUI.CUI --><a style='display: none;'></a><!-- /CUI.CUI -->")
CUI.__downloadDataElement = nodes[1]
CUI.dom.append(document.body, nodes)
if not window.addEventListener
alert("Your browser is not supported. Please update to a current version of Google Chrome, Mozilla Firefox or Internet Explorer.")
else
window.addEventListener("load", =>
CUI.start()
)
module.exports = CUI
| 46939 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# Base class for the Coffeescript UI system. It is used for
# Theme-Management as well as for basic event management tasks.
#
# @example Startup
#
marked = require('marked')
class CUI
@__readyFuncs = []
@__themes = []
@__ng__: true
@start: ->
trigger_viewport_resize = =>
# console.info("CUI: trigger viewport resize.")
CUI.Events.trigger
type: "viewport-resize"
CUI.Events.listen
type: "resize"
node: window
call: (ev, info) =>
# console.info("CUI: caught window resize event.")
if !CUI.browser.ie
trigger_viewport_resize()
else
CUI.scheduleCallback(ms: 500, call: trigger_viewport_resize)
return
CUI.Events.listen
type: "drop"
node: document.documentElement
call: (ev) ->
ev.preventDefault()
CUI.Events.listen
type: "keyup"
node: window
capture: true
call: (ev) =>
if ev.getKeyboard() == "C+U+I"
CUI.toaster(text: "CUI!")
if CUI.defaults.debug
if ev.getKeyboard() == "Alt+Shift+U"
@__toggleUIElements()
return
CUI.Events.listen
type: "keydown"
node: window
call: (ev) ->
if ev.getKeyboard() == "c+"
CUI.toaster(text: "CUI!")
# backspace acts as "BACK" in some browser, like FF
if ev.keyCode() == 8
for node in CUI.dom.elementsUntil(ev.getTarget(), null, document.documentElement)
if node.tagName in ["INPUT", "TEXTAREA"]
return
if node.getAttribute("contenteditable") == "true"
return
# console.info("swalloded BACKSPACE keydown event to prevent default")
ev.preventDefault()
return
document.body.scrollTop=0
icons = require('../scss/icons/icons.svg').default
CUI.Template.loadText(icons)
CUI.Template.load()
@chainedCall.apply(@, @__readyFuncs).always =>
@__ready = true
@
@getPathToScript: ->
if not @__pathToScript
scripts = document.getElementsByTagName('script')
cui_script = scripts[scripts.length - 1]
if m = cui_script.src.match("(.*/).*?\.js$")
@__pathToScript = m[1]
else
CUI.util.assert(@__pathToScript, "CUI", "Could not determine script path.")
@__pathToScript
@ready: (func) ->
if @__ready
return func.call(@)
@__readyFuncs.push(func)
@defaults:
FileUpload:
name:
"files[]"
debug: true
asserts: true
asserts_alert: 'js' # or 'cui' or 'off' or 'debugger'
class: {}
# Returns a resolved CUI.Promise.
@resolvedPromise: ->
dfr = new CUI.Deferred()
dfr.resolve.apply(dfr, arguments)
dfr.promise()
# Returns a rejected CUI.Promise.
@rejectedPromise: ->
dfr = new CUI.Deferred()
dfr.reject.apply(dfr, arguments)
dfr.promise()
# calls the as arguments passed functions in order
# of appearance. if a function returns
# a deferred or promise, the next function waits
# for that function to complete the promise
# if the argument is a value or a promise
# it is used the same way
# returns a promise which resolve when all
# functions resolve or the first doesnt
@chainedCall: ->
idx = 0
__this = @
# return a real array from arguments
get_args = (_arguments) ->
_args = []
for arg in _arguments
_args.push(arg)
_args
# mimic the behaviour of jQuery "when"
get_return_value = (_arguments) ->
_args = get_args(_arguments)
if _args.length == 0
return undefined
else if _args.length == 1
return _args[0]
else
return _args
args = get_args(arguments)
return_values = []
init_next = =>
if idx == args.length
dfr.resolve.apply(dfr, return_values)
return
if CUI.util.isFunction(args[idx])
if __this != CUI
ret = args[idx].call(__this)
else
ret = args[idx]()
else
ret = args[idx]
# console.debug "idx", idx, "ret", ret, "state:", ret?.state?()
idx++
if CUI.util.isPromise(ret)
ret
.done =>
return_values.push(get_return_value(arguments))
init_next()
.fail =>
return_values.push(get_return_value(arguments))
dfr.reject.apply(dfr, return_values)
else
return_values.push(ret)
init_next()
return
dfr = new CUI.Deferred()
init_next()
dfr.promise()
# Executes 'call' function in batches of 'chunk_size' for all the 'items'.
# It must be called with '.call(this, opts)'
@chunkWork: (_opts = {}) ->
opts = CUI.Element.readOpts _opts, "CUI.chunkWork",
items:
mandatory: true
check: (v) ->
CUI.util.isArray(v)
chunk_size:
mandatory: true
default: 10
check: (v) ->
v >= 1
timeout:
mandatory: true
default: 0
check: (v) ->
v >= -1
call:
mandatory: true
check: (v) ->
v instanceof Function
chunk_size = opts.chunk_size
timeout = opts.timeout
CUI.util.assert(@ != CUI, "CUI.chunkWork", "Cannot call CUI.chunkWork with 'this' not set to the caller.")
idx = 0
len = opts.items.length
next_chunk = =>
progress = (idx+1) + " - " + Math.min(len, idx+chunk_size) + " / " +len
# console.error "progress:", progress
dfr.notify
progress: progress
idx: idx
len: len
chunk_size: chunk_size
go_on = =>
if idx + chunk_size >= len
dfr.resolve()
else
idx = idx + chunk_size
if timeout == -1
next_chunk()
else
CUI.setTimeout
ms: timeout
call: next_chunk
return
ret = opts.call.call(@, opts.items.slice(idx, idx+opts.chunk_size), idx, len)
if ret == false
# interrupt this
dfr.reject()
return
if CUI.util.isPromise(ret)
ret.fail(dfr.reject).done(go_on)
else
go_on()
return
dfr = new CUI.Deferred()
CUI.setTimeout
ms: Math.min(0, timeout)
call: =>
if len > 0
next_chunk()
else
dfr.resolve()
return dfr.promise()
# returns a Deferred, the Deferred
# notifies the worker for each
# object
@chunkWorkOLD: (objects, chunkSize = 10, timeout = 0) ->
dfr = new CUI.Deferred()
idx = 0
do_next_chunk = =>
chunk = 0
while idx < objects.length and (chunk < chunkSize or chunkSize == 0)
if dfr.state() == "rejected"
return
# console.debug idx, chunk, chunkSize, dfr.state()
dfr.notify(objects[idx], idx)
if idx == objects.length-1
dfr.resolve()
return
idx++
chunk++
if idx < objects.length
CUI.setTimeout(do_next_chunk, timeout)
if objects.length == 0
CUI.setTimeout =>
if dfr.state() == "rejected"
return
dfr.resolve()
else
CUI.setTimeout(do_next_chunk)
dfr
# proxy methods
@proxyMethods: (target, source, methods) ->
# console.debug target, source, methods
for k in methods
target.prototype[k] = source.prototype[k]
@__timeouts = []
# list of function which we need to call if
# the timeouts counter changes
@__timeoutCallbacks = []
@__callTimeoutChangeCallbacks: ->
tracked = @countTimeouts()
for cb in @__timeoutCallbacks
cb(tracked)
return
@__removeTimeout: (timeout) ->
if CUI.util.removeFromArray(timeout, @__timeouts)
if timeout.track
@__callTimeoutChangeCallbacks()
return
@__getTimeoutById: (timeoutID, ignoreNotFound = false) ->
for timeout in @__timeouts
if timeout.id == timeoutID
return timeout
CUI.util.assert(ignoreNotFound, "CUI.__getTimeoutById", "Timeout ##{timeoutID} not found.")
null
@resetTimeout: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID)
CUI.util.assert(not timeout.__isRunning, "CUI.resetTimeout", "Timeout #{timeoutID} cannot be resetted while running.", timeout: timeout)
timeout.onReset?(timeout)
window.clearTimeout(timeout.real_id)
old_real_id = timeout.real_id
tid = @__startTimeout(timeout)
return tid
@registerTimeoutChangeCallback: (cb) ->
@__timeoutCallbacks.push(cb)
@setTimeout: (_func, ms=0, track) ->
if CUI.util.isPlainObject(_func)
ms = _func.ms or 0
track = _func.track
func = _func.call
onDone = _func.onDone
onReset = _func.onReset
else
func = _func
if CUI.util.isNull(track)
if ms == 0
track = false
else
track = true
CUI.util.assert(CUI.util.isFunction(func), "CUI.setTimeout", "Function needs to be a Function (opts.call)", parameter: _func)
timeout =
call: =>
timeout.__isRunning = true
func()
@__removeTimeout(timeout)
timeout.onDone?(timeout)
ms: ms
func: func # for debug purposes
track: track
onDone: onDone
onReset: onReset
@__timeouts.push(timeout)
if track and ms > 0
@__callTimeoutChangeCallbacks()
@__startTimeout(timeout)
@__scheduledCallbacks = []
# schedules to run a function after
# a timeout has occurred. does not schedule
# the same function a second time
# returns a deferred, which resolves when
# the callback is done
@scheduleCallback: (_opts) ->
opts = CUI.Element.readOpts _opts, "CUI.scheduleCallback",
call:
mandatory: true
check: Function
ms:
default: 0
check: (v) ->
CUI.util.isInteger(v) and v >= 0
track:
default: false
check: Boolean
idx = CUI.util.idxInArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
if idx > -1 and CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeoutID)
# don't schedule the same call while it is already running, schedule
# a new one
idx = -1
if idx == -1
idx = @__scheduledCallbacks.length
# console.debug "...schedule", idx
else
# function already scheduled
# console.info("scheduleCallback, already scheduled: ", @__scheduledCallbacks[idx].timeout, CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeout))
CUI.resetTimeout(@__scheduledCallbacks[idx].timeoutID)
return @__scheduledCallbacks[idx].promise
dfr = new CUI.Deferred()
timeoutID = CUI.setTimeout
ms: opts.ms
track: opts.track
call: =>
opts.call()
dfr.resolve()
cb = @__scheduledCallbacks[idx] =
call: opts.call
timeoutID: timeoutID
promise: dfr.promise()
# console.error "scheduleCallback", cb.timeoutID, opts.call
dfr.done =>
# remove this callback after we are done
CUI.util.removeFromArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
cb.promise
# call: function callback to cancel
# return: true if found, false if not
@scheduleCallbackCancel: (_opts) ->
opts = CUI.Element.readOpts _opts, "CUI.scheduleCallbackCancel",
call:
mandatory: true
check: Function
idx = CUI.util.idxInArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
if idx > -1 and not CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeoutID)
# console.error "cancel timeout...", @__scheduledCallbacks[idx].timeoutID
CUI.clearTimeout(@__scheduledCallbacks[idx].timeoutID)
@__scheduledCallbacks.splice(idx, 1)
return true
else
return false
@utf8ArrayBufferToString: (arrayBuffer) ->
out = []
array = new Uint8Array(arrayBuffer)
len = array.length
i = 0
while (i < len)
c = array[i++]
switch(c >> 4)
when 0, 1, 2, 3, 4, 5, 6, 7
# 0xxxxxxx
out.push(String.fromCharCode(c))
when 12, 13
# 110x xxxx 10xx xxxx
char2 = array[i++]
out.push(String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)))
when 14
# 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++]
char3 = array[i++]
out.push(String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)))
out.join("")
@__startTimeout: (timeout) ->
real_id = window.setTimeout(timeout.call, timeout.ms)
if not timeout.id
# first time we put the real id
timeout.id = real_id
timeout.real_id = real_id
# console.error "new timeout:", timeoutID, "ms:", ms, "current timeouts:", @__timeouts.length
timeout.id
@countTimeouts: ->
tracked = 0
for timeout in @__timeouts
if timeout.track
tracked++
tracked
@clearTimeout: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID, true) # ignore not found
if not timeout
return
window.clearTimeout(timeout.real_id)
@__removeTimeout(timeout)
timeout.id
@isTimeoutRunning: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID, true) # ignore not found
if not timeout?.__isRunning
false
else
true
@setInterval: (func, ms) ->
window.setInterval(func, ms)
@clearInterval: (interval) ->
window.clearInterval(interval)
# used to set a css-class while testing with webdriver. this way
# we can hide things on the screen that should not irritate our screenshot comparison
@startWebdriverTest: ->
a= "body"
CUI.dom.addClass(a, "cui-webdriver-test")
@getParameterByName: (name, search=document.location.search) ->
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]")
regex = new RegExp("[\\?&]" + name + "=([^&#]*)")
results = regex.exec(search)
if results == null
""
else
decodeURIComponent(results[1].replace(/\+/g, " "))
@setSessionStorage: (key, value) ->
@__setStorage("sessionStorage", key, value)
@getSessionStorage: (key = null) ->
@__getStorage("sessionStorage", key)
@clearSessionStorage: ->
@__clearStorage("sessionStorage")
@setLocalStorage: (key, value) ->
@__setStorage("localStorage", key, value)
@getLocalStorage: (key = null) ->
@__getStorage("localStorage", key)
@clearLocalStorage: ->
@__clearStorage("localStorage")
@__storage: localStorage: null, sessionStorage: null
@__setStorage: (skey, key, value) ->
data = @__getStorage(skey)
if value == undefined
delete(data[key])
else
data[key] = value
try
window[skey].setItem("CUI", JSON.stringify(data))
catch e
console.warn("CUI.__setStorage: Storage not available.", e)
@__storage[skey] = JSON.stringify(data)
data
@__getStorage: (skey, key = null) ->
try
data_json = window[skey].getItem("CUI")
catch e
console.warn("CUI.__getStorage: Storage not available.", e)
data_json = @__storage[skey]
if data_json
data = JSON.parse(data_json)
else
data = {}
if key != null
data[key]
else
data
@__clearStorage: (skey) ->
try
window[skey].removeItem("CUI")
catch e
console.warn("CUI.__clearStorage: Storage not available.", e)
@__storage[skey] = null
@encodeUrlData: (params, replacer = null, connect = "&", connect_pair = "=") ->
url = []
if replacer
if CUI.util.isFunction(replacer)
encode_func = replacer
else
encode_func = (v) -> CUI.util.stringMapReplace(v+"", replace_map)
else
encode_func = (v) -> encodeURIComponent(v)
for k, v of params
if CUI.util.isArray(v)
for _v in v
url.push(encode_func(k) + connect_pair + encode_func(_v))
else if not CUI.util.isEmpty(v)
url.push(encode_func(k) + connect_pair + encode_func(v))
else if v != undefined
url.push(encode_func(k))
url.join(connect)
# keep "," and ":" in url intact, encodeURI all other parts
@encodeURIComponentNicely: (str="") ->
s = []
for v, idx in (str+"").split(",")
if idx > 0
s.push(",")
for v2, idx2 in v.split(":")
if idx2 > 0
s.push(":")
s.push(encodeURIComponent(v2))
s.join("")
@decodeURIComponentNicely: (v) ->
decodeURIComponent(v)
@decodeUrlData: (url, replacer = null, connect = "&", connect_pair = "=", use_array=false) ->
params = {}
if replacer
if CUI.util.isFunction(replacer)
decode_func = replacer
else
decode_func = (v) -> CUI.util.stringMapReplace(v+"", replacer)
else
decode_func = (v) -> decodeURIComponent(v)
for part in url.split(connect)
if part.length == 0
continue
if part.indexOf(connect_pair) > -1
pair = part.split(connect_pair)
key = decode_func(pair[0])
value = decode_func(pair[1])
else
key = decode_func(part)
value = ""
if use_array
if not params[key]
params[key] = []
params[key].push(value)
else
params[key] = value
params
@decodeUrlDataArray: (url, replace_map = null, connect = "&", connect_pair = "=") ->
@decodeUrlData(url, replace_map, connect, connect_pair, true)
# Deprecated -> Use CUI.util
@mergeMap: (targetMap, mergeMap) ->
for k, v of mergeMap
if not targetMap.hasOwnProperty(k)
targetMap[k] = v
else if CUI.util.isPlainObject(targetMap[k]) and CUI.util.isPlainObject(v)
CUI.util.mergeMap(targetMap[k], v)
targetMap
# Deprecated -> Use CUI.util
@revertMap: (map) ->
map_reverted = {}
for k, v of map
map_reverted[v] = k
map_reverted
# Deprecated -> Use CUI.util
@stringMapReplace: (s, map) ->
regex = []
for key of map
if CUI.util.isEmpty(key)
continue
regex.push(key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"))
if regex.length > 0
s.replace(new RegExp(regex.join('|'),"g"), (word) -> map[word])
else
s
# Deprecated -> Use CUI.util
@isFunction: (v) ->
v and typeof(v) == "function"
# Deprecated -> Use CUI.util
@isPlainObject: (v) ->
v and typeof(v) == "object" and v.constructor?.prototype.hasOwnProperty("isPrototypeOf")
# Deprecated -> Use CUI.util
@isEmptyObject: (v) ->
for k of v
return false
return true
# Deprecated -> Use CUI.util
@isMap: (v) ->
@isPlainObject(v)
# Deprecated -> Use CUI.util
@isArray: (v) ->
Array.isArray(v)
# Deprecated -> Use CUI.util
@inArray: (value, array) ->
array.indexOf(value)
# Deprecated -> Use CUI.util
@isString: (s) ->
typeof(s) == "string"
@downloadData: (data, fileName) ->
blob = new Blob([data], type: "octet/stream")
if window.navigator.msSaveOrOpenBlob
window.navigator.msSaveOrOpenBlob(blob, fileName)
else
url = window.URL.createObjectURL(blob)
@__downloadDataElement.href = url
@__downloadDataElement.download = fileName
@__downloadDataElement.click()
window.URL.revokeObjectURL(url)
# https://gist.github.com/dperini/729294
@urlRegex: new RegExp(
"^" +
# protocol identifier
"(?:(?:(sftp|ftp|ftps|https|http))://|)" +
# user:pass authentication
"(?:(\\S+?)(?::(\\S*))?@)?" +
"((?:(?:" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 192.168.127.12
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host & domain name
"(?:[a-z0-9\\u00a1-\\uffff](?:|[a-z\\u00a1-\\uffff0-9-]*[a-z0-9\\u00a1-\\uffff])\\.)*" +
# last identifier
"(?:[a-z\\u00a1-\\uffff]{2,})" +
# hostname only
"|" +
"(?:[a-z0-9\\u00a1-\\uffff][a-z0-9-\\u00a1-\\uffff]*[a-z0-9\\u00a1-\\uffff])" +
"))|)" +
# port number
"(?::(\\d{2,5}))?" +
# resource path
"(?:([/?#]\\S*))?" +
"$", "i"
)
@evalCode: (code) ->
script = document.createElement("script")
script.text = code
document.head.appendChild(script).parentNode.removeChild(script)
@appendToUrl: (url, data) ->
for key, value of data
if value == undefined
continue
# add token to the url
if url.match(/\?/)
url += "&"
else
url += "?"
url += encodeURIComponent(key)+"="+encodeURIComponent(value)
url
@parseLocation: (url) ->
if not CUI.util.isFunction(url?.match) or url.length == 0
return null
match = url.match(@urlRegex)
if not match
return null
# console.debug "CUI.parseLocation:", url, match
p =
protocol: match[1] or ""
user: match[2] or ""
password: match[3] or ""
hostname: match[4] or ""
port: match[5] or ""
path: match[6] or ""
origin: ""
if p.hostname
if not p.protocol
p.protocol = "http"
p.origin = p.protocol+"://"+p.hostname
if p.port
p.origin += ":"+p.port
p.url = p.protocol+"://"
if p.user
p.url = p.url + p.user + ":" + p.password + "@"
p.url = p.url + p.hostname
if p.port
p.url = p.url + ":" + p.port
else
p.url = ""
if p.path.length > 0
_match = p.path.match(/(.*?)(|\?.*?)(|\#.*)$/)
p.pathname = _match[1]
p.search = _match[2]
if p.search == "?"
p.search = ""
p.fragment = _match[3]
else
p.search = ""
p.pathname = ""
p.fragment = ""
p.href = p.origin+p.path
p.hash = p.fragment
if p.login
p.auth = btoa(p.user+":"+p.password)
# url includes user+password
p.url = p.url + p.path
p
@escapeAttribute: (data) ->
if CUI.util.isNull(data) or !CUI.util.isString(data)
return ""
data = data.replace(/"/g, """).replace(/\'/g, "'")
data
@loadScript: (src) ->
deferred = new CUI.Deferred
script = CUI.dom.element("script", charset: "utf-8", src: src)
CUI.Events.listen
type: "load"
node: script
instance: script
call: (ev) =>
deferred.resolve(ev)
return
CUI.Events.listen
type: "error"
node: script
instance: script
call: (ev) =>
document.head.removeChild(script)
deferred.reject(ev)
return
deferred.always =>
CUI.Events.ignore(instance: script)
document.head.appendChild(script)
return deferred.promise()
# http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
@browser: (->
map =
opera: `(!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0`
firefox: `typeof InstallTrigger !== 'undefined'`
safari: `Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0`
ie: `/*@cc_on!@*/false || !!document.documentMode`
chrome: !!window.chrome and !!window.chrome.webstore
map.edge = not map.ie && !!window.StyleMedia
map.blink = (map.chrome or map.opera) && !!window.CSS
map
)()
@__toggleUIElements: ->
if @__uiHighlightDivs?.length > 0
for highlightDiv in @__uiHighlightDivs
CUI.dom.remove(highlightDiv)
delete @__uiHighlightDivs
return
@__uiHighlightDivs = []
uiElements = document.querySelectorAll("[ui]")
for uiElement in uiElements
div = CUI.dom.div()
@__uiHighlightDivs.push(div)
do(div, uiElement) =>
divRect = div.getBoundingClientRect();
uiElementRect = uiElement.getBoundingClientRect();
div.textContent = uiElement.getAttribute("ui")
CUI.dom.setStyle(div,
padding: "4px"
background: "yellow"
position: "absolute"
"white-space": "nowrap"
cursor: "pointer"
border: "solid 1.5px grey"
)
div.title = "Click to copy!"
span = CUI.dom.span()
span.textContent = " [X]"
CUI.dom.append(div, span)
CUI.dom.append(document.body, div)
borderStyle = CUI.dom.getStyle(uiElement).border
div.addEventListener('mouseenter', =>
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.hideElement(otherHighlightDiv)
CUI.dom.showElement(div)
CUI.dom.setStyle(uiElement, {border: "2px solid yellow"})
)
div.addEventListener('mouseleave', =>
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.showElement(otherHighlightDiv)
CUI.dom.setStyle(uiElement, {border: borderStyle})
)
div.addEventListener('click', =>
navigator.clipboard.writeText(uiElement.getAttribute("ui"))
)
span.addEventListener('click', =>
CUI.dom.remove(div)
CUI.util.removeFromArray(div, @__uiHighlightDivs)
CUI.dom.setStyle(uiElement, {border: borderStyle})
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.showElement(otherHighlightDiv)
return
)
top = uiElementRect.y + uiElementRect.height / 2 - divRect.height / 2
if top < 0
# Skip not visible elements.
CUI.dom.remove(div)
return
left = uiElementRect.x - divRect.width
if left <= 0
if uiElementRect.width > divRect.width
left = uiElementRect.x
else
left = uiElementRect.x + uiElementRect.width
CUI.dom.setStyle(div,
top: top
left: left
)
CUI.dom.setStyle(div, "zIndex": 5, "")
return
CUI.ready =>
for k of CUI.browser
if CUI.browser[k]
document.body.classList.add("cui-browser-"+k)
CUI.defaults.marked_opts =
renderer: new marked.Renderer()
gfm: true
tables: true
breaks: false
pedantic: false
smartLists: true
smartypants: false
# initialize a markdown renderer
marked.setOptions(CUI.defaults.marked_opts)
nodes = CUI.dom.htmlToNodes("<!-- CUI.CUI --><a style='display: none;'></a><!-- /CUI.CUI -->")
CUI.__downloadDataElement = nodes[1]
CUI.dom.append(document.body, nodes)
if not window.addEventListener
alert("Your browser is not supported. Please update to a current version of Google Chrome, Mozilla Firefox or Internet Explorer.")
else
window.addEventListener("load", =>
CUI.start()
)
module.exports = CUI
| true | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# Base class for the Coffeescript UI system. It is used for
# Theme-Management as well as for basic event management tasks.
#
# @example Startup
#
marked = require('marked')
class CUI
@__readyFuncs = []
@__themes = []
@__ng__: true
@start: ->
trigger_viewport_resize = =>
# console.info("CUI: trigger viewport resize.")
CUI.Events.trigger
type: "viewport-resize"
CUI.Events.listen
type: "resize"
node: window
call: (ev, info) =>
# console.info("CUI: caught window resize event.")
if !CUI.browser.ie
trigger_viewport_resize()
else
CUI.scheduleCallback(ms: 500, call: trigger_viewport_resize)
return
CUI.Events.listen
type: "drop"
node: document.documentElement
call: (ev) ->
ev.preventDefault()
CUI.Events.listen
type: "keyup"
node: window
capture: true
call: (ev) =>
if ev.getKeyboard() == "C+U+I"
CUI.toaster(text: "CUI!")
if CUI.defaults.debug
if ev.getKeyboard() == "Alt+Shift+U"
@__toggleUIElements()
return
CUI.Events.listen
type: "keydown"
node: window
call: (ev) ->
if ev.getKeyboard() == "c+"
CUI.toaster(text: "CUI!")
# backspace acts as "BACK" in some browser, like FF
if ev.keyCode() == 8
for node in CUI.dom.elementsUntil(ev.getTarget(), null, document.documentElement)
if node.tagName in ["INPUT", "TEXTAREA"]
return
if node.getAttribute("contenteditable") == "true"
return
# console.info("swalloded BACKSPACE keydown event to prevent default")
ev.preventDefault()
return
document.body.scrollTop=0
icons = require('../scss/icons/icons.svg').default
CUI.Template.loadText(icons)
CUI.Template.load()
@chainedCall.apply(@, @__readyFuncs).always =>
@__ready = true
@
@getPathToScript: ->
if not @__pathToScript
scripts = document.getElementsByTagName('script')
cui_script = scripts[scripts.length - 1]
if m = cui_script.src.match("(.*/).*?\.js$")
@__pathToScript = m[1]
else
CUI.util.assert(@__pathToScript, "CUI", "Could not determine script path.")
@__pathToScript
@ready: (func) ->
if @__ready
return func.call(@)
@__readyFuncs.push(func)
@defaults:
FileUpload:
name:
"files[]"
debug: true
asserts: true
asserts_alert: 'js' # or 'cui' or 'off' or 'debugger'
class: {}
# Returns a resolved CUI.Promise.
@resolvedPromise: ->
dfr = new CUI.Deferred()
dfr.resolve.apply(dfr, arguments)
dfr.promise()
# Returns a rejected CUI.Promise.
@rejectedPromise: ->
dfr = new CUI.Deferred()
dfr.reject.apply(dfr, arguments)
dfr.promise()
# calls the as arguments passed functions in order
# of appearance. if a function returns
# a deferred or promise, the next function waits
# for that function to complete the promise
# if the argument is a value or a promise
# it is used the same way
# returns a promise which resolve when all
# functions resolve or the first doesnt
@chainedCall: ->
idx = 0
__this = @
# return a real array from arguments
get_args = (_arguments) ->
_args = []
for arg in _arguments
_args.push(arg)
_args
# mimic the behaviour of jQuery "when"
get_return_value = (_arguments) ->
_args = get_args(_arguments)
if _args.length == 0
return undefined
else if _args.length == 1
return _args[0]
else
return _args
args = get_args(arguments)
return_values = []
init_next = =>
if idx == args.length
dfr.resolve.apply(dfr, return_values)
return
if CUI.util.isFunction(args[idx])
if __this != CUI
ret = args[idx].call(__this)
else
ret = args[idx]()
else
ret = args[idx]
# console.debug "idx", idx, "ret", ret, "state:", ret?.state?()
idx++
if CUI.util.isPromise(ret)
ret
.done =>
return_values.push(get_return_value(arguments))
init_next()
.fail =>
return_values.push(get_return_value(arguments))
dfr.reject.apply(dfr, return_values)
else
return_values.push(ret)
init_next()
return
dfr = new CUI.Deferred()
init_next()
dfr.promise()
# Executes 'call' function in batches of 'chunk_size' for all the 'items'.
# It must be called with '.call(this, opts)'
@chunkWork: (_opts = {}) ->
opts = CUI.Element.readOpts _opts, "CUI.chunkWork",
items:
mandatory: true
check: (v) ->
CUI.util.isArray(v)
chunk_size:
mandatory: true
default: 10
check: (v) ->
v >= 1
timeout:
mandatory: true
default: 0
check: (v) ->
v >= -1
call:
mandatory: true
check: (v) ->
v instanceof Function
chunk_size = opts.chunk_size
timeout = opts.timeout
CUI.util.assert(@ != CUI, "CUI.chunkWork", "Cannot call CUI.chunkWork with 'this' not set to the caller.")
idx = 0
len = opts.items.length
next_chunk = =>
progress = (idx+1) + " - " + Math.min(len, idx+chunk_size) + " / " +len
# console.error "progress:", progress
dfr.notify
progress: progress
idx: idx
len: len
chunk_size: chunk_size
go_on = =>
if idx + chunk_size >= len
dfr.resolve()
else
idx = idx + chunk_size
if timeout == -1
next_chunk()
else
CUI.setTimeout
ms: timeout
call: next_chunk
return
ret = opts.call.call(@, opts.items.slice(idx, idx+opts.chunk_size), idx, len)
if ret == false
# interrupt this
dfr.reject()
return
if CUI.util.isPromise(ret)
ret.fail(dfr.reject).done(go_on)
else
go_on()
return
dfr = new CUI.Deferred()
CUI.setTimeout
ms: Math.min(0, timeout)
call: =>
if len > 0
next_chunk()
else
dfr.resolve()
return dfr.promise()
# returns a Deferred, the Deferred
# notifies the worker for each
# object
@chunkWorkOLD: (objects, chunkSize = 10, timeout = 0) ->
dfr = new CUI.Deferred()
idx = 0
do_next_chunk = =>
chunk = 0
while idx < objects.length and (chunk < chunkSize or chunkSize == 0)
if dfr.state() == "rejected"
return
# console.debug idx, chunk, chunkSize, dfr.state()
dfr.notify(objects[idx], idx)
if idx == objects.length-1
dfr.resolve()
return
idx++
chunk++
if idx < objects.length
CUI.setTimeout(do_next_chunk, timeout)
if objects.length == 0
CUI.setTimeout =>
if dfr.state() == "rejected"
return
dfr.resolve()
else
CUI.setTimeout(do_next_chunk)
dfr
# proxy methods
@proxyMethods: (target, source, methods) ->
# console.debug target, source, methods
for k in methods
target.prototype[k] = source.prototype[k]
@__timeouts = []
# list of function which we need to call if
# the timeouts counter changes
@__timeoutCallbacks = []
@__callTimeoutChangeCallbacks: ->
tracked = @countTimeouts()
for cb in @__timeoutCallbacks
cb(tracked)
return
@__removeTimeout: (timeout) ->
if CUI.util.removeFromArray(timeout, @__timeouts)
if timeout.track
@__callTimeoutChangeCallbacks()
return
@__getTimeoutById: (timeoutID, ignoreNotFound = false) ->
for timeout in @__timeouts
if timeout.id == timeoutID
return timeout
CUI.util.assert(ignoreNotFound, "CUI.__getTimeoutById", "Timeout ##{timeoutID} not found.")
null
@resetTimeout: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID)
CUI.util.assert(not timeout.__isRunning, "CUI.resetTimeout", "Timeout #{timeoutID} cannot be resetted while running.", timeout: timeout)
timeout.onReset?(timeout)
window.clearTimeout(timeout.real_id)
old_real_id = timeout.real_id
tid = @__startTimeout(timeout)
return tid
@registerTimeoutChangeCallback: (cb) ->
@__timeoutCallbacks.push(cb)
@setTimeout: (_func, ms=0, track) ->
if CUI.util.isPlainObject(_func)
ms = _func.ms or 0
track = _func.track
func = _func.call
onDone = _func.onDone
onReset = _func.onReset
else
func = _func
if CUI.util.isNull(track)
if ms == 0
track = false
else
track = true
CUI.util.assert(CUI.util.isFunction(func), "CUI.setTimeout", "Function needs to be a Function (opts.call)", parameter: _func)
timeout =
call: =>
timeout.__isRunning = true
func()
@__removeTimeout(timeout)
timeout.onDone?(timeout)
ms: ms
func: func # for debug purposes
track: track
onDone: onDone
onReset: onReset
@__timeouts.push(timeout)
if track and ms > 0
@__callTimeoutChangeCallbacks()
@__startTimeout(timeout)
@__scheduledCallbacks = []
# schedules to run a function after
# a timeout has occurred. does not schedule
# the same function a second time
# returns a deferred, which resolves when
# the callback is done
@scheduleCallback: (_opts) ->
opts = CUI.Element.readOpts _opts, "CUI.scheduleCallback",
call:
mandatory: true
check: Function
ms:
default: 0
check: (v) ->
CUI.util.isInteger(v) and v >= 0
track:
default: false
check: Boolean
idx = CUI.util.idxInArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
if idx > -1 and CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeoutID)
# don't schedule the same call while it is already running, schedule
# a new one
idx = -1
if idx == -1
idx = @__scheduledCallbacks.length
# console.debug "...schedule", idx
else
# function already scheduled
# console.info("scheduleCallback, already scheduled: ", @__scheduledCallbacks[idx].timeout, CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeout))
CUI.resetTimeout(@__scheduledCallbacks[idx].timeoutID)
return @__scheduledCallbacks[idx].promise
dfr = new CUI.Deferred()
timeoutID = CUI.setTimeout
ms: opts.ms
track: opts.track
call: =>
opts.call()
dfr.resolve()
cb = @__scheduledCallbacks[idx] =
call: opts.call
timeoutID: timeoutID
promise: dfr.promise()
# console.error "scheduleCallback", cb.timeoutID, opts.call
dfr.done =>
# remove this callback after we are done
CUI.util.removeFromArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
cb.promise
# call: function callback to cancel
# return: true if found, false if not
@scheduleCallbackCancel: (_opts) ->
opts = CUI.Element.readOpts _opts, "CUI.scheduleCallbackCancel",
call:
mandatory: true
check: Function
idx = CUI.util.idxInArray(opts.call, @__scheduledCallbacks, (v) -> v.call == opts.call)
if idx > -1 and not CUI.isTimeoutRunning(@__scheduledCallbacks[idx].timeoutID)
# console.error "cancel timeout...", @__scheduledCallbacks[idx].timeoutID
CUI.clearTimeout(@__scheduledCallbacks[idx].timeoutID)
@__scheduledCallbacks.splice(idx, 1)
return true
else
return false
@utf8ArrayBufferToString: (arrayBuffer) ->
out = []
array = new Uint8Array(arrayBuffer)
len = array.length
i = 0
while (i < len)
c = array[i++]
switch(c >> 4)
when 0, 1, 2, 3, 4, 5, 6, 7
# 0xxxxxxx
out.push(String.fromCharCode(c))
when 12, 13
# 110x xxxx 10xx xxxx
char2 = array[i++]
out.push(String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)))
when 14
# 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++]
char3 = array[i++]
out.push(String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)))
out.join("")
@__startTimeout: (timeout) ->
real_id = window.setTimeout(timeout.call, timeout.ms)
if not timeout.id
# first time we put the real id
timeout.id = real_id
timeout.real_id = real_id
# console.error "new timeout:", timeoutID, "ms:", ms, "current timeouts:", @__timeouts.length
timeout.id
@countTimeouts: ->
tracked = 0
for timeout in @__timeouts
if timeout.track
tracked++
tracked
@clearTimeout: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID, true) # ignore not found
if not timeout
return
window.clearTimeout(timeout.real_id)
@__removeTimeout(timeout)
timeout.id
@isTimeoutRunning: (timeoutID) ->
timeout = @__getTimeoutById(timeoutID, true) # ignore not found
if not timeout?.__isRunning
false
else
true
@setInterval: (func, ms) ->
window.setInterval(func, ms)
@clearInterval: (interval) ->
window.clearInterval(interval)
# used to set a css-class while testing with webdriver. this way
# we can hide things on the screen that should not irritate our screenshot comparison
@startWebdriverTest: ->
a= "body"
CUI.dom.addClass(a, "cui-webdriver-test")
@getParameterByName: (name, search=document.location.search) ->
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]")
regex = new RegExp("[\\?&]" + name + "=([^&#]*)")
results = regex.exec(search)
if results == null
""
else
decodeURIComponent(results[1].replace(/\+/g, " "))
@setSessionStorage: (key, value) ->
@__setStorage("sessionStorage", key, value)
@getSessionStorage: (key = null) ->
@__getStorage("sessionStorage", key)
@clearSessionStorage: ->
@__clearStorage("sessionStorage")
@setLocalStorage: (key, value) ->
@__setStorage("localStorage", key, value)
@getLocalStorage: (key = null) ->
@__getStorage("localStorage", key)
@clearLocalStorage: ->
@__clearStorage("localStorage")
@__storage: localStorage: null, sessionStorage: null
@__setStorage: (skey, key, value) ->
data = @__getStorage(skey)
if value == undefined
delete(data[key])
else
data[key] = value
try
window[skey].setItem("CUI", JSON.stringify(data))
catch e
console.warn("CUI.__setStorage: Storage not available.", e)
@__storage[skey] = JSON.stringify(data)
data
@__getStorage: (skey, key = null) ->
try
data_json = window[skey].getItem("CUI")
catch e
console.warn("CUI.__getStorage: Storage not available.", e)
data_json = @__storage[skey]
if data_json
data = JSON.parse(data_json)
else
data = {}
if key != null
data[key]
else
data
@__clearStorage: (skey) ->
try
window[skey].removeItem("CUI")
catch e
console.warn("CUI.__clearStorage: Storage not available.", e)
@__storage[skey] = null
@encodeUrlData: (params, replacer = null, connect = "&", connect_pair = "=") ->
url = []
if replacer
if CUI.util.isFunction(replacer)
encode_func = replacer
else
encode_func = (v) -> CUI.util.stringMapReplace(v+"", replace_map)
else
encode_func = (v) -> encodeURIComponent(v)
for k, v of params
if CUI.util.isArray(v)
for _v in v
url.push(encode_func(k) + connect_pair + encode_func(_v))
else if not CUI.util.isEmpty(v)
url.push(encode_func(k) + connect_pair + encode_func(v))
else if v != undefined
url.push(encode_func(k))
url.join(connect)
# keep "," and ":" in url intact, encodeURI all other parts
@encodeURIComponentNicely: (str="") ->
s = []
for v, idx in (str+"").split(",")
if idx > 0
s.push(",")
for v2, idx2 in v.split(":")
if idx2 > 0
s.push(":")
s.push(encodeURIComponent(v2))
s.join("")
@decodeURIComponentNicely: (v) ->
decodeURIComponent(v)
@decodeUrlData: (url, replacer = null, connect = "&", connect_pair = "=", use_array=false) ->
params = {}
if replacer
if CUI.util.isFunction(replacer)
decode_func = replacer
else
decode_func = (v) -> CUI.util.stringMapReplace(v+"", replacer)
else
decode_func = (v) -> decodeURIComponent(v)
for part in url.split(connect)
if part.length == 0
continue
if part.indexOf(connect_pair) > -1
pair = part.split(connect_pair)
key = decode_func(pair[0])
value = decode_func(pair[1])
else
key = decode_func(part)
value = ""
if use_array
if not params[key]
params[key] = []
params[key].push(value)
else
params[key] = value
params
@decodeUrlDataArray: (url, replace_map = null, connect = "&", connect_pair = "=") ->
@decodeUrlData(url, replace_map, connect, connect_pair, true)
# Deprecated -> Use CUI.util
@mergeMap: (targetMap, mergeMap) ->
for k, v of mergeMap
if not targetMap.hasOwnProperty(k)
targetMap[k] = v
else if CUI.util.isPlainObject(targetMap[k]) and CUI.util.isPlainObject(v)
CUI.util.mergeMap(targetMap[k], v)
targetMap
# Deprecated -> Use CUI.util
@revertMap: (map) ->
map_reverted = {}
for k, v of map
map_reverted[v] = k
map_reverted
# Deprecated -> Use CUI.util
@stringMapReplace: (s, map) ->
regex = []
for key of map
if CUI.util.isEmpty(key)
continue
regex.push(key.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"))
if regex.length > 0
s.replace(new RegExp(regex.join('|'),"g"), (word) -> map[word])
else
s
# Deprecated -> Use CUI.util
@isFunction: (v) ->
v and typeof(v) == "function"
# Deprecated -> Use CUI.util
@isPlainObject: (v) ->
v and typeof(v) == "object" and v.constructor?.prototype.hasOwnProperty("isPrototypeOf")
# Deprecated -> Use CUI.util
@isEmptyObject: (v) ->
for k of v
return false
return true
# Deprecated -> Use CUI.util
@isMap: (v) ->
@isPlainObject(v)
# Deprecated -> Use CUI.util
@isArray: (v) ->
Array.isArray(v)
# Deprecated -> Use CUI.util
@inArray: (value, array) ->
array.indexOf(value)
# Deprecated -> Use CUI.util
@isString: (s) ->
typeof(s) == "string"
@downloadData: (data, fileName) ->
blob = new Blob([data], type: "octet/stream")
if window.navigator.msSaveOrOpenBlob
window.navigator.msSaveOrOpenBlob(blob, fileName)
else
url = window.URL.createObjectURL(blob)
@__downloadDataElement.href = url
@__downloadDataElement.download = fileName
@__downloadDataElement.click()
window.URL.revokeObjectURL(url)
# https://gist.github.com/dperini/729294
@urlRegex: new RegExp(
"^" +
# protocol identifier
"(?:(?:(sftp|ftp|ftps|https|http))://|)" +
# user:pass authentication
"(?:(\\S+?)(?::(\\S*))?@)?" +
"((?:(?:" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= PI:IP_ADDRESS:192.168.127.12END_PI
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host & domain name
"(?:[a-z0-9\\u00a1-\\uffff](?:|[a-z\\u00a1-\\uffff0-9-]*[a-z0-9\\u00a1-\\uffff])\\.)*" +
# last identifier
"(?:[a-z\\u00a1-\\uffff]{2,})" +
# hostname only
"|" +
"(?:[a-z0-9\\u00a1-\\uffff][a-z0-9-\\u00a1-\\uffff]*[a-z0-9\\u00a1-\\uffff])" +
"))|)" +
# port number
"(?::(\\d{2,5}))?" +
# resource path
"(?:([/?#]\\S*))?" +
"$", "i"
)
@evalCode: (code) ->
script = document.createElement("script")
script.text = code
document.head.appendChild(script).parentNode.removeChild(script)
@appendToUrl: (url, data) ->
for key, value of data
if value == undefined
continue
# add token to the url
if url.match(/\?/)
url += "&"
else
url += "?"
url += encodeURIComponent(key)+"="+encodeURIComponent(value)
url
@parseLocation: (url) ->
if not CUI.util.isFunction(url?.match) or url.length == 0
return null
match = url.match(@urlRegex)
if not match
return null
# console.debug "CUI.parseLocation:", url, match
p =
protocol: match[1] or ""
user: match[2] or ""
password: match[3] or ""
hostname: match[4] or ""
port: match[5] or ""
path: match[6] or ""
origin: ""
if p.hostname
if not p.protocol
p.protocol = "http"
p.origin = p.protocol+"://"+p.hostname
if p.port
p.origin += ":"+p.port
p.url = p.protocol+"://"
if p.user
p.url = p.url + p.user + ":" + p.password + "@"
p.url = p.url + p.hostname
if p.port
p.url = p.url + ":" + p.port
else
p.url = ""
if p.path.length > 0
_match = p.path.match(/(.*?)(|\?.*?)(|\#.*)$/)
p.pathname = _match[1]
p.search = _match[2]
if p.search == "?"
p.search = ""
p.fragment = _match[3]
else
p.search = ""
p.pathname = ""
p.fragment = ""
p.href = p.origin+p.path
p.hash = p.fragment
if p.login
p.auth = btoa(p.user+":"+p.password)
# url includes user+password
p.url = p.url + p.path
p
@escapeAttribute: (data) ->
if CUI.util.isNull(data) or !CUI.util.isString(data)
return ""
data = data.replace(/"/g, """).replace(/\'/g, "'")
data
@loadScript: (src) ->
deferred = new CUI.Deferred
script = CUI.dom.element("script", charset: "utf-8", src: src)
CUI.Events.listen
type: "load"
node: script
instance: script
call: (ev) =>
deferred.resolve(ev)
return
CUI.Events.listen
type: "error"
node: script
instance: script
call: (ev) =>
document.head.removeChild(script)
deferred.reject(ev)
return
deferred.always =>
CUI.Events.ignore(instance: script)
document.head.appendChild(script)
return deferred.promise()
# http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
@browser: (->
map =
opera: `(!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0`
firefox: `typeof InstallTrigger !== 'undefined'`
safari: `Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0`
ie: `/*@cc_on!@*/false || !!document.documentMode`
chrome: !!window.chrome and !!window.chrome.webstore
map.edge = not map.ie && !!window.StyleMedia
map.blink = (map.chrome or map.opera) && !!window.CSS
map
)()
@__toggleUIElements: ->
if @__uiHighlightDivs?.length > 0
for highlightDiv in @__uiHighlightDivs
CUI.dom.remove(highlightDiv)
delete @__uiHighlightDivs
return
@__uiHighlightDivs = []
uiElements = document.querySelectorAll("[ui]")
for uiElement in uiElements
div = CUI.dom.div()
@__uiHighlightDivs.push(div)
do(div, uiElement) =>
divRect = div.getBoundingClientRect();
uiElementRect = uiElement.getBoundingClientRect();
div.textContent = uiElement.getAttribute("ui")
CUI.dom.setStyle(div,
padding: "4px"
background: "yellow"
position: "absolute"
"white-space": "nowrap"
cursor: "pointer"
border: "solid 1.5px grey"
)
div.title = "Click to copy!"
span = CUI.dom.span()
span.textContent = " [X]"
CUI.dom.append(div, span)
CUI.dom.append(document.body, div)
borderStyle = CUI.dom.getStyle(uiElement).border
div.addEventListener('mouseenter', =>
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.hideElement(otherHighlightDiv)
CUI.dom.showElement(div)
CUI.dom.setStyle(uiElement, {border: "2px solid yellow"})
)
div.addEventListener('mouseleave', =>
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.showElement(otherHighlightDiv)
CUI.dom.setStyle(uiElement, {border: borderStyle})
)
div.addEventListener('click', =>
navigator.clipboard.writeText(uiElement.getAttribute("ui"))
)
span.addEventListener('click', =>
CUI.dom.remove(div)
CUI.util.removeFromArray(div, @__uiHighlightDivs)
CUI.dom.setStyle(uiElement, {border: borderStyle})
for otherHighlightDiv in @__uiHighlightDivs
CUI.dom.showElement(otherHighlightDiv)
return
)
top = uiElementRect.y + uiElementRect.height / 2 - divRect.height / 2
if top < 0
# Skip not visible elements.
CUI.dom.remove(div)
return
left = uiElementRect.x - divRect.width
if left <= 0
if uiElementRect.width > divRect.width
left = uiElementRect.x
else
left = uiElementRect.x + uiElementRect.width
CUI.dom.setStyle(div,
top: top
left: left
)
CUI.dom.setStyle(div, "zIndex": 5, "")
return
CUI.ready =>
for k of CUI.browser
if CUI.browser[k]
document.body.classList.add("cui-browser-"+k)
CUI.defaults.marked_opts =
renderer: new marked.Renderer()
gfm: true
tables: true
breaks: false
pedantic: false
smartLists: true
smartypants: false
# initialize a markdown renderer
marked.setOptions(CUI.defaults.marked_opts)
nodes = CUI.dom.htmlToNodes("<!-- CUI.CUI --><a style='display: none;'></a><!-- /CUI.CUI -->")
CUI.__downloadDataElement = nodes[1]
CUI.dom.append(document.body, nodes)
if not window.addEventListener
alert("Your browser is not supported. Please update to a current version of Google Chrome, Mozilla Firefox or Internet Explorer.")
else
window.addEventListener("load", =>
CUI.start()
)
module.exports = CUI
|
[
{
"context": "egular'\n\n data.vertices.unshift({\n name: 'Scheduled'\n 'start-time': data.timestamps['CREATED']\n ",
"end": 2206,
"score": 0.7174856662750244,
"start": 2197,
"tag": "NAME",
"value": "Scheduled"
}
] | flink-runtime-web/web-dashboard/app/scripts/modules/jobs/jobs.svc.coffee | guochuanzhi/flink | 0 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
angular.module('flinkApp')
.service 'JobsService', ($http, flinkConfig, $log, amMoment, $q, $timeout) ->
currentJob = null
currentPlan = null
deferreds = {}
jobs = {
running: []
finished: []
cancelled: []
failed: []
}
jobObservers = []
notifyObservers = ->
angular.forEach jobObservers, (callback) ->
callback()
@registerObserver = (callback) ->
jobObservers.push(callback)
@unRegisterObserver = (callback) ->
index = jobObservers.indexOf(callback)
jobObservers.splice(index, 1)
@stateList = ->
[
# 'CREATED'
'SCHEDULED'
'DEPLOYING'
'RUNNING'
'FINISHED'
'FAILED'
'CANCELING'
'CANCELED'
]
@translateLabelState = (state) ->
switch state.toLowerCase()
when 'finished' then 'success'
when 'failed' then 'danger'
when 'scheduled' then 'default'
when 'deploying' then 'info'
when 'running' then 'primary'
when 'canceling' then 'warning'
when 'pending' then 'info'
when 'total' then 'black'
else 'default'
@setEndTimes = (list) ->
angular.forEach list, (item, jobKey) ->
unless item['end-time'] > -1
item['end-time'] = item['start-time'] + item['duration']
@processVertices = (data) ->
angular.forEach data.vertices, (vertex, i) ->
vertex.type = 'regular'
data.vertices.unshift({
name: 'Scheduled'
'start-time': data.timestamps['CREATED']
'end-time': data.timestamps['CREATED'] + 1
type: 'scheduled'
})
@listJobs = ->
deferred = $q.defer()
$http.get flinkConfig.jobServer + "joboverview"
.success (data, status, headers, config) =>
angular.forEach data, (list, listKey) =>
switch listKey
when 'running' then jobs.running = @setEndTimes(list)
when 'finished' then jobs.finished = @setEndTimes(list)
when 'cancelled' then jobs.cancelled = @setEndTimes(list)
when 'failed' then jobs.failed = @setEndTimes(list)
deferred.resolve(jobs)
notifyObservers()
deferred.promise
@getJobs = (type) ->
jobs[type]
@getAllJobs = ->
jobs
@loadJob = (jobid) ->
currentJob = null
deferreds.job = $q.defer()
$http.get flinkConfig.jobServer + "jobs/" + jobid
.success (data, status, headers, config) =>
@setEndTimes(data.vertices)
@processVertices(data)
$http.get flinkConfig.jobServer + "jobs/" + jobid + "/config"
.success (jobConfig) ->
data = angular.extend(data, jobConfig)
currentJob = data
deferreds.job.resolve(currentJob)
deferreds.job.promise
@getNode = (nodeid) ->
seekNode = (nodeid, data) ->
for node in data
return node if node.id is nodeid
sub = seekNode(nodeid, node.step_function) if node.step_function
return sub if sub
null
deferred = $q.defer()
deferreds.job.promise.then (data) =>
foundNode = seekNode(nodeid, currentJob.plan.nodes)
foundNode.vertex = @seekVertex(nodeid)
deferred.resolve(foundNode)
deferred.promise
@seekVertex = (nodeid) ->
for vertex in currentJob.vertices
return vertex if vertex.id is nodeid
return null
@getVertex = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/subtasktimes"
.success (data) =>
# TODO: change to subtasktimes
vertex.subtasks = data.subtasks
deferred.resolve(vertex)
deferred.promise
@getSubtasks = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
# vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid
.success (data) ->
subtasks = data.subtasks
deferred.resolve(subtasks)
deferred.promise
@getAccumulators = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
# vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/accumulators"
.success (data) ->
accumulators = data['user-accumulators']
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/subtasks/accumulators"
.success (data) ->
subtaskAccumulators = data.subtasks
deferred.resolve({ main: accumulators, subtasks: subtaskAccumulators })
deferred.promise
@loadExceptions = ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/exceptions"
.success (exceptions) ->
currentJob.exceptions = exceptions
deferred.resolve(exceptions)
deferred.promise
@cancelJob = (jobid) ->
# uses the non REST-compliant GET yarn-cancel handler which is available in addition to the
# proper "DELETE jobs/<jobid>/"
$http.get flinkConfig.jobServer + "jobs/" + jobid + "/yarn-cancel"
@
| 61012 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
angular.module('flinkApp')
.service 'JobsService', ($http, flinkConfig, $log, amMoment, $q, $timeout) ->
currentJob = null
currentPlan = null
deferreds = {}
jobs = {
running: []
finished: []
cancelled: []
failed: []
}
jobObservers = []
notifyObservers = ->
angular.forEach jobObservers, (callback) ->
callback()
@registerObserver = (callback) ->
jobObservers.push(callback)
@unRegisterObserver = (callback) ->
index = jobObservers.indexOf(callback)
jobObservers.splice(index, 1)
@stateList = ->
[
# 'CREATED'
'SCHEDULED'
'DEPLOYING'
'RUNNING'
'FINISHED'
'FAILED'
'CANCELING'
'CANCELED'
]
@translateLabelState = (state) ->
switch state.toLowerCase()
when 'finished' then 'success'
when 'failed' then 'danger'
when 'scheduled' then 'default'
when 'deploying' then 'info'
when 'running' then 'primary'
when 'canceling' then 'warning'
when 'pending' then 'info'
when 'total' then 'black'
else 'default'
@setEndTimes = (list) ->
angular.forEach list, (item, jobKey) ->
unless item['end-time'] > -1
item['end-time'] = item['start-time'] + item['duration']
@processVertices = (data) ->
angular.forEach data.vertices, (vertex, i) ->
vertex.type = 'regular'
data.vertices.unshift({
name: '<NAME>'
'start-time': data.timestamps['CREATED']
'end-time': data.timestamps['CREATED'] + 1
type: 'scheduled'
})
@listJobs = ->
deferred = $q.defer()
$http.get flinkConfig.jobServer + "joboverview"
.success (data, status, headers, config) =>
angular.forEach data, (list, listKey) =>
switch listKey
when 'running' then jobs.running = @setEndTimes(list)
when 'finished' then jobs.finished = @setEndTimes(list)
when 'cancelled' then jobs.cancelled = @setEndTimes(list)
when 'failed' then jobs.failed = @setEndTimes(list)
deferred.resolve(jobs)
notifyObservers()
deferred.promise
@getJobs = (type) ->
jobs[type]
@getAllJobs = ->
jobs
@loadJob = (jobid) ->
currentJob = null
deferreds.job = $q.defer()
$http.get flinkConfig.jobServer + "jobs/" + jobid
.success (data, status, headers, config) =>
@setEndTimes(data.vertices)
@processVertices(data)
$http.get flinkConfig.jobServer + "jobs/" + jobid + "/config"
.success (jobConfig) ->
data = angular.extend(data, jobConfig)
currentJob = data
deferreds.job.resolve(currentJob)
deferreds.job.promise
@getNode = (nodeid) ->
seekNode = (nodeid, data) ->
for node in data
return node if node.id is nodeid
sub = seekNode(nodeid, node.step_function) if node.step_function
return sub if sub
null
deferred = $q.defer()
deferreds.job.promise.then (data) =>
foundNode = seekNode(nodeid, currentJob.plan.nodes)
foundNode.vertex = @seekVertex(nodeid)
deferred.resolve(foundNode)
deferred.promise
@seekVertex = (nodeid) ->
for vertex in currentJob.vertices
return vertex if vertex.id is nodeid
return null
@getVertex = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/subtasktimes"
.success (data) =>
# TODO: change to subtasktimes
vertex.subtasks = data.subtasks
deferred.resolve(vertex)
deferred.promise
@getSubtasks = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
# vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid
.success (data) ->
subtasks = data.subtasks
deferred.resolve(subtasks)
deferred.promise
@getAccumulators = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
# vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/accumulators"
.success (data) ->
accumulators = data['user-accumulators']
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/subtasks/accumulators"
.success (data) ->
subtaskAccumulators = data.subtasks
deferred.resolve({ main: accumulators, subtasks: subtaskAccumulators })
deferred.promise
@loadExceptions = ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/exceptions"
.success (exceptions) ->
currentJob.exceptions = exceptions
deferred.resolve(exceptions)
deferred.promise
@cancelJob = (jobid) ->
# uses the non REST-compliant GET yarn-cancel handler which is available in addition to the
# proper "DELETE jobs/<jobid>/"
$http.get flinkConfig.jobServer + "jobs/" + jobid + "/yarn-cancel"
@
| true | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
angular.module('flinkApp')
.service 'JobsService', ($http, flinkConfig, $log, amMoment, $q, $timeout) ->
currentJob = null
currentPlan = null
deferreds = {}
jobs = {
running: []
finished: []
cancelled: []
failed: []
}
jobObservers = []
notifyObservers = ->
angular.forEach jobObservers, (callback) ->
callback()
@registerObserver = (callback) ->
jobObservers.push(callback)
@unRegisterObserver = (callback) ->
index = jobObservers.indexOf(callback)
jobObservers.splice(index, 1)
@stateList = ->
[
# 'CREATED'
'SCHEDULED'
'DEPLOYING'
'RUNNING'
'FINISHED'
'FAILED'
'CANCELING'
'CANCELED'
]
@translateLabelState = (state) ->
switch state.toLowerCase()
when 'finished' then 'success'
when 'failed' then 'danger'
when 'scheduled' then 'default'
when 'deploying' then 'info'
when 'running' then 'primary'
when 'canceling' then 'warning'
when 'pending' then 'info'
when 'total' then 'black'
else 'default'
@setEndTimes = (list) ->
angular.forEach list, (item, jobKey) ->
unless item['end-time'] > -1
item['end-time'] = item['start-time'] + item['duration']
@processVertices = (data) ->
angular.forEach data.vertices, (vertex, i) ->
vertex.type = 'regular'
data.vertices.unshift({
name: 'PI:NAME:<NAME>END_PI'
'start-time': data.timestamps['CREATED']
'end-time': data.timestamps['CREATED'] + 1
type: 'scheduled'
})
@listJobs = ->
deferred = $q.defer()
$http.get flinkConfig.jobServer + "joboverview"
.success (data, status, headers, config) =>
angular.forEach data, (list, listKey) =>
switch listKey
when 'running' then jobs.running = @setEndTimes(list)
when 'finished' then jobs.finished = @setEndTimes(list)
when 'cancelled' then jobs.cancelled = @setEndTimes(list)
when 'failed' then jobs.failed = @setEndTimes(list)
deferred.resolve(jobs)
notifyObservers()
deferred.promise
@getJobs = (type) ->
jobs[type]
@getAllJobs = ->
jobs
@loadJob = (jobid) ->
currentJob = null
deferreds.job = $q.defer()
$http.get flinkConfig.jobServer + "jobs/" + jobid
.success (data, status, headers, config) =>
@setEndTimes(data.vertices)
@processVertices(data)
$http.get flinkConfig.jobServer + "jobs/" + jobid + "/config"
.success (jobConfig) ->
data = angular.extend(data, jobConfig)
currentJob = data
deferreds.job.resolve(currentJob)
deferreds.job.promise
@getNode = (nodeid) ->
seekNode = (nodeid, data) ->
for node in data
return node if node.id is nodeid
sub = seekNode(nodeid, node.step_function) if node.step_function
return sub if sub
null
deferred = $q.defer()
deferreds.job.promise.then (data) =>
foundNode = seekNode(nodeid, currentJob.plan.nodes)
foundNode.vertex = @seekVertex(nodeid)
deferred.resolve(foundNode)
deferred.promise
@seekVertex = (nodeid) ->
for vertex in currentJob.vertices
return vertex if vertex.id is nodeid
return null
@getVertex = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/subtasktimes"
.success (data) =>
# TODO: change to subtasktimes
vertex.subtasks = data.subtasks
deferred.resolve(vertex)
deferred.promise
@getSubtasks = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
# vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid
.success (data) ->
subtasks = data.subtasks
deferred.resolve(subtasks)
deferred.promise
@getAccumulators = (vertexid) ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
# vertex = @seekVertex(vertexid)
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/accumulators"
.success (data) ->
accumulators = data['user-accumulators']
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/vertices/" + vertexid + "/subtasks/accumulators"
.success (data) ->
subtaskAccumulators = data.subtasks
deferred.resolve({ main: accumulators, subtasks: subtaskAccumulators })
deferred.promise
@loadExceptions = ->
deferred = $q.defer()
deferreds.job.promise.then (data) =>
$http.get flinkConfig.jobServer + "jobs/" + currentJob.jid + "/exceptions"
.success (exceptions) ->
currentJob.exceptions = exceptions
deferred.resolve(exceptions)
deferred.promise
@cancelJob = (jobid) ->
# uses the non REST-compliant GET yarn-cancel handler which is available in addition to the
# proper "DELETE jobs/<jobid>/"
$http.get flinkConfig.jobServer + "jobs/" + jobid + "/yarn-cancel"
@
|
[
{
"context": "\n doesJavaScriptLoadRoot: true,\n DISPLAY_NAME: \"Turbofilm\",\n DEBUG_LEVEL: 4,\n ROOT_URL: \"https://trailers",
"end": 71,
"score": 0.9346294403076172,
"start": 62,
"tag": "NAME",
"value": "Turbofilm"
}
] | assets/js/utils.coffee | iwater/atvproxy | 0 | atv.config =
doesJavaScriptLoadRoot: true,
DISPLAY_NAME: "Turbofilm",
DEBUG_LEVEL: 4,
ROOT_URL: "https://trailers.apple.com"
require = (module) ->
xhr = new XMLHttpRequest()
xhr.open("GET", atv.config.ROOT_URL + "/js/" + module, false)
xhr.send()
eval(xhr.responseText)
utils = require('helpers')
loadMenuPage = (event) ->
id = event.navigationItemId
utils.Ajax.get atv.config.ROOT_URL + '/page/' + id, {}, (page) ->
event.success(page)
playEpisode = (episodeUrl) ->
position = atv.localStorage['savedPosition:' + episodeUrl] || 0
videoUrl = atv.config.ROOT_URL + '/page/video'
utils.loadPage(videoUrl, { episodeUrl, position }) | 32745 | atv.config =
doesJavaScriptLoadRoot: true,
DISPLAY_NAME: "<NAME>",
DEBUG_LEVEL: 4,
ROOT_URL: "https://trailers.apple.com"
require = (module) ->
xhr = new XMLHttpRequest()
xhr.open("GET", atv.config.ROOT_URL + "/js/" + module, false)
xhr.send()
eval(xhr.responseText)
utils = require('helpers')
loadMenuPage = (event) ->
id = event.navigationItemId
utils.Ajax.get atv.config.ROOT_URL + '/page/' + id, {}, (page) ->
event.success(page)
playEpisode = (episodeUrl) ->
position = atv.localStorage['savedPosition:' + episodeUrl] || 0
videoUrl = atv.config.ROOT_URL + '/page/video'
utils.loadPage(videoUrl, { episodeUrl, position }) | true | atv.config =
doesJavaScriptLoadRoot: true,
DISPLAY_NAME: "PI:NAME:<NAME>END_PI",
DEBUG_LEVEL: 4,
ROOT_URL: "https://trailers.apple.com"
require = (module) ->
xhr = new XMLHttpRequest()
xhr.open("GET", atv.config.ROOT_URL + "/js/" + module, false)
xhr.send()
eval(xhr.responseText)
utils = require('helpers')
loadMenuPage = (event) ->
id = event.navigationItemId
utils.Ajax.get atv.config.ROOT_URL + '/page/' + id, {}, (page) ->
event.success(page)
playEpisode = (episodeUrl) ->
position = atv.localStorage['savedPosition:' + episodeUrl] || 0
videoUrl = atv.config.ROOT_URL + '/page/video'
utils.loadPage(videoUrl, { episodeUrl, position }) |
[
{
"context": "v: {\n host: \"localhost\"\n user: \"brian\"\n version: \"0.12.2\"\n }\n }\n\n ",
"end": 22642,
"score": 0.999540388584137,
"start": 22637,
"tag": "USERNAME",
"value": "brian"
},
{
"context": "eq({\n host: \"localhost\"\n ... | packages/server/test/unit/config_spec.coffee | JesterOrNot/cypress | 0 | require("../spec_helper")
_ = require("lodash")
path = require("path")
R = require("ramda")
config = require("#{root}lib/config")
errors = require("#{root}lib/errors")
configUtil = require("#{root}lib/util/config")
findSystemNode = require("#{root}lib/util/find_system_node")
scaffold = require("#{root}lib/scaffold")
settings = require("#{root}lib/util/settings")
describe "lib/config", ->
beforeEach ->
@env = process.env
process.env = _.omit(process.env, "CYPRESS_DEBUG")
afterEach ->
process.env = @env
context "environment name check", ->
it "throws an error for unknown CYPRESS_ENV", ->
sinon.stub(errors, "throw").withArgs("INVALID_CYPRESS_ENV", "foo-bar")
process.env.CYPRESS_ENV = "foo-bar"
cfg = {
projectRoot: "/foo/bar/"
}
options = {}
config.mergeDefaults(cfg, options)
expect(errors.throw).have.been.calledOnce
it "allows known CYPRESS_ENV", ->
sinon.stub(errors, "throw")
process.env.CYPRESS_ENV = "test"
cfg = {
projectRoot: "/foo/bar/"
}
options = {}
config.mergeDefaults(cfg, options)
expect(errors.throw).not.to.be.called
context ".get", ->
beforeEach ->
@projectRoot = "/_test-output/path/to/project"
@setup = (cypressJson = {}, cypressEnvJson = {}) =>
sinon.stub(settings, "read").withArgs(@projectRoot).resolves(cypressJson)
sinon.stub(settings, "readEnv").withArgs(@projectRoot).resolves(cypressEnvJson)
it "sets projectRoot", ->
@setup({}, {foo: "bar"})
config.get(@projectRoot)
.then (obj) =>
expect(obj.projectRoot).to.eq(@projectRoot)
expect(obj.env).to.deep.eq({foo: "bar"})
it "sets projectName", ->
@setup({}, {foo: "bar"})
config.get(@projectRoot)
.then (obj) ->
expect(obj.projectName).to.eq("project")
context "port", ->
beforeEach ->
@setup({}, {foo: "bar"})
it "can override default port", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.port).to.eq(8080)
it "updates browserUrl", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.browserUrl).to.eq "http://localhost:8080/__/"
it "updates proxyUrl", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.proxyUrl).to.eq "http://localhost:8080"
context "validation", ->
beforeEach ->
@expectValidationPasses = =>
config.get(@projectRoot) ## shouldn't throw
@expectValidationFails = (errorMessage = "validation error") =>
config.get(@projectRoot)
.then ->
throw new Error("should throw validation error")
.catch (err) ->
expect(err.message).to.include(errorMessage)
it "values are optional", ->
@setup()
@expectValidationPasses()
it "validates cypress.json", ->
@setup({reporter: 5})
@expectValidationFails("cypress.json")
it "validates cypress.env.json", ->
@setup({}, {reporter: 5})
@expectValidationFails("cypress.env.json")
it "only validates known values", ->
@setup({foo: "bar"})
@expectValidationPasses()
context "animationDistanceThreshold", ->
it "passes if a number", ->
@setup({animationDistanceThreshold: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({animationDistanceThreshold: {foo: "bar"}})
@expectValidationFails("be a number")
@expectValidationFails("the value was: \`{\"foo\":\"bar\"}\`")
context "baseUrl", ->
it "passes if begins with http://", ->
@setup({baseUrl: "http://example.com"})
@expectValidationPasses()
it "passes if begins with https://", ->
@setup({baseUrl: "https://example.com"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({baseUrl: false})
@expectValidationFails("be a fully qualified URL")
it "fails if not a fully qualified url", ->
@setup({baseUrl: "localhost"})
@expectValidationFails("be a fully qualified URL")
context "chromeWebSecurity", ->
it "passes if a boolean", ->
@setup({chromeWebSecurity: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({chromeWebSecurity: 42})
@expectValidationFails("be a boolean")
@expectValidationFails("the value was: `42`")
context "modifyObstructiveCode", ->
it "passes if a boolean", ->
@setup({modifyObstructiveCode: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({modifyObstructiveCode: 42})
@expectValidationFails("be a boolean")
@expectValidationFails("the value was: `42`")
context "defaultCommandTimeout", ->
it "passes if a number", ->
@setup({defaultCommandTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({defaultCommandTimeout: "foo"})
@expectValidationFails("be a number")
@expectValidationFails("the value was: `\"foo\"`")
context "env", ->
it "passes if an object", ->
@setup({env: {}})
@expectValidationPasses()
it "fails if not an object", ->
@setup({env: "not an object that's for sure"})
@expectValidationFails("a plain object")
context "execTimeout", ->
it "passes if a number", ->
@setup({execTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({execTimeout: "foo"})
@expectValidationFails("be a number")
context "taskTimeout", ->
it "passes if a number", ->
@setup({taskTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({taskTimeout: "foo"})
@expectValidationFails("be a number")
context "fileServerFolder", ->
it "passes if a string", ->
@setup({fileServerFolder: "_files"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({fileServerFolder: true})
@expectValidationFails("be a string")
@expectValidationFails("the value was: `true`")
context "fixturesFolder", ->
it "passes if a string", ->
@setup({fixturesFolder: "_fixtures"})
@expectValidationPasses()
it "passes if false", ->
@setup({fixturesFolder: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({fixturesFolder: true})
@expectValidationFails("be a string or false")
context "ignoreTestFiles", ->
it "passes if a string", ->
@setup({ignoreTestFiles: "*.jsx"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({ignoreTestFiles: ["*.jsx"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({ignoreTestFiles: 5})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({ignoreTestFiles: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "integrationFolder", ->
it "passes if a string", ->
@setup({integrationFolder: "_tests"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({integrationFolder: true})
@expectValidationFails("be a string")
context "userAgent", ->
it "passes if a string", ->
@setup({userAgent: "_tests"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({userAgent: true})
@expectValidationFails("be a string")
context "numTestsKeptInMemory", ->
it "passes if a number", ->
@setup({numTestsKeptInMemory: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({numTestsKeptInMemory: "foo"})
@expectValidationFails("be a number")
context "pageLoadTimeout", ->
it "passes if a number", ->
@setup({pageLoadTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({pageLoadTimeout: "foo"})
@expectValidationFails("be a number")
context "pluginsFile", ->
it "passes if a string", ->
@setup({pluginsFile: "cypress/plugins"})
@expectValidationPasses()
it "passes if false", ->
@setup({pluginsFile: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({pluginsFile: 42})
@expectValidationFails("be a string")
context "port", ->
it "passes if a number", ->
@setup({port: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({port: "foo"})
@expectValidationFails("be a number")
context "reporter", ->
it "passes if a string", ->
@setup({reporter: "_custom"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({reporter: true})
@expectValidationFails("be a string")
context "requestTimeout", ->
it "passes if a number", ->
@setup({requestTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({requestTimeout: "foo"})
@expectValidationFails("be a number")
context "responseTimeout", ->
it "passes if a number", ->
@setup({responseTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({responseTimeout: "foo"})
@expectValidationFails("be a number")
context "testFiles", ->
it "passes if a string", ->
@setup({testFiles: "**/*.coffee"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({testFiles: ["**/*.coffee", "**/*.jsx"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({testFiles: 42})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({testFiles: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "supportFile", ->
it "passes if a string", ->
@setup({supportFile: "cypress/support"})
@expectValidationPasses()
it "passes if false", ->
@setup({supportFile: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({supportFile: true})
@expectValidationFails("be a string or false")
context "trashAssetsBeforeRuns", ->
it "passes if a boolean", ->
@setup({trashAssetsBeforeRuns: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({trashAssetsBeforeRuns: 42})
@expectValidationFails("be a boolean")
context "videoCompression", ->
it "passes if a number", ->
@setup({videoCompression: 10})
@expectValidationPasses()
it "passes if false", ->
@setup({videoCompression: false})
@expectValidationPasses()
it "fails if not a number", ->
@setup({videoCompression: "foo"})
@expectValidationFails("be a number or false")
context "video", ->
it "passes if a boolean", ->
@setup({video: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({video: 42})
@expectValidationFails("be a boolean")
context "videoUploadOnPasses", ->
it "passes if a boolean", ->
@setup({videoUploadOnPasses: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({videoUploadOnPasses: 99})
@expectValidationFails("be a boolean")
context "videosFolder", ->
it "passes if a string", ->
@setup({videosFolder: "_videos"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({videosFolder: true})
@expectValidationFails("be a string")
context "viewportHeight", ->
it "passes if a number", ->
@setup({viewportHeight: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({viewportHeight: "foo"})
@expectValidationFails("be a number")
context "viewportWidth", ->
it "passes if a number", ->
@setup({viewportWidth: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({viewportWidth: "foo"})
@expectValidationFails("be a number")
context "waitForAnimations", ->
it "passes if a boolean", ->
@setup({waitForAnimations: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({waitForAnimations: 42})
@expectValidationFails("be a boolean")
context "watchForFileChanges", ->
it "passes if a boolean", ->
@setup({watchForFileChanges: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({watchForFileChanges: 42})
@expectValidationFails("be a boolean")
context "blacklistHosts", ->
it "passes if a string", ->
@setup({blacklistHosts: "google.com"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({blacklistHosts: ["google.com"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({blacklistHosts: 5})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({blacklistHosts: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "firefoxGcInterval", ->
it "passes if a number", ->
@setup({ firefoxGcInterval: 1 })
@expectValidationPasses()
it "passes if null", ->
@setup({ firefoxGcInterval: null })
@expectValidationPasses()
it "passes if correctly shaped object", ->
@setup({ firefoxGcInterval: { runMode: 1, openMode: null } })
@expectValidationPasses()
it "fails if string", ->
@setup({ firefoxGcInterval: 'foo' })
@expectValidationFails("a positive number or null or an object")
it "fails if invalid object", ->
@setup({ firefoxGcInterval: { foo: 'bar' } })
@expectValidationFails("a positive number or null or an object")
context ".getConfigKeys", ->
beforeEach ->
@includes = (key) ->
expect(config.getConfigKeys()).to.include(key)
it "includes blacklistHosts", ->
@includes("blacklistHosts")
context ".resolveConfigValues", ->
beforeEach ->
@expected = (obj) ->
merged = config.resolveConfigValues(obj.config, obj.defaults, obj.resolved)
expect(merged).to.deep.eq(obj.final)
it "sets baseUrl to default", ->
@expected({
config: {baseUrl: null}
defaults: {baseUrl: null}
resolved: {}
final: {
baseUrl: {
value: null
from: "default"
}
}
})
it "sets baseUrl to config", ->
@expected({
config: {baseUrl: "localhost"}
defaults: {baseUrl: null}
resolved: {}
final: {
baseUrl: {
value: "localhost"
from: "config"
}
}
})
it "does not change existing resolved values", ->
@expected({
config: {baseUrl: "localhost"}
defaults: {baseUrl: null}
resolved: {baseUrl: "cli"}
final: {
baseUrl: {
value: "localhost"
from: "cli"
}
}
})
it "ignores values not found in configKeys", ->
@expected({
config: {baseUrl: "localhost", foo: "bar"}
defaults: {baseUrl: null}
resolved: {baseUrl: "cli"}
final: {
baseUrl: {
value: "localhost"
from: "cli"
}
}
})
context ".mergeDefaults", ->
beforeEach ->
@defaults = (prop, value, cfg = {}, options = {}) =>
cfg.projectRoot = "/foo/bar/"
config.mergeDefaults(cfg, options)
.then R.prop(prop)
.then (result) ->
expect(result).to.deep.eq(value)
it "port=null", ->
@defaults "port", null
it "projectId=null", ->
@defaults("projectId", null)
it "autoOpen=false", ->
@defaults "autoOpen", false
it "browserUrl=http://localhost:2020/__/", ->
@defaults "browserUrl", "http://localhost:2020/__/", {port: 2020}
it "proxyUrl=http://localhost:2020", ->
@defaults "proxyUrl", "http://localhost:2020", {port: 2020}
it "namespace=__cypress", ->
@defaults "namespace", "__cypress"
it "baseUrl=http://localhost:8000/app/", ->
@defaults "baseUrl", "http://localhost:8000/app/", {
baseUrl: "http://localhost:8000/app///"
}
it "baseUrl=http://localhost:8000/app/", ->
@defaults "baseUrl", "http://localhost:8000/app/", {
baseUrl: "http://localhost:8000/app//"
}
it "baseUrl=http://localhost:8000/app", ->
@defaults "baseUrl", "http://localhost:8000/app", {
baseUrl: "http://localhost:8000/app"
}
it "baseUrl=http://localhost:8000/", ->
@defaults "baseUrl", "http://localhost:8000/", {
baseUrl: "http://localhost:8000//"
}
it "baseUrl=http://localhost:8000/", ->
@defaults "baseUrl", "http://localhost:8000/", {
baseUrl: "http://localhost:8000/"
}
it "baseUrl=http://localhost:8000", ->
@defaults "baseUrl", "http://localhost:8000", {
baseUrl: "http://localhost:8000"
}
it "javascripts=[]", ->
@defaults "javascripts", []
it "viewportWidth=1000", ->
@defaults "viewportWidth", 1000
it "viewportHeight=660", ->
@defaults "viewportHeight", 660
it "userAgent=null", ->
@defaults("userAgent", null)
it "baseUrl=null", ->
@defaults "baseUrl", null
it "defaultCommandTimeout=4000", ->
@defaults "defaultCommandTimeout", 4000
it "pageLoadTimeout=60000", ->
@defaults "pageLoadTimeout", 60000
it "requestTimeout=5000", ->
@defaults "requestTimeout", 5000
it "responseTimeout=30000", ->
@defaults "responseTimeout", 30000
it "execTimeout=60000", ->
@defaults "execTimeout", 60000
it "waitForAnimations=true", ->
@defaults "waitForAnimations", true
it "animationDistanceThreshold=5", ->
@defaults "animationDistanceThreshold", 5
it "video=true", ->
@defaults "video", true
it "videoCompression=32", ->
@defaults "videoCompression", 32
it "videoUploadOnPasses=true", ->
@defaults "videoUploadOnPasses", true
it "trashAssetsBeforeRuns=32", ->
@defaults "trashAssetsBeforeRuns", true
it "morgan=true", ->
@defaults "morgan", true
it "isTextTerminal=false", ->
@defaults "isTextTerminal", false
it "socketId=null", ->
@defaults "socketId", null
it "reporter=spec", ->
@defaults "reporter", "spec"
it "watchForFileChanges=true", ->
@defaults "watchForFileChanges", true
it "numTestsKeptInMemory=50", ->
@defaults "numTestsKeptInMemory", 50
it "modifyObstructiveCode=true", ->
@defaults "modifyObstructiveCode", true
it "supportFile=false", ->
@defaults "supportFile", false, {supportFile: false}
it "blacklistHosts=null", ->
@defaults("blacklistHosts", null)
it "blacklistHosts=[a,b]", ->
@defaults("blacklistHosts", ["a", "b"], {
blacklistHosts: ["a", "b"]
})
it "blacklistHosts=a|b", ->
@defaults("blacklistHosts", ["a", "b"], {
blacklistHosts: ["a", "b"]
})
it "hosts=null", ->
@defaults("hosts", null)
it "hosts={}", ->
@defaults("hosts", {
foo: "bar"
baz: "quux"
}, {
hosts: {
foo: "bar",
baz: "quux"
}
})
it "resets numTestsKeptInMemory to 0 when runMode", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.numTestsKeptInMemory).to.eq(0)
it "resets watchForFileChanges to false when runMode", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.watchForFileChanges).to.be.false
it "can override morgan in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {morgan: false})
.then (cfg) ->
expect(cfg.morgan).to.be.false
it "can override isTextTerminal in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.isTextTerminal).to.be.true
it "can override socketId in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {socketId: 1234})
.then (cfg) ->
expect(cfg.socketId).to.eq(1234)
it "deletes envFile", ->
obj = {
projectRoot: "/foo/bar/"
env: {
foo: "bar"
version: "0.5.2"
}
envFile: {
bar: "baz"
version: "1.0.1"
}
}
config.mergeDefaults(obj)
.then (cfg) ->
expect(cfg.env).to.deep.eq({
foo: "bar"
bar: "baz"
version: "1.0.1"
})
expect(cfg.cypressEnv).to.eq(process.env["CYPRESS_ENV"])
expect(cfg).not.to.have.property("envFile")
it "merges env into @config.env", ->
obj = {
projectRoot: "/foo/bar/"
env: {
host: "localhost"
user: "brian"
version: "0.12.2"
}
}
options = {
env: {
version: "0.13.1"
foo: "bar"
}
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.env).to.deep.eq({
host: "localhost"
user: "brian"
version: "0.13.1"
foo: "bar"
})
describe ".resolved", ->
it "sets reporter and port to cli", ->
obj = {
projectRoot: "/foo/bar"
}
options = {
reporter: "json"
port: 1234
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.resolved).to.deep.eq({
env: { }
projectId: { value: null, from: "default" },
port: { value: 1234, from: "cli" },
hosts: { value: null, from: "default" }
blacklistHosts: { value: null, from: "default" },
browsers: { value: [], from: "default" },
userAgent: { value: null, from: "default" }
reporter: { value: "json", from: "cli" },
reporterOptions: { value: null, from: "default" },
baseUrl: { value: null, from: "default" },
defaultCommandTimeout: { value: 4000, from: "default" },
pageLoadTimeout: { value: 60000, from: "default" },
requestTimeout: { value: 5000, from: "default" },
responseTimeout: { value: 30000, from: "default" },
execTimeout: { value: 60000, from: "default" },
taskTimeout: { value: 60000, from: "default" },
numTestsKeptInMemory: { value: 50, from: "default" },
waitForAnimations: { value: true, from: "default" },
animationDistanceThreshold: { value: 5, from: "default" },
trashAssetsBeforeRuns: { value: true, from: "default" },
watchForFileChanges: { value: true, from: "default" },
modifyObstructiveCode: { value: true, from: "default" },
chromeWebSecurity: { value: true, from: "default" },
viewportWidth: { value: 1000, from: "default" },
viewportHeight: { value: 660, from: "default" },
fileServerFolder: { value: "", from: "default" },
firefoxGcInterval: { value: { openMode: null, runMode: 1 }, from: "default" },
video: { value: true, from: "default" }
videoCompression: { value: 32, from: "default" }
videoUploadOnPasses: { value: true, from: "default" }
videosFolder: { value: "cypress/videos", from: "default" },
supportFile: { value: "cypress/support", from: "default" },
pluginsFile: { value: "cypress/plugins", from: "default" },
fixturesFolder: { value: "cypress/fixtures", from: "default" },
ignoreTestFiles: { value: "*.hot-update.js", from: "default" },
integrationFolder: { value: "cypress/integration", from: "default" },
screenshotsFolder: { value: "cypress/screenshots", from: "default" },
testFiles: { value: "**/*.*", from: "default" },
nodeVersion: { value: "default", from: "default" },
})
it "sets config, envFile and env", ->
sinon.stub(config, "getProcessEnvVars").returns({
quux: "quux"
RECORD_KEY: "foobarbazquux",
CI_KEY: "justanothercikey",
PROJECT_ID: "projectId123"
})
obj = {
projectRoot: "/foo/bar"
baseUrl: "http://localhost:8080"
port: 2020
env: {
foo: "foo"
}
envFile: {
bar: "bar"
}
}
options = {
env: {
baz: "baz"
}
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.resolved).to.deep.eq({
projectId: { value: "projectId123", from: "env" },
port: { value: 2020, from: "config" },
hosts: { value: null, from: "default" }
blacklistHosts: { value: null, from: "default" }
browsers: { value: [], from: "default" }
userAgent: { value: null, from: "default" }
reporter: { value: "spec", from: "default" },
reporterOptions: { value: null, from: "default" },
baseUrl: { value: "http://localhost:8080", from: "config" },
defaultCommandTimeout: { value: 4000, from: "default" },
pageLoadTimeout: { value: 60000, from: "default" },
requestTimeout: { value: 5000, from: "default" },
responseTimeout: { value: 30000, from: "default" },
execTimeout: { value: 60000, from: "default" },
taskTimeout: { value: 60000, from: "default" },
numTestsKeptInMemory: { value: 50, from: "default" },
waitForAnimations: { value: true, from: "default" },
animationDistanceThreshold: { value: 5, from: "default" },
trashAssetsBeforeRuns: { value: true, from: "default" },
watchForFileChanges: { value: true, from: "default" },
modifyObstructiveCode: { value: true, from: "default" },
chromeWebSecurity: { value: true, from: "default" },
viewportWidth: { value: 1000, from: "default" },
viewportHeight: { value: 660, from: "default" },
fileServerFolder: { value: "", from: "default" },
video: { value: true, from: "default" }
videoCompression: { value: 32, from: "default" }
videoUploadOnPasses: { value: true, from: "default" }
videosFolder: { value: "cypress/videos", from: "default" },
supportFile: { value: "cypress/support", from: "default" },
pluginsFile: { value: "cypress/plugins", from: "default" },
firefoxGcInterval: { value: { openMode: null, runMode: 1 }, from: "default" },
fixturesFolder: { value: "cypress/fixtures", from: "default" },
ignoreTestFiles: { value: "*.hot-update.js", from: "default" },
integrationFolder: { value: "cypress/integration", from: "default" },
screenshotsFolder: { value: "cypress/screenshots", from: "default" },
testFiles: { value: "**/*.*", from: "default" },
nodeVersion: { value: "default", from: "default" },
env: {
foo: {
value: "foo"
from: "config"
}
bar: {
value: "bar"
from: "envFile"
}
baz: {
value: "baz"
from: "cli"
}
quux: {
value: "quux"
from: "env"
}
RECORD_KEY: {
value: "fooba...zquux",
from: "env"
}
CI_KEY: {
value: "justa...cikey",
from: "env"
}
}
})
context ".setPluginResolvedOn", ->
it "resolves an object with single property", ->
cfg = {}
obj = {
foo: "bar"
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg).to.deep.eq({
foo: {
value: "bar",
from: "plugin"
}
})
it "resolves an object with multiple properties", ->
cfg = {}
obj = {
foo: "bar",
baz: [1, 2, 3]
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg).to.deep.eq({
foo: {
value: "bar",
from: "plugin"
},
baz: {
value: [1, 2, 3],
from: "plugin"
}
})
it "resolves a nested object", ->
# we need at least the structure
cfg = {
foo: {
bar: 1
}
}
obj = {
foo: {
bar: 42
}
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg, "foo.bar gets value").to.deep.eq({
foo: {
bar: {
value: 42,
from: "plugin"
}
}
})
context "_.defaultsDeep", ->
it "merges arrays", ->
# sanity checks to confirm how Lodash merges arrays in defaultsDeep
diffs = {
list: [1]
}
cfg = {
list: [1, 2]
}
merged = _.defaultsDeep({}, diffs, cfg)
expect(merged, "arrays are combined").to.deep.eq({
list: [1, 2]
})
context ".updateWithPluginValues", ->
it "is noop when no overrides", ->
expect(config.updateWithPluginValues({foo: 'bar'}, null)).to.deep.eq({
foo: 'bar'
})
it "is noop with empty overrides", ->
expect(config.updateWithPluginValues({foo: 'bar'}, {})).to.deep.eq({
foo: 'bar'
})
it "updates resolved config values and returns config with overrides", ->
cfg = {
foo: "bar"
baz: "quux"
quux: "foo"
lol: 1234
env: {
a: "a"
b: "b"
}
# previously resolved values
resolved: {
foo: { value: "bar", from: "default" }
baz: { value: "quux", from: "cli" }
quux: { value: "foo", from: "default" }
lol: { value: 1234, from: "env" }
env: {
a: { value: "a", from: "config" }
b: { value: "b", from: "config" }
}
}
}
overrides = {
baz: "baz"
quux: ["bar", "quux"]
env: {
b: "bb"
c: "c"
}
}
expect(config.updateWithPluginValues(cfg, overrides)).to.deep.eq({
foo: "bar"
baz: "baz"
lol: 1234
quux: ["bar", "quux"]
env: {
a: "a"
b: "bb"
c: "c"
}
resolved: {
foo: { value: "bar", from: "default" }
baz: { value: "baz", from: "plugin" }
quux: { value: ["bar", "quux"], from: "plugin" }
lol: { value: 1234, from: "env" }
env: {
a: { value: "a", from: "config" }
b: { value: "bb", from: "plugin" }
c: { value: "c", from: "plugin" }
}
}
})
it "keeps the list of browsers if the plugins returns empty object", ->
browser = {
name: "fake browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
cfg = {
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
}
overrides = {}
expect(config.updateWithPluginValues(cfg, overrides)).to.deep.eq({
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
})
it "catches browsers=null returned from plugins", ->
browser = {
name: "fake browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
cfg = {
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
}
overrides = {
browsers: null
}
sinon.stub(errors, "throw")
config.updateWithPluginValues(cfg, overrides)
expect(errors.throw).to.have.been.calledWith("CONFIG_VALIDATION_ERROR")
it "allows user to filter browsers", ->
browserOne = {
name: "fake browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
browserTwo = {
name: "fake electron",
family: "chromium",
displayName: "Electron",
version: "x.y.z",
# Electron browser is built-in, no external path
path: "",
majorVersion: "x"
}
cfg = {
browsers: [browserOne, browserTwo],
resolved: {
browsers: {
value: [browserOne, browserTwo],
from: "default"
}
}
}
overrides = {
browsers: [browserTwo]
}
updated = config.updateWithPluginValues(cfg, overrides)
expect(updated.resolved, "resolved values").to.deep.eq({
browsers: {
value: [browserTwo],
from: 'plugin'
}
})
expect(updated, "all values").to.deep.eq({
browsers: [browserTwo],
resolved: {
browsers: {
value: [browserTwo],
from: 'plugin'
}
}
})
context ".parseEnv", ->
it "merges together env from config, env from file, env from process, and env from CLI", ->
sinon.stub(config, "getProcessEnvVars").returns({
version: "0.12.1",
user: "bob",
})
obj = {
env: {
version: "0.10.9"
project: "todos"
host: "localhost"
baz: "quux"
}
envFile: {
host: "http://localhost:8888"
user: "brian"
foo: "bar"
}
}
envCLI = {
version: "0.14.0"
project: "pie"
}
expect(config.parseEnv(obj, envCLI)).to.deep.eq({
version: "0.14.0"
project: "pie"
host: "http://localhost:8888"
user: "bob"
foo: "bar"
baz: "quux"
})
context ".getProcessEnvVars", ->
["cypress_", "CYPRESS_"].forEach (key) ->
it "reduces key: #{key}", ->
obj = {
cypress_host: "http://localhost:8888"
foo: "bar"
env: "123"
}
obj[key + "version"] = "0.12.0"
expect(config.getProcessEnvVars(obj)).to.deep.eq({
host: "http://localhost:8888"
version: "0.12.0"
})
it "does not merge reserved environment variables", ->
obj = {
CYPRESS_ENV: "production"
CYPRESS_FOO: "bar"
CYPRESS_CRASH_REPORTS: "0"
CYPRESS_PROJECT_ID: "abc123"
}
expect(config.getProcessEnvVars(obj)).to.deep.eq({
FOO: "bar"
PROJECT_ID: "abc123"
CRASH_REPORTS: 0
})
context ".setUrls", ->
it "does not mutate existing obj", ->
obj = {}
expect(config.setUrls(obj)).not.to.eq(obj)
it "uses baseUrl when set", ->
obj = {
port: 65432
baseUrl: "https://www.google.com"
clientRoute: "/__/"
}
urls = config.setUrls(obj)
expect(urls.browserUrl).to.eq("https://www.google.com/__/")
expect(urls.proxyUrl).to.eq("http://localhost:65432")
it "strips baseUrl to host when set", ->
obj = {
port: 65432
baseUrl: "http://localhost:9999/app/?foo=bar#index.html"
clientRoute: "/__/"
}
urls = config.setUrls(obj)
expect(urls.browserUrl).to.eq("http://localhost:9999/__/")
expect(urls.proxyUrl).to.eq("http://localhost:65432")
context ".setScaffoldPaths", ->
it "sets integrationExamplePath + integrationExampleName + scaffoldedFiles", ->
obj = {
integrationFolder: "/_test-output/path/to/project/cypress/integration"
}
sinon.stub(scaffold, "fileTree").resolves([])
config.setScaffoldPaths(obj).then (result) ->
expect(result).to.deep.eq({
integrationFolder: "/_test-output/path/to/project/cypress/integration"
integrationExamplePath: "/_test-output/path/to/project/cypress/integration/examples"
integrationExampleName: "examples"
scaffoldedFiles: []
})
context ".setSupportFileAndFolder", ->
it "does nothing if supportFile is falsey", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql(obj)
it "sets the full path to the supportFile and supportFolder if it exists", ->
projectRoot = process.cwd()
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "test/unit/config_spec.coffee"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: "#{projectRoot}/test/unit/config_spec.coffee"
supportFolder: "#{projectRoot}/test/unit"
})
it "sets the supportFile to default index.js if it does not exist, support folder does not exist, and supportFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/no-scaffolding")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "cypress/support"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: "#{projectRoot}/cypress/support/index.js"
supportFolder: "#{projectRoot}/cypress/support"
})
it "sets the supportFile to false if it does not exist, support folder exists, and supportFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/empty-folders")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "cypress/support"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: false
})
it "throws error if supportFile is not default and does not exist", ->
projectRoot = process.cwd()
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "does/not/exist"
})
config.setSupportFileAndFolder(obj)
.catch (err) ->
expect(err.message).to.include("The support file is missing or invalid.")
context ".setPluginsFile", ->
it "does nothing if pluginsFile is falsey", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql(obj)
it "sets the pluginsFile to default index.js if does not exist", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/no-scaffolding")
obj = {
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins"
}
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins/index.js"
})
it "set the pluginsFile to false if it does not exist, plugins folder exists, and pluginsFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/empty-folders")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins"
})
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
pluginsFile: false
})
it "throws error if pluginsFile is not default and does not exist", ->
projectRoot = process.cwd()
obj = {
projectRoot: projectRoot
pluginsFile: "does/not/exist"
}
config.setPluginsFile(obj)
.catch (err) ->
expect(err.message).to.include("The plugins file is missing or invalid.")
context ".setParentTestsPaths", ->
it "sets parentTestsFolder and parentTestsFolderDisplay", ->
obj = {
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/cypress/integration"
}
expect(config.setParentTestsPaths(obj)).to.deep.eq({
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/cypress/integration"
parentTestsFolder: "/_test-output/path/to/project/cypress"
parentTestsFolderDisplay: "project/cypress"
})
it "sets parentTestsFolderDisplay to parentTestsFolder if they are the same", ->
obj = {
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/tests"
}
expect(config.setParentTestsPaths(obj)).to.deep.eq({
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/tests"
parentTestsFolder: "/_test-output/path/to/project"
parentTestsFolderDisplay: "project"
})
context ".setAbsolutePaths", ->
it "is noop without projectRoot", ->
expect(config.setAbsolutePaths({})).to.deep.eq({})
# it "resolves fileServerFolder with projectRoot", ->
# obj = {
# projectRoot: "/_test-output/path/to/project"
# fileServerFolder: "foo"
# }
# expect(config.setAbsolutePaths(obj)).to.deep.eq({
# projectRoot: "/_test-output/path/to/project"
# fileServerFolder: "/_test-output/path/to/project/foo"
# })
it "does not mutate existing obj", ->
obj = {}
expect(config.setAbsolutePaths(obj)).not.to.eq(obj)
it "ignores non special *folder properties", ->
obj = {
projectRoot: "/_test-output/path/to/project"
blehFolder: "some/rando/path"
foo: "bar"
baz: "quux"
}
expect(config.setAbsolutePaths(obj)).to.deep.eq(obj)
["fileServerFolder", "fixturesFolder", "integrationFolder", "unitFolder", "supportFile", "pluginsFile"].forEach (folder) ->
it "converts relative #{folder} to absolute path", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
obj[folder] = "foo/bar"
expected = {
projectRoot: "/_test-output/path/to/project"
}
expected[folder] = "/_test-output/path/to/project/foo/bar"
expect(config.setAbsolutePaths(obj)).to.deep.eq(expected)
context ".setNodeBinary", ->
beforeEach ->
@findSystemNode = sinon.stub(findSystemNode, "findNodePathAndVersion")
@nodeVersion = process.versions.node
it "sets current Node ver if nodeVersion != system", ->
config.setNodeBinary({
nodeVersion: undefined
})
.then (obj) =>
expect(@findSystemNode).to.not.be.called
expect(obj).to.deep.eq({
nodeVersion: undefined,
resolvedNodeVersion: @nodeVersion
})
it "sets found Node ver if nodeVersion = system and findNodePathAndVersion resolves", ->
@findSystemNode.resolves({
path: '/foo/bar/node',
version: '1.2.3'
})
config.setNodeBinary({
nodeVersion: "system"
})
.then (obj) =>
expect(@findSystemNode).to.be.calledOnce
expect(obj).to.deep.eq({
nodeVersion: "system",
resolvedNodeVersion: "1.2.3",
resolvedNodePath: "/foo/bar/node"
})
it "sets current Node ver and warns if nodeVersion = system and findNodePathAndVersion rejects", ->
err = new Error()
onWarning = sinon.stub()
@findSystemNode.rejects(err)
config.setNodeBinary({
nodeVersion: "system"
}, onWarning)
.then (obj) =>
expect(@findSystemNode).to.be.calledOnce
expect(onWarning).to.be.calledOnce
expect(obj).to.deep.eq({
nodeVersion: "system",
resolvedNodeVersion: @nodeVersion,
})
expect(obj.resolvedNodePath).to.be.undefined
describe "lib/util/config", ->
context ".isDefault", ->
it "returns true if value is default value", ->
settings = {baseUrl: null}
defaults = {baseUrl: null}
resolved = {}
merged = config.setResolvedConfigValues(settings, defaults, resolved)
expect(configUtil.isDefault(merged, "baseUrl")).to.be.true
it "returns false if value is not default value", ->
settings = {baseUrl: null}
defaults = {baseUrl: "http://localhost:8080"}
resolved = {}
merged = config.setResolvedConfigValues(settings, defaults, resolved)
expect(configUtil.isDefault(merged, "baseUrl")).to.be.false
| 194544 | require("../spec_helper")
_ = require("lodash")
path = require("path")
R = require("ramda")
config = require("#{root}lib/config")
errors = require("#{root}lib/errors")
configUtil = require("#{root}lib/util/config")
findSystemNode = require("#{root}lib/util/find_system_node")
scaffold = require("#{root}lib/scaffold")
settings = require("#{root}lib/util/settings")
describe "lib/config", ->
beforeEach ->
@env = process.env
process.env = _.omit(process.env, "CYPRESS_DEBUG")
afterEach ->
process.env = @env
context "environment name check", ->
it "throws an error for unknown CYPRESS_ENV", ->
sinon.stub(errors, "throw").withArgs("INVALID_CYPRESS_ENV", "foo-bar")
process.env.CYPRESS_ENV = "foo-bar"
cfg = {
projectRoot: "/foo/bar/"
}
options = {}
config.mergeDefaults(cfg, options)
expect(errors.throw).have.been.calledOnce
it "allows known CYPRESS_ENV", ->
sinon.stub(errors, "throw")
process.env.CYPRESS_ENV = "test"
cfg = {
projectRoot: "/foo/bar/"
}
options = {}
config.mergeDefaults(cfg, options)
expect(errors.throw).not.to.be.called
context ".get", ->
beforeEach ->
@projectRoot = "/_test-output/path/to/project"
@setup = (cypressJson = {}, cypressEnvJson = {}) =>
sinon.stub(settings, "read").withArgs(@projectRoot).resolves(cypressJson)
sinon.stub(settings, "readEnv").withArgs(@projectRoot).resolves(cypressEnvJson)
it "sets projectRoot", ->
@setup({}, {foo: "bar"})
config.get(@projectRoot)
.then (obj) =>
expect(obj.projectRoot).to.eq(@projectRoot)
expect(obj.env).to.deep.eq({foo: "bar"})
it "sets projectName", ->
@setup({}, {foo: "bar"})
config.get(@projectRoot)
.then (obj) ->
expect(obj.projectName).to.eq("project")
context "port", ->
beforeEach ->
@setup({}, {foo: "bar"})
it "can override default port", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.port).to.eq(8080)
it "updates browserUrl", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.browserUrl).to.eq "http://localhost:8080/__/"
it "updates proxyUrl", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.proxyUrl).to.eq "http://localhost:8080"
context "validation", ->
beforeEach ->
@expectValidationPasses = =>
config.get(@projectRoot) ## shouldn't throw
@expectValidationFails = (errorMessage = "validation error") =>
config.get(@projectRoot)
.then ->
throw new Error("should throw validation error")
.catch (err) ->
expect(err.message).to.include(errorMessage)
it "values are optional", ->
@setup()
@expectValidationPasses()
it "validates cypress.json", ->
@setup({reporter: 5})
@expectValidationFails("cypress.json")
it "validates cypress.env.json", ->
@setup({}, {reporter: 5})
@expectValidationFails("cypress.env.json")
it "only validates known values", ->
@setup({foo: "bar"})
@expectValidationPasses()
context "animationDistanceThreshold", ->
it "passes if a number", ->
@setup({animationDistanceThreshold: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({animationDistanceThreshold: {foo: "bar"}})
@expectValidationFails("be a number")
@expectValidationFails("the value was: \`{\"foo\":\"bar\"}\`")
context "baseUrl", ->
it "passes if begins with http://", ->
@setup({baseUrl: "http://example.com"})
@expectValidationPasses()
it "passes if begins with https://", ->
@setup({baseUrl: "https://example.com"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({baseUrl: false})
@expectValidationFails("be a fully qualified URL")
it "fails if not a fully qualified url", ->
@setup({baseUrl: "localhost"})
@expectValidationFails("be a fully qualified URL")
context "chromeWebSecurity", ->
it "passes if a boolean", ->
@setup({chromeWebSecurity: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({chromeWebSecurity: 42})
@expectValidationFails("be a boolean")
@expectValidationFails("the value was: `42`")
context "modifyObstructiveCode", ->
it "passes if a boolean", ->
@setup({modifyObstructiveCode: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({modifyObstructiveCode: 42})
@expectValidationFails("be a boolean")
@expectValidationFails("the value was: `42`")
context "defaultCommandTimeout", ->
it "passes if a number", ->
@setup({defaultCommandTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({defaultCommandTimeout: "foo"})
@expectValidationFails("be a number")
@expectValidationFails("the value was: `\"foo\"`")
context "env", ->
it "passes if an object", ->
@setup({env: {}})
@expectValidationPasses()
it "fails if not an object", ->
@setup({env: "not an object that's for sure"})
@expectValidationFails("a plain object")
context "execTimeout", ->
it "passes if a number", ->
@setup({execTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({execTimeout: "foo"})
@expectValidationFails("be a number")
context "taskTimeout", ->
it "passes if a number", ->
@setup({taskTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({taskTimeout: "foo"})
@expectValidationFails("be a number")
context "fileServerFolder", ->
it "passes if a string", ->
@setup({fileServerFolder: "_files"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({fileServerFolder: true})
@expectValidationFails("be a string")
@expectValidationFails("the value was: `true`")
context "fixturesFolder", ->
it "passes if a string", ->
@setup({fixturesFolder: "_fixtures"})
@expectValidationPasses()
it "passes if false", ->
@setup({fixturesFolder: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({fixturesFolder: true})
@expectValidationFails("be a string or false")
context "ignoreTestFiles", ->
it "passes if a string", ->
@setup({ignoreTestFiles: "*.jsx"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({ignoreTestFiles: ["*.jsx"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({ignoreTestFiles: 5})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({ignoreTestFiles: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "integrationFolder", ->
it "passes if a string", ->
@setup({integrationFolder: "_tests"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({integrationFolder: true})
@expectValidationFails("be a string")
context "userAgent", ->
it "passes if a string", ->
@setup({userAgent: "_tests"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({userAgent: true})
@expectValidationFails("be a string")
context "numTestsKeptInMemory", ->
it "passes if a number", ->
@setup({numTestsKeptInMemory: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({numTestsKeptInMemory: "foo"})
@expectValidationFails("be a number")
context "pageLoadTimeout", ->
it "passes if a number", ->
@setup({pageLoadTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({pageLoadTimeout: "foo"})
@expectValidationFails("be a number")
context "pluginsFile", ->
it "passes if a string", ->
@setup({pluginsFile: "cypress/plugins"})
@expectValidationPasses()
it "passes if false", ->
@setup({pluginsFile: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({pluginsFile: 42})
@expectValidationFails("be a string")
context "port", ->
it "passes if a number", ->
@setup({port: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({port: "foo"})
@expectValidationFails("be a number")
context "reporter", ->
it "passes if a string", ->
@setup({reporter: "_custom"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({reporter: true})
@expectValidationFails("be a string")
context "requestTimeout", ->
it "passes if a number", ->
@setup({requestTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({requestTimeout: "foo"})
@expectValidationFails("be a number")
context "responseTimeout", ->
it "passes if a number", ->
@setup({responseTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({responseTimeout: "foo"})
@expectValidationFails("be a number")
context "testFiles", ->
it "passes if a string", ->
@setup({testFiles: "**/*.coffee"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({testFiles: ["**/*.coffee", "**/*.jsx"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({testFiles: 42})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({testFiles: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "supportFile", ->
it "passes if a string", ->
@setup({supportFile: "cypress/support"})
@expectValidationPasses()
it "passes if false", ->
@setup({supportFile: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({supportFile: true})
@expectValidationFails("be a string or false")
context "trashAssetsBeforeRuns", ->
it "passes if a boolean", ->
@setup({trashAssetsBeforeRuns: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({trashAssetsBeforeRuns: 42})
@expectValidationFails("be a boolean")
context "videoCompression", ->
it "passes if a number", ->
@setup({videoCompression: 10})
@expectValidationPasses()
it "passes if false", ->
@setup({videoCompression: false})
@expectValidationPasses()
it "fails if not a number", ->
@setup({videoCompression: "foo"})
@expectValidationFails("be a number or false")
context "video", ->
it "passes if a boolean", ->
@setup({video: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({video: 42})
@expectValidationFails("be a boolean")
context "videoUploadOnPasses", ->
it "passes if a boolean", ->
@setup({videoUploadOnPasses: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({videoUploadOnPasses: 99})
@expectValidationFails("be a boolean")
context "videosFolder", ->
it "passes if a string", ->
@setup({videosFolder: "_videos"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({videosFolder: true})
@expectValidationFails("be a string")
context "viewportHeight", ->
it "passes if a number", ->
@setup({viewportHeight: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({viewportHeight: "foo"})
@expectValidationFails("be a number")
context "viewportWidth", ->
it "passes if a number", ->
@setup({viewportWidth: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({viewportWidth: "foo"})
@expectValidationFails("be a number")
context "waitForAnimations", ->
it "passes if a boolean", ->
@setup({waitForAnimations: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({waitForAnimations: 42})
@expectValidationFails("be a boolean")
context "watchForFileChanges", ->
it "passes if a boolean", ->
@setup({watchForFileChanges: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({watchForFileChanges: 42})
@expectValidationFails("be a boolean")
context "blacklistHosts", ->
it "passes if a string", ->
@setup({blacklistHosts: "google.com"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({blacklistHosts: ["google.com"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({blacklistHosts: 5})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({blacklistHosts: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "firefoxGcInterval", ->
it "passes if a number", ->
@setup({ firefoxGcInterval: 1 })
@expectValidationPasses()
it "passes if null", ->
@setup({ firefoxGcInterval: null })
@expectValidationPasses()
it "passes if correctly shaped object", ->
@setup({ firefoxGcInterval: { runMode: 1, openMode: null } })
@expectValidationPasses()
it "fails if string", ->
@setup({ firefoxGcInterval: 'foo' })
@expectValidationFails("a positive number or null or an object")
it "fails if invalid object", ->
@setup({ firefoxGcInterval: { foo: 'bar' } })
@expectValidationFails("a positive number or null or an object")
context ".getConfigKeys", ->
beforeEach ->
@includes = (key) ->
expect(config.getConfigKeys()).to.include(key)
it "includes blacklistHosts", ->
@includes("blacklistHosts")
context ".resolveConfigValues", ->
beforeEach ->
@expected = (obj) ->
merged = config.resolveConfigValues(obj.config, obj.defaults, obj.resolved)
expect(merged).to.deep.eq(obj.final)
it "sets baseUrl to default", ->
@expected({
config: {baseUrl: null}
defaults: {baseUrl: null}
resolved: {}
final: {
baseUrl: {
value: null
from: "default"
}
}
})
it "sets baseUrl to config", ->
@expected({
config: {baseUrl: "localhost"}
defaults: {baseUrl: null}
resolved: {}
final: {
baseUrl: {
value: "localhost"
from: "config"
}
}
})
it "does not change existing resolved values", ->
@expected({
config: {baseUrl: "localhost"}
defaults: {baseUrl: null}
resolved: {baseUrl: "cli"}
final: {
baseUrl: {
value: "localhost"
from: "cli"
}
}
})
it "ignores values not found in configKeys", ->
@expected({
config: {baseUrl: "localhost", foo: "bar"}
defaults: {baseUrl: null}
resolved: {baseUrl: "cli"}
final: {
baseUrl: {
value: "localhost"
from: "cli"
}
}
})
context ".mergeDefaults", ->
beforeEach ->
@defaults = (prop, value, cfg = {}, options = {}) =>
cfg.projectRoot = "/foo/bar/"
config.mergeDefaults(cfg, options)
.then R.prop(prop)
.then (result) ->
expect(result).to.deep.eq(value)
it "port=null", ->
@defaults "port", null
it "projectId=null", ->
@defaults("projectId", null)
it "autoOpen=false", ->
@defaults "autoOpen", false
it "browserUrl=http://localhost:2020/__/", ->
@defaults "browserUrl", "http://localhost:2020/__/", {port: 2020}
it "proxyUrl=http://localhost:2020", ->
@defaults "proxyUrl", "http://localhost:2020", {port: 2020}
it "namespace=__cypress", ->
@defaults "namespace", "__cypress"
it "baseUrl=http://localhost:8000/app/", ->
@defaults "baseUrl", "http://localhost:8000/app/", {
baseUrl: "http://localhost:8000/app///"
}
it "baseUrl=http://localhost:8000/app/", ->
@defaults "baseUrl", "http://localhost:8000/app/", {
baseUrl: "http://localhost:8000/app//"
}
it "baseUrl=http://localhost:8000/app", ->
@defaults "baseUrl", "http://localhost:8000/app", {
baseUrl: "http://localhost:8000/app"
}
it "baseUrl=http://localhost:8000/", ->
@defaults "baseUrl", "http://localhost:8000/", {
baseUrl: "http://localhost:8000//"
}
it "baseUrl=http://localhost:8000/", ->
@defaults "baseUrl", "http://localhost:8000/", {
baseUrl: "http://localhost:8000/"
}
it "baseUrl=http://localhost:8000", ->
@defaults "baseUrl", "http://localhost:8000", {
baseUrl: "http://localhost:8000"
}
it "javascripts=[]", ->
@defaults "javascripts", []
it "viewportWidth=1000", ->
@defaults "viewportWidth", 1000
it "viewportHeight=660", ->
@defaults "viewportHeight", 660
it "userAgent=null", ->
@defaults("userAgent", null)
it "baseUrl=null", ->
@defaults "baseUrl", null
it "defaultCommandTimeout=4000", ->
@defaults "defaultCommandTimeout", 4000
it "pageLoadTimeout=60000", ->
@defaults "pageLoadTimeout", 60000
it "requestTimeout=5000", ->
@defaults "requestTimeout", 5000
it "responseTimeout=30000", ->
@defaults "responseTimeout", 30000
it "execTimeout=60000", ->
@defaults "execTimeout", 60000
it "waitForAnimations=true", ->
@defaults "waitForAnimations", true
it "animationDistanceThreshold=5", ->
@defaults "animationDistanceThreshold", 5
it "video=true", ->
@defaults "video", true
it "videoCompression=32", ->
@defaults "videoCompression", 32
it "videoUploadOnPasses=true", ->
@defaults "videoUploadOnPasses", true
it "trashAssetsBeforeRuns=32", ->
@defaults "trashAssetsBeforeRuns", true
it "morgan=true", ->
@defaults "morgan", true
it "isTextTerminal=false", ->
@defaults "isTextTerminal", false
it "socketId=null", ->
@defaults "socketId", null
it "reporter=spec", ->
@defaults "reporter", "spec"
it "watchForFileChanges=true", ->
@defaults "watchForFileChanges", true
it "numTestsKeptInMemory=50", ->
@defaults "numTestsKeptInMemory", 50
it "modifyObstructiveCode=true", ->
@defaults "modifyObstructiveCode", true
it "supportFile=false", ->
@defaults "supportFile", false, {supportFile: false}
it "blacklistHosts=null", ->
@defaults("blacklistHosts", null)
it "blacklistHosts=[a,b]", ->
@defaults("blacklistHosts", ["a", "b"], {
blacklistHosts: ["a", "b"]
})
it "blacklistHosts=a|b", ->
@defaults("blacklistHosts", ["a", "b"], {
blacklistHosts: ["a", "b"]
})
it "hosts=null", ->
@defaults("hosts", null)
it "hosts={}", ->
@defaults("hosts", {
foo: "bar"
baz: "quux"
}, {
hosts: {
foo: "bar",
baz: "quux"
}
})
it "resets numTestsKeptInMemory to 0 when runMode", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.numTestsKeptInMemory).to.eq(0)
it "resets watchForFileChanges to false when runMode", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.watchForFileChanges).to.be.false
it "can override morgan in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {morgan: false})
.then (cfg) ->
expect(cfg.morgan).to.be.false
it "can override isTextTerminal in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.isTextTerminal).to.be.true
it "can override socketId in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {socketId: 1234})
.then (cfg) ->
expect(cfg.socketId).to.eq(1234)
it "deletes envFile", ->
obj = {
projectRoot: "/foo/bar/"
env: {
foo: "bar"
version: "0.5.2"
}
envFile: {
bar: "baz"
version: "1.0.1"
}
}
config.mergeDefaults(obj)
.then (cfg) ->
expect(cfg.env).to.deep.eq({
foo: "bar"
bar: "baz"
version: "1.0.1"
})
expect(cfg.cypressEnv).to.eq(process.env["CYPRESS_ENV"])
expect(cfg).not.to.have.property("envFile")
it "merges env into @config.env", ->
obj = {
projectRoot: "/foo/bar/"
env: {
host: "localhost"
user: "brian"
version: "0.12.2"
}
}
options = {
env: {
version: "0.13.1"
foo: "bar"
}
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.env).to.deep.eq({
host: "localhost"
user: "brian"
version: "0.13.1"
foo: "bar"
})
describe ".resolved", ->
it "sets reporter and port to cli", ->
obj = {
projectRoot: "/foo/bar"
}
options = {
reporter: "json"
port: 1234
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.resolved).to.deep.eq({
env: { }
projectId: { value: null, from: "default" },
port: { value: 1234, from: "cli" },
hosts: { value: null, from: "default" }
blacklistHosts: { value: null, from: "default" },
browsers: { value: [], from: "default" },
userAgent: { value: null, from: "default" }
reporter: { value: "json", from: "cli" },
reporterOptions: { value: null, from: "default" },
baseUrl: { value: null, from: "default" },
defaultCommandTimeout: { value: 4000, from: "default" },
pageLoadTimeout: { value: 60000, from: "default" },
requestTimeout: { value: 5000, from: "default" },
responseTimeout: { value: 30000, from: "default" },
execTimeout: { value: 60000, from: "default" },
taskTimeout: { value: 60000, from: "default" },
numTestsKeptInMemory: { value: 50, from: "default" },
waitForAnimations: { value: true, from: "default" },
animationDistanceThreshold: { value: 5, from: "default" },
trashAssetsBeforeRuns: { value: true, from: "default" },
watchForFileChanges: { value: true, from: "default" },
modifyObstructiveCode: { value: true, from: "default" },
chromeWebSecurity: { value: true, from: "default" },
viewportWidth: { value: 1000, from: "default" },
viewportHeight: { value: 660, from: "default" },
fileServerFolder: { value: "", from: "default" },
firefoxGcInterval: { value: { openMode: null, runMode: 1 }, from: "default" },
video: { value: true, from: "default" }
videoCompression: { value: 32, from: "default" }
videoUploadOnPasses: { value: true, from: "default" }
videosFolder: { value: "cypress/videos", from: "default" },
supportFile: { value: "cypress/support", from: "default" },
pluginsFile: { value: "cypress/plugins", from: "default" },
fixturesFolder: { value: "cypress/fixtures", from: "default" },
ignoreTestFiles: { value: "*.hot-update.js", from: "default" },
integrationFolder: { value: "cypress/integration", from: "default" },
screenshotsFolder: { value: "cypress/screenshots", from: "default" },
testFiles: { value: "**/*.*", from: "default" },
nodeVersion: { value: "default", from: "default" },
})
it "sets config, envFile and env", ->
sinon.stub(config, "getProcessEnvVars").returns({
quux: "quux"
RECORD_KEY: "<KEY>",
CI_KEY: "<KEY>",
PROJECT_ID: "projectId123"
})
obj = {
projectRoot: "/foo/bar"
baseUrl: "http://localhost:8080"
port: 2020
env: {
foo: "foo"
}
envFile: {
bar: "bar"
}
}
options = {
env: {
baz: "baz"
}
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.resolved).to.deep.eq({
projectId: { value: "projectId123", from: "env" },
port: { value: 2020, from: "config" },
hosts: { value: null, from: "default" }
blacklistHosts: { value: null, from: "default" }
browsers: { value: [], from: "default" }
userAgent: { value: null, from: "default" }
reporter: { value: "spec", from: "default" },
reporterOptions: { value: null, from: "default" },
baseUrl: { value: "http://localhost:8080", from: "config" },
defaultCommandTimeout: { value: 4000, from: "default" },
pageLoadTimeout: { value: 60000, from: "default" },
requestTimeout: { value: 5000, from: "default" },
responseTimeout: { value: 30000, from: "default" },
execTimeout: { value: 60000, from: "default" },
taskTimeout: { value: 60000, from: "default" },
numTestsKeptInMemory: { value: 50, from: "default" },
waitForAnimations: { value: true, from: "default" },
animationDistanceThreshold: { value: 5, from: "default" },
trashAssetsBeforeRuns: { value: true, from: "default" },
watchForFileChanges: { value: true, from: "default" },
modifyObstructiveCode: { value: true, from: "default" },
chromeWebSecurity: { value: true, from: "default" },
viewportWidth: { value: 1000, from: "default" },
viewportHeight: { value: 660, from: "default" },
fileServerFolder: { value: "", from: "default" },
video: { value: true, from: "default" }
videoCompression: { value: 32, from: "default" }
videoUploadOnPasses: { value: true, from: "default" }
videosFolder: { value: "cypress/videos", from: "default" },
supportFile: { value: "cypress/support", from: "default" },
pluginsFile: { value: "cypress/plugins", from: "default" },
firefoxGcInterval: { value: { openMode: null, runMode: 1 }, from: "default" },
fixturesFolder: { value: "cypress/fixtures", from: "default" },
ignoreTestFiles: { value: "*.hot-update.js", from: "default" },
integrationFolder: { value: "cypress/integration", from: "default" },
screenshotsFolder: { value: "cypress/screenshots", from: "default" },
testFiles: { value: "**/*.*", from: "default" },
nodeVersion: { value: "default", from: "default" },
env: {
foo: {
value: "foo"
from: "config"
}
bar: {
value: "bar"
from: "envFile"
}
baz: {
value: "baz"
from: "cli"
}
quux: {
value: "quux"
from: "env"
}
RECORD_KEY: {
value: "<KEY>",
from: "env"
}
CI_KEY: {
value: "<KEY>",
from: "env"
}
}
})
context ".setPluginResolvedOn", ->
it "resolves an object with single property", ->
cfg = {}
obj = {
foo: "bar"
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg).to.deep.eq({
foo: {
value: "bar",
from: "plugin"
}
})
it "resolves an object with multiple properties", ->
cfg = {}
obj = {
foo: "bar",
baz: [1, 2, 3]
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg).to.deep.eq({
foo: {
value: "bar",
from: "plugin"
},
baz: {
value: [1, 2, 3],
from: "plugin"
}
})
it "resolves a nested object", ->
# we need at least the structure
cfg = {
foo: {
bar: 1
}
}
obj = {
foo: {
bar: 42
}
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg, "foo.bar gets value").to.deep.eq({
foo: {
bar: {
value: 42,
from: "plugin"
}
}
})
context "_.defaultsDeep", ->
it "merges arrays", ->
# sanity checks to confirm how Lodash merges arrays in defaultsDeep
diffs = {
list: [1]
}
cfg = {
list: [1, 2]
}
merged = _.defaultsDeep({}, diffs, cfg)
expect(merged, "arrays are combined").to.deep.eq({
list: [1, 2]
})
context ".updateWithPluginValues", ->
it "is noop when no overrides", ->
expect(config.updateWithPluginValues({foo: 'bar'}, null)).to.deep.eq({
foo: 'bar'
})
it "is noop with empty overrides", ->
expect(config.updateWithPluginValues({foo: 'bar'}, {})).to.deep.eq({
foo: 'bar'
})
it "updates resolved config values and returns config with overrides", ->
cfg = {
foo: "bar"
baz: "quux"
quux: "foo"
lol: 1234
env: {
a: "a"
b: "b"
}
# previously resolved values
resolved: {
foo: { value: "bar", from: "default" }
baz: { value: "quux", from: "cli" }
quux: { value: "foo", from: "default" }
lol: { value: 1234, from: "env" }
env: {
a: { value: "a", from: "config" }
b: { value: "b", from: "config" }
}
}
}
overrides = {
baz: "baz"
quux: ["bar", "quux"]
env: {
b: "bb"
c: "c"
}
}
expect(config.updateWithPluginValues(cfg, overrides)).to.deep.eq({
foo: "bar"
baz: "baz"
lol: 1234
quux: ["bar", "quux"]
env: {
a: "a"
b: "bb"
c: "c"
}
resolved: {
foo: { value: "bar", from: "default" }
baz: { value: "baz", from: "plugin" }
quux: { value: ["bar", "quux"], from: "plugin" }
lol: { value: 1234, from: "env" }
env: {
a: { value: "a", from: "config" }
b: { value: "bb", from: "plugin" }
c: { value: "c", from: "plugin" }
}
}
})
it "keeps the list of browsers if the plugins returns empty object", ->
browser = {
name: "fake browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
cfg = {
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
}
overrides = {}
expect(config.updateWithPluginValues(cfg, overrides)).to.deep.eq({
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
})
it "catches browsers=null returned from plugins", ->
browser = {
name: "<NAME> browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
cfg = {
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
}
overrides = {
browsers: null
}
sinon.stub(errors, "throw")
config.updateWithPluginValues(cfg, overrides)
expect(errors.throw).to.have.been.calledWith("CONFIG_VALIDATION_ERROR")
it "allows user to filter browsers", ->
browserOne = {
name: "<NAME> browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
browserTwo = {
name: "fake electron",
family: "chromium",
displayName: "Electron",
version: "x.y.z",
# Electron browser is built-in, no external path
path: "",
majorVersion: "x"
}
cfg = {
browsers: [browserOne, browserTwo],
resolved: {
browsers: {
value: [browserOne, browserTwo],
from: "default"
}
}
}
overrides = {
browsers: [browserTwo]
}
updated = config.updateWithPluginValues(cfg, overrides)
expect(updated.resolved, "resolved values").to.deep.eq({
browsers: {
value: [browserTwo],
from: 'plugin'
}
})
expect(updated, "all values").to.deep.eq({
browsers: [browserTwo],
resolved: {
browsers: {
value: [browserTwo],
from: 'plugin'
}
}
})
context ".parseEnv", ->
it "merges together env from config, env from file, env from process, and env from CLI", ->
sinon.stub(config, "getProcessEnvVars").returns({
version: "0.12.1",
user: "bob",
})
obj = {
env: {
version: "0.10.9"
project: "todos"
host: "localhost"
baz: "quux"
}
envFile: {
host: "http://localhost:8888"
user: "brian"
foo: "bar"
}
}
envCLI = {
version: "0.14.0"
project: "pie"
}
expect(config.parseEnv(obj, envCLI)).to.deep.eq({
version: "0.14.0"
project: "pie"
host: "http://localhost:8888"
user: "bob"
foo: "bar"
baz: "quux"
})
context ".getProcessEnvVars", ->
["cypress_", "CYPRESS_"].forEach (key) ->
it "reduces key: #{key}", ->
obj = {
cypress_host: "http://localhost:8888"
foo: "bar"
env: "123"
}
obj[key + "version"] = "0.12.0"
expect(config.getProcessEnvVars(obj)).to.deep.eq({
host: "http://localhost:8888"
version: "0.12.0"
})
it "does not merge reserved environment variables", ->
obj = {
CYPRESS_ENV: "production"
CYPRESS_FOO: "bar"
CYPRESS_CRASH_REPORTS: "0"
CYPRESS_PROJECT_ID: "abc123"
}
expect(config.getProcessEnvVars(obj)).to.deep.eq({
FOO: "bar"
PROJECT_ID: "abc123"
CRASH_REPORTS: 0
})
context ".setUrls", ->
it "does not mutate existing obj", ->
obj = {}
expect(config.setUrls(obj)).not.to.eq(obj)
it "uses baseUrl when set", ->
obj = {
port: 65432
baseUrl: "https://www.google.com"
clientRoute: "/__/"
}
urls = config.setUrls(obj)
expect(urls.browserUrl).to.eq("https://www.google.com/__/")
expect(urls.proxyUrl).to.eq("http://localhost:65432")
it "strips baseUrl to host when set", ->
obj = {
port: 65432
baseUrl: "http://localhost:9999/app/?foo=bar#index.html"
clientRoute: "/__/"
}
urls = config.setUrls(obj)
expect(urls.browserUrl).to.eq("http://localhost:9999/__/")
expect(urls.proxyUrl).to.eq("http://localhost:65432")
context ".setScaffoldPaths", ->
it "sets integrationExamplePath + integrationExampleName + scaffoldedFiles", ->
obj = {
integrationFolder: "/_test-output/path/to/project/cypress/integration"
}
sinon.stub(scaffold, "fileTree").resolves([])
config.setScaffoldPaths(obj).then (result) ->
expect(result).to.deep.eq({
integrationFolder: "/_test-output/path/to/project/cypress/integration"
integrationExamplePath: "/_test-output/path/to/project/cypress/integration/examples"
integrationExampleName: "examples"
scaffoldedFiles: []
})
context ".setSupportFileAndFolder", ->
it "does nothing if supportFile is falsey", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql(obj)
it "sets the full path to the supportFile and supportFolder if it exists", ->
projectRoot = process.cwd()
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "test/unit/config_spec.coffee"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: "#{projectRoot}/test/unit/config_spec.coffee"
supportFolder: "#{projectRoot}/test/unit"
})
it "sets the supportFile to default index.js if it does not exist, support folder does not exist, and supportFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/no-scaffolding")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "cypress/support"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: "#{projectRoot}/cypress/support/index.js"
supportFolder: "#{projectRoot}/cypress/support"
})
it "sets the supportFile to false if it does not exist, support folder exists, and supportFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/empty-folders")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "cypress/support"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: false
})
it "throws error if supportFile is not default and does not exist", ->
projectRoot = process.cwd()
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "does/not/exist"
})
config.setSupportFileAndFolder(obj)
.catch (err) ->
expect(err.message).to.include("The support file is missing or invalid.")
context ".setPluginsFile", ->
it "does nothing if pluginsFile is falsey", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql(obj)
it "sets the pluginsFile to default index.js if does not exist", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/no-scaffolding")
obj = {
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins"
}
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins/index.js"
})
it "set the pluginsFile to false if it does not exist, plugins folder exists, and pluginsFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/empty-folders")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins"
})
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
pluginsFile: false
})
it "throws error if pluginsFile is not default and does not exist", ->
projectRoot = process.cwd()
obj = {
projectRoot: projectRoot
pluginsFile: "does/not/exist"
}
config.setPluginsFile(obj)
.catch (err) ->
expect(err.message).to.include("The plugins file is missing or invalid.")
context ".setParentTestsPaths", ->
it "sets parentTestsFolder and parentTestsFolderDisplay", ->
obj = {
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/cypress/integration"
}
expect(config.setParentTestsPaths(obj)).to.deep.eq({
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/cypress/integration"
parentTestsFolder: "/_test-output/path/to/project/cypress"
parentTestsFolderDisplay: "project/cypress"
})
it "sets parentTestsFolderDisplay to parentTestsFolder if they are the same", ->
obj = {
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/tests"
}
expect(config.setParentTestsPaths(obj)).to.deep.eq({
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/tests"
parentTestsFolder: "/_test-output/path/to/project"
parentTestsFolderDisplay: "project"
})
context ".setAbsolutePaths", ->
it "is noop without projectRoot", ->
expect(config.setAbsolutePaths({})).to.deep.eq({})
# it "resolves fileServerFolder with projectRoot", ->
# obj = {
# projectRoot: "/_test-output/path/to/project"
# fileServerFolder: "foo"
# }
# expect(config.setAbsolutePaths(obj)).to.deep.eq({
# projectRoot: "/_test-output/path/to/project"
# fileServerFolder: "/_test-output/path/to/project/foo"
# })
it "does not mutate existing obj", ->
obj = {}
expect(config.setAbsolutePaths(obj)).not.to.eq(obj)
it "ignores non special *folder properties", ->
obj = {
projectRoot: "/_test-output/path/to/project"
blehFolder: "some/rando/path"
foo: "bar"
baz: "quux"
}
expect(config.setAbsolutePaths(obj)).to.deep.eq(obj)
["fileServerFolder", "fixturesFolder", "integrationFolder", "unitFolder", "supportFile", "pluginsFile"].forEach (folder) ->
it "converts relative #{folder} to absolute path", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
obj[folder] = "foo/bar"
expected = {
projectRoot: "/_test-output/path/to/project"
}
expected[folder] = "/_test-output/path/to/project/foo/bar"
expect(config.setAbsolutePaths(obj)).to.deep.eq(expected)
context ".setNodeBinary", ->
beforeEach ->
@findSystemNode = sinon.stub(findSystemNode, "findNodePathAndVersion")
@nodeVersion = process.versions.node
it "sets current Node ver if nodeVersion != system", ->
config.setNodeBinary({
nodeVersion: undefined
})
.then (obj) =>
expect(@findSystemNode).to.not.be.called
expect(obj).to.deep.eq({
nodeVersion: undefined,
resolvedNodeVersion: @nodeVersion
})
it "sets found Node ver if nodeVersion = system and findNodePathAndVersion resolves", ->
@findSystemNode.resolves({
path: '/foo/bar/node',
version: '1.2.3'
})
config.setNodeBinary({
nodeVersion: "system"
})
.then (obj) =>
expect(@findSystemNode).to.be.calledOnce
expect(obj).to.deep.eq({
nodeVersion: "system",
resolvedNodeVersion: "1.2.3",
resolvedNodePath: "/foo/bar/node"
})
it "sets current Node ver and warns if nodeVersion = system and findNodePathAndVersion rejects", ->
err = new Error()
onWarning = sinon.stub()
@findSystemNode.rejects(err)
config.setNodeBinary({
nodeVersion: "system"
}, onWarning)
.then (obj) =>
expect(@findSystemNode).to.be.calledOnce
expect(onWarning).to.be.calledOnce
expect(obj).to.deep.eq({
nodeVersion: "system",
resolvedNodeVersion: @nodeVersion,
})
expect(obj.resolvedNodePath).to.be.undefined
describe "lib/util/config", ->
context ".isDefault", ->
it "returns true if value is default value", ->
settings = {baseUrl: null}
defaults = {baseUrl: null}
resolved = {}
merged = config.setResolvedConfigValues(settings, defaults, resolved)
expect(configUtil.isDefault(merged, "baseUrl")).to.be.true
it "returns false if value is not default value", ->
settings = {baseUrl: null}
defaults = {baseUrl: "http://localhost:8080"}
resolved = {}
merged = config.setResolvedConfigValues(settings, defaults, resolved)
expect(configUtil.isDefault(merged, "baseUrl")).to.be.false
| true | require("../spec_helper")
_ = require("lodash")
path = require("path")
R = require("ramda")
config = require("#{root}lib/config")
errors = require("#{root}lib/errors")
configUtil = require("#{root}lib/util/config")
findSystemNode = require("#{root}lib/util/find_system_node")
scaffold = require("#{root}lib/scaffold")
settings = require("#{root}lib/util/settings")
describe "lib/config", ->
beforeEach ->
@env = process.env
process.env = _.omit(process.env, "CYPRESS_DEBUG")
afterEach ->
process.env = @env
context "environment name check", ->
it "throws an error for unknown CYPRESS_ENV", ->
sinon.stub(errors, "throw").withArgs("INVALID_CYPRESS_ENV", "foo-bar")
process.env.CYPRESS_ENV = "foo-bar"
cfg = {
projectRoot: "/foo/bar/"
}
options = {}
config.mergeDefaults(cfg, options)
expect(errors.throw).have.been.calledOnce
it "allows known CYPRESS_ENV", ->
sinon.stub(errors, "throw")
process.env.CYPRESS_ENV = "test"
cfg = {
projectRoot: "/foo/bar/"
}
options = {}
config.mergeDefaults(cfg, options)
expect(errors.throw).not.to.be.called
context ".get", ->
beforeEach ->
@projectRoot = "/_test-output/path/to/project"
@setup = (cypressJson = {}, cypressEnvJson = {}) =>
sinon.stub(settings, "read").withArgs(@projectRoot).resolves(cypressJson)
sinon.stub(settings, "readEnv").withArgs(@projectRoot).resolves(cypressEnvJson)
it "sets projectRoot", ->
@setup({}, {foo: "bar"})
config.get(@projectRoot)
.then (obj) =>
expect(obj.projectRoot).to.eq(@projectRoot)
expect(obj.env).to.deep.eq({foo: "bar"})
it "sets projectName", ->
@setup({}, {foo: "bar"})
config.get(@projectRoot)
.then (obj) ->
expect(obj.projectName).to.eq("project")
context "port", ->
beforeEach ->
@setup({}, {foo: "bar"})
it "can override default port", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.port).to.eq(8080)
it "updates browserUrl", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.browserUrl).to.eq "http://localhost:8080/__/"
it "updates proxyUrl", ->
config.get(@projectRoot, {port: 8080})
.then (obj) ->
expect(obj.proxyUrl).to.eq "http://localhost:8080"
context "validation", ->
beforeEach ->
@expectValidationPasses = =>
config.get(@projectRoot) ## shouldn't throw
@expectValidationFails = (errorMessage = "validation error") =>
config.get(@projectRoot)
.then ->
throw new Error("should throw validation error")
.catch (err) ->
expect(err.message).to.include(errorMessage)
it "values are optional", ->
@setup()
@expectValidationPasses()
it "validates cypress.json", ->
@setup({reporter: 5})
@expectValidationFails("cypress.json")
it "validates cypress.env.json", ->
@setup({}, {reporter: 5})
@expectValidationFails("cypress.env.json")
it "only validates known values", ->
@setup({foo: "bar"})
@expectValidationPasses()
context "animationDistanceThreshold", ->
it "passes if a number", ->
@setup({animationDistanceThreshold: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({animationDistanceThreshold: {foo: "bar"}})
@expectValidationFails("be a number")
@expectValidationFails("the value was: \`{\"foo\":\"bar\"}\`")
context "baseUrl", ->
it "passes if begins with http://", ->
@setup({baseUrl: "http://example.com"})
@expectValidationPasses()
it "passes if begins with https://", ->
@setup({baseUrl: "https://example.com"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({baseUrl: false})
@expectValidationFails("be a fully qualified URL")
it "fails if not a fully qualified url", ->
@setup({baseUrl: "localhost"})
@expectValidationFails("be a fully qualified URL")
context "chromeWebSecurity", ->
it "passes if a boolean", ->
@setup({chromeWebSecurity: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({chromeWebSecurity: 42})
@expectValidationFails("be a boolean")
@expectValidationFails("the value was: `42`")
context "modifyObstructiveCode", ->
it "passes if a boolean", ->
@setup({modifyObstructiveCode: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({modifyObstructiveCode: 42})
@expectValidationFails("be a boolean")
@expectValidationFails("the value was: `42`")
context "defaultCommandTimeout", ->
it "passes if a number", ->
@setup({defaultCommandTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({defaultCommandTimeout: "foo"})
@expectValidationFails("be a number")
@expectValidationFails("the value was: `\"foo\"`")
context "env", ->
it "passes if an object", ->
@setup({env: {}})
@expectValidationPasses()
it "fails if not an object", ->
@setup({env: "not an object that's for sure"})
@expectValidationFails("a plain object")
context "execTimeout", ->
it "passes if a number", ->
@setup({execTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({execTimeout: "foo"})
@expectValidationFails("be a number")
context "taskTimeout", ->
it "passes if a number", ->
@setup({taskTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({taskTimeout: "foo"})
@expectValidationFails("be a number")
context "fileServerFolder", ->
it "passes if a string", ->
@setup({fileServerFolder: "_files"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({fileServerFolder: true})
@expectValidationFails("be a string")
@expectValidationFails("the value was: `true`")
context "fixturesFolder", ->
it "passes if a string", ->
@setup({fixturesFolder: "_fixtures"})
@expectValidationPasses()
it "passes if false", ->
@setup({fixturesFolder: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({fixturesFolder: true})
@expectValidationFails("be a string or false")
context "ignoreTestFiles", ->
it "passes if a string", ->
@setup({ignoreTestFiles: "*.jsx"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({ignoreTestFiles: ["*.jsx"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({ignoreTestFiles: 5})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({ignoreTestFiles: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "integrationFolder", ->
it "passes if a string", ->
@setup({integrationFolder: "_tests"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({integrationFolder: true})
@expectValidationFails("be a string")
context "userAgent", ->
it "passes if a string", ->
@setup({userAgent: "_tests"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({userAgent: true})
@expectValidationFails("be a string")
context "numTestsKeptInMemory", ->
it "passes if a number", ->
@setup({numTestsKeptInMemory: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({numTestsKeptInMemory: "foo"})
@expectValidationFails("be a number")
context "pageLoadTimeout", ->
it "passes if a number", ->
@setup({pageLoadTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({pageLoadTimeout: "foo"})
@expectValidationFails("be a number")
context "pluginsFile", ->
it "passes if a string", ->
@setup({pluginsFile: "cypress/plugins"})
@expectValidationPasses()
it "passes if false", ->
@setup({pluginsFile: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({pluginsFile: 42})
@expectValidationFails("be a string")
context "port", ->
it "passes if a number", ->
@setup({port: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({port: "foo"})
@expectValidationFails("be a number")
context "reporter", ->
it "passes if a string", ->
@setup({reporter: "_custom"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({reporter: true})
@expectValidationFails("be a string")
context "requestTimeout", ->
it "passes if a number", ->
@setup({requestTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({requestTimeout: "foo"})
@expectValidationFails("be a number")
context "responseTimeout", ->
it "passes if a number", ->
@setup({responseTimeout: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({responseTimeout: "foo"})
@expectValidationFails("be a number")
context "testFiles", ->
it "passes if a string", ->
@setup({testFiles: "**/*.coffee"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({testFiles: ["**/*.coffee", "**/*.jsx"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({testFiles: 42})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({testFiles: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "supportFile", ->
it "passes if a string", ->
@setup({supportFile: "cypress/support"})
@expectValidationPasses()
it "passes if false", ->
@setup({supportFile: false})
@expectValidationPasses()
it "fails if not a string or false", ->
@setup({supportFile: true})
@expectValidationFails("be a string or false")
context "trashAssetsBeforeRuns", ->
it "passes if a boolean", ->
@setup({trashAssetsBeforeRuns: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({trashAssetsBeforeRuns: 42})
@expectValidationFails("be a boolean")
context "videoCompression", ->
it "passes if a number", ->
@setup({videoCompression: 10})
@expectValidationPasses()
it "passes if false", ->
@setup({videoCompression: false})
@expectValidationPasses()
it "fails if not a number", ->
@setup({videoCompression: "foo"})
@expectValidationFails("be a number or false")
context "video", ->
it "passes if a boolean", ->
@setup({video: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({video: 42})
@expectValidationFails("be a boolean")
context "videoUploadOnPasses", ->
it "passes if a boolean", ->
@setup({videoUploadOnPasses: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({videoUploadOnPasses: 99})
@expectValidationFails("be a boolean")
context "videosFolder", ->
it "passes if a string", ->
@setup({videosFolder: "_videos"})
@expectValidationPasses()
it "fails if not a string", ->
@setup({videosFolder: true})
@expectValidationFails("be a string")
context "viewportHeight", ->
it "passes if a number", ->
@setup({viewportHeight: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({viewportHeight: "foo"})
@expectValidationFails("be a number")
context "viewportWidth", ->
it "passes if a number", ->
@setup({viewportWidth: 10})
@expectValidationPasses()
it "fails if not a number", ->
@setup({viewportWidth: "foo"})
@expectValidationFails("be a number")
context "waitForAnimations", ->
it "passes if a boolean", ->
@setup({waitForAnimations: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({waitForAnimations: 42})
@expectValidationFails("be a boolean")
context "watchForFileChanges", ->
it "passes if a boolean", ->
@setup({watchForFileChanges: false})
@expectValidationPasses()
it "fails if not a boolean", ->
@setup({watchForFileChanges: 42})
@expectValidationFails("be a boolean")
context "blacklistHosts", ->
it "passes if a string", ->
@setup({blacklistHosts: "google.com"})
@expectValidationPasses()
it "passes if an array of strings", ->
@setup({blacklistHosts: ["google.com"]})
@expectValidationPasses()
it "fails if not a string or array", ->
@setup({blacklistHosts: 5})
@expectValidationFails("be a string or an array of strings")
it "fails if not an array of strings", ->
@setup({blacklistHosts: [5]})
@expectValidationFails("be a string or an array of strings")
@expectValidationFails("the value was: `[5]`")
context "firefoxGcInterval", ->
it "passes if a number", ->
@setup({ firefoxGcInterval: 1 })
@expectValidationPasses()
it "passes if null", ->
@setup({ firefoxGcInterval: null })
@expectValidationPasses()
it "passes if correctly shaped object", ->
@setup({ firefoxGcInterval: { runMode: 1, openMode: null } })
@expectValidationPasses()
it "fails if string", ->
@setup({ firefoxGcInterval: 'foo' })
@expectValidationFails("a positive number or null or an object")
it "fails if invalid object", ->
@setup({ firefoxGcInterval: { foo: 'bar' } })
@expectValidationFails("a positive number or null or an object")
context ".getConfigKeys", ->
beforeEach ->
@includes = (key) ->
expect(config.getConfigKeys()).to.include(key)
it "includes blacklistHosts", ->
@includes("blacklistHosts")
context ".resolveConfigValues", ->
beforeEach ->
@expected = (obj) ->
merged = config.resolveConfigValues(obj.config, obj.defaults, obj.resolved)
expect(merged).to.deep.eq(obj.final)
it "sets baseUrl to default", ->
@expected({
config: {baseUrl: null}
defaults: {baseUrl: null}
resolved: {}
final: {
baseUrl: {
value: null
from: "default"
}
}
})
it "sets baseUrl to config", ->
@expected({
config: {baseUrl: "localhost"}
defaults: {baseUrl: null}
resolved: {}
final: {
baseUrl: {
value: "localhost"
from: "config"
}
}
})
it "does not change existing resolved values", ->
@expected({
config: {baseUrl: "localhost"}
defaults: {baseUrl: null}
resolved: {baseUrl: "cli"}
final: {
baseUrl: {
value: "localhost"
from: "cli"
}
}
})
it "ignores values not found in configKeys", ->
@expected({
config: {baseUrl: "localhost", foo: "bar"}
defaults: {baseUrl: null}
resolved: {baseUrl: "cli"}
final: {
baseUrl: {
value: "localhost"
from: "cli"
}
}
})
context ".mergeDefaults", ->
beforeEach ->
@defaults = (prop, value, cfg = {}, options = {}) =>
cfg.projectRoot = "/foo/bar/"
config.mergeDefaults(cfg, options)
.then R.prop(prop)
.then (result) ->
expect(result).to.deep.eq(value)
it "port=null", ->
@defaults "port", null
it "projectId=null", ->
@defaults("projectId", null)
it "autoOpen=false", ->
@defaults "autoOpen", false
it "browserUrl=http://localhost:2020/__/", ->
@defaults "browserUrl", "http://localhost:2020/__/", {port: 2020}
it "proxyUrl=http://localhost:2020", ->
@defaults "proxyUrl", "http://localhost:2020", {port: 2020}
it "namespace=__cypress", ->
@defaults "namespace", "__cypress"
it "baseUrl=http://localhost:8000/app/", ->
@defaults "baseUrl", "http://localhost:8000/app/", {
baseUrl: "http://localhost:8000/app///"
}
it "baseUrl=http://localhost:8000/app/", ->
@defaults "baseUrl", "http://localhost:8000/app/", {
baseUrl: "http://localhost:8000/app//"
}
it "baseUrl=http://localhost:8000/app", ->
@defaults "baseUrl", "http://localhost:8000/app", {
baseUrl: "http://localhost:8000/app"
}
it "baseUrl=http://localhost:8000/", ->
@defaults "baseUrl", "http://localhost:8000/", {
baseUrl: "http://localhost:8000//"
}
it "baseUrl=http://localhost:8000/", ->
@defaults "baseUrl", "http://localhost:8000/", {
baseUrl: "http://localhost:8000/"
}
it "baseUrl=http://localhost:8000", ->
@defaults "baseUrl", "http://localhost:8000", {
baseUrl: "http://localhost:8000"
}
it "javascripts=[]", ->
@defaults "javascripts", []
it "viewportWidth=1000", ->
@defaults "viewportWidth", 1000
it "viewportHeight=660", ->
@defaults "viewportHeight", 660
it "userAgent=null", ->
@defaults("userAgent", null)
it "baseUrl=null", ->
@defaults "baseUrl", null
it "defaultCommandTimeout=4000", ->
@defaults "defaultCommandTimeout", 4000
it "pageLoadTimeout=60000", ->
@defaults "pageLoadTimeout", 60000
it "requestTimeout=5000", ->
@defaults "requestTimeout", 5000
it "responseTimeout=30000", ->
@defaults "responseTimeout", 30000
it "execTimeout=60000", ->
@defaults "execTimeout", 60000
it "waitForAnimations=true", ->
@defaults "waitForAnimations", true
it "animationDistanceThreshold=5", ->
@defaults "animationDistanceThreshold", 5
it "video=true", ->
@defaults "video", true
it "videoCompression=32", ->
@defaults "videoCompression", 32
it "videoUploadOnPasses=true", ->
@defaults "videoUploadOnPasses", true
it "trashAssetsBeforeRuns=32", ->
@defaults "trashAssetsBeforeRuns", true
it "morgan=true", ->
@defaults "morgan", true
it "isTextTerminal=false", ->
@defaults "isTextTerminal", false
it "socketId=null", ->
@defaults "socketId", null
it "reporter=spec", ->
@defaults "reporter", "spec"
it "watchForFileChanges=true", ->
@defaults "watchForFileChanges", true
it "numTestsKeptInMemory=50", ->
@defaults "numTestsKeptInMemory", 50
it "modifyObstructiveCode=true", ->
@defaults "modifyObstructiveCode", true
it "supportFile=false", ->
@defaults "supportFile", false, {supportFile: false}
it "blacklistHosts=null", ->
@defaults("blacklistHosts", null)
it "blacklistHosts=[a,b]", ->
@defaults("blacklistHosts", ["a", "b"], {
blacklistHosts: ["a", "b"]
})
it "blacklistHosts=a|b", ->
@defaults("blacklistHosts", ["a", "b"], {
blacklistHosts: ["a", "b"]
})
it "hosts=null", ->
@defaults("hosts", null)
it "hosts={}", ->
@defaults("hosts", {
foo: "bar"
baz: "quux"
}, {
hosts: {
foo: "bar",
baz: "quux"
}
})
it "resets numTestsKeptInMemory to 0 when runMode", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.numTestsKeptInMemory).to.eq(0)
it "resets watchForFileChanges to false when runMode", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.watchForFileChanges).to.be.false
it "can override morgan in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {morgan: false})
.then (cfg) ->
expect(cfg.morgan).to.be.false
it "can override isTextTerminal in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {isTextTerminal: true})
.then (cfg) ->
expect(cfg.isTextTerminal).to.be.true
it "can override socketId in options", ->
config.mergeDefaults({projectRoot: "/foo/bar/"}, {socketId: 1234})
.then (cfg) ->
expect(cfg.socketId).to.eq(1234)
it "deletes envFile", ->
obj = {
projectRoot: "/foo/bar/"
env: {
foo: "bar"
version: "0.5.2"
}
envFile: {
bar: "baz"
version: "1.0.1"
}
}
config.mergeDefaults(obj)
.then (cfg) ->
expect(cfg.env).to.deep.eq({
foo: "bar"
bar: "baz"
version: "1.0.1"
})
expect(cfg.cypressEnv).to.eq(process.env["CYPRESS_ENV"])
expect(cfg).not.to.have.property("envFile")
it "merges env into @config.env", ->
obj = {
projectRoot: "/foo/bar/"
env: {
host: "localhost"
user: "brian"
version: "0.12.2"
}
}
options = {
env: {
version: "0.13.1"
foo: "bar"
}
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.env).to.deep.eq({
host: "localhost"
user: "brian"
version: "0.13.1"
foo: "bar"
})
describe ".resolved", ->
it "sets reporter and port to cli", ->
obj = {
projectRoot: "/foo/bar"
}
options = {
reporter: "json"
port: 1234
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.resolved).to.deep.eq({
env: { }
projectId: { value: null, from: "default" },
port: { value: 1234, from: "cli" },
hosts: { value: null, from: "default" }
blacklistHosts: { value: null, from: "default" },
browsers: { value: [], from: "default" },
userAgent: { value: null, from: "default" }
reporter: { value: "json", from: "cli" },
reporterOptions: { value: null, from: "default" },
baseUrl: { value: null, from: "default" },
defaultCommandTimeout: { value: 4000, from: "default" },
pageLoadTimeout: { value: 60000, from: "default" },
requestTimeout: { value: 5000, from: "default" },
responseTimeout: { value: 30000, from: "default" },
execTimeout: { value: 60000, from: "default" },
taskTimeout: { value: 60000, from: "default" },
numTestsKeptInMemory: { value: 50, from: "default" },
waitForAnimations: { value: true, from: "default" },
animationDistanceThreshold: { value: 5, from: "default" },
trashAssetsBeforeRuns: { value: true, from: "default" },
watchForFileChanges: { value: true, from: "default" },
modifyObstructiveCode: { value: true, from: "default" },
chromeWebSecurity: { value: true, from: "default" },
viewportWidth: { value: 1000, from: "default" },
viewportHeight: { value: 660, from: "default" },
fileServerFolder: { value: "", from: "default" },
firefoxGcInterval: { value: { openMode: null, runMode: 1 }, from: "default" },
video: { value: true, from: "default" }
videoCompression: { value: 32, from: "default" }
videoUploadOnPasses: { value: true, from: "default" }
videosFolder: { value: "cypress/videos", from: "default" },
supportFile: { value: "cypress/support", from: "default" },
pluginsFile: { value: "cypress/plugins", from: "default" },
fixturesFolder: { value: "cypress/fixtures", from: "default" },
ignoreTestFiles: { value: "*.hot-update.js", from: "default" },
integrationFolder: { value: "cypress/integration", from: "default" },
screenshotsFolder: { value: "cypress/screenshots", from: "default" },
testFiles: { value: "**/*.*", from: "default" },
nodeVersion: { value: "default", from: "default" },
})
it "sets config, envFile and env", ->
sinon.stub(config, "getProcessEnvVars").returns({
quux: "quux"
RECORD_KEY: "PI:KEY:<KEY>END_PI",
CI_KEY: "PI:KEY:<KEY>END_PI",
PROJECT_ID: "projectId123"
})
obj = {
projectRoot: "/foo/bar"
baseUrl: "http://localhost:8080"
port: 2020
env: {
foo: "foo"
}
envFile: {
bar: "bar"
}
}
options = {
env: {
baz: "baz"
}
}
config.mergeDefaults(obj, options)
.then (cfg) ->
expect(cfg.resolved).to.deep.eq({
projectId: { value: "projectId123", from: "env" },
port: { value: 2020, from: "config" },
hosts: { value: null, from: "default" }
blacklistHosts: { value: null, from: "default" }
browsers: { value: [], from: "default" }
userAgent: { value: null, from: "default" }
reporter: { value: "spec", from: "default" },
reporterOptions: { value: null, from: "default" },
baseUrl: { value: "http://localhost:8080", from: "config" },
defaultCommandTimeout: { value: 4000, from: "default" },
pageLoadTimeout: { value: 60000, from: "default" },
requestTimeout: { value: 5000, from: "default" },
responseTimeout: { value: 30000, from: "default" },
execTimeout: { value: 60000, from: "default" },
taskTimeout: { value: 60000, from: "default" },
numTestsKeptInMemory: { value: 50, from: "default" },
waitForAnimations: { value: true, from: "default" },
animationDistanceThreshold: { value: 5, from: "default" },
trashAssetsBeforeRuns: { value: true, from: "default" },
watchForFileChanges: { value: true, from: "default" },
modifyObstructiveCode: { value: true, from: "default" },
chromeWebSecurity: { value: true, from: "default" },
viewportWidth: { value: 1000, from: "default" },
viewportHeight: { value: 660, from: "default" },
fileServerFolder: { value: "", from: "default" },
video: { value: true, from: "default" }
videoCompression: { value: 32, from: "default" }
videoUploadOnPasses: { value: true, from: "default" }
videosFolder: { value: "cypress/videos", from: "default" },
supportFile: { value: "cypress/support", from: "default" },
pluginsFile: { value: "cypress/plugins", from: "default" },
firefoxGcInterval: { value: { openMode: null, runMode: 1 }, from: "default" },
fixturesFolder: { value: "cypress/fixtures", from: "default" },
ignoreTestFiles: { value: "*.hot-update.js", from: "default" },
integrationFolder: { value: "cypress/integration", from: "default" },
screenshotsFolder: { value: "cypress/screenshots", from: "default" },
testFiles: { value: "**/*.*", from: "default" },
nodeVersion: { value: "default", from: "default" },
env: {
foo: {
value: "foo"
from: "config"
}
bar: {
value: "bar"
from: "envFile"
}
baz: {
value: "baz"
from: "cli"
}
quux: {
value: "quux"
from: "env"
}
RECORD_KEY: {
value: "PI:KEY:<KEY>END_PI",
from: "env"
}
CI_KEY: {
value: "PI:KEY:<KEY>END_PI",
from: "env"
}
}
})
context ".setPluginResolvedOn", ->
it "resolves an object with single property", ->
cfg = {}
obj = {
foo: "bar"
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg).to.deep.eq({
foo: {
value: "bar",
from: "plugin"
}
})
it "resolves an object with multiple properties", ->
cfg = {}
obj = {
foo: "bar",
baz: [1, 2, 3]
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg).to.deep.eq({
foo: {
value: "bar",
from: "plugin"
},
baz: {
value: [1, 2, 3],
from: "plugin"
}
})
it "resolves a nested object", ->
# we need at least the structure
cfg = {
foo: {
bar: 1
}
}
obj = {
foo: {
bar: 42
}
}
config.setPluginResolvedOn(cfg, obj)
expect(cfg, "foo.bar gets value").to.deep.eq({
foo: {
bar: {
value: 42,
from: "plugin"
}
}
})
context "_.defaultsDeep", ->
it "merges arrays", ->
# sanity checks to confirm how Lodash merges arrays in defaultsDeep
diffs = {
list: [1]
}
cfg = {
list: [1, 2]
}
merged = _.defaultsDeep({}, diffs, cfg)
expect(merged, "arrays are combined").to.deep.eq({
list: [1, 2]
})
context ".updateWithPluginValues", ->
it "is noop when no overrides", ->
expect(config.updateWithPluginValues({foo: 'bar'}, null)).to.deep.eq({
foo: 'bar'
})
it "is noop with empty overrides", ->
expect(config.updateWithPluginValues({foo: 'bar'}, {})).to.deep.eq({
foo: 'bar'
})
it "updates resolved config values and returns config with overrides", ->
cfg = {
foo: "bar"
baz: "quux"
quux: "foo"
lol: 1234
env: {
a: "a"
b: "b"
}
# previously resolved values
resolved: {
foo: { value: "bar", from: "default" }
baz: { value: "quux", from: "cli" }
quux: { value: "foo", from: "default" }
lol: { value: 1234, from: "env" }
env: {
a: { value: "a", from: "config" }
b: { value: "b", from: "config" }
}
}
}
overrides = {
baz: "baz"
quux: ["bar", "quux"]
env: {
b: "bb"
c: "c"
}
}
expect(config.updateWithPluginValues(cfg, overrides)).to.deep.eq({
foo: "bar"
baz: "baz"
lol: 1234
quux: ["bar", "quux"]
env: {
a: "a"
b: "bb"
c: "c"
}
resolved: {
foo: { value: "bar", from: "default" }
baz: { value: "baz", from: "plugin" }
quux: { value: ["bar", "quux"], from: "plugin" }
lol: { value: 1234, from: "env" }
env: {
a: { value: "a", from: "config" }
b: { value: "bb", from: "plugin" }
c: { value: "c", from: "plugin" }
}
}
})
it "keeps the list of browsers if the plugins returns empty object", ->
browser = {
name: "fake browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
cfg = {
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
}
overrides = {}
expect(config.updateWithPluginValues(cfg, overrides)).to.deep.eq({
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
})
it "catches browsers=null returned from plugins", ->
browser = {
name: "PI:NAME:<NAME>END_PI browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
cfg = {
browsers: [browser],
resolved: {
browsers: {
value: [browser],
from: "default"
}
}
}
overrides = {
browsers: null
}
sinon.stub(errors, "throw")
config.updateWithPluginValues(cfg, overrides)
expect(errors.throw).to.have.been.calledWith("CONFIG_VALIDATION_ERROR")
it "allows user to filter browsers", ->
browserOne = {
name: "PI:NAME:<NAME>END_PI browser name",
family: "chromium",
displayName: "My browser",
version: "x.y.z",
path: "/path/to/browser",
majorVersion: "x"
}
browserTwo = {
name: "fake electron",
family: "chromium",
displayName: "Electron",
version: "x.y.z",
# Electron browser is built-in, no external path
path: "",
majorVersion: "x"
}
cfg = {
browsers: [browserOne, browserTwo],
resolved: {
browsers: {
value: [browserOne, browserTwo],
from: "default"
}
}
}
overrides = {
browsers: [browserTwo]
}
updated = config.updateWithPluginValues(cfg, overrides)
expect(updated.resolved, "resolved values").to.deep.eq({
browsers: {
value: [browserTwo],
from: 'plugin'
}
})
expect(updated, "all values").to.deep.eq({
browsers: [browserTwo],
resolved: {
browsers: {
value: [browserTwo],
from: 'plugin'
}
}
})
context ".parseEnv", ->
it "merges together env from config, env from file, env from process, and env from CLI", ->
sinon.stub(config, "getProcessEnvVars").returns({
version: "0.12.1",
user: "bob",
})
obj = {
env: {
version: "0.10.9"
project: "todos"
host: "localhost"
baz: "quux"
}
envFile: {
host: "http://localhost:8888"
user: "brian"
foo: "bar"
}
}
envCLI = {
version: "0.14.0"
project: "pie"
}
expect(config.parseEnv(obj, envCLI)).to.deep.eq({
version: "0.14.0"
project: "pie"
host: "http://localhost:8888"
user: "bob"
foo: "bar"
baz: "quux"
})
context ".getProcessEnvVars", ->
["cypress_", "CYPRESS_"].forEach (key) ->
it "reduces key: #{key}", ->
obj = {
cypress_host: "http://localhost:8888"
foo: "bar"
env: "123"
}
obj[key + "version"] = "0.12.0"
expect(config.getProcessEnvVars(obj)).to.deep.eq({
host: "http://localhost:8888"
version: "0.12.0"
})
it "does not merge reserved environment variables", ->
obj = {
CYPRESS_ENV: "production"
CYPRESS_FOO: "bar"
CYPRESS_CRASH_REPORTS: "0"
CYPRESS_PROJECT_ID: "abc123"
}
expect(config.getProcessEnvVars(obj)).to.deep.eq({
FOO: "bar"
PROJECT_ID: "abc123"
CRASH_REPORTS: 0
})
context ".setUrls", ->
it "does not mutate existing obj", ->
obj = {}
expect(config.setUrls(obj)).not.to.eq(obj)
it "uses baseUrl when set", ->
obj = {
port: 65432
baseUrl: "https://www.google.com"
clientRoute: "/__/"
}
urls = config.setUrls(obj)
expect(urls.browserUrl).to.eq("https://www.google.com/__/")
expect(urls.proxyUrl).to.eq("http://localhost:65432")
it "strips baseUrl to host when set", ->
obj = {
port: 65432
baseUrl: "http://localhost:9999/app/?foo=bar#index.html"
clientRoute: "/__/"
}
urls = config.setUrls(obj)
expect(urls.browserUrl).to.eq("http://localhost:9999/__/")
expect(urls.proxyUrl).to.eq("http://localhost:65432")
context ".setScaffoldPaths", ->
it "sets integrationExamplePath + integrationExampleName + scaffoldedFiles", ->
obj = {
integrationFolder: "/_test-output/path/to/project/cypress/integration"
}
sinon.stub(scaffold, "fileTree").resolves([])
config.setScaffoldPaths(obj).then (result) ->
expect(result).to.deep.eq({
integrationFolder: "/_test-output/path/to/project/cypress/integration"
integrationExamplePath: "/_test-output/path/to/project/cypress/integration/examples"
integrationExampleName: "examples"
scaffoldedFiles: []
})
context ".setSupportFileAndFolder", ->
it "does nothing if supportFile is falsey", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql(obj)
it "sets the full path to the supportFile and supportFolder if it exists", ->
projectRoot = process.cwd()
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "test/unit/config_spec.coffee"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: "#{projectRoot}/test/unit/config_spec.coffee"
supportFolder: "#{projectRoot}/test/unit"
})
it "sets the supportFile to default index.js if it does not exist, support folder does not exist, and supportFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/no-scaffolding")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "cypress/support"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: "#{projectRoot}/cypress/support/index.js"
supportFolder: "#{projectRoot}/cypress/support"
})
it "sets the supportFile to false if it does not exist, support folder exists, and supportFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/empty-folders")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "cypress/support"
})
config.setSupportFileAndFolder(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
supportFile: false
})
it "throws error if supportFile is not default and does not exist", ->
projectRoot = process.cwd()
obj = config.setAbsolutePaths({
projectRoot: projectRoot
supportFile: "does/not/exist"
})
config.setSupportFileAndFolder(obj)
.catch (err) ->
expect(err.message).to.include("The support file is missing or invalid.")
context ".setPluginsFile", ->
it "does nothing if pluginsFile is falsey", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql(obj)
it "sets the pluginsFile to default index.js if does not exist", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/no-scaffolding")
obj = {
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins"
}
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins/index.js"
})
it "set the pluginsFile to false if it does not exist, plugins folder exists, and pluginsFile is the default", ->
projectRoot = path.join(process.cwd(), "test/support/fixtures/projects/empty-folders")
obj = config.setAbsolutePaths({
projectRoot: projectRoot
pluginsFile: "#{projectRoot}/cypress/plugins"
})
config.setPluginsFile(obj)
.then (result) ->
expect(result).to.eql({
projectRoot: projectRoot
pluginsFile: false
})
it "throws error if pluginsFile is not default and does not exist", ->
projectRoot = process.cwd()
obj = {
projectRoot: projectRoot
pluginsFile: "does/not/exist"
}
config.setPluginsFile(obj)
.catch (err) ->
expect(err.message).to.include("The plugins file is missing or invalid.")
context ".setParentTestsPaths", ->
it "sets parentTestsFolder and parentTestsFolderDisplay", ->
obj = {
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/cypress/integration"
}
expect(config.setParentTestsPaths(obj)).to.deep.eq({
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/cypress/integration"
parentTestsFolder: "/_test-output/path/to/project/cypress"
parentTestsFolderDisplay: "project/cypress"
})
it "sets parentTestsFolderDisplay to parentTestsFolder if they are the same", ->
obj = {
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/tests"
}
expect(config.setParentTestsPaths(obj)).to.deep.eq({
projectRoot: "/_test-output/path/to/project"
integrationFolder: "/_test-output/path/to/project/tests"
parentTestsFolder: "/_test-output/path/to/project"
parentTestsFolderDisplay: "project"
})
context ".setAbsolutePaths", ->
it "is noop without projectRoot", ->
expect(config.setAbsolutePaths({})).to.deep.eq({})
# it "resolves fileServerFolder with projectRoot", ->
# obj = {
# projectRoot: "/_test-output/path/to/project"
# fileServerFolder: "foo"
# }
# expect(config.setAbsolutePaths(obj)).to.deep.eq({
# projectRoot: "/_test-output/path/to/project"
# fileServerFolder: "/_test-output/path/to/project/foo"
# })
it "does not mutate existing obj", ->
obj = {}
expect(config.setAbsolutePaths(obj)).not.to.eq(obj)
it "ignores non special *folder properties", ->
obj = {
projectRoot: "/_test-output/path/to/project"
blehFolder: "some/rando/path"
foo: "bar"
baz: "quux"
}
expect(config.setAbsolutePaths(obj)).to.deep.eq(obj)
["fileServerFolder", "fixturesFolder", "integrationFolder", "unitFolder", "supportFile", "pluginsFile"].forEach (folder) ->
it "converts relative #{folder} to absolute path", ->
obj = {
projectRoot: "/_test-output/path/to/project"
}
obj[folder] = "foo/bar"
expected = {
projectRoot: "/_test-output/path/to/project"
}
expected[folder] = "/_test-output/path/to/project/foo/bar"
expect(config.setAbsolutePaths(obj)).to.deep.eq(expected)
context ".setNodeBinary", ->
beforeEach ->
@findSystemNode = sinon.stub(findSystemNode, "findNodePathAndVersion")
@nodeVersion = process.versions.node
it "sets current Node ver if nodeVersion != system", ->
config.setNodeBinary({
nodeVersion: undefined
})
.then (obj) =>
expect(@findSystemNode).to.not.be.called
expect(obj).to.deep.eq({
nodeVersion: undefined,
resolvedNodeVersion: @nodeVersion
})
it "sets found Node ver if nodeVersion = system and findNodePathAndVersion resolves", ->
@findSystemNode.resolves({
path: '/foo/bar/node',
version: '1.2.3'
})
config.setNodeBinary({
nodeVersion: "system"
})
.then (obj) =>
expect(@findSystemNode).to.be.calledOnce
expect(obj).to.deep.eq({
nodeVersion: "system",
resolvedNodeVersion: "1.2.3",
resolvedNodePath: "/foo/bar/node"
})
it "sets current Node ver and warns if nodeVersion = system and findNodePathAndVersion rejects", ->
err = new Error()
onWarning = sinon.stub()
@findSystemNode.rejects(err)
config.setNodeBinary({
nodeVersion: "system"
}, onWarning)
.then (obj) =>
expect(@findSystemNode).to.be.calledOnce
expect(onWarning).to.be.calledOnce
expect(obj).to.deep.eq({
nodeVersion: "system",
resolvedNodeVersion: @nodeVersion,
})
expect(obj.resolvedNodePath).to.be.undefined
describe "lib/util/config", ->
context ".isDefault", ->
it "returns true if value is default value", ->
settings = {baseUrl: null}
defaults = {baseUrl: null}
resolved = {}
merged = config.setResolvedConfigValues(settings, defaults, resolved)
expect(configUtil.isDefault(merged, "baseUrl")).to.be.true
it "returns false if value is not default value", ->
settings = {baseUrl: null}
defaults = {baseUrl: "http://localhost:8080"}
resolved = {}
merged = config.setResolvedConfigValues(settings, defaults, resolved)
expect(configUtil.isDefault(merged, "baseUrl")).to.be.false
|
[
{
"context": "oadImageFields: {\n 'authenticity_token': '#image_upload_auth_token'\n }\n imageUploadCallb",
"end": 432,
"score": 0.45082542300224304,
"start": 427,
"tag": "PASSWORD",
"value": "image"
}
] | app/assets/javascripts/redactor_page_field.js.coffee | ndlib/honeycomb | 5 | class RedactorPageField
constructor: (@fieldElement) ->
if @fieldElement.length > 0
@setupField()
setupField: ->
@fieldElement.redactor({
focus: true
formatting: ['p', 'blockquote', 'h3', 'h4', 'h5']
imageUpload: '/v1/collections/' + $("#image_collection_unique_id").val() + '/items'
imageUploadParam: 'item[uploaded_image]'
uploadImageFields: {
'authenticity_token': '#image_upload_auth_token'
}
imageUploadCallback: (image, json) ->
if json.errors
EventEmitter.emit("MessageCenterDisplay", "warning", "Error Uploading Image")
else
$(image).attr 'alt', json.name
$(image).attr 'title', json.name
$(image).attr 'item_id', json.id
$(image).attr 'src', json.image['thumbnail/medium']['contentUrl']
imageManagerJson: '/v1/collections/' + $("#image_collection_unique_id").val() + '/items'
plugins: ['imagemanager', 'source', 'scriptbuttons']
})
jQuery ->
setupRedactor = ->
field = $(".honeycomb_image_redactor")
if field.size() > 0
new RedactorPageField(field)
ready = ->
setupRedactor()
$(document).ready ->
ready()
| 54812 | class RedactorPageField
constructor: (@fieldElement) ->
if @fieldElement.length > 0
@setupField()
setupField: ->
@fieldElement.redactor({
focus: true
formatting: ['p', 'blockquote', 'h3', 'h4', 'h5']
imageUpload: '/v1/collections/' + $("#image_collection_unique_id").val() + '/items'
imageUploadParam: 'item[uploaded_image]'
uploadImageFields: {
'authenticity_token': '#<PASSWORD>_upload_auth_token'
}
imageUploadCallback: (image, json) ->
if json.errors
EventEmitter.emit("MessageCenterDisplay", "warning", "Error Uploading Image")
else
$(image).attr 'alt', json.name
$(image).attr 'title', json.name
$(image).attr 'item_id', json.id
$(image).attr 'src', json.image['thumbnail/medium']['contentUrl']
imageManagerJson: '/v1/collections/' + $("#image_collection_unique_id").val() + '/items'
plugins: ['imagemanager', 'source', 'scriptbuttons']
})
jQuery ->
setupRedactor = ->
field = $(".honeycomb_image_redactor")
if field.size() > 0
new RedactorPageField(field)
ready = ->
setupRedactor()
$(document).ready ->
ready()
| true | class RedactorPageField
constructor: (@fieldElement) ->
if @fieldElement.length > 0
@setupField()
setupField: ->
@fieldElement.redactor({
focus: true
formatting: ['p', 'blockquote', 'h3', 'h4', 'h5']
imageUpload: '/v1/collections/' + $("#image_collection_unique_id").val() + '/items'
imageUploadParam: 'item[uploaded_image]'
uploadImageFields: {
'authenticity_token': '#PI:PASSWORD:<PASSWORD>END_PI_upload_auth_token'
}
imageUploadCallback: (image, json) ->
if json.errors
EventEmitter.emit("MessageCenterDisplay", "warning", "Error Uploading Image")
else
$(image).attr 'alt', json.name
$(image).attr 'title', json.name
$(image).attr 'item_id', json.id
$(image).attr 'src', json.image['thumbnail/medium']['contentUrl']
imageManagerJson: '/v1/collections/' + $("#image_collection_unique_id").val() + '/items'
plugins: ['imagemanager', 'source', 'scriptbuttons']
})
jQuery ->
setupRedactor = ->
field = $(".honeycomb_image_redactor")
if field.size() > 0
new RedactorPageField(field)
ready = ->
setupRedactor()
$(document).ready ->
ready()
|
[
{
"context": "e './views/ChromeView'\n\n\n username = Cookie.get(\"username\")\n password = Cookie.get(\"password\")\n\n Coconut.",
"end": 1564,
"score": 0.9986053109169006,
"start": 1556,
"tag": "USERNAME",
"value": "username"
},
{
"context": "= Cookie.get(\"username\")\n passwo... | _attachments/app/start.coffee | jongoz/coconut-analytice | 3 | # This is the entry point for creating bundle.js
# Only packages that get required here or inside the packages that are required here will be included in bundle.js
# New packages are added to the node_modules directory by doing npm install --save package-name
# Make these global so that they can be used from the javascript console
global.$ = require 'jquery'
global._ = require 'underscore'
global.Backbone = require 'backbone'
Backbone.$ = $
global.PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-upsert'))
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
BackbonePouch = require 'backbone-pouch'
moment = require 'moment'
require 'material-design-lite'
global.Cookies = require 'js-cookie'
# These are local .coffee files
global.Coconut = new (require './Coconut')
global.Env = {
# is_chrome: /chrome/i.test(navigator.userAgent)
is_chrome: /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)
}
Coconut.promptUntilCredentialsWork().then =>
global.HTMLHelpers = require './HTMLHelpers'
User = require './models/User'
MenuView = require './views/MenuView'
Config = require './models/Config'
Router = require './Router'
HeaderView = require './views/HeaderView'
GeoHierarchyClass = require './models/GeoHierarchy'
DhisOrganisationUnits = require './models/DhisOrganisationUnits'
QuestionCollection = require './models/QuestionCollection'
Dhis2 = require './models/Dhis2'
ChromeView = require './views/ChromeView'
username = Cookie.get("username")
password = Cookie.get("password")
Coconut.plainCouchURL = Coconut.database.name.replace(/\/\/.*@/,"//").replace(/[^\/]+$/, "")
# This sets a couchdb session which is necessary for lists, aka spreadsheet downloads
fetch "#{Coconut.plainCouchURL}/_session",
method: 'POST',
credentials: 'include',
headers:
'content-type': 'application/json',
authorization: "Basic #{btoa("#{username}:#{password}")}"
body: JSON.stringify({name: username, password: password})
global.Router = require './Router'
Coconut.router = new Router(require './AppView')
# This is a PouchDB - Backbone connector - we only use it for a few things like getting the list of questions
Backbone.sync = BackbonePouch.sync
db: Coconut.database
fetch: 'query'
Backbone.Model.prototype.idAttribute = '_id'
checkBrowser = (callback) ->
if !Env.is_chrome
chromeView = new ChromeView()
chromeView.render()
callback?.success()
else
callback?.success()
User.isAuthenticated
success: ->
$('header.coconut-header').show()
$('div.coconut-drawer').show()
error: (err) ->
console.log(err)
# Render headerView here instead of below with MenuView, otherwise the hamburger menu will be missing in smaller screen
Coconut.headerView = new HeaderView
Coconut.headerView.render()
Config.getConfig
error: ->
console.log("Error Retrieving Config")
success: ->
Config.getLogoUrl()
.catch (error) ->
console.error "Logo Url not setup"
console.error error
.then (url) ->
Coconut.logoUrl = url
Coconut.menuView = new MenuView
Coconut.menuView.render()
_(["shehias_high_risk","shehias_received_irs"]).each (docId) ->
Coconut.database.get docId
.catch (error) -> console.error error
.then (result) ->
Coconut[docId] = result
global.GeoHierarchy = new GeoHierarchyClass()
global.FacilityHierarchy = GeoHierarchy # These have been combined
await GeoHierarchy.load()
Coconut.questions = new QuestionCollection()
Coconut.questions.fetch
error: (error) -> console.error error
success: ->
Coconut.CaseClassifications = Coconut.questions.get("Household Members").questions().filter( (question) =>
question.get("label") is "Case Category"
)[0].get("radio-options").split(/, */)
Coconut.database.allDocs
startkey: "user"
endkey: "user\uf000"
include_docs: true
.then (result) =>
Coconut.nameByUsername = {}
for row in result.rows
Coconut.nameByUsername[row.id.replace(/user./,"")] = row.doc.name
Backbone.history.start()
checkBrowser()
global.Issues = require './models/Issues'
| 48160 | # This is the entry point for creating bundle.js
# Only packages that get required here or inside the packages that are required here will be included in bundle.js
# New packages are added to the node_modules directory by doing npm install --save package-name
# Make these global so that they can be used from the javascript console
global.$ = require 'jquery'
global._ = require 'underscore'
global.Backbone = require 'backbone'
Backbone.$ = $
global.PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-upsert'))
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
BackbonePouch = require 'backbone-pouch'
moment = require 'moment'
require 'material-design-lite'
global.Cookies = require 'js-cookie'
# These are local .coffee files
global.Coconut = new (require './Coconut')
global.Env = {
# is_chrome: /chrome/i.test(navigator.userAgent)
is_chrome: /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)
}
Coconut.promptUntilCredentialsWork().then =>
global.HTMLHelpers = require './HTMLHelpers'
User = require './models/User'
MenuView = require './views/MenuView'
Config = require './models/Config'
Router = require './Router'
HeaderView = require './views/HeaderView'
GeoHierarchyClass = require './models/GeoHierarchy'
DhisOrganisationUnits = require './models/DhisOrganisationUnits'
QuestionCollection = require './models/QuestionCollection'
Dhis2 = require './models/Dhis2'
ChromeView = require './views/ChromeView'
username = Cookie.get("username")
password = Cookie.get("<PASSWORD>")
Coconut.plainCouchURL = Coconut.database.name.replace(/\/\/.*@/,"//").replace(/[^\/]+$/, "")
# This sets a couchdb session which is necessary for lists, aka spreadsheet downloads
fetch "#{Coconut.plainCouchURL}/_session",
method: 'POST',
credentials: 'include',
headers:
'content-type': 'application/json',
authorization: "Basic #{btoa("#{username}:#{password}")}"
body: JSON.stringify({name: username, password: <PASSWORD>})
global.Router = require './Router'
Coconut.router = new Router(require './AppView')
# This is a PouchDB - Backbone connector - we only use it for a few things like getting the list of questions
Backbone.sync = BackbonePouch.sync
db: Coconut.database
fetch: 'query'
Backbone.Model.prototype.idAttribute = '_id'
checkBrowser = (callback) ->
if !Env.is_chrome
chromeView = new ChromeView()
chromeView.render()
callback?.success()
else
callback?.success()
User.isAuthenticated
success: ->
$('header.coconut-header').show()
$('div.coconut-drawer').show()
error: (err) ->
console.log(err)
# Render headerView here instead of below with MenuView, otherwise the hamburger menu will be missing in smaller screen
Coconut.headerView = new HeaderView
Coconut.headerView.render()
Config.getConfig
error: ->
console.log("Error Retrieving Config")
success: ->
Config.getLogoUrl()
.catch (error) ->
console.error "Logo Url not setup"
console.error error
.then (url) ->
Coconut.logoUrl = url
Coconut.menuView = new MenuView
Coconut.menuView.render()
_(["shehias_high_risk","shehias_received_irs"]).each (docId) ->
Coconut.database.get docId
.catch (error) -> console.error error
.then (result) ->
Coconut[docId] = result
global.GeoHierarchy = new GeoHierarchyClass()
global.FacilityHierarchy = GeoHierarchy # These have been combined
await GeoHierarchy.load()
Coconut.questions = new QuestionCollection()
Coconut.questions.fetch
error: (error) -> console.error error
success: ->
Coconut.CaseClassifications = Coconut.questions.get("Household Members").questions().filter( (question) =>
question.get("label") is "Case Category"
)[0].get("radio-options").split(/, */)
Coconut.database.allDocs
startkey: "user"
endkey: "<KEY>"
include_docs: true
.then (result) =>
Coconut.nameByUsername = {}
for row in result.rows
Coconut.nameByUsername[row.id.replace(/user./,"")] = row.doc.name
Backbone.history.start()
checkBrowser()
global.Issues = require './models/Issues'
| true | # This is the entry point for creating bundle.js
# Only packages that get required here or inside the packages that are required here will be included in bundle.js
# New packages are added to the node_modules directory by doing npm install --save package-name
# Make these global so that they can be used from the javascript console
global.$ = require 'jquery'
global._ = require 'underscore'
global.Backbone = require 'backbone'
Backbone.$ = $
global.PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-upsert'))
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
BackbonePouch = require 'backbone-pouch'
moment = require 'moment'
require 'material-design-lite'
global.Cookies = require 'js-cookie'
# These are local .coffee files
global.Coconut = new (require './Coconut')
global.Env = {
# is_chrome: /chrome/i.test(navigator.userAgent)
is_chrome: /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)
}
Coconut.promptUntilCredentialsWork().then =>
global.HTMLHelpers = require './HTMLHelpers'
User = require './models/User'
MenuView = require './views/MenuView'
Config = require './models/Config'
Router = require './Router'
HeaderView = require './views/HeaderView'
GeoHierarchyClass = require './models/GeoHierarchy'
DhisOrganisationUnits = require './models/DhisOrganisationUnits'
QuestionCollection = require './models/QuestionCollection'
Dhis2 = require './models/Dhis2'
ChromeView = require './views/ChromeView'
username = Cookie.get("username")
password = Cookie.get("PI:PASSWORD:<PASSWORD>END_PI")
Coconut.plainCouchURL = Coconut.database.name.replace(/\/\/.*@/,"//").replace(/[^\/]+$/, "")
# This sets a couchdb session which is necessary for lists, aka spreadsheet downloads
fetch "#{Coconut.plainCouchURL}/_session",
method: 'POST',
credentials: 'include',
headers:
'content-type': 'application/json',
authorization: "Basic #{btoa("#{username}:#{password}")}"
body: JSON.stringify({name: username, password: PI:PASSWORD:<PASSWORD>END_PI})
global.Router = require './Router'
Coconut.router = new Router(require './AppView')
# This is a PouchDB - Backbone connector - we only use it for a few things like getting the list of questions
Backbone.sync = BackbonePouch.sync
db: Coconut.database
fetch: 'query'
Backbone.Model.prototype.idAttribute = '_id'
checkBrowser = (callback) ->
if !Env.is_chrome
chromeView = new ChromeView()
chromeView.render()
callback?.success()
else
callback?.success()
User.isAuthenticated
success: ->
$('header.coconut-header').show()
$('div.coconut-drawer').show()
error: (err) ->
console.log(err)
# Render headerView here instead of below with MenuView, otherwise the hamburger menu will be missing in smaller screen
Coconut.headerView = new HeaderView
Coconut.headerView.render()
Config.getConfig
error: ->
console.log("Error Retrieving Config")
success: ->
Config.getLogoUrl()
.catch (error) ->
console.error "Logo Url not setup"
console.error error
.then (url) ->
Coconut.logoUrl = url
Coconut.menuView = new MenuView
Coconut.menuView.render()
_(["shehias_high_risk","shehias_received_irs"]).each (docId) ->
Coconut.database.get docId
.catch (error) -> console.error error
.then (result) ->
Coconut[docId] = result
global.GeoHierarchy = new GeoHierarchyClass()
global.FacilityHierarchy = GeoHierarchy # These have been combined
await GeoHierarchy.load()
Coconut.questions = new QuestionCollection()
Coconut.questions.fetch
error: (error) -> console.error error
success: ->
Coconut.CaseClassifications = Coconut.questions.get("Household Members").questions().filter( (question) =>
question.get("label") is "Case Category"
)[0].get("radio-options").split(/, */)
Coconut.database.allDocs
startkey: "user"
endkey: "PI:KEY:<KEY>END_PI"
include_docs: true
.then (result) =>
Coconut.nameByUsername = {}
for row in result.rows
Coconut.nameByUsername[row.id.replace(/user./,"")] = row.doc.name
Backbone.history.start()
checkBrowser()
global.Issues = require './models/Issues'
|
[
{
"context": "p.EventEmitter.fromEmitArgs(['my:event', { key1: 'value1', key2: 'value2' }])\n expect(emitter.event",
"end": 549,
"score": 0.9678554534912109,
"start": 543,
"tag": "KEY",
"value": "value1"
},
{
"context": "romEmitArgs(['my:event', { key1: 'value1', key2: 'value2... | spec/unpoly/classes/event_emitter_spec.coffee | apollo13/unpoly | 1,129 | describe 'up.EventEmitter', ->
describe '.fromEmitArgs', ->
describe 'with ([String])', ->
it 'builds an event with the given name, which emits on the document', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(document)
describe 'with ([String, Object])', ->
it 'builds an event with the given name and props, which emits on the document', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event', { key1: 'value1', key2: 'value2' }])
expect(emitter.event).toBeEvent('my:event', key1: 'value1', key2: 'value2')
expect(emitter.target).toBe(document)
describe 'with ([String, Object], Object)', ->
it 'builds an event with the given name and props, defaulting to options from the second argument', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event', { key1: 'value1' }], { key2: 'value2' })
expect(emitter.event).toBeEvent('my:event', key1: 'value1', key2: 'value2')
expect(emitter.target).toBe(document)
describe 'with ([Element, String])', ->
it 'builds an event with the given name, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([up.Layer, String])', ->
it "builds an event with the given name, which emits on the given layer's element, setting the current layer to that layer", (done) ->
up.layer.open(content: 'content').then (layer) ->
emitter = up.EventEmitter.fromEmitArgs([layer, 'my:event'])
expect(emitter.event).toBeEvent('my:event', layer: layer) # has { layer } property for event listeners
expect(emitter.target).toBe(layer.element)
expect(emitter.baseLayer).toBe(layer) # this will set up.layer.current during event emission
done()
describe 'with ([Element, String, Object])', ->
it 'builds an event with the given name and props, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event', { key1: 'value1', key2: 'value2' }])
expect(emitter.event).toBeEvent('my:event', key1: 'value1', key2: 'value2')
expect(emitter.target).toBe(element)
describe 'with ([Element, String])', ->
it 'builds an event with the given name, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([Event])', ->
it "emits the given event on the document", ->
event = up.event.build('my:event')
emitter = up.EventEmitter.fromEmitArgs([event])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
describe 'with ([Element, Event])', ->
it "emits the given event on the given element", ->
element = fixture('.element')
event = up.event.build('my:event')
emitter = up.EventEmitter.fromEmitArgs([element, event])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(element)
describe 'with ([Event, Object])', ->
it "emits the given event on the document, using the given options for emission", ->
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([event, { callback }])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
expect(emitter.callback).toBe(callback)
describe 'with ([Event, Object], Object)', ->
it "emits the given event on the document, using the given options for emission, using the second argment as default options", ->
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([event, { callback }], { log: 'log message' })
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
expect(emitter.callback).toBe(callback)
expect(emitter.log).toEqual('log message')
describe 'with ([Element, Event, Object])', ->
it "emits the given event on the given element, using the given options for emission", ->
element = fixture('.element')
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([element, event, { callback }])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(element)
expect(emitter.callback).toBe(callback)
describe 'with ([Object])', ->
it "builds an event with the type from the given object's { type } property, which emits on the document", ->
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', key: 'value'}])
expect(emitter.event).toBeEvent('my:event', key: 'value')
expect(emitter.target).toBe(document)
it 'throws an error if the given object does not have a { type } property, which emits on the document', ->
build = -> up.EventEmitter.fromEmitArgs([{key: 'value'}])
expect(build).toThrowError(/type/i)
it 'accepts an event target as { target } property', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', target: element}])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
it 'accepts a CSS selector string in the { target } property', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', target: '.element'}])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([Element, Object])', ->
it "builds an event with the type from the given object's { type } property", ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, {type: 'my:event', key: 'value'}])
expect(emitter.event).toBeEvent('my:event', key: 'value')
expect(emitter.target).toBe(element)
it 'throws an error if the given object does not have a { type } property', ->
element = fixture('.element')
build = -> up.EventEmitter.fromEmitArgs([element, {key: 'value'}])
expect(build).toThrowError(/type/i)
describe 'with ([Object], Object)', ->
it "builds an event with the type from the given object's { type } property, using the second argument as default props", ->
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', key: 'value'}], defaultKey: 'defaultValue')
expect(emitter.event).toBeEvent('my:event', key: 'value', defaultKey: 'defaultValue')
expect(emitter.target).toBe(document)
| 35796 | describe 'up.EventEmitter', ->
describe '.fromEmitArgs', ->
describe 'with ([String])', ->
it 'builds an event with the given name, which emits on the document', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(document)
describe 'with ([String, Object])', ->
it 'builds an event with the given name and props, which emits on the document', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event', { key1: '<KEY>', key2: '<KEY>' }])
expect(emitter.event).toBeEvent('my:event', key1: '<KEY>', key2: '<KEY>')
expect(emitter.target).toBe(document)
describe 'with ([String, Object], Object)', ->
it 'builds an event with the given name and props, defaulting to options from the second argument', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event', { key1: '<KEY>' }], { key2: '<KEY>' })
expect(emitter.event).toBeEvent('my:event', key1: '<KEY>', key2: '<KEY>')
expect(emitter.target).toBe(document)
describe 'with ([Element, String])', ->
it 'builds an event with the given name, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([up.Layer, String])', ->
it "builds an event with the given name, which emits on the given layer's element, setting the current layer to that layer", (done) ->
up.layer.open(content: 'content').then (layer) ->
emitter = up.EventEmitter.fromEmitArgs([layer, 'my:event'])
expect(emitter.event).toBeEvent('my:event', layer: layer) # has { layer } property for event listeners
expect(emitter.target).toBe(layer.element)
expect(emitter.baseLayer).toBe(layer) # this will set up.layer.current during event emission
done()
describe 'with ([Element, String, Object])', ->
it 'builds an event with the given name and props, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event', { key1: '<KEY>', key2: '<KEY>' }])
expect(emitter.event).toBeEvent('my:event', key1: '<KEY>', key2: '<KEY>')
expect(emitter.target).toBe(element)
describe 'with ([Element, String])', ->
it 'builds an event with the given name, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([Event])', ->
it "emits the given event on the document", ->
event = up.event.build('my:event')
emitter = up.EventEmitter.fromEmitArgs([event])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
describe 'with ([Element, Event])', ->
it "emits the given event on the given element", ->
element = fixture('.element')
event = up.event.build('my:event')
emitter = up.EventEmitter.fromEmitArgs([element, event])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(element)
describe 'with ([Event, Object])', ->
it "emits the given event on the document, using the given options for emission", ->
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([event, { callback }])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
expect(emitter.callback).toBe(callback)
describe 'with ([Event, Object], Object)', ->
it "emits the given event on the document, using the given options for emission, using the second argment as default options", ->
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([event, { callback }], { log: 'log message' })
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
expect(emitter.callback).toBe(callback)
expect(emitter.log).toEqual('log message')
describe 'with ([Element, Event, Object])', ->
it "emits the given event on the given element, using the given options for emission", ->
element = fixture('.element')
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([element, event, { callback }])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(element)
expect(emitter.callback).toBe(callback)
describe 'with ([Object])', ->
it "builds an event with the type from the given object's { type } property, which emits on the document", ->
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', key: 'value'}])
expect(emitter.event).toBeEvent('my:event', key: 'value')
expect(emitter.target).toBe(document)
it 'throws an error if the given object does not have a { type } property, which emits on the document', ->
build = -> up.EventEmitter.fromEmitArgs([{key: 'value'}])
expect(build).toThrowError(/type/i)
it 'accepts an event target as { target } property', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', target: element}])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
it 'accepts a CSS selector string in the { target } property', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', target: '.element'}])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([Element, Object])', ->
it "builds an event with the type from the given object's { type } property", ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, {type: 'my:event', key: 'value'}])
expect(emitter.event).toBeEvent('my:event', key: 'value')
expect(emitter.target).toBe(element)
it 'throws an error if the given object does not have a { type } property', ->
element = fixture('.element')
build = -> up.EventEmitter.fromEmitArgs([element, {key: 'value'}])
expect(build).toThrowError(/type/i)
describe 'with ([Object], Object)', ->
it "builds an event with the type from the given object's { type } property, using the second argument as default props", ->
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', key: 'value'}], defaultKey: 'defaultValue')
expect(emitter.event).toBeEvent('my:event', key: 'value', defaultKey: 'defaultValue')
expect(emitter.target).toBe(document)
| true | describe 'up.EventEmitter', ->
describe '.fromEmitArgs', ->
describe 'with ([String])', ->
it 'builds an event with the given name, which emits on the document', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(document)
describe 'with ([String, Object])', ->
it 'builds an event with the given name and props, which emits on the document', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event', { key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI' }])
expect(emitter.event).toBeEvent('my:event', key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI')
expect(emitter.target).toBe(document)
describe 'with ([String, Object], Object)', ->
it 'builds an event with the given name and props, defaulting to options from the second argument', ->
emitter = up.EventEmitter.fromEmitArgs(['my:event', { key1: 'PI:KEY:<KEY>END_PI' }], { key2: 'PI:KEY:<KEY>END_PI' })
expect(emitter.event).toBeEvent('my:event', key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI')
expect(emitter.target).toBe(document)
describe 'with ([Element, String])', ->
it 'builds an event with the given name, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([up.Layer, String])', ->
it "builds an event with the given name, which emits on the given layer's element, setting the current layer to that layer", (done) ->
up.layer.open(content: 'content').then (layer) ->
emitter = up.EventEmitter.fromEmitArgs([layer, 'my:event'])
expect(emitter.event).toBeEvent('my:event', layer: layer) # has { layer } property for event listeners
expect(emitter.target).toBe(layer.element)
expect(emitter.baseLayer).toBe(layer) # this will set up.layer.current during event emission
done()
describe 'with ([Element, String, Object])', ->
it 'builds an event with the given name and props, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event', { key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI' }])
expect(emitter.event).toBeEvent('my:event', key1: 'PI:KEY:<KEY>END_PI', key2: 'PI:KEY:<KEY>END_PI')
expect(emitter.target).toBe(element)
describe 'with ([Element, String])', ->
it 'builds an event with the given name, which emits on the given element', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, 'my:event'])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([Event])', ->
it "emits the given event on the document", ->
event = up.event.build('my:event')
emitter = up.EventEmitter.fromEmitArgs([event])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
describe 'with ([Element, Event])', ->
it "emits the given event on the given element", ->
element = fixture('.element')
event = up.event.build('my:event')
emitter = up.EventEmitter.fromEmitArgs([element, event])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(element)
describe 'with ([Event, Object])', ->
it "emits the given event on the document, using the given options for emission", ->
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([event, { callback }])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
expect(emitter.callback).toBe(callback)
describe 'with ([Event, Object], Object)', ->
it "emits the given event on the document, using the given options for emission, using the second argment as default options", ->
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([event, { callback }], { log: 'log message' })
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(document)
expect(emitter.callback).toBe(callback)
expect(emitter.log).toEqual('log message')
describe 'with ([Element, Event, Object])', ->
it "emits the given event on the given element, using the given options for emission", ->
element = fixture('.element')
event = up.event.build('my:event')
callback = (_event) ->
emitter = up.EventEmitter.fromEmitArgs([element, event, { callback }])
expect(emitter.event).toBe(event)
expect(emitter.target).toBe(element)
expect(emitter.callback).toBe(callback)
describe 'with ([Object])', ->
it "builds an event with the type from the given object's { type } property, which emits on the document", ->
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', key: 'value'}])
expect(emitter.event).toBeEvent('my:event', key: 'value')
expect(emitter.target).toBe(document)
it 'throws an error if the given object does not have a { type } property, which emits on the document', ->
build = -> up.EventEmitter.fromEmitArgs([{key: 'value'}])
expect(build).toThrowError(/type/i)
it 'accepts an event target as { target } property', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', target: element}])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
it 'accepts a CSS selector string in the { target } property', ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', target: '.element'}])
expect(emitter.event).toBeEvent('my:event')
expect(emitter.target).toBe(element)
describe 'with ([Element, Object])', ->
it "builds an event with the type from the given object's { type } property", ->
element = fixture('.element')
emitter = up.EventEmitter.fromEmitArgs([element, {type: 'my:event', key: 'value'}])
expect(emitter.event).toBeEvent('my:event', key: 'value')
expect(emitter.target).toBe(element)
it 'throws an error if the given object does not have a { type } property', ->
element = fixture('.element')
build = -> up.EventEmitter.fromEmitArgs([element, {key: 'value'}])
expect(build).toThrowError(/type/i)
describe 'with ([Object], Object)', ->
it "builds an event with the type from the given object's { type } property, using the second argument as default props", ->
emitter = up.EventEmitter.fromEmitArgs([{type: 'my:event', key: 'value'}], defaultKey: 'defaultValue')
expect(emitter.event).toBeEvent('my:event', key: 'value', defaultKey: 'defaultValue')
expect(emitter.target).toBe(document)
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998647570610046,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/plugins/formula.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic enter a nice-looking formula
# in the page head:
# <!-- math processing -->
# <script type="text/x-mathjax-config">
# MathJax.Hub.Config({
# tex2jax: {
# inlineMath: [['\\(inline_math\\(','\\)inline_math\\)']]
# , displayMath: [['\\(math\\(','\\)math\\)']]
# , preview:[["img",{src:"icons/throbber.gif"}]]
# , showMathMenu: false
# }
# });
# </script>
# <script type="text/javascript" src="MathJax.js?config=TeX_HTML"></script>
# unpack the MathJax library into the root of you server, maybe patch
# BASE.JAX(~@666) config: {root: "lib/mathjax"}, // URL of root directory to load from
# and something about the webfontDir was weird with my configuration
# requires utilities for wke (webkitedit):
# openUrlInBrowser
# leaves the editable in a broken-undo-state
# requires on-store (.formula.html('') or svg transformation)
# requires on-load (.formula.html(.formula.attr('rel')))
# MathJax.Hub.Queue(['Typeset',MathJax.Hub])
# depends on the dropdownform widget plugin
((jQuery) ->
jQuery.widget 'IKS.halloformula',
dropdownform: null
tmpid: 0
html: null
has_mathjax: typeof MathJax != 'undefined'
debug: false
options:
editable: null
toolbar: null
uuid: ''
rows: 6
cols: 32
buttonCssClass: null
default: '\\zeta(s) = \\sum_{n=1}^\\infty {\\frac{1}{n^s}}'
mathjax_alternative: 'http://mathurl.com/'
mathjax_base_alternative: 'http://www.sciweavers.org/free-online-latex-equation-editor'
mathjax_delim_left: '\\(math\\('
mathjax_delim_right: '\\)math\\)'
mathjax_inline_delim_left: '\\(inline_math\\('
mathjax_inline_delim_right: '\\)inline_math\\)'
inline: true
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= (select_target,target_id) =>
return if rangy.getSelection().rangeCount == 0
@options.editable.restoreContentPosition()
@_setupUndoWaypoint()
contentId = target_id
# target_id != parent-function:contentId
# as the setup function is called by live()
# and subsequent activations will lead to a different this here
# and in the keyup/click handlers in _prepareDropdown
@tmpid = 'mod_' + (new Date()).getTime()
selection = rangy.getSelection()
# sel may not be correct
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
else
range = rangy.createRange()
range.selectNode(@options.editable.element[0])
range.collapse()
@cur_formula = null
@action = 'insert'
if ( typeof select_target == 'object' )
selected_formula = jQuery(select_target).closest('.formula')
if ( selected_formula.length )
@cur_formula = selected_formula
@cur_formula.attr('id',@tmpid)
@action = 'update'
if ( @action == 'insert' )
@options.editable.element.find('.formula').each (index,item) =>
if ( selection.containsNode(item,true) )
@cur_formula = jQuery(item)
@action = 'update'
return false # break
if ( !@has_mathjax )
return true
if ( @cur_formula && @cur_formula.length )
#modify
latex_formula = decodeURIComponent(@cur_formula.attr('rel'))
title = decodeURIComponent(@cur_formula.attr('title'))
console.log('modify',latex_formula,@cur_formula) if @debug
$('#' + contentId + 'latex').val(latex_formula)
$('#' + contentId + 'title').val(title)
if ( @cur_formula.hasClass('inline') )
$('#' + contentId + 'inline').addClass('active')
else
$('#' + contentId + 'inline').removeClass('active')
@cur_formula.attr('id',@tmpid)
@cur_formula.html('')
else
@cur_formula = jQuery('<span class="formula" id="' + @tmpid + '" contenteditable="false"/>')
@cur_formula.find('.formula').attr('rel',encodeURIComponent(@options.default))
@cur_formula.find('.formula').attr('title','')
if ( @options.inline )
@cur_formula.find('.formula').addClass('inline')
@options.editable.getSelectionStartNode (selection) =>
if ( selection.length )
@cur_formula.insertBefore(selection)
range.selectNode(@cur_formula[0])
rangy.getSelection().setSingleRange(range)
$('#' + contentId + 'latex').val(@options.default)
if ( @options.inline )
$('#' + contentId + 'inline').addClass('active')
else
$('#' + contentId + 'inline').removeClass('active')
$('#' + contentId + 'title').val()
console.log('insert',@cur_formula) if @debug
@updateFormulaHTML(contentId)
recalc = =>
@recalcHTML(contentId)
@recalcPreview(contentId)
@recalcMath()
window.setTimeout recalc, 300
return true
@dropdownform = @_prepareButton setup, target
@dropdownform.hallodropdownform 'bindShow', '.formula'
buttonset.append @dropdownform
toolbar.append buttonset
updateFormulaHTML: (contentId) ->
console.log('update formula',contentId,@tmpid,this) if @debug
formula = $('#' + @tmpid)
if ( !formula.length )
console.error('expected identifier not found',@tmpid)
console.error(@options.editable)
console.error(@options.editable.element.html())
return
latex_formula = $('#' + contentId + 'latex').val();
inline = $('#' + contentId + 'inline').hasClass('active');
title = $('#' + contentId + 'title').val();
console.log(latex_formula,inline,title,formula,@tmpid) if @debug
#if ( formula.html() == '' )
formula.removeClass('inline')
formula.html('')
if ( @has_mathjax )
if ( inline )
string = '<span id="' + @tmpid + '">' + @options.mathjax_inline_delim_left + utils.sanitize(latex_formula) + @options.mathjax_inline_delim_right + '</span>'
formula.replaceWith(string)
formula = $('#' + @tmpid)
formula.addClass('inline')
else
string = '<div id="' + @tmpid + '">' + @options.mathjax_delim_left + utils.sanitize(latex_formula) + @options.mathjax_delim_right + '</div>'
formula.replaceWith(string);
formula = $('#' + @tmpid);
if @debug
console.log('FormulaWRAPPING',formula,formula.parents(),formula.contents())
else
formula.html(latex_formula)
encoded_latex = encodeURIComponent(latex_formula)
encoded_title = encodeURIComponent(title)
formula.addClass('formula')
formula.attr('rel',encoded_latex)
formula.attr('title',encoded_title)
formula.attr('contenteditable','false')
# console.log(latex_formula,encoded_latex,formula[0].outerHTML)
return formula[0].outerHTML
recalcMath: () ->
if ( @has_mathjax )
@options.editable.element.find('.formula').each (index,formula_item) =>
formula_node = jQuery(formula_item)
if ( formula_node.hasClass('inline') )
formula_node.html(@options.mathjax_inline_delim_left + utils.sanitize(decodeURIComponent(formula_node.attr('rel'))) + @options.mathjax_inline_delim_right)
else
formula_node.html(@options.mathjax_delim_left + utils.sanitize(decodeURIComponent(formula_node.attr('rel'))) + @options.mathjax_delim_right)
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
recalcHTML: (contentId) ->
@html = @updateFormulaHTML(contentId)
@options.editable.store()
recalcPreview: (contentId) ->
preview = jQuery('#' + contentId + ' .preview')
if ( preview.length == 0 )
return
latex_formula = $('#' + contentId + 'latex').val();
inline = $('#' + contentId + 'inline').hasClass('active');
if ( inline )
preview.html(@options.mathjax_inline_delim_left + utils.sanitize(latex_formula) + @options.mathjax_inline_delim_right)
else
preview.html(@options.mathjax_delim_left + utils.sanitize(latex_formula) + @options.mathjax_delim_right)
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addArea = (element,default_value) =>
elid="#{contentId}#{element}"
el = jQuery "<li><label for=\"#{elid}\">" + utils.tr(element) + "</label><textarea id=\"#{elid}\" rows=\"#{@options.rows}\" cols=\"#{@options.cols}\"></textarea></li>"
textarea = el.find('textarea')
textarea.val(default_value)
recalc= =>
@recalcHTML(contentId)
@recalcPreview(contentId)
@recalcMath()
textarea.bind('keyup change',recalc)
el
addInput = (type,element,default_value,recalc_preview) =>
elid = "#{contentId}#{element}"
el = jQuery "<li></li>"
if ( type == 'checkbox' )
toggle_button = jQuery('<button type="button" class="toggle_button" id="' + elid + '"/>')
toggle_button_container = jQuery('<div>')
toggle_button_container.css({'height':'2em'})
recalc= =>
toggle_button.toggleClass('active')
@recalcHTML(contentId)
if ( recalc_preview )
@recalcPreview(contentId)
@recalcMath()
toggle_button.html(utils.tr(element))
toggle_button.bind('click', recalc)
if ( default_value == true )
toggle_button.addClass('active')
toggle_button_container.append(toggle_button)
el.append(toggle_button_container)
else
recalc= =>
@recalcHTML(contentId)
if ( recalc_preview )
@recalcPreview(contentId)
@recalcMath()
el.append('<label for="' + elid + '">' + utils.tr(element) + '</label>')
el.append('<input type="' + type + '" id="' + elid + '"/>')
if ( default_value )
el.find('input').val(default_value)
el.find('input').bind('keyup change',recalc)
el
addButton = (element,event_handler) =>
elid="#{contentId}#{element}"
el = jQuery "<button class=\"action_button\" id=\"" + @elid + "\">" + utils.tr(element) + "</button>"
el.bind 'click', event_handler
el
if ( @has_mathjax )
contentAreaUL.append addInput("text","title", @options.title,false)
contentAreaUL.append addArea("latex", @options.default)
contentInfoText = jQuery('<li><label for="' + contentId + 'formula">' + utils.tr('preview') + '</label><span class="formula preview">' + @options.mathjax_delim_left + @options["default"] + @options.mathjax_delim_right + '</span><span class="formula preview_over"></span></li>')
contentInfoText.find('.preview_over').bind 'click', (event) =>
event.preventDefault()
contentAreaUL.append(contentInfoText)
contentAreaUL.append(addInput("checkbox", "inline", this.options.inline, true));
buttons = jQuery('<div>')
buttons_li = jQuery('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula', () =>
wke.openUrlInBrowser(@options.mathjax_alternative + '?latex=' + $('#' + contentId + 'latex').val())
buttons.append(buttons_li)
else
buttons = jQuery('<div>')
buttons_li = jQuery('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula', () =>
wke.openUrlInBrowser(@options.mathjax_alternative)
buttons.append(buttons_li)
buttons_li = $('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula base', () =>
wke.openUrlInBrowser(@options.mathjax_base_alternative)
buttons.append(buttons_li)
buttons.find('button').addClass('external_button')
contentAreaUL.append(buttons.children())
buttons = jQuery('<li>')
buttons.append addButton "apply", =>
@recalcHTML(contentId)
@recalcMath()
@_setupUndoWaypoint()
formula = $('#' + @tmpid)
if ( formula.length )
if ( ! formula[0].nextSibling )
jQuery('<br/>').insertAfter(formula)
formula.removeAttr('id')
else
formulas = $('.formula').each (index,item) =>
jQuery(item).removeAttr('id')
@_commitUndoWaypoint()
@dropdownform.hallodropdownform('hideForm')
buttons.append addButton "remove", =>
@_setupUndoWaypoint()
$('#' + @tmpid).remove()
@_commitUndoWaypoint()
@dropdownform.hallodropdownform('hideForm')
contentAreaUL.append(buttons)
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'formula'
if ( window.action_list && window.action_list['hallojs_formula'] != undefined )
button_label = window.action_list['hallojs_formula'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'formula'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
_setupUndoWaypoint: () ->
@options.editable.undoWaypointStart('formula')
postdo_handler = () =>
# console.log('POSTDO FORMULA')
@recalcMath()
@options.editable._current_undo_command.postdo = postdo_handler
# make sure on undo and redo with non-formulas, the math is recalced too
current_undo_stack = @options.editable.undoWaypointLoad(@options.editable.element)
if ( current_undo_stack.canUndo() && current_undo_stack.index() > 0 )
current_undo_stack.command(current_undo_stack.index()).postdo = postdo_handler
if ( current_undo_stack.canRedo() && current_undo_stack.index() > 1 )
current_undo_stack.command(current_undo_stack.index() + 1).postdo = postdo_handler
_commitUndoWaypoint: () ->
@options.editable.undoWaypointCommit()
)(jQuery)
| 48615 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic enter a nice-looking formula
# in the page head:
# <!-- math processing -->
# <script type="text/x-mathjax-config">
# MathJax.Hub.Config({
# tex2jax: {
# inlineMath: [['\\(inline_math\\(','\\)inline_math\\)']]
# , displayMath: [['\\(math\\(','\\)math\\)']]
# , preview:[["img",{src:"icons/throbber.gif"}]]
# , showMathMenu: false
# }
# });
# </script>
# <script type="text/javascript" src="MathJax.js?config=TeX_HTML"></script>
# unpack the MathJax library into the root of you server, maybe patch
# BASE.JAX(~@666) config: {root: "lib/mathjax"}, // URL of root directory to load from
# and something about the webfontDir was weird with my configuration
# requires utilities for wke (webkitedit):
# openUrlInBrowser
# leaves the editable in a broken-undo-state
# requires on-store (.formula.html('') or svg transformation)
# requires on-load (.formula.html(.formula.attr('rel')))
# MathJax.Hub.Queue(['Typeset',MathJax.Hub])
# depends on the dropdownform widget plugin
((jQuery) ->
jQuery.widget 'IKS.halloformula',
dropdownform: null
tmpid: 0
html: null
has_mathjax: typeof MathJax != 'undefined'
debug: false
options:
editable: null
toolbar: null
uuid: ''
rows: 6
cols: 32
buttonCssClass: null
default: '\\zeta(s) = \\sum_{n=1}^\\infty {\\frac{1}{n^s}}'
mathjax_alternative: 'http://mathurl.com/'
mathjax_base_alternative: 'http://www.sciweavers.org/free-online-latex-equation-editor'
mathjax_delim_left: '\\(math\\('
mathjax_delim_right: '\\)math\\)'
mathjax_inline_delim_left: '\\(inline_math\\('
mathjax_inline_delim_right: '\\)inline_math\\)'
inline: true
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= (select_target,target_id) =>
return if rangy.getSelection().rangeCount == 0
@options.editable.restoreContentPosition()
@_setupUndoWaypoint()
contentId = target_id
# target_id != parent-function:contentId
# as the setup function is called by live()
# and subsequent activations will lead to a different this here
# and in the keyup/click handlers in _prepareDropdown
@tmpid = 'mod_' + (new Date()).getTime()
selection = rangy.getSelection()
# sel may not be correct
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
else
range = rangy.createRange()
range.selectNode(@options.editable.element[0])
range.collapse()
@cur_formula = null
@action = 'insert'
if ( typeof select_target == 'object' )
selected_formula = jQuery(select_target).closest('.formula')
if ( selected_formula.length )
@cur_formula = selected_formula
@cur_formula.attr('id',@tmpid)
@action = 'update'
if ( @action == 'insert' )
@options.editable.element.find('.formula').each (index,item) =>
if ( selection.containsNode(item,true) )
@cur_formula = jQuery(item)
@action = 'update'
return false # break
if ( !@has_mathjax )
return true
if ( @cur_formula && @cur_formula.length )
#modify
latex_formula = decodeURIComponent(@cur_formula.attr('rel'))
title = decodeURIComponent(@cur_formula.attr('title'))
console.log('modify',latex_formula,@cur_formula) if @debug
$('#' + contentId + 'latex').val(latex_formula)
$('#' + contentId + 'title').val(title)
if ( @cur_formula.hasClass('inline') )
$('#' + contentId + 'inline').addClass('active')
else
$('#' + contentId + 'inline').removeClass('active')
@cur_formula.attr('id',@tmpid)
@cur_formula.html('')
else
@cur_formula = jQuery('<span class="formula" id="' + @tmpid + '" contenteditable="false"/>')
@cur_formula.find('.formula').attr('rel',encodeURIComponent(@options.default))
@cur_formula.find('.formula').attr('title','')
if ( @options.inline )
@cur_formula.find('.formula').addClass('inline')
@options.editable.getSelectionStartNode (selection) =>
if ( selection.length )
@cur_formula.insertBefore(selection)
range.selectNode(@cur_formula[0])
rangy.getSelection().setSingleRange(range)
$('#' + contentId + 'latex').val(@options.default)
if ( @options.inline )
$('#' + contentId + 'inline').addClass('active')
else
$('#' + contentId + 'inline').removeClass('active')
$('#' + contentId + 'title').val()
console.log('insert',@cur_formula) if @debug
@updateFormulaHTML(contentId)
recalc = =>
@recalcHTML(contentId)
@recalcPreview(contentId)
@recalcMath()
window.setTimeout recalc, 300
return true
@dropdownform = @_prepareButton setup, target
@dropdownform.hallodropdownform 'bindShow', '.formula'
buttonset.append @dropdownform
toolbar.append buttonset
updateFormulaHTML: (contentId) ->
console.log('update formula',contentId,@tmpid,this) if @debug
formula = $('#' + @tmpid)
if ( !formula.length )
console.error('expected identifier not found',@tmpid)
console.error(@options.editable)
console.error(@options.editable.element.html())
return
latex_formula = $('#' + contentId + 'latex').val();
inline = $('#' + contentId + 'inline').hasClass('active');
title = $('#' + contentId + 'title').val();
console.log(latex_formula,inline,title,formula,@tmpid) if @debug
#if ( formula.html() == '' )
formula.removeClass('inline')
formula.html('')
if ( @has_mathjax )
if ( inline )
string = '<span id="' + @tmpid + '">' + @options.mathjax_inline_delim_left + utils.sanitize(latex_formula) + @options.mathjax_inline_delim_right + '</span>'
formula.replaceWith(string)
formula = $('#' + @tmpid)
formula.addClass('inline')
else
string = '<div id="' + @tmpid + '">' + @options.mathjax_delim_left + utils.sanitize(latex_formula) + @options.mathjax_delim_right + '</div>'
formula.replaceWith(string);
formula = $('#' + @tmpid);
if @debug
console.log('FormulaWRAPPING',formula,formula.parents(),formula.contents())
else
formula.html(latex_formula)
encoded_latex = encodeURIComponent(latex_formula)
encoded_title = encodeURIComponent(title)
formula.addClass('formula')
formula.attr('rel',encoded_latex)
formula.attr('title',encoded_title)
formula.attr('contenteditable','false')
# console.log(latex_formula,encoded_latex,formula[0].outerHTML)
return formula[0].outerHTML
recalcMath: () ->
if ( @has_mathjax )
@options.editable.element.find('.formula').each (index,formula_item) =>
formula_node = jQuery(formula_item)
if ( formula_node.hasClass('inline') )
formula_node.html(@options.mathjax_inline_delim_left + utils.sanitize(decodeURIComponent(formula_node.attr('rel'))) + @options.mathjax_inline_delim_right)
else
formula_node.html(@options.mathjax_delim_left + utils.sanitize(decodeURIComponent(formula_node.attr('rel'))) + @options.mathjax_delim_right)
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
recalcHTML: (contentId) ->
@html = @updateFormulaHTML(contentId)
@options.editable.store()
recalcPreview: (contentId) ->
preview = jQuery('#' + contentId + ' .preview')
if ( preview.length == 0 )
return
latex_formula = $('#' + contentId + 'latex').val();
inline = $('#' + contentId + 'inline').hasClass('active');
if ( inline )
preview.html(@options.mathjax_inline_delim_left + utils.sanitize(latex_formula) + @options.mathjax_inline_delim_right)
else
preview.html(@options.mathjax_delim_left + utils.sanitize(latex_formula) + @options.mathjax_delim_right)
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addArea = (element,default_value) =>
elid="#{contentId}#{element}"
el = jQuery "<li><label for=\"#{elid}\">" + utils.tr(element) + "</label><textarea id=\"#{elid}\" rows=\"#{@options.rows}\" cols=\"#{@options.cols}\"></textarea></li>"
textarea = el.find('textarea')
textarea.val(default_value)
recalc= =>
@recalcHTML(contentId)
@recalcPreview(contentId)
@recalcMath()
textarea.bind('keyup change',recalc)
el
addInput = (type,element,default_value,recalc_preview) =>
elid = "#{contentId}#{element}"
el = jQuery "<li></li>"
if ( type == 'checkbox' )
toggle_button = jQuery('<button type="button" class="toggle_button" id="' + elid + '"/>')
toggle_button_container = jQuery('<div>')
toggle_button_container.css({'height':'2em'})
recalc= =>
toggle_button.toggleClass('active')
@recalcHTML(contentId)
if ( recalc_preview )
@recalcPreview(contentId)
@recalcMath()
toggle_button.html(utils.tr(element))
toggle_button.bind('click', recalc)
if ( default_value == true )
toggle_button.addClass('active')
toggle_button_container.append(toggle_button)
el.append(toggle_button_container)
else
recalc= =>
@recalcHTML(contentId)
if ( recalc_preview )
@recalcPreview(contentId)
@recalcMath()
el.append('<label for="' + elid + '">' + utils.tr(element) + '</label>')
el.append('<input type="' + type + '" id="' + elid + '"/>')
if ( default_value )
el.find('input').val(default_value)
el.find('input').bind('keyup change',recalc)
el
addButton = (element,event_handler) =>
elid="#{contentId}#{element}"
el = jQuery "<button class=\"action_button\" id=\"" + @elid + "\">" + utils.tr(element) + "</button>"
el.bind 'click', event_handler
el
if ( @has_mathjax )
contentAreaUL.append addInput("text","title", @options.title,false)
contentAreaUL.append addArea("latex", @options.default)
contentInfoText = jQuery('<li><label for="' + contentId + 'formula">' + utils.tr('preview') + '</label><span class="formula preview">' + @options.mathjax_delim_left + @options["default"] + @options.mathjax_delim_right + '</span><span class="formula preview_over"></span></li>')
contentInfoText.find('.preview_over').bind 'click', (event) =>
event.preventDefault()
contentAreaUL.append(contentInfoText)
contentAreaUL.append(addInput("checkbox", "inline", this.options.inline, true));
buttons = jQuery('<div>')
buttons_li = jQuery('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula', () =>
wke.openUrlInBrowser(@options.mathjax_alternative + '?latex=' + $('#' + contentId + 'latex').val())
buttons.append(buttons_li)
else
buttons = jQuery('<div>')
buttons_li = jQuery('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula', () =>
wke.openUrlInBrowser(@options.mathjax_alternative)
buttons.append(buttons_li)
buttons_li = $('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula base', () =>
wke.openUrlInBrowser(@options.mathjax_base_alternative)
buttons.append(buttons_li)
buttons.find('button').addClass('external_button')
contentAreaUL.append(buttons.children())
buttons = jQuery('<li>')
buttons.append addButton "apply", =>
@recalcHTML(contentId)
@recalcMath()
@_setupUndoWaypoint()
formula = $('#' + @tmpid)
if ( formula.length )
if ( ! formula[0].nextSibling )
jQuery('<br/>').insertAfter(formula)
formula.removeAttr('id')
else
formulas = $('.formula').each (index,item) =>
jQuery(item).removeAttr('id')
@_commitUndoWaypoint()
@dropdownform.hallodropdownform('hideForm')
buttons.append addButton "remove", =>
@_setupUndoWaypoint()
$('#' + @tmpid).remove()
@_commitUndoWaypoint()
@dropdownform.hallodropdownform('hideForm')
contentAreaUL.append(buttons)
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'formula'
if ( window.action_list && window.action_list['hallojs_formula'] != undefined )
button_label = window.action_list['hallojs_formula'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'formula'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
_setupUndoWaypoint: () ->
@options.editable.undoWaypointStart('formula')
postdo_handler = () =>
# console.log('POSTDO FORMULA')
@recalcMath()
@options.editable._current_undo_command.postdo = postdo_handler
# make sure on undo and redo with non-formulas, the math is recalced too
current_undo_stack = @options.editable.undoWaypointLoad(@options.editable.element)
if ( current_undo_stack.canUndo() && current_undo_stack.index() > 0 )
current_undo_stack.command(current_undo_stack.index()).postdo = postdo_handler
if ( current_undo_stack.canRedo() && current_undo_stack.index() > 1 )
current_undo_stack.command(current_undo_stack.index() + 1).postdo = postdo_handler
_commitUndoWaypoint: () ->
@options.editable.undoWaypointCommit()
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic enter a nice-looking formula
# in the page head:
# <!-- math processing -->
# <script type="text/x-mathjax-config">
# MathJax.Hub.Config({
# tex2jax: {
# inlineMath: [['\\(inline_math\\(','\\)inline_math\\)']]
# , displayMath: [['\\(math\\(','\\)math\\)']]
# , preview:[["img",{src:"icons/throbber.gif"}]]
# , showMathMenu: false
# }
# });
# </script>
# <script type="text/javascript" src="MathJax.js?config=TeX_HTML"></script>
# unpack the MathJax library into the root of you server, maybe patch
# BASE.JAX(~@666) config: {root: "lib/mathjax"}, // URL of root directory to load from
# and something about the webfontDir was weird with my configuration
# requires utilities for wke (webkitedit):
# openUrlInBrowser
# leaves the editable in a broken-undo-state
# requires on-store (.formula.html('') or svg transformation)
# requires on-load (.formula.html(.formula.attr('rel')))
# MathJax.Hub.Queue(['Typeset',MathJax.Hub])
# depends on the dropdownform widget plugin
((jQuery) ->
jQuery.widget 'IKS.halloformula',
dropdownform: null
tmpid: 0
html: null
has_mathjax: typeof MathJax != 'undefined'
debug: false
options:
editable: null
toolbar: null
uuid: ''
rows: 6
cols: 32
buttonCssClass: null
default: '\\zeta(s) = \\sum_{n=1}^\\infty {\\frac{1}{n^s}}'
mathjax_alternative: 'http://mathurl.com/'
mathjax_base_alternative: 'http://www.sciweavers.org/free-online-latex-equation-editor'
mathjax_delim_left: '\\(math\\('
mathjax_delim_right: '\\)math\\)'
mathjax_inline_delim_left: '\\(inline_math\\('
mathjax_inline_delim_right: '\\)inline_math\\)'
inline: true
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= (select_target,target_id) =>
return if rangy.getSelection().rangeCount == 0
@options.editable.restoreContentPosition()
@_setupUndoWaypoint()
contentId = target_id
# target_id != parent-function:contentId
# as the setup function is called by live()
# and subsequent activations will lead to a different this here
# and in the keyup/click handlers in _prepareDropdown
@tmpid = 'mod_' + (new Date()).getTime()
selection = rangy.getSelection()
# sel may not be correct
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
else
range = rangy.createRange()
range.selectNode(@options.editable.element[0])
range.collapse()
@cur_formula = null
@action = 'insert'
if ( typeof select_target == 'object' )
selected_formula = jQuery(select_target).closest('.formula')
if ( selected_formula.length )
@cur_formula = selected_formula
@cur_formula.attr('id',@tmpid)
@action = 'update'
if ( @action == 'insert' )
@options.editable.element.find('.formula').each (index,item) =>
if ( selection.containsNode(item,true) )
@cur_formula = jQuery(item)
@action = 'update'
return false # break
if ( !@has_mathjax )
return true
if ( @cur_formula && @cur_formula.length )
#modify
latex_formula = decodeURIComponent(@cur_formula.attr('rel'))
title = decodeURIComponent(@cur_formula.attr('title'))
console.log('modify',latex_formula,@cur_formula) if @debug
$('#' + contentId + 'latex').val(latex_formula)
$('#' + contentId + 'title').val(title)
if ( @cur_formula.hasClass('inline') )
$('#' + contentId + 'inline').addClass('active')
else
$('#' + contentId + 'inline').removeClass('active')
@cur_formula.attr('id',@tmpid)
@cur_formula.html('')
else
@cur_formula = jQuery('<span class="formula" id="' + @tmpid + '" contenteditable="false"/>')
@cur_formula.find('.formula').attr('rel',encodeURIComponent(@options.default))
@cur_formula.find('.formula').attr('title','')
if ( @options.inline )
@cur_formula.find('.formula').addClass('inline')
@options.editable.getSelectionStartNode (selection) =>
if ( selection.length )
@cur_formula.insertBefore(selection)
range.selectNode(@cur_formula[0])
rangy.getSelection().setSingleRange(range)
$('#' + contentId + 'latex').val(@options.default)
if ( @options.inline )
$('#' + contentId + 'inline').addClass('active')
else
$('#' + contentId + 'inline').removeClass('active')
$('#' + contentId + 'title').val()
console.log('insert',@cur_formula) if @debug
@updateFormulaHTML(contentId)
recalc = =>
@recalcHTML(contentId)
@recalcPreview(contentId)
@recalcMath()
window.setTimeout recalc, 300
return true
@dropdownform = @_prepareButton setup, target
@dropdownform.hallodropdownform 'bindShow', '.formula'
buttonset.append @dropdownform
toolbar.append buttonset
updateFormulaHTML: (contentId) ->
console.log('update formula',contentId,@tmpid,this) if @debug
formula = $('#' + @tmpid)
if ( !formula.length )
console.error('expected identifier not found',@tmpid)
console.error(@options.editable)
console.error(@options.editable.element.html())
return
latex_formula = $('#' + contentId + 'latex').val();
inline = $('#' + contentId + 'inline').hasClass('active');
title = $('#' + contentId + 'title').val();
console.log(latex_formula,inline,title,formula,@tmpid) if @debug
#if ( formula.html() == '' )
formula.removeClass('inline')
formula.html('')
if ( @has_mathjax )
if ( inline )
string = '<span id="' + @tmpid + '">' + @options.mathjax_inline_delim_left + utils.sanitize(latex_formula) + @options.mathjax_inline_delim_right + '</span>'
formula.replaceWith(string)
formula = $('#' + @tmpid)
formula.addClass('inline')
else
string = '<div id="' + @tmpid + '">' + @options.mathjax_delim_left + utils.sanitize(latex_formula) + @options.mathjax_delim_right + '</div>'
formula.replaceWith(string);
formula = $('#' + @tmpid);
if @debug
console.log('FormulaWRAPPING',formula,formula.parents(),formula.contents())
else
formula.html(latex_formula)
encoded_latex = encodeURIComponent(latex_formula)
encoded_title = encodeURIComponent(title)
formula.addClass('formula')
formula.attr('rel',encoded_latex)
formula.attr('title',encoded_title)
formula.attr('contenteditable','false')
# console.log(latex_formula,encoded_latex,formula[0].outerHTML)
return formula[0].outerHTML
recalcMath: () ->
if ( @has_mathjax )
@options.editable.element.find('.formula').each (index,formula_item) =>
formula_node = jQuery(formula_item)
if ( formula_node.hasClass('inline') )
formula_node.html(@options.mathjax_inline_delim_left + utils.sanitize(decodeURIComponent(formula_node.attr('rel'))) + @options.mathjax_inline_delim_right)
else
formula_node.html(@options.mathjax_delim_left + utils.sanitize(decodeURIComponent(formula_node.attr('rel'))) + @options.mathjax_delim_right)
MathJax.Hub.Queue(['Typeset',MathJax.Hub])
recalcHTML: (contentId) ->
@html = @updateFormulaHTML(contentId)
@options.editable.store()
recalcPreview: (contentId) ->
preview = jQuery('#' + contentId + ' .preview')
if ( preview.length == 0 )
return
latex_formula = $('#' + contentId + 'latex').val();
inline = $('#' + contentId + 'inline').hasClass('active');
if ( inline )
preview.html(@options.mathjax_inline_delim_left + utils.sanitize(latex_formula) + @options.mathjax_inline_delim_right)
else
preview.html(@options.mathjax_delim_left + utils.sanitize(latex_formula) + @options.mathjax_delim_right)
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addArea = (element,default_value) =>
elid="#{contentId}#{element}"
el = jQuery "<li><label for=\"#{elid}\">" + utils.tr(element) + "</label><textarea id=\"#{elid}\" rows=\"#{@options.rows}\" cols=\"#{@options.cols}\"></textarea></li>"
textarea = el.find('textarea')
textarea.val(default_value)
recalc= =>
@recalcHTML(contentId)
@recalcPreview(contentId)
@recalcMath()
textarea.bind('keyup change',recalc)
el
addInput = (type,element,default_value,recalc_preview) =>
elid = "#{contentId}#{element}"
el = jQuery "<li></li>"
if ( type == 'checkbox' )
toggle_button = jQuery('<button type="button" class="toggle_button" id="' + elid + '"/>')
toggle_button_container = jQuery('<div>')
toggle_button_container.css({'height':'2em'})
recalc= =>
toggle_button.toggleClass('active')
@recalcHTML(contentId)
if ( recalc_preview )
@recalcPreview(contentId)
@recalcMath()
toggle_button.html(utils.tr(element))
toggle_button.bind('click', recalc)
if ( default_value == true )
toggle_button.addClass('active')
toggle_button_container.append(toggle_button)
el.append(toggle_button_container)
else
recalc= =>
@recalcHTML(contentId)
if ( recalc_preview )
@recalcPreview(contentId)
@recalcMath()
el.append('<label for="' + elid + '">' + utils.tr(element) + '</label>')
el.append('<input type="' + type + '" id="' + elid + '"/>')
if ( default_value )
el.find('input').val(default_value)
el.find('input').bind('keyup change',recalc)
el
addButton = (element,event_handler) =>
elid="#{contentId}#{element}"
el = jQuery "<button class=\"action_button\" id=\"" + @elid + "\">" + utils.tr(element) + "</button>"
el.bind 'click', event_handler
el
if ( @has_mathjax )
contentAreaUL.append addInput("text","title", @options.title,false)
contentAreaUL.append addArea("latex", @options.default)
contentInfoText = jQuery('<li><label for="' + contentId + 'formula">' + utils.tr('preview') + '</label><span class="formula preview">' + @options.mathjax_delim_left + @options["default"] + @options.mathjax_delim_right + '</span><span class="formula preview_over"></span></li>')
contentInfoText.find('.preview_over').bind 'click', (event) =>
event.preventDefault()
contentAreaUL.append(contentInfoText)
contentAreaUL.append(addInput("checkbox", "inline", this.options.inline, true));
buttons = jQuery('<div>')
buttons_li = jQuery('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula', () =>
wke.openUrlInBrowser(@options.mathjax_alternative + '?latex=' + $('#' + contentId + 'latex').val())
buttons.append(buttons_li)
else
buttons = jQuery('<div>')
buttons_li = jQuery('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula', () =>
wke.openUrlInBrowser(@options.mathjax_alternative)
buttons.append(buttons_li)
buttons_li = $('<li></li>').append('<label></label>')
buttons_label = buttons_li.find('>label')
buttons_label.after addButton 'compose formula base', () =>
wke.openUrlInBrowser(@options.mathjax_base_alternative)
buttons.append(buttons_li)
buttons.find('button').addClass('external_button')
contentAreaUL.append(buttons.children())
buttons = jQuery('<li>')
buttons.append addButton "apply", =>
@recalcHTML(contentId)
@recalcMath()
@_setupUndoWaypoint()
formula = $('#' + @tmpid)
if ( formula.length )
if ( ! formula[0].nextSibling )
jQuery('<br/>').insertAfter(formula)
formula.removeAttr('id')
else
formulas = $('.formula').each (index,item) =>
jQuery(item).removeAttr('id')
@_commitUndoWaypoint()
@dropdownform.hallodropdownform('hideForm')
buttons.append addButton "remove", =>
@_setupUndoWaypoint()
$('#' + @tmpid).remove()
@_commitUndoWaypoint()
@dropdownform.hallodropdownform('hideForm')
contentAreaUL.append(buttons)
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'formula'
if ( window.action_list && window.action_list['hallojs_formula'] != undefined )
button_label = window.action_list['hallojs_formula'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'formula'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
_setupUndoWaypoint: () ->
@options.editable.undoWaypointStart('formula')
postdo_handler = () =>
# console.log('POSTDO FORMULA')
@recalcMath()
@options.editable._current_undo_command.postdo = postdo_handler
# make sure on undo and redo with non-formulas, the math is recalced too
current_undo_stack = @options.editable.undoWaypointLoad(@options.editable.element)
if ( current_undo_stack.canUndo() && current_undo_stack.index() > 0 )
current_undo_stack.command(current_undo_stack.index()).postdo = postdo_handler
if ( current_undo_stack.canRedo() && current_undo_stack.index() > 1 )
current_undo_stack.command(current_undo_stack.index() + 1).postdo = postdo_handler
_commitUndoWaypoint: () ->
@options.editable.undoWaypointCommit()
)(jQuery)
|
[
{
"context": "\")= code'\n from: \"System\"\n users: ['admin', 'superadmin']\n userFromToken: userFromToke",
"end": 1302,
"score": 0.9953657388687134,
"start": 1297,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "\n from: \"System\"\n users: ['a... | src/invite.coffee | ndxbxrme/ndx-passport | 0 | 'use strict'
module.exports = (ndx) ->
if ndx.settings.HAS_INVITE or process.env.HAS_INVITE
ndx.passport.inviteTokenHours = 7 * 24
if typeof btoa is 'undefined'
global.btoa = (str) ->
new Buffer(str).toString 'base64'
if typeof atob is 'undefined'
global.atob = (b64Encoded) ->
new Buffer(b64Encoded, 'base64').toString()
b64Enc = (str) ->
btoa
userFromToken = (token, cb) ->
parseToken = (token, cb) ->
try
cb null, JSON.parse ndx.parseToken(atob(decodeURIComponent(token)), true)
catch e
return cb e
if ndx.shortToken
ndx.shortToken.fetch token, (err, _token) ->
if err
cb err
else
parseToken _token, cb
else
parseToken token, cb
tokenFromUser = (user, cb) ->
token = encodeURIComponent(btoa(ndx.generateToken(JSON.stringify(user), null, ndx.passport.inviteTokenHours, true)))
if ndx.shortToken
ndx.shortToken.generate token, (shortToken) ->
cb shortToken
else
cb token
ndx.invite =
fetchTemplate: (data, cb) ->
cb
subject: "You have been invited"
body: 'h1 invite\np\n a(href="#{code}")= code'
from: "System"
users: ['admin', 'superadmin']
userFromToken: userFromToken
tokenFromUser: tokenFromUser
ndx.app.post '/invite/accept', (req, res, next) ->
userFromToken req.body.code, (err, user) ->
if err
return next err
else
ndx.database.select ndx.settings.USER_TABLE,
where:
local:
email: user.local.email
, (users) ->
if users and users.length
return next 'User already exists'
delete req.body.user.roles
delete req.body.user.type
ndx.extend user, req.body.user
user.local.password = ndx.generateHash user.local.password
ndx.database.insert ndx.settings.USER_TABLE, user, ->
if ndx.shortToken
ndx.shortToken.remove req.body.code
ndx.passport.syncCallback 'inviteAccepted',
obj: user
code: req.body.code
res.end 'OK'
ndx.app.get '/invite/user/:code', (req, res, next) ->
userFromToken req.params.code, (err, user) ->
if err
return next err
ndx.passport.fetchByEmail user.local.email, (users) ->
if users and users.length
user.$exists = true
res.json user
ndx.app.post '/api/get-invite-code', ndx.authenticate(), (req, res, next) ->
delete req.body._id
((user) ->
ndx.passport.fetchByEmail req.body.local.email, (users) ->
if users and users.length
obj =
error: 'User already exists'
dbUser: users[0]
newUser: req.body
ndx.passport.asyncCallback 'inviteUserExists', obj, (result) ->
if obj.error
return next obj.error
else
return res.json obj
else
tokenFromUser req.body, (token) ->
host = process.env.HOST or ndx.settings.HOST or "#{req.protocol}://#{req.hostname}"
ndx.invite.fetchTemplate req.body, (inviteTemplate) ->
if ndx.email
ndx.email.send
to: req.body.local.email
from: inviteTemplate.from
subject: inviteTemplate.subject
body: inviteTemplate.body
data: req.body
code: "#{host}/invite/#{token}"
host: host
ndx.passport.syncCallback 'invited',
user: user
obj: req.body
code: token
expires: new Date().valueOf() + (ndx.passport.inviteTokenHours * 60 * 60 * 1000)
res.end "#{host}/invite/#{token}"
)(ndx.user) | 143936 | 'use strict'
module.exports = (ndx) ->
if ndx.settings.HAS_INVITE or process.env.HAS_INVITE
ndx.passport.inviteTokenHours = 7 * 24
if typeof btoa is 'undefined'
global.btoa = (str) ->
new Buffer(str).toString 'base64'
if typeof atob is 'undefined'
global.atob = (b64Encoded) ->
new Buffer(b64Encoded, 'base64').toString()
b64Enc = (str) ->
btoa
userFromToken = (token, cb) ->
parseToken = (token, cb) ->
try
cb null, JSON.parse ndx.parseToken(atob(decodeURIComponent(token)), true)
catch e
return cb e
if ndx.shortToken
ndx.shortToken.fetch token, (err, _token) ->
if err
cb err
else
parseToken _token, cb
else
parseToken token, cb
tokenFromUser = (user, cb) ->
token = encodeURIComponent(btoa(ndx.generateToken(JSON.stringify(user), null, ndx.passport.inviteTokenHours, true)))
if ndx.shortToken
ndx.shortToken.generate token, (shortToken) ->
cb shortToken
else
cb token
ndx.invite =
fetchTemplate: (data, cb) ->
cb
subject: "You have been invited"
body: 'h1 invite\np\n a(href="#{code}")= code'
from: "System"
users: ['admin', 'superadmin']
userFromToken: userFromToken
tokenFromUser: tokenFromUser
ndx.app.post '/invite/accept', (req, res, next) ->
userFromToken req.body.code, (err, user) ->
if err
return next err
else
ndx.database.select ndx.settings.USER_TABLE,
where:
local:
email: user.local.email
, (users) ->
if users and users.length
return next 'User already exists'
delete req.body.user.roles
delete req.body.user.type
ndx.extend user, req.body.user
user.local.password = <PASSWORD>Hash user.local.password
ndx.database.insert ndx.settings.USER_TABLE, user, ->
if ndx.shortToken
ndx.shortToken.remove req.body.code
ndx.passport.syncCallback 'inviteAccepted',
obj: user
code: req.body.code
res.end 'OK'
ndx.app.get '/invite/user/:code', (req, res, next) ->
userFromToken req.params.code, (err, user) ->
if err
return next err
ndx.passport.fetchByEmail user.local.email, (users) ->
if users and users.length
user.$exists = true
res.json user
ndx.app.post '/api/get-invite-code', ndx.authenticate(), (req, res, next) ->
delete req.body._id
((user) ->
ndx.passport.fetchByEmail req.body.local.email, (users) ->
if users and users.length
obj =
error: 'User already exists'
dbUser: users[0]
newUser: req.body
ndx.passport.asyncCallback 'inviteUserExists', obj, (result) ->
if obj.error
return next obj.error
else
return res.json obj
else
tokenFromUser req.body, (token) ->
host = process.env.HOST or ndx.settings.HOST or "#{req.protocol}://#{req.hostname}"
ndx.invite.fetchTemplate req.body, (inviteTemplate) ->
if ndx.email
ndx.email.send
to: req.body.local.email
from: inviteTemplate.from
subject: inviteTemplate.subject
body: inviteTemplate.body
data: req.body
code: "#{host}/invite/#{token}"
host: host
ndx.passport.syncCallback 'invited',
user: user
obj: req.body
code: token
expires: new Date().valueOf() + (ndx.passport.inviteTokenHours * 60 * 60 * 1000)
res.end "#{host}/invite/#{token}"
)(ndx.user) | true | 'use strict'
module.exports = (ndx) ->
if ndx.settings.HAS_INVITE or process.env.HAS_INVITE
ndx.passport.inviteTokenHours = 7 * 24
if typeof btoa is 'undefined'
global.btoa = (str) ->
new Buffer(str).toString 'base64'
if typeof atob is 'undefined'
global.atob = (b64Encoded) ->
new Buffer(b64Encoded, 'base64').toString()
b64Enc = (str) ->
btoa
userFromToken = (token, cb) ->
parseToken = (token, cb) ->
try
cb null, JSON.parse ndx.parseToken(atob(decodeURIComponent(token)), true)
catch e
return cb e
if ndx.shortToken
ndx.shortToken.fetch token, (err, _token) ->
if err
cb err
else
parseToken _token, cb
else
parseToken token, cb
tokenFromUser = (user, cb) ->
token = encodeURIComponent(btoa(ndx.generateToken(JSON.stringify(user), null, ndx.passport.inviteTokenHours, true)))
if ndx.shortToken
ndx.shortToken.generate token, (shortToken) ->
cb shortToken
else
cb token
ndx.invite =
fetchTemplate: (data, cb) ->
cb
subject: "You have been invited"
body: 'h1 invite\np\n a(href="#{code}")= code'
from: "System"
users: ['admin', 'superadmin']
userFromToken: userFromToken
tokenFromUser: tokenFromUser
ndx.app.post '/invite/accept', (req, res, next) ->
userFromToken req.body.code, (err, user) ->
if err
return next err
else
ndx.database.select ndx.settings.USER_TABLE,
where:
local:
email: user.local.email
, (users) ->
if users and users.length
return next 'User already exists'
delete req.body.user.roles
delete req.body.user.type
ndx.extend user, req.body.user
user.local.password = PI:PASSWORD:<PASSWORD>END_PIHash user.local.password
ndx.database.insert ndx.settings.USER_TABLE, user, ->
if ndx.shortToken
ndx.shortToken.remove req.body.code
ndx.passport.syncCallback 'inviteAccepted',
obj: user
code: req.body.code
res.end 'OK'
ndx.app.get '/invite/user/:code', (req, res, next) ->
userFromToken req.params.code, (err, user) ->
if err
return next err
ndx.passport.fetchByEmail user.local.email, (users) ->
if users and users.length
user.$exists = true
res.json user
ndx.app.post '/api/get-invite-code', ndx.authenticate(), (req, res, next) ->
delete req.body._id
((user) ->
ndx.passport.fetchByEmail req.body.local.email, (users) ->
if users and users.length
obj =
error: 'User already exists'
dbUser: users[0]
newUser: req.body
ndx.passport.asyncCallback 'inviteUserExists', obj, (result) ->
if obj.error
return next obj.error
else
return res.json obj
else
tokenFromUser req.body, (token) ->
host = process.env.HOST or ndx.settings.HOST or "#{req.protocol}://#{req.hostname}"
ndx.invite.fetchTemplate req.body, (inviteTemplate) ->
if ndx.email
ndx.email.send
to: req.body.local.email
from: inviteTemplate.from
subject: inviteTemplate.subject
body: inviteTemplate.body
data: req.body
code: "#{host}/invite/#{token}"
host: host
ndx.passport.syncCallback 'invited',
user: user
obj: req.body
code: token
expires: new Date().valueOf() + (ndx.passport.inviteTokenHours * 60 * 60 * 1000)
res.end "#{host}/invite/#{token}"
)(ndx.user) |
[
{
"context": "ew Tests for array-element-newline rule.\n# @author Jan Peer Stöcklmair <https:#github.com/JPeer264>\n###\n\n'use strict'\n\n#",
"end": 88,
"score": 0.9998975992202759,
"start": 69,
"tag": "NAME",
"value": "Jan Peer Stöcklmair"
},
{
"context": "\n# @author Jan Peer Stöc... | src/tests/rules/array-element-newline.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for array-element-newline rule.
# @author Jan Peer Stöcklmair <https:#github.com/JPeer264>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/array-element-newline'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'array-element-newline', rule,
valid: [
###
# ArrayExpression
# "always"
###
'foo = []'
'foo = [1]'
'''
foo = [1,
2]
'''
'''
foo = [1
2]
'''
'''
foo = [1, # any comment
2]
'''
'''
foo = [# any comment
1
2]
'''
'''
foo = [1,
2 # any comment
]
'''
'''
foo = [1,
2,
3
]
'''
'''
foo = [1
, (2
; 3)]
'''
'''
foo = [1,
( 2 ),
3]
'''
'''
foo = [1,
((((2)))),
3]
'''
'''
foo = [1,
(
2
),
3]
'''
'''
foo = [1,
(2),
3]
'''
'''
foo = [1,
(2)
, 3]
'''
'''
foo = [1
, 2
, 3]
'''
'''
foo = [1,
2,
,
3]
'''
'''
foo = [
->
dosomething()
, ->
osomething()
]
'''
,
code: 'foo = []', options: ['always']
,
code: 'foo = [1]', options: ['always']
,
code: '''
foo = [1,
2]
'''
options: ['always']
,
code: '''
foo = [1,
(2)]
'''
options: ['always']
,
code: '''
foo = [1
, (2)]
'''
options: ['always']
,
code: '''
foo = [1, # any comment
2]
'''
options: ['always']
,
code: '''
foo = [# any comment
1
2]
'''
options: ['always']
,
code: '''
foo = [1
2 # any comment
]
'''
options: ['always']
,
code: '''
foo = [1,
2,
3]
'''
options: ['always']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['always']
,
# "never"
code: 'foo = []', options: ['never']
,
code: 'foo = [1]', options: ['never']
,
code: 'foo = [1, 2]', options: ['never']
,
code: 'foo = [1, ### any comment ### 2]', options: ['never']
,
code: 'foo = [### any comment ### 1, 2]', options: ['never']
,
code: 'foo = ### any comment ### [1, 2]', options: ['never']
,
code: 'foo = [1, 2, 3]', options: ['never']
,
code: '''
foo = [1, (
2
), 3]
'''
options: ['never']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['never']
,
code: '''
foo = [
->
dosomething()
,
->
dosomething()
]
'''
options: ['never']
,
# "consistent"
code: 'foo = []', options: ['consistent']
,
code: 'foo = [1]', options: ['consistent']
,
code: 'foo = [1, 2]', options: ['consistent']
,
code: '''
foo = [1,
2]
'''
options: ['consistent']
,
code: 'foo = [1, 2, 3]', options: ['consistent']
,
code: '''
foo = [1,
2,
3]
'''
options: ['consistent']
,
code: '''
foo = [1,
2,
,
3]
'''
options: ['consistent']
,
code: '''
foo = [1, # any comment
2]
'''
options: ['consistent']
,
code: 'foo = [### any comment ### 1, 2]', options: ['consistent']
,
code: '''
foo = [1, (
2
), 3]
'''
options: ['consistent']
,
code: '''
foo = [1,
(2)
, 3]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
, ->
dosomething()
, ->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: 'foo = []', options: [multiline: yes]
,
code: 'foo = [1]', options: [multiline: yes]
,
code: 'foo = [1, 2]', options: [multiline: yes]
,
code: 'foo = [1, 2, 3]', options: [multiline: yes]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [multiline: yes]
,
# { minItems: null }
code: 'foo = []', options: [minItems: null]
,
code: 'foo = [1]', options: [minItems: null]
,
code: 'foo = [1, 2]', options: [minItems: null]
,
code: 'foo = [1, 2, 3]', options: [minItems: null]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: null]
,
# { minItems: 0 }
code: 'foo = []', options: [minItems: 0]
,
code: 'foo = [1]', options: [minItems: 0]
,
code: '''
foo = [1,
2]
'''
options: [minItems: 0]
,
code: '''
foo = [1,
2,
3]
'''
options: [minItems: 0]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: 0]
,
# { minItems: 3 }
code: 'foo = []', options: [minItems: 3]
,
code: 'foo = [1]', options: [minItems: 3]
,
code: 'foo = [1, 2]', options: [minItems: 3]
,
code: '''
foo = [1,
2,
3]
'''
options: [minItems: 3]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: 3]
,
# { multiline: true, minItems: 3 }
code: 'foo = []', options: [multiline: yes, minItems: 3]
,
code: 'foo = [1]', options: [multiline: yes, minItems: 3]
,
code: 'foo = [1, 2]', options: [multiline: yes, minItems: 3]
,
code: '''
foo = [1, # any comment
2,
, 3]
'''
options: [multiline: yes, minItems: 3]
,
code: '''
foo = [1,
2,
# any comment
, 3]
'''
options: [multiline: yes, minItems: 3]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [multiline: yes, minItems: 3]
,
###
# ArrayPattern
# "always"
###
code: '[] = foo'
,
code: '[a] = foo'
,
code: '''
[a,
b] = foo
'''
,
code: '''
[a, # any comment
b] = foo
'''
,
code: '''
[# any comment
a,
b] = foo
'''
,
code: '''
[a,
b # any comment
] = foo
'''
,
code: '''
[a,
b,
b] = foo
'''
,
# { minItems: 3 }
code: '[] = foo'
options: [minItems: 3]
,
code: '[a] = foo'
options: [minItems: 3]
,
code: '[a, b] = foo'
options: [minItems: 3]
,
code: '''
[a,
b,
c] = foo
'''
options: [minItems: 3]
]
invalid: [
###
# ArrayExpression
# "always"
###
code: 'foo = [1, 2]'
# output: 'foo = [1,\n2]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 13
endLine: 1
endColumn: 14
]
,
code: 'foo = [1,2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 10
,
messageId: 'missingLineBreak'
line: 1
column: 12
endLine: 1
endColumn: 13
]
,
code: 'foo = [1, (2), 3]'
# output: 'foo = [1,\n(2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 15
endLine: 1
endColumn: 16
]
,
code: '''
foo = [1,(
2
), 3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 3
column: 5
]
,
code: '''
foo = [1, \t (
2
),
3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, ((((2)))), 3]'
# output: 'foo = [1,\n((((2)))),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 21
endLine: 1
endColumn: 22
]
,
code: 'foo = [1,### any comment ###(2), 3]'
# output: 'foo = [1,### any comment ###\n(2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 29
endLine: 1
endColumn: 29
,
messageId: 'missingLineBreak'
line: 1
column: 33
endLine: 1
endColumn: 34
]
,
code: 'foo = [1,( 2), 3]'
# output: 'foo = [1,\n( 2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 10
,
messageId: 'missingLineBreak'
line: 1
column: 16
endLine: 1
endColumn: 17
]
,
code: 'foo = [1, [2], 3]'
# output: 'foo = [1,\n[2],\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 15
endLine: 1
endColumn: 16
]
,
# "never"
code: '''
foo = [
1,
2
]
'''
# output: 'foo = [\n1, 2\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
]
,
code: '''
foo = [
1
, 2
]
'''
# output: 'foo = [\n1, 2\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 3
column: 4
]
,
code: '''
foo = [
1 # any comment
, 2
]
'''
# output: null
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 3
column: 4
]
,
code: '''
foo = [
1, # any comment
2
]
'''
# output: null
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 19
]
,
code: '''
foo = [
1,
2 # any comment
]
'''
# output: 'foo = [\n1, 2 # any comment\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
]
,
code: '''
foo = [
1,
2,
3
]
'''
# output: 'foo = [\n1, 2, 3\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
endLine: 3
endColumn: 3
,
messageId: 'unexpectedLineBreak'
line: 3
column: 5
endLine: 4
endColumn: 3
]
,
# "consistent"
code: '''
foo = [1,
2, 3]
'''
# output: 'foo = [1,\n2,\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 2
column: 3
endLine: 2
endColumn: 4
]
,
code: '''
foo = [1, 2,
3]
'''
# output: 'foo = [1,\n2,\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
]
,
code: '''
foo = [1,
(
2), 3]
'''
# output: 'foo = [1,\n(\n2),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 3
column: 6
endLine: 3
endColumn: 7
]
,
code: '''
foo = [1, \t (
2
),
3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 25
]
,
code: '''
foo = [1, ### any comment ###(2),
3]
'''
# output: 'foo = [1, ### any comment ###\n(2),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 30
]
,
# { multiline: true }
code: '''
foo = [1,
2, 3]
'''
# output: 'foo = [1, 2, 3]'
options: [multiline: yes]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
# { minItems: null }
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [minItems: null]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
code: '''
foo = [1,
2,
3]
'''
# output: 'foo = [1, 2, 3]'
options: [minItems: null]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
,
messageId: 'unexpectedLineBreak'
line: 2
column: 3
]
,
# { minItems: 0 }
code: 'foo = [1, 2]'
# output: 'foo = [1,\n2]'
options: [minItems: 0]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [minItems: 0]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
# { minItems: 3 }
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
# { multiline: true, minItems: 3 }
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [multiline: yes, minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [multiline: yes, minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
###
# ArrayPattern
# "always"
###
code: '[a, b] = foo'
# output: '[a,\nb] = foo'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
]
,
code: '[a, b, c] = foo'
# output: '[a,\nb,\nc] = foo'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
,
messageId: 'missingLineBreak'
line: 1
column: 7
]
,
# { minItems: 3 }
code: '''
[a,
b] = foo
'''
# output: '[a, b] = foo'
options: [minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 4
]
,
code: '[a, b, c] = foo'
# output: '[a,\nb,\nc] = foo'
options: [minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
,
messageId: 'missingLineBreak'
line: 1
column: 7
]
]
| 64918 | ###*
# @fileoverview Tests for array-element-newline rule.
# @author <NAME> <https:#github.com/JPeer264>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/array-element-newline'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'array-element-newline', rule,
valid: [
###
# ArrayExpression
# "always"
###
'foo = []'
'foo = [1]'
'''
foo = [1,
2]
'''
'''
foo = [1
2]
'''
'''
foo = [1, # any comment
2]
'''
'''
foo = [# any comment
1
2]
'''
'''
foo = [1,
2 # any comment
]
'''
'''
foo = [1,
2,
3
]
'''
'''
foo = [1
, (2
; 3)]
'''
'''
foo = [1,
( 2 ),
3]
'''
'''
foo = [1,
((((2)))),
3]
'''
'''
foo = [1,
(
2
),
3]
'''
'''
foo = [1,
(2),
3]
'''
'''
foo = [1,
(2)
, 3]
'''
'''
foo = [1
, 2
, 3]
'''
'''
foo = [1,
2,
,
3]
'''
'''
foo = [
->
dosomething()
, ->
osomething()
]
'''
,
code: 'foo = []', options: ['always']
,
code: 'foo = [1]', options: ['always']
,
code: '''
foo = [1,
2]
'''
options: ['always']
,
code: '''
foo = [1,
(2)]
'''
options: ['always']
,
code: '''
foo = [1
, (2)]
'''
options: ['always']
,
code: '''
foo = [1, # any comment
2]
'''
options: ['always']
,
code: '''
foo = [# any comment
1
2]
'''
options: ['always']
,
code: '''
foo = [1
2 # any comment
]
'''
options: ['always']
,
code: '''
foo = [1,
2,
3]
'''
options: ['always']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['always']
,
# "never"
code: 'foo = []', options: ['never']
,
code: 'foo = [1]', options: ['never']
,
code: 'foo = [1, 2]', options: ['never']
,
code: 'foo = [1, ### any comment ### 2]', options: ['never']
,
code: 'foo = [### any comment ### 1, 2]', options: ['never']
,
code: 'foo = ### any comment ### [1, 2]', options: ['never']
,
code: 'foo = [1, 2, 3]', options: ['never']
,
code: '''
foo = [1, (
2
), 3]
'''
options: ['never']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['never']
,
code: '''
foo = [
->
dosomething()
,
->
dosomething()
]
'''
options: ['never']
,
# "consistent"
code: 'foo = []', options: ['consistent']
,
code: 'foo = [1]', options: ['consistent']
,
code: 'foo = [1, 2]', options: ['consistent']
,
code: '''
foo = [1,
2]
'''
options: ['consistent']
,
code: 'foo = [1, 2, 3]', options: ['consistent']
,
code: '''
foo = [1,
2,
3]
'''
options: ['consistent']
,
code: '''
foo = [1,
2,
,
3]
'''
options: ['consistent']
,
code: '''
foo = [1, # any comment
2]
'''
options: ['consistent']
,
code: 'foo = [### any comment ### 1, 2]', options: ['consistent']
,
code: '''
foo = [1, (
2
), 3]
'''
options: ['consistent']
,
code: '''
foo = [1,
(2)
, 3]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
, ->
dosomething()
, ->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: 'foo = []', options: [multiline: yes]
,
code: 'foo = [1]', options: [multiline: yes]
,
code: 'foo = [1, 2]', options: [multiline: yes]
,
code: 'foo = [1, 2, 3]', options: [multiline: yes]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [multiline: yes]
,
# { minItems: null }
code: 'foo = []', options: [minItems: null]
,
code: 'foo = [1]', options: [minItems: null]
,
code: 'foo = [1, 2]', options: [minItems: null]
,
code: 'foo = [1, 2, 3]', options: [minItems: null]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: null]
,
# { minItems: 0 }
code: 'foo = []', options: [minItems: 0]
,
code: 'foo = [1]', options: [minItems: 0]
,
code: '''
foo = [1,
2]
'''
options: [minItems: 0]
,
code: '''
foo = [1,
2,
3]
'''
options: [minItems: 0]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: 0]
,
# { minItems: 3 }
code: 'foo = []', options: [minItems: 3]
,
code: 'foo = [1]', options: [minItems: 3]
,
code: 'foo = [1, 2]', options: [minItems: 3]
,
code: '''
foo = [1,
2,
3]
'''
options: [minItems: 3]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: 3]
,
# { multiline: true, minItems: 3 }
code: 'foo = []', options: [multiline: yes, minItems: 3]
,
code: 'foo = [1]', options: [multiline: yes, minItems: 3]
,
code: 'foo = [1, 2]', options: [multiline: yes, minItems: 3]
,
code: '''
foo = [1, # any comment
2,
, 3]
'''
options: [multiline: yes, minItems: 3]
,
code: '''
foo = [1,
2,
# any comment
, 3]
'''
options: [multiline: yes, minItems: 3]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [multiline: yes, minItems: 3]
,
###
# ArrayPattern
# "always"
###
code: '[] = foo'
,
code: '[a] = foo'
,
code: '''
[a,
b] = foo
'''
,
code: '''
[a, # any comment
b] = foo
'''
,
code: '''
[# any comment
a,
b] = foo
'''
,
code: '''
[a,
b # any comment
] = foo
'''
,
code: '''
[a,
b,
b] = foo
'''
,
# { minItems: 3 }
code: '[] = foo'
options: [minItems: 3]
,
code: '[a] = foo'
options: [minItems: 3]
,
code: '[a, b] = foo'
options: [minItems: 3]
,
code: '''
[a,
b,
c] = foo
'''
options: [minItems: 3]
]
invalid: [
###
# ArrayExpression
# "always"
###
code: 'foo = [1, 2]'
# output: 'foo = [1,\n2]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 13
endLine: 1
endColumn: 14
]
,
code: 'foo = [1,2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 10
,
messageId: 'missingLineBreak'
line: 1
column: 12
endLine: 1
endColumn: 13
]
,
code: 'foo = [1, (2), 3]'
# output: 'foo = [1,\n(2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 15
endLine: 1
endColumn: 16
]
,
code: '''
foo = [1,(
2
), 3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 3
column: 5
]
,
code: '''
foo = [1, \t (
2
),
3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, ((((2)))), 3]'
# output: 'foo = [1,\n((((2)))),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 21
endLine: 1
endColumn: 22
]
,
code: 'foo = [1,### any comment ###(2), 3]'
# output: 'foo = [1,### any comment ###\n(2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 29
endLine: 1
endColumn: 29
,
messageId: 'missingLineBreak'
line: 1
column: 33
endLine: 1
endColumn: 34
]
,
code: 'foo = [1,( 2), 3]'
# output: 'foo = [1,\n( 2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 10
,
messageId: 'missingLineBreak'
line: 1
column: 16
endLine: 1
endColumn: 17
]
,
code: 'foo = [1, [2], 3]'
# output: 'foo = [1,\n[2],\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 15
endLine: 1
endColumn: 16
]
,
# "never"
code: '''
foo = [
1,
2
]
'''
# output: 'foo = [\n1, 2\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
]
,
code: '''
foo = [
1
, 2
]
'''
# output: 'foo = [\n1, 2\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 3
column: 4
]
,
code: '''
foo = [
1 # any comment
, 2
]
'''
# output: null
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 3
column: 4
]
,
code: '''
foo = [
1, # any comment
2
]
'''
# output: null
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 19
]
,
code: '''
foo = [
1,
2 # any comment
]
'''
# output: 'foo = [\n1, 2 # any comment\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
]
,
code: '''
foo = [
1,
2,
3
]
'''
# output: 'foo = [\n1, 2, 3\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
endLine: 3
endColumn: 3
,
messageId: 'unexpectedLineBreak'
line: 3
column: 5
endLine: 4
endColumn: 3
]
,
# "consistent"
code: '''
foo = [1,
2, 3]
'''
# output: 'foo = [1,\n2,\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 2
column: 3
endLine: 2
endColumn: 4
]
,
code: '''
foo = [1, 2,
3]
'''
# output: 'foo = [1,\n2,\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
]
,
code: '''
foo = [1,
(
2), 3]
'''
# output: 'foo = [1,\n(\n2),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 3
column: 6
endLine: 3
endColumn: 7
]
,
code: '''
foo = [1, \t (
2
),
3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 25
]
,
code: '''
foo = [1, ### any comment ###(2),
3]
'''
# output: 'foo = [1, ### any comment ###\n(2),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 30
]
,
# { multiline: true }
code: '''
foo = [1,
2, 3]
'''
# output: 'foo = [1, 2, 3]'
options: [multiline: yes]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
# { minItems: null }
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [minItems: null]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
code: '''
foo = [1,
2,
3]
'''
# output: 'foo = [1, 2, 3]'
options: [minItems: null]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
,
messageId: 'unexpectedLineBreak'
line: 2
column: 3
]
,
# { minItems: 0 }
code: 'foo = [1, 2]'
# output: 'foo = [1,\n2]'
options: [minItems: 0]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [minItems: 0]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
# { minItems: 3 }
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
# { multiline: true, minItems: 3 }
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [multiline: yes, minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [multiline: yes, minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
###
# ArrayPattern
# "always"
###
code: '[a, b] = foo'
# output: '[a,\nb] = foo'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
]
,
code: '[a, b, c] = foo'
# output: '[a,\nb,\nc] = foo'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
,
messageId: 'missingLineBreak'
line: 1
column: 7
]
,
# { minItems: 3 }
code: '''
[a,
b] = foo
'''
# output: '[a, b] = foo'
options: [minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 4
]
,
code: '[a, b, c] = foo'
# output: '[a,\nb,\nc] = foo'
options: [minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
,
messageId: 'missingLineBreak'
line: 1
column: 7
]
]
| true | ###*
# @fileoverview Tests for array-element-newline rule.
# @author PI:NAME:<NAME>END_PI <https:#github.com/JPeer264>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/array-element-newline'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'array-element-newline', rule,
valid: [
###
# ArrayExpression
# "always"
###
'foo = []'
'foo = [1]'
'''
foo = [1,
2]
'''
'''
foo = [1
2]
'''
'''
foo = [1, # any comment
2]
'''
'''
foo = [# any comment
1
2]
'''
'''
foo = [1,
2 # any comment
]
'''
'''
foo = [1,
2,
3
]
'''
'''
foo = [1
, (2
; 3)]
'''
'''
foo = [1,
( 2 ),
3]
'''
'''
foo = [1,
((((2)))),
3]
'''
'''
foo = [1,
(
2
),
3]
'''
'''
foo = [1,
(2),
3]
'''
'''
foo = [1,
(2)
, 3]
'''
'''
foo = [1
, 2
, 3]
'''
'''
foo = [1,
2,
,
3]
'''
'''
foo = [
->
dosomething()
, ->
osomething()
]
'''
,
code: 'foo = []', options: ['always']
,
code: 'foo = [1]', options: ['always']
,
code: '''
foo = [1,
2]
'''
options: ['always']
,
code: '''
foo = [1,
(2)]
'''
options: ['always']
,
code: '''
foo = [1
, (2)]
'''
options: ['always']
,
code: '''
foo = [1, # any comment
2]
'''
options: ['always']
,
code: '''
foo = [# any comment
1
2]
'''
options: ['always']
,
code: '''
foo = [1
2 # any comment
]
'''
options: ['always']
,
code: '''
foo = [1,
2,
3]
'''
options: ['always']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['always']
,
# "never"
code: 'foo = []', options: ['never']
,
code: 'foo = [1]', options: ['never']
,
code: 'foo = [1, 2]', options: ['never']
,
code: 'foo = [1, ### any comment ### 2]', options: ['never']
,
code: 'foo = [### any comment ### 1, 2]', options: ['never']
,
code: 'foo = ### any comment ### [1, 2]', options: ['never']
,
code: 'foo = [1, 2, 3]', options: ['never']
,
code: '''
foo = [1, (
2
), 3]
'''
options: ['never']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['never']
,
code: '''
foo = [
->
dosomething()
,
->
dosomething()
]
'''
options: ['never']
,
# "consistent"
code: 'foo = []', options: ['consistent']
,
code: 'foo = [1]', options: ['consistent']
,
code: 'foo = [1, 2]', options: ['consistent']
,
code: '''
foo = [1,
2]
'''
options: ['consistent']
,
code: 'foo = [1, 2, 3]', options: ['consistent']
,
code: '''
foo = [1,
2,
3]
'''
options: ['consistent']
,
code: '''
foo = [1,
2,
,
3]
'''
options: ['consistent']
,
code: '''
foo = [1, # any comment
2]
'''
options: ['consistent']
,
code: 'foo = [### any comment ### 1, 2]', options: ['consistent']
,
code: '''
foo = [1, (
2
), 3]
'''
options: ['consistent']
,
code: '''
foo = [1,
(2)
, 3]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
, ->
dosomething()
, ->
dosomething()
]
'''
options: ['consistent']
,
code: '''
foo = [
->
dosomething()
->
dosomething()
->
dosomething()
]
'''
options: ['consistent']
,
code: 'foo = []', options: [multiline: yes]
,
code: 'foo = [1]', options: [multiline: yes]
,
code: 'foo = [1, 2]', options: [multiline: yes]
,
code: 'foo = [1, 2, 3]', options: [multiline: yes]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [multiline: yes]
,
# { minItems: null }
code: 'foo = []', options: [minItems: null]
,
code: 'foo = [1]', options: [minItems: null]
,
code: 'foo = [1, 2]', options: [minItems: null]
,
code: 'foo = [1, 2, 3]', options: [minItems: null]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: null]
,
# { minItems: 0 }
code: 'foo = []', options: [minItems: 0]
,
code: 'foo = [1]', options: [minItems: 0]
,
code: '''
foo = [1,
2]
'''
options: [minItems: 0]
,
code: '''
foo = [1,
2,
3]
'''
options: [minItems: 0]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: 0]
,
# { minItems: 3 }
code: 'foo = []', options: [minItems: 3]
,
code: 'foo = [1]', options: [minItems: 3]
,
code: 'foo = [1, 2]', options: [minItems: 3]
,
code: '''
foo = [1,
2,
3]
'''
options: [minItems: 3]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [minItems: 3]
,
# { multiline: true, minItems: 3 }
code: 'foo = []', options: [multiline: yes, minItems: 3]
,
code: 'foo = [1]', options: [multiline: yes, minItems: 3]
,
code: 'foo = [1, 2]', options: [multiline: yes, minItems: 3]
,
code: '''
foo = [1, # any comment
2,
, 3]
'''
options: [multiline: yes, minItems: 3]
,
code: '''
foo = [1,
2,
# any comment
, 3]
'''
options: [multiline: yes, minItems: 3]
,
code: '''
f = [
->
dosomething()
->
dosomething()
]
'''
options: [multiline: yes, minItems: 3]
,
###
# ArrayPattern
# "always"
###
code: '[] = foo'
,
code: '[a] = foo'
,
code: '''
[a,
b] = foo
'''
,
code: '''
[a, # any comment
b] = foo
'''
,
code: '''
[# any comment
a,
b] = foo
'''
,
code: '''
[a,
b # any comment
] = foo
'''
,
code: '''
[a,
b,
b] = foo
'''
,
# { minItems: 3 }
code: '[] = foo'
options: [minItems: 3]
,
code: '[a] = foo'
options: [minItems: 3]
,
code: '[a, b] = foo'
options: [minItems: 3]
,
code: '''
[a,
b,
c] = foo
'''
options: [minItems: 3]
]
invalid: [
###
# ArrayExpression
# "always"
###
code: 'foo = [1, 2]'
# output: 'foo = [1,\n2]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 13
endLine: 1
endColumn: 14
]
,
code: 'foo = [1,2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 10
,
messageId: 'missingLineBreak'
line: 1
column: 12
endLine: 1
endColumn: 13
]
,
code: 'foo = [1, (2), 3]'
# output: 'foo = [1,\n(2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 15
endLine: 1
endColumn: 16
]
,
code: '''
foo = [1,(
2
), 3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 3
column: 5
]
,
code: '''
foo = [1, \t (
2
),
3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, ((((2)))), 3]'
# output: 'foo = [1,\n((((2)))),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 21
endLine: 1
endColumn: 22
]
,
code: 'foo = [1,### any comment ###(2), 3]'
# output: 'foo = [1,### any comment ###\n(2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 29
endLine: 1
endColumn: 29
,
messageId: 'missingLineBreak'
line: 1
column: 33
endLine: 1
endColumn: 34
]
,
code: 'foo = [1,( 2), 3]'
# output: 'foo = [1,\n( 2),\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 10
,
messageId: 'missingLineBreak'
line: 1
column: 16
endLine: 1
endColumn: 17
]
,
code: 'foo = [1, [2], 3]'
# output: 'foo = [1,\n[2],\n3]'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
,
messageId: 'missingLineBreak'
line: 1
column: 15
endLine: 1
endColumn: 16
]
,
# "never"
code: '''
foo = [
1,
2
]
'''
# output: 'foo = [\n1, 2\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
]
,
code: '''
foo = [
1
, 2
]
'''
# output: 'foo = [\n1, 2\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 3
column: 4
]
,
code: '''
foo = [
1 # any comment
, 2
]
'''
# output: null
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 3
column: 4
]
,
code: '''
foo = [
1, # any comment
2
]
'''
# output: null
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 19
]
,
code: '''
foo = [
1,
2 # any comment
]
'''
# output: 'foo = [\n1, 2 # any comment\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
]
,
code: '''
foo = [
1,
2,
3
]
'''
# output: 'foo = [\n1, 2, 3\n]'
options: ['never']
errors: [
messageId: 'unexpectedLineBreak'
line: 2
column: 5
endLine: 3
endColumn: 3
,
messageId: 'unexpectedLineBreak'
line: 3
column: 5
endLine: 4
endColumn: 3
]
,
# "consistent"
code: '''
foo = [1,
2, 3]
'''
# output: 'foo = [1,\n2,\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 2
column: 3
endLine: 2
endColumn: 4
]
,
code: '''
foo = [1, 2,
3]
'''
# output: 'foo = [1,\n2,\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 11
]
,
code: '''
foo = [1,
(
2), 3]
'''
# output: 'foo = [1,\n(\n2),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 3
column: 6
endLine: 3
endColumn: 7
]
,
code: '''
foo = [1, \t (
2
),
3]
'''
# output: 'foo = [1,\n(\n2\n),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
endLine: 1
endColumn: 25
]
,
code: '''
foo = [1, ### any comment ###(2),
3]
'''
# output: 'foo = [1, ### any comment ###\n(2),\n3]'
options: ['consistent']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 30
]
,
# { multiline: true }
code: '''
foo = [1,
2, 3]
'''
# output: 'foo = [1, 2, 3]'
options: [multiline: yes]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
# { minItems: null }
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [minItems: null]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
code: '''
foo = [1,
2,
3]
'''
# output: 'foo = [1, 2, 3]'
options: [minItems: null]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
,
messageId: 'unexpectedLineBreak'
line: 2
column: 3
]
,
# { minItems: 0 }
code: 'foo = [1, 2]'
# output: 'foo = [1,\n2]'
options: [minItems: 0]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [minItems: 0]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
# { minItems: 3 }
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
# { multiline: true, minItems: 3 }
code: 'foo = [1, 2, 3]'
# output: 'foo = [1,\n2,\n3]'
options: [multiline: yes, minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 10
,
messageId: 'missingLineBreak'
line: 1
column: 13
]
,
code: '''
foo = [1,
2]
'''
# output: 'foo = [1, 2]'
options: [multiline: yes, minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 10
]
,
###
# ArrayPattern
# "always"
###
code: '[a, b] = foo'
# output: '[a,\nb] = foo'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
]
,
code: '[a, b, c] = foo'
# output: '[a,\nb,\nc] = foo'
options: ['always']
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
,
messageId: 'missingLineBreak'
line: 1
column: 7
]
,
# { minItems: 3 }
code: '''
[a,
b] = foo
'''
# output: '[a, b] = foo'
options: [minItems: 3]
errors: [
messageId: 'unexpectedLineBreak'
line: 1
column: 4
]
,
code: '[a, b, c] = foo'
# output: '[a,\nb,\nc] = foo'
options: [minItems: 3]
errors: [
messageId: 'missingLineBreak'
line: 1
column: 4
,
messageId: 'missingLineBreak'
line: 1
column: 7
]
]
|
[
{
"context": "# iplotScanone_noeff: LOD curves (nothing else)\n# Karl W Broman\n\niplotScanone_noeff = (data, chartOpts) ->\n\n #",
"end": 63,
"score": 0.9997667074203491,
"start": 50,
"tag": "NAME",
"value": "Karl W Broman"
}
] | inst/charts/iplotScanone_noeff.coffee | FourchettesDeInterActive/qtlcharts | 0 | # iplotScanone_noeff: LOD curves (nothing else)
# Karl W Broman
iplotScanone_noeff = (data, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 450 # height of image in pixels
width = chartOpts?.width ? 900 # width of image in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? chartOpts?.lod_ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis
yticks = chartOpts?.yticks ? chartOpts?.lod_yticks ? null # vector of tick positions for y-axis
chrGap = chartOpts?.chrGap ? 8 # gap between chromosomes in pixels
darkrect = chartOpts?.darkrect ? "#C8C8C8" # color of darker background rectangle
lightrect = chartOpts?.lightrect ? "#E6E6E6" # color of lighter background rectangle
linecolor = chartOpts?.linecolor ? chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves
linewidth = chartOpts?.linewidth ? chartOpts?.lod_linewidth ? 2 # line width for LOD curves
pointcolor = chartOpts?.pointcolor ? chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers
pointsize = chartOpts?.pointsize ? chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers)
pointstroke = chartOpts?.pointstroke ? chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers
title = chartOpts?.title ? chartOpts?.lod_title ? "" # title of chart
xlab = chartOpts?.xlab ? chartOpts?.lod_xlab ? "Chromosome" # x-axis label
ylab = chartOpts?.ylab ? chartOpts?.lod_ylab ? "LOD score" # y-axis label
rotate_ylab = chartOpts?.rotate_ylab ? chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
halfh = (height+margin.top+margin.bottom)
totalh = halfh*2
totalw = (width+margin.left+margin.right)
mylodchart = lodchart().lodvarname("lod")
.height(height)
.width(width)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.ylim(ylim)
.nyticks(nyticks)
.yticks(yticks)
.chrGap(chrGap)
.darkrect(darkrect)
.lightrect(lightrect)
.linecolor(linecolor)
.linewidth(linewidth)
.pointcolor(pointcolor)
.pointsize(pointsize)
.pointstroke(pointstroke)
.title(title)
.xlab(xlab)
.ylab(ylab)
.rotate_ylab(rotate_ylab)
d3.select("div##{chartdivid}")
.datum(data)
.call(mylodchart)
# animate points at markers on click
mylodchart.markerSelect()
.on "click", (d) ->
r = d3.select(this).attr("r")
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
| 211055 | # iplotScanone_noeff: LOD curves (nothing else)
# <NAME>
iplotScanone_noeff = (data, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 450 # height of image in pixels
width = chartOpts?.width ? 900 # width of image in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? chartOpts?.lod_ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis
yticks = chartOpts?.yticks ? chartOpts?.lod_yticks ? null # vector of tick positions for y-axis
chrGap = chartOpts?.chrGap ? 8 # gap between chromosomes in pixels
darkrect = chartOpts?.darkrect ? "#C8C8C8" # color of darker background rectangle
lightrect = chartOpts?.lightrect ? "#E6E6E6" # color of lighter background rectangle
linecolor = chartOpts?.linecolor ? chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves
linewidth = chartOpts?.linewidth ? chartOpts?.lod_linewidth ? 2 # line width for LOD curves
pointcolor = chartOpts?.pointcolor ? chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers
pointsize = chartOpts?.pointsize ? chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers)
pointstroke = chartOpts?.pointstroke ? chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers
title = chartOpts?.title ? chartOpts?.lod_title ? "" # title of chart
xlab = chartOpts?.xlab ? chartOpts?.lod_xlab ? "Chromosome" # x-axis label
ylab = chartOpts?.ylab ? chartOpts?.lod_ylab ? "LOD score" # y-axis label
rotate_ylab = chartOpts?.rotate_ylab ? chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
halfh = (height+margin.top+margin.bottom)
totalh = halfh*2
totalw = (width+margin.left+margin.right)
mylodchart = lodchart().lodvarname("lod")
.height(height)
.width(width)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.ylim(ylim)
.nyticks(nyticks)
.yticks(yticks)
.chrGap(chrGap)
.darkrect(darkrect)
.lightrect(lightrect)
.linecolor(linecolor)
.linewidth(linewidth)
.pointcolor(pointcolor)
.pointsize(pointsize)
.pointstroke(pointstroke)
.title(title)
.xlab(xlab)
.ylab(ylab)
.rotate_ylab(rotate_ylab)
d3.select("div##{chartdivid}")
.datum(data)
.call(mylodchart)
# animate points at markers on click
mylodchart.markerSelect()
.on "click", (d) ->
r = d3.select(this).attr("r")
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
| true | # iplotScanone_noeff: LOD curves (nothing else)
# PI:NAME:<NAME>END_PI
iplotScanone_noeff = (data, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 450 # height of image in pixels
width = chartOpts?.width ? 900 # width of image in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? chartOpts?.lod_ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis
yticks = chartOpts?.yticks ? chartOpts?.lod_yticks ? null # vector of tick positions for y-axis
chrGap = chartOpts?.chrGap ? 8 # gap between chromosomes in pixels
darkrect = chartOpts?.darkrect ? "#C8C8C8" # color of darker background rectangle
lightrect = chartOpts?.lightrect ? "#E6E6E6" # color of lighter background rectangle
linecolor = chartOpts?.linecolor ? chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves
linewidth = chartOpts?.linewidth ? chartOpts?.lod_linewidth ? 2 # line width for LOD curves
pointcolor = chartOpts?.pointcolor ? chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers
pointsize = chartOpts?.pointsize ? chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers)
pointstroke = chartOpts?.pointstroke ? chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers
title = chartOpts?.title ? chartOpts?.lod_title ? "" # title of chart
xlab = chartOpts?.xlab ? chartOpts?.lod_xlab ? "Chromosome" # x-axis label
ylab = chartOpts?.ylab ? chartOpts?.lod_ylab ? "LOD score" # y-axis label
rotate_ylab = chartOpts?.rotate_ylab ? chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
halfh = (height+margin.top+margin.bottom)
totalh = halfh*2
totalw = (width+margin.left+margin.right)
mylodchart = lodchart().lodvarname("lod")
.height(height)
.width(width)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.ylim(ylim)
.nyticks(nyticks)
.yticks(yticks)
.chrGap(chrGap)
.darkrect(darkrect)
.lightrect(lightrect)
.linecolor(linecolor)
.linewidth(linewidth)
.pointcolor(pointcolor)
.pointsize(pointsize)
.pointstroke(pointstroke)
.title(title)
.xlab(xlab)
.ylab(ylab)
.rotate_ylab(rotate_ylab)
d3.select("div##{chartdivid}")
.datum(data)
.call(mylodchart)
# animate points at markers on click
mylodchart.markerSelect()
.on "click", (d) ->
r = d3.select(this).attr("r")
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
|
[
{
"context": "imply run the stats job'\n .example '$0 stats -m info@alinex.de', 'run the job but send to given address'\n # g",
"end": 2552,
"score": 0.999923825263977,
"start": 2538,
"tag": "EMAIL",
"value": "info@alinex.de"
}
] | src/cli.coffee | alinex/node-dbreport | 0 | # Main class
# =================================================
# Node Modules
# -------------------------------------------------
# include base modules
yargs = require 'yargs'
# include alinex modules
config = require 'alinex-config'
database = require 'alinex-database'
Report = require 'alinex-report'
alinex = require 'alinex-core'
# include classes and helpers
dbreport = require './index'
process.title = 'DbReport'
logo = alinex.logo 'Database Reports'
# Support quiet mode through switch
# -------------------------------------------------
quiet = false
for a in ['--get-yargs-completions', 'bashrc', '-q', '--quiet']
quiet = true if a in process.argv
# Error management
# -------------------------------------------------
alinex.initExit()
process.on 'exit', ->
console.log "Goodbye\n"
database.close()
# Command Setup
# -------------------------------------------------
command = (name, conf) ->
# return builder and handler
builder: (yargs) ->
yargs
.usage "\nUsage: $0 #{name} [options]\n\n#{conf.description.trim() ? ''}"
.strict()
.options
help:
alias: 'h',
description: 'display help message'
nocolors:
alias: 'C'
description: 'turn of color output'
type: 'boolean'
quiet:
alias: 'q'
describe: "don't output header and footer"
type: 'boolean'
mail:
alias: 'm'
description: 'alternative email address to send to'
type: 'string'
json:
alias: 'j'
description: 'json formatted data object'
type: 'string'
.group ['m', 'j'], 'Report Options:'
.epilogue """
This is the description of the '#{name}' job. You may also look into the
general help or the man page.
"""
handler: (argv) ->
if argv.json
try
variables = JSON.parse argv.json
catch error
alinex.exit 2, error
dbreport.init
mail: argv.mail
variables: variables ? {}
# run the command
dbreport.run name, (err) ->
alinex.exit err
return true
# Main routine
# -------------------------------------------------
unless quiet
console.log logo
console.log "Initializing..."
dbreport.setup (err) ->
alinex.exit 16, err if err
config.init (err) ->
alinex.exit err if err
yargs
.usage "\nUsage: $0 <job...> [options]"
.env 'DBREPORT' # use environment arguments prefixed with DBREPORT_
# examples
.example '$0 stats', 'to simply run the stats job'
.example '$0 stats -m info@alinex.de', 'run the job but send to given address'
# general options
.options
help:
alias: 'h',
description: 'display help message'
nocolors:
alias: 'C'
description: 'turn of color output'
type: 'boolean'
quiet:
alias: 'q'
description: "don't output header and footer"
type: 'boolean'
list:
alias: 'l'
description: 'only list the possible jobs'
type: 'boolean'
mail:
alias: 'm'
description: 'alternative email address to send to'
type: 'string'
json:
alias: 'j'
description: 'json formatted data object'
type: 'string'
.group ['m', 'j'], 'Report Options:'
# add Commands
for job in dbreport.list()
conf = dbreport.get job
yargs.command job, conf.title, command job, conf
# general help
yargs.help 'help'
.updateStrings
'Options:': 'General Options:'
.epilogue """
You may use environment variables prefixed with 'DBREPORT_' to set any of
the options like 'DBREPORT_MAIL' to set the email address.
For more information, look into the man page.
"""
.completion 'bashrc-script', false
# validation
#.strict()
.fail (err) ->
err = new Error "CLI #{err}"
err.description = 'Specify --help for available options'
alinex.exit 2, err
# now parse the arguments
argv = yargs.argv
# list possible jobs
if argv.list
data = []
for job in dbreport.list()
conf = dbreport.get job
data.push
job: job
title: conf.title
to: conf.email.to?.map (e) -> e.replace /[ .@].*/, ''
.join ', '
report = new Report()
report.h1 "List of possible jobs:"
if data.length
report.table data, ['JOB', 'TITLE', 'TO']
report.p 'Run them using their job name.'
else
report.p 'No jobs defined, add them in your config!'
console.log()
console.log report.toConsole()
console.log()
# check for corrct call
else unless argv._.length
alinex.exit 2, new Error "Nothing to do specify --help for available options"
| 183776 | # Main class
# =================================================
# Node Modules
# -------------------------------------------------
# include base modules
yargs = require 'yargs'
# include alinex modules
config = require 'alinex-config'
database = require 'alinex-database'
Report = require 'alinex-report'
alinex = require 'alinex-core'
# include classes and helpers
dbreport = require './index'
process.title = 'DbReport'
logo = alinex.logo 'Database Reports'
# Support quiet mode through switch
# -------------------------------------------------
quiet = false
for a in ['--get-yargs-completions', 'bashrc', '-q', '--quiet']
quiet = true if a in process.argv
# Error management
# -------------------------------------------------
alinex.initExit()
process.on 'exit', ->
console.log "Goodbye\n"
database.close()
# Command Setup
# -------------------------------------------------
command = (name, conf) ->
# return builder and handler
builder: (yargs) ->
yargs
.usage "\nUsage: $0 #{name} [options]\n\n#{conf.description.trim() ? ''}"
.strict()
.options
help:
alias: 'h',
description: 'display help message'
nocolors:
alias: 'C'
description: 'turn of color output'
type: 'boolean'
quiet:
alias: 'q'
describe: "don't output header and footer"
type: 'boolean'
mail:
alias: 'm'
description: 'alternative email address to send to'
type: 'string'
json:
alias: 'j'
description: 'json formatted data object'
type: 'string'
.group ['m', 'j'], 'Report Options:'
.epilogue """
This is the description of the '#{name}' job. You may also look into the
general help or the man page.
"""
handler: (argv) ->
if argv.json
try
variables = JSON.parse argv.json
catch error
alinex.exit 2, error
dbreport.init
mail: argv.mail
variables: variables ? {}
# run the command
dbreport.run name, (err) ->
alinex.exit err
return true
# Main routine
# -------------------------------------------------
unless quiet
console.log logo
console.log "Initializing..."
dbreport.setup (err) ->
alinex.exit 16, err if err
config.init (err) ->
alinex.exit err if err
yargs
.usage "\nUsage: $0 <job...> [options]"
.env 'DBREPORT' # use environment arguments prefixed with DBREPORT_
# examples
.example '$0 stats', 'to simply run the stats job'
.example '$0 stats -m <EMAIL>', 'run the job but send to given address'
# general options
.options
help:
alias: 'h',
description: 'display help message'
nocolors:
alias: 'C'
description: 'turn of color output'
type: 'boolean'
quiet:
alias: 'q'
description: "don't output header and footer"
type: 'boolean'
list:
alias: 'l'
description: 'only list the possible jobs'
type: 'boolean'
mail:
alias: 'm'
description: 'alternative email address to send to'
type: 'string'
json:
alias: 'j'
description: 'json formatted data object'
type: 'string'
.group ['m', 'j'], 'Report Options:'
# add Commands
for job in dbreport.list()
conf = dbreport.get job
yargs.command job, conf.title, command job, conf
# general help
yargs.help 'help'
.updateStrings
'Options:': 'General Options:'
.epilogue """
You may use environment variables prefixed with 'DBREPORT_' to set any of
the options like 'DBREPORT_MAIL' to set the email address.
For more information, look into the man page.
"""
.completion 'bashrc-script', false
# validation
#.strict()
.fail (err) ->
err = new Error "CLI #{err}"
err.description = 'Specify --help for available options'
alinex.exit 2, err
# now parse the arguments
argv = yargs.argv
# list possible jobs
if argv.list
data = []
for job in dbreport.list()
conf = dbreport.get job
data.push
job: job
title: conf.title
to: conf.email.to?.map (e) -> e.replace /[ .@].*/, ''
.join ', '
report = new Report()
report.h1 "List of possible jobs:"
if data.length
report.table data, ['JOB', 'TITLE', 'TO']
report.p 'Run them using their job name.'
else
report.p 'No jobs defined, add them in your config!'
console.log()
console.log report.toConsole()
console.log()
# check for corrct call
else unless argv._.length
alinex.exit 2, new Error "Nothing to do specify --help for available options"
| true | # Main class
# =================================================
# Node Modules
# -------------------------------------------------
# include base modules
yargs = require 'yargs'
# include alinex modules
config = require 'alinex-config'
database = require 'alinex-database'
Report = require 'alinex-report'
alinex = require 'alinex-core'
# include classes and helpers
dbreport = require './index'
process.title = 'DbReport'
logo = alinex.logo 'Database Reports'
# Support quiet mode through switch
# -------------------------------------------------
quiet = false
for a in ['--get-yargs-completions', 'bashrc', '-q', '--quiet']
quiet = true if a in process.argv
# Error management
# -------------------------------------------------
alinex.initExit()
process.on 'exit', ->
console.log "Goodbye\n"
database.close()
# Command Setup
# -------------------------------------------------
command = (name, conf) ->
# return builder and handler
builder: (yargs) ->
yargs
.usage "\nUsage: $0 #{name} [options]\n\n#{conf.description.trim() ? ''}"
.strict()
.options
help:
alias: 'h',
description: 'display help message'
nocolors:
alias: 'C'
description: 'turn of color output'
type: 'boolean'
quiet:
alias: 'q'
describe: "don't output header and footer"
type: 'boolean'
mail:
alias: 'm'
description: 'alternative email address to send to'
type: 'string'
json:
alias: 'j'
description: 'json formatted data object'
type: 'string'
.group ['m', 'j'], 'Report Options:'
.epilogue """
This is the description of the '#{name}' job. You may also look into the
general help or the man page.
"""
handler: (argv) ->
if argv.json
try
variables = JSON.parse argv.json
catch error
alinex.exit 2, error
dbreport.init
mail: argv.mail
variables: variables ? {}
# run the command
dbreport.run name, (err) ->
alinex.exit err
return true
# Main routine
# -------------------------------------------------
unless quiet
console.log logo
console.log "Initializing..."
dbreport.setup (err) ->
alinex.exit 16, err if err
config.init (err) ->
alinex.exit err if err
yargs
.usage "\nUsage: $0 <job...> [options]"
.env 'DBREPORT' # use environment arguments prefixed with DBREPORT_
# examples
.example '$0 stats', 'to simply run the stats job'
.example '$0 stats -m PI:EMAIL:<EMAIL>END_PI', 'run the job but send to given address'
# general options
.options
help:
alias: 'h',
description: 'display help message'
nocolors:
alias: 'C'
description: 'turn of color output'
type: 'boolean'
quiet:
alias: 'q'
description: "don't output header and footer"
type: 'boolean'
list:
alias: 'l'
description: 'only list the possible jobs'
type: 'boolean'
mail:
alias: 'm'
description: 'alternative email address to send to'
type: 'string'
json:
alias: 'j'
description: 'json formatted data object'
type: 'string'
.group ['m', 'j'], 'Report Options:'
# add Commands
for job in dbreport.list()
conf = dbreport.get job
yargs.command job, conf.title, command job, conf
# general help
yargs.help 'help'
.updateStrings
'Options:': 'General Options:'
.epilogue """
You may use environment variables prefixed with 'DBREPORT_' to set any of
the options like 'DBREPORT_MAIL' to set the email address.
For more information, look into the man page.
"""
.completion 'bashrc-script', false
# validation
#.strict()
.fail (err) ->
err = new Error "CLI #{err}"
err.description = 'Specify --help for available options'
alinex.exit 2, err
# now parse the arguments
argv = yargs.argv
# list possible jobs
if argv.list
data = []
for job in dbreport.list()
conf = dbreport.get job
data.push
job: job
title: conf.title
to: conf.email.to?.map (e) -> e.replace /[ .@].*/, ''
.join ', '
report = new Report()
report.h1 "List of possible jobs:"
if data.length
report.table data, ['JOB', 'TITLE', 'TO']
report.p 'Run them using their job name.'
else
report.p 'No jobs defined, add them in your config!'
console.log()
console.log report.toConsole()
console.log()
# check for corrct call
else unless argv._.length
alinex.exit 2, new Error "Nothing to do specify --help for available options"
|
[
{
"context": " 1, false]\n\t[21, \"queen\", \"a\", 1, true]\n\t[22, \"domino\", \"\", 1, true]\n\t[23, \"photo\", \"a\", 1, true]\n\t[24,",
"end": 759,
"score": 0.8781747221946716,
"start": 756,
"tag": "NAME",
"value": "ino"
},
{
"context": "\"a\", 1, false]\n\t[29, \"salt\", \"\", 1... | wordlistEN1.server.coffee | mateuto/Sketchy | 0 | # id, word, prefix, difficulty, active
# difficulty not yet implemented
exports.wordList = -> [
[0, "rabbit", "a", 1, true]
[1, "strawberry", "a", 1, false]
[2, "crazy", "", 1, false]
[3, "painting", "a", 1, true]
[4, "fence", "a", 1, true]
[5, "horse", "a", 1, true]
[6, "door", "a", 1, false]
[7, "song", "a", 1, false]
[8, "trip", "", 1, false]
[9, "backbone", "a", 1, false]
[10, "bomb", "a", 1, false]
[11, "treasure", "a", 1, true]
[12, "garbage", "", 1, true]
[13, "park", "a", 1, false]
[14, "pirate", "a", 1, true]
[15, "ski", "a", 1, false]
[16, "state", "a", 1, true]
[17, "whistle", "a", 1, true]
[18, "palace", "a", 1, true]
[19, "baseball", "a", 1, true]
[20, "coal", "", 1, false]
[21, "queen", "a", 1, true]
[22, "domino", "", 1, true]
[23, "photo", "a", 1, true]
[24, "computer", "a", 1, true]
[25, "hockey", "a", 1, true]
[26, "aircraft", "an", 1, true]
[27, "hot", "", 1, false]
[28, "dog", "a", 1, false]
[29, "salt", "", 1, false]
[30, "pepper", "", 1, true]
[31, "key", "a", 1, false]
[32, "iPad", "an", 1, true]
[33, "frog", "a", 1, false]
[34, "lawn mower", "a", 1, false]
[35, "mattress", "a", 1, true]
[36, "cake", "a", 1, false]
[37, "circus", "a", 1, true]
[38, "battery", "a", 1, true]
[39, "mailman", "a", 1, true]
[40, "cowboy", "a", 1, true]
[41, "password", "a", 1, true]
[42, "bicycle", "a", 1, true]
[43, "skate", "a", 1, false]
[44, "electricity", "", 1, false]
[45, "lightsaber", "a", 1, false]
[46, "thief", "a", 1, true]
[47, "teapot", "a", 1, true]
[48, "spring", "", 1, true]
[49, "nature", "", 1, true]
[50, "shallow", "", 1, false]
[51, "toast", "a", 1, true]
[52, "outside", "", 1, true]
[53, "America", "", 1, true]
[54, "man", "a", 1, false]
[55, "bowtie", "a", 1, true]
[56, "half", "", 1, false]
[57, "spare", "", 1, false]
[58, "wax", "", 1, false]
[59, "lightbulb", "a", 1, false]
[60, "chicken", "a", 1, true]
[61, "music", "", 1, true]
[62, "sailboat", "a", 1, true]
[63, "popsicle", "a", 1, true]
[64, "brain", "a", 1, true]
[65, "birthday", "a", 1, true]
[66, "skirt", "a", 1, false]
[67, "knee", "a", 1, false]
[68, "pineapple", "a", 1, false]
[69, "sprinkler", "a", 1, false]
[70, "money", "a", 1, true]
[71, "lighthouse", "a", 1, false]
[72, "doormat", "a", 1, true]
[73, "face", "a", 1, false]
[74, "flute", "a", 1, true]
[75, "rug", "a", 1, false]
[76, "snowball", "a", 1, true]
[77, "purse", "a", 1, true]
[78, "owl", "an", 1, false]
[79, "gate", "a", 1, false]
[80, "suitcase", "a", 1, true]
[81, "stomach", "a", 1, true]
[82, "doghouse", "a", 1, true]
[83, "bathroom", "a", 1, true]
[84, "peach", "a", 1, true]
[85, "newspaper", "a", 1, false]
[86, "hook", "a", 1, false]
[87, "school", "a", 1, true]
[88, "beaver", "a", 1, true]
[89, "fries", "", 1, true]
[90, "beehive", "a", 1, true]
[91, "beach", "a", 1, true]
[92, "artist", "an", 1, true]
[93, "flagpole", "a", 1, true]
[94, "camera", "a", 1, true]
[95, "hairdryer", "a", 1, false]
[96, "mushroom", "a", 1, true]
[97, "toe", "a", 1, false]
[98, "pretzel", "a", 1, true]
[99, "tv", "a", 1, false]
[100, "jeans", "", 1, true]
[101, "chalk", "a", 1, true]
[102, "dollar", "a", 1, true]
[103, "soda", "a", 1, false]
[104, "chin", "a", 1, false]
[105, "swing", "a", 1, true]
[106, "garden", "a", 1, true]
[107, "ticket", "a", 1, true]
[108, "boot", "a", 1, false]
[109, "cello", "a", 1, true]
[110, "rain", "", 1, false]
[111, "clam", "a", 1, false]
[112, "treehouse", "a", 1, false]
[113, "rocket", "a", 1, true]
[114, "fur", "a", 1, false]
[115, "fish", "a", 1, false]
[116, "rainbow", "a", 1, true]
[117, "happy", "", 1, true]
[118, "fist", "a", 1, false]
[119, "base", "a", 1, false]
[120, "storm", "a", 1, true]
[121, "mitten", "a", 1, true]
[122, "nail", "a", 1, false]
[123, "sheep", "a", 1, true]
[124, "traffic light", "a", 1, false]
[125, "coconut", "a", 1, true]
[126, "helmet", "a", 1, true]
[127, "ring", "a", 1, false]
[128, "seesaw", "a", 1, true]
[129, "plate", "a", 1, true]
[130, "hammer", "a", 1, true]
[131, "bell", "a", 1, false]
[132, "street", "", 1, true]
[133, "roof", "a", 1, false]
[134, "cheek", "a", 1, true]
[135, "phone", "a", 1, true]
[136, "barn", "a", 1, false]
[137, "snowflake", "a", 1, false]
[138, "flashlight", "a", 1, false]
[139, "muffin", "a", 1, true]
[140, "sunflower", "a", 1, false]
[141, "tophat", "a", 1, true]
[142, "pool", "a", 1, false]
[143, "tusk", "a", 1, false]
[144, "radish", "a", 1, true]
[145, "peanut", "a", 1, true]
[146, "chair", "a", 1, true]
[147, "poodle", "a", 1, true]
[148, "potato", "a", 1, true]
[149, "shark", "a", 1, true]
[150, "jaws", "a", 1, false]
[151, "waist", "a", 1, true]
[152, "spoon", "a", 1, true]
[153, "bottle", "a", 1, true]
[154, "mail", "", 1, false]
[155, "crab", "a", 1, false]
[156, "ice", "", 1, false]
[157, "lawn", "a", 1, false]
[158, "bubble", "a", 1, true]
[159, "pencil", "a", 1, true]
[160, "hamburger", "a", 1, false]
[161, "corner", "a", 1, true]
[162, "popcorn", "", 1, true]
[163, "starfish", "a", 1, true]
[164, "octopus", "an", 1, true]
[165, "desk", "an", 1, false]
[166, "pie", "a", 1, false]
[167, "kitten", "a", 1, true]
[168, "Sun", "the", 1, false]
[169, "Mars", "", 1, true]
[170, "cup", "a", 1, false]
[171, "ghost", "a", 1, true]
[172, "flower", "a", 1, true]
[173, "cow", "a", 1, false]
[174, "banana", "a", 1, true]
[175, "bug", "a", 1, false]
[176, "book", "a", 1, false]
[177, "jar", "a", 1, false]
[178, "snake", "a", 1, true]
[179, "tree", "a", 1, false]
[180, "lips", "a", 1, false]
[181, "apple", "an", 1, true]
[182, "socks", "", 1, true]
[183, "swing", "a", 1, true]
[184, "coat", "a", 1, false]
[185, "shoe", "a", 1, false]
[186, "water", "", 1, true]
[187, "heart", "a", 1, true]
[188, "ocean", "an", 1, true]
[189, "kite", "a", 1, false]
[190, "mouth", "a", 1, true]
[191, "milk", "a", 1, false]
[192, "duck", "a", 1, false]
[193, "eyes", "", 1, false]
[194, "bird", "a", 1, false]
[195, "boy", "a", 1, false]
[196, "person", "a", 1, true]
[197, "man", "a", 1, false]
[198, "woman", "a", 1, true]
[199, "girl", "a", 1, false]
[200, "mouse", "a", 1, true]
[201, "ball", "a", 1, false]
[202, "house", "a", 1, true]
[203, "star", "a", 1, false]
[204, "nose", "a", 1, false]
[205, "bed", "a", 1, false]
[206, "whale", "a", 1, true]
[207, "jacket", "a", 1, true]
[208, "shirt", "a", 1, true]
[209, "hippo", "a", 1, true]
[210, "beach", "a", 1, false]
[211, "egg", "an", 1, false]
[212, "face", "a", 1, false]
[213, "cookie", "a", 1, true]
[214, "cheese", "a", 1, true]
[215, "ice", "", 1, false]
[216, "cream", "a", 1, true]
[217, "cone", "a", 1, false]
[218, "drum", "a", 1, false]
[219, "circle", "a", 1, true]
[220, "spoon", "a", 1, false]
[221, "worm", "a", 1, false]
[222, "spider", "a", 1, true]
[223, "web", "a", 1, false]
[224, "bridge", "a", 1, true]
[225, "bone", "a", 1, false]
[226, "grapes", "", 1, true]
[227, "bell", "a", 1, false]
[228, "truck", "a", 1, true]
[229, "grass", "", 1, true]
[230, "monkey", "a", 1, true]
[231, "bread", "a", 1, true]
[232, "ears", "", 1, false]
[233, "bowl", "a", 1, false]
[234, "bat", "a", 1, false]
[235, "clock", "a", 1, true]
[236, "doll", "a", 1, false]
[237, "orange", "an", 1, true]
[238, "bike", "a", 1, false]
[239, "pen", "a", 1, false]
[240, "seashell", "a", 1, true]
[241, "cloud", "a", 1, true]
[242, "bear", "a", 1, false]
[243, "corn", "", 1, false]
[244, "glasses", "", 1, true]
[245, "blocks", "", 1, true]
[246, "carrot", "a", 1, true]
[247, "turtle", "a", 1, true]
[248, "pencil", "a", 1, false]
[249, "dinosaur", "a", 1, true]
[250, "head", "a", 1, false]
[251, "lamp", "a", 1, false]
[252, "snowman", "a", 1, true]
[253, "ant", "an", 1, false]
[254, "giraffe", "a", 1, true]
[255, "cupcake", "a", 1, true]
[256, "leaf", "a", 1, false]
[257, "bunk", "a", 1, false]
[258, "snail", "a", 1, true]
[259, "baby", "a", 1, false]
[260, "balloon", "a", 1, true]
[261, "bus", "a", 1, false]
[262, "cherry", "a", 1, true]
[263, "football", "a", 1, true]
[264, "branch", "a", 1, true]
[265, "robot", "a", 1, true]
[266, "laptop", "a", 1, true]
[267, "pillow", "a", 1, true]
[268, "monitor", "a", 1, true]
[269, "dinner", "a", 1, true]
[270, "bottle", "a", 1, false]
[271, "tomato", "a", 1, true]
[272, "butter", "", 1, true]
[273, "salami", "a", 1, true]
[274, "pancake", "a", 1, true]
[275, "waiter", "a", 1, true]
[276, "omelet", "", 1, true]
[277, "keyboard", "", 1, true]
[278, "coffee", "", 1, true]
[279, "adapter", "", 1, true]
[280, "webcam", "", 1, true]
[281, "window", "a", 1, true]
[282, "drill", "a", 1, true]
[283, "pliers", "", 1, true]
[284, "shotgun", "a", 1, true]
[285, "shield", "a", 1, true]
[286, "sword", "a", 1, true]
[287, "catapult", "a", 1, true]
[288, "carpet", "a", 1, true]
[289, "tennis", "", 1, true]
[290, "racket", "a", 1, true]
[291, "stick", "a", 1, true]
[292, "speaker", "a", 1, true]
[293, "church", "a", 1, true]
[294, "light", "", 1, true]
[295, "stereo", "a", 1, true]
[296, "donkey", "a", 1, true]
[297, "dragon", "a", 1, true]
[298, "guitar", "a", 1, true]
[299, "arrow", "an", 1, true]
[300, "pants", "", 1, true]
[301, "eyebrow", "an", 1, true]
[302, "umbrella", "an", 1, true]
[303, "wheel", "a", 1, true]
[304, "snail", "a", 1, true]
[305, "lizard", "a", 1, true]
[306, "sneeze", "a", 1, true]
[307, "dwarf", "a", 1, true]
[308, "goblin", "a", 1, true]
[309, "police", "", 1, true]
[310, "fireman", "a", 1, true]
[311, "cable", "a", 1, true]
[312, "printer", "a", 1, true]
[313, "trophy", "a", 1, true]
[314, "Earth", "the", 1, true]
[315, "Saturn", "the", 1, true]
[316, "Europe", "the", 1, true]
[317, "flamingo", "a", 1, true]
[318, "volcano", "a", 1, true]
[319, "badge", "a", 1, true]
[320, "mirror", "a", 1, true]
[321, "shadow", "a", 1, true]
[322, "windmill", "a", 1, true]
[323, "shampoo", "", 1, true]
[324, "website", "a", 1, true]
[325, "children", "", 1, true]
[326, "blushing", "", 1, true]
[327, "tattoo", "a", 1, true]
[328, "piercing", "a", 1, true]
[329, "teacher", "a", 1, true]
[330, "gasoline", "", 1, true]
[331, "koala", "a", 1, true]
[332, "panda", "a", 1, true]
[333, "penguin", "a", 1, true]
[334, "shopping", "", 1, true]
[335, "brick", "a", 1, true]
[336, "necklace", "a", 1, true]
[337, "surprise", "", 1, true]
[338, "shoes", "", 1, true]
[339, "group", "a", 1, true]
[340, "selfie", "", 1, true]
[341, "plant", "a", 1, true]
[342, "toilet", "a", 1, true]
[343, "study", "a", 1, true]
[344, "kitchen", "a", 1, true]
[345, "towel", "a", 1, true]
[346, "hyena", "a", 1, true]
[347, "mascara", "", 1, true]
[348, "eyeliner", "", 1, true]
[349, "makeup", "", 1, true]
[350, "lipstick", "", 1, true]
[351, "fridge", "a", 1, true]
[352, "movie", "a", 1, true]
[353, "sleeve", "a", 1, true]
[354, "candy", "", 1, true]
[355, "trashcan", "a", 1, true]
[356, "elevator", "an", 1, true]
[357, "dagger", "a", 1, true]
[358, "Titanic", "the", 1, true]
[359, "drowning", "", 1, true]
[360, "iceberg", "an", 1, true]
[361, "colors", "", 1, true]
[362, "river", "a", 1, true]
[363, "wizard", "a", 1, true]
[364, "witch", "a", 1, true]
[365, "captain", "a", 1, true]
[366, "pillar", "a", 1, true]
[367, "donut", "a", 1, true]
[368, "lantern", "a", 1, true]
] | 39606 | # id, word, prefix, difficulty, active
# difficulty not yet implemented
exports.wordList = -> [
[0, "rabbit", "a", 1, true]
[1, "strawberry", "a", 1, false]
[2, "crazy", "", 1, false]
[3, "painting", "a", 1, true]
[4, "fence", "a", 1, true]
[5, "horse", "a", 1, true]
[6, "door", "a", 1, false]
[7, "song", "a", 1, false]
[8, "trip", "", 1, false]
[9, "backbone", "a", 1, false]
[10, "bomb", "a", 1, false]
[11, "treasure", "a", 1, true]
[12, "garbage", "", 1, true]
[13, "park", "a", 1, false]
[14, "pirate", "a", 1, true]
[15, "ski", "a", 1, false]
[16, "state", "a", 1, true]
[17, "whistle", "a", 1, true]
[18, "palace", "a", 1, true]
[19, "baseball", "a", 1, true]
[20, "coal", "", 1, false]
[21, "queen", "a", 1, true]
[22, "dom<NAME>", "", 1, true]
[23, "photo", "a", 1, true]
[24, "computer", "a", 1, true]
[25, "hockey", "a", 1, true]
[26, "aircraft", "an", 1, true]
[27, "hot", "", 1, false]
[28, "dog", "a", 1, false]
[29, "salt", "", 1, false]
[30, "<NAME>", "", 1, true]
[31, "key", "a", 1, false]
[32, "iPad", "an", 1, true]
[33, "frog", "a", 1, false]
[34, "l<NAME> mower", "a", 1, false]
[35, "<NAME>", "a", 1, true]
[36, "cake", "a", 1, false]
[37, "circ<NAME>", "a", 1, true]
[38, "battery", "a", 1, true]
[39, "<NAME>", "a", 1, true]
[40, "<NAME>", "a", 1, true]
[41, "password", "<PASSWORD>", 1, true]
[42, "bicycle", "a", 1, true]
[43, "skate", "a", 1, false]
[44, "electricity", "", 1, false]
[45, "lightsaber", "a", 1, false]
[46, "thief", "a", 1, true]
[47, "teapot", "a", 1, true]
[48, "spring", "", 1, true]
[49, "nature", "", 1, true]
[50, "shallow", "", 1, false]
[51, "toast", "a", 1, true]
[52, "outside", "", 1, true]
[53, "America", "", 1, true]
[54, "man", "a", 1, false]
[55, "bowtie", "a", 1, true]
[56, "half", "", 1, false]
[57, "spare", "", 1, false]
[58, "wax", "", 1, false]
[59, "lightbulb", "a", 1, false]
[60, "chicken", "a", 1, true]
[61, "music", "", 1, true]
[62, "sailboat", "a", 1, true]
[63, "popsicle", "a", 1, true]
[64, "brain", "a", 1, true]
[65, "birthday", "a", 1, true]
[66, "skirt", "a", 1, false]
[67, "knee", "a", 1, false]
[68, "pineapple", "a", 1, false]
[69, "sprinkler", "a", 1, false]
[70, "money", "a", 1, true]
[71, "lighthouse", "a", 1, false]
[72, "doormat", "a", 1, true]
[73, "face", "a", 1, false]
[74, "flute", "a", 1, true]
[75, "rug", "a", 1, false]
[76, "snowball", "a", 1, true]
[77, "purse", "a", 1, true]
[78, "owl", "an", 1, false]
[79, "gate", "a", 1, false]
[80, "suitcase", "a", 1, true]
[81, "stomach", "a", 1, true]
[82, "doghouse", "a", 1, true]
[83, "bathroom", "a", 1, true]
[84, "peach", "a", 1, true]
[85, "newspaper", "a", 1, false]
[86, "hook", "a", 1, false]
[87, "school", "a", 1, true]
[88, "beaver", "a", 1, true]
[89, "<NAME>ries", "", 1, true]
[90, "beehive", "a", 1, true]
[91, "beach", "a", 1, true]
[92, "artist", "an", 1, true]
[93, "flagpole", "a", 1, true]
[94, "camera", "a", 1, true]
[95, "hairdryer", "a", 1, false]
[96, "mushroom", "a", 1, true]
[97, "toe", "a", 1, false]
[98, "pretzel", "a", 1, true]
[99, "tv", "a", 1, false]
[100, "<NAME>", "", 1, true]
[101, "chalk", "a", 1, true]
[102, "<NAME>", "a", 1, true]
[103, "soda", "a", 1, false]
[104, "chin", "a", 1, false]
[105, "swing", "a", 1, true]
[106, "garden", "a", 1, true]
[107, "ticket", "a", 1, true]
[108, "boot", "a", 1, false]
[109, "<NAME>", "a", 1, true]
[110, "rain", "", 1, false]
[111, "clam", "a", 1, false]
[112, "treehouse", "a", 1, false]
[113, "rocket", "a", 1, true]
[114, "fur", "a", 1, false]
[115, "fish", "a", 1, false]
[116, "rainbow", "a", 1, true]
[117, "happy", "", 1, true]
[118, "fist", "a", 1, false]
[119, "base", "a", 1, false]
[120, "storm", "a", 1, true]
[121, "mit<NAME>", "a", 1, true]
[122, "nail", "a", 1, false]
[123, "sheep", "a", 1, true]
[124, "traffic light", "a", 1, false]
[125, "coconut", "a", 1, true]
[126, "helmet", "a", 1, true]
[127, "ring", "a", 1, false]
[128, "seesaw", "a", 1, true]
[129, "plate", "a", 1, true]
[130, "hammer", "a", 1, true]
[131, "bell", "a", 1, false]
[132, "street", "", 1, true]
[133, "roof", "a", 1, false]
[134, "cheek", "a", 1, true]
[135, "phone", "a", 1, true]
[136, "<NAME>", "a", 1, false]
[137, "snowflake", "a", 1, false]
[138, "flashlight", "a", 1, false]
[139, "muffin", "a", 1, true]
[140, "sunflower", "a", 1, false]
[141, "tophat", "a", 1, true]
[142, "pool", "a", 1, false]
[143, "tusk", "a", 1, false]
[144, "radish", "a", 1, true]
[145, "peanut", "a", 1, true]
[146, "chair", "a", 1, true]
[147, "poodle", "a", 1, true]
[148, "potato", "a", 1, true]
[149, "shark", "a", 1, true]
[150, "jaws", "a", 1, false]
[151, "waist", "a", 1, true]
[152, "spoon", "a", 1, true]
[153, "bottle", "a", 1, true]
[154, "mail", "", 1, false]
[155, "crab", "a", 1, false]
[156, "ice", "", 1, false]
[157, "lawn", "a", 1, false]
[158, "bubble", "a", 1, true]
[159, "pencil", "a", 1, true]
[160, "hamburger", "a", 1, false]
[161, "corner", "a", 1, true]
[162, "<NAME>corn", "", 1, true]
[163, "starfish", "a", 1, true]
[164, "octopus", "an", 1, true]
[165, "desk", "an", 1, false]
[166, "pie", "a", 1, false]
[167, "kitten", "a", 1, true]
[168, "Sun", "the", 1, false]
[169, "<NAME>", "", 1, true]
[170, "cup", "a", 1, false]
[171, "ghost", "a", 1, true]
[172, "flower", "a", 1, true]
[173, "cow", "a", 1, false]
[174, "banana", "a", 1, true]
[175, "bug", "a", 1, false]
[176, "book", "a", 1, false]
[177, "jar", "a", 1, false]
[178, "snake", "a", 1, true]
[179, "tree", "a", 1, false]
[180, "lips", "a", 1, false]
[181, "apple", "an", 1, true]
[182, "socks", "", 1, true]
[183, "swing", "a", 1, true]
[184, "coat", "a", 1, false]
[185, "shoe", "a", 1, false]
[186, "water", "", 1, true]
[187, "heart", "a", 1, true]
[188, "ocean", "an", 1, true]
[189, "kite", "a", 1, false]
[190, "mouth", "a", 1, true]
[191, "milk", "a", 1, false]
[192, "duck", "a", 1, false]
[193, "eyes", "", 1, false]
[194, "bird", "a", 1, false]
[195, "boy", "a", 1, false]
[196, "person", "a", 1, true]
[197, "man", "a", 1, false]
[198, "woman", "a", 1, true]
[199, "girl", "a", 1, false]
[200, "mouse", "a", 1, true]
[201, "ball", "a", 1, false]
[202, "house", "a", 1, true]
[203, "star", "a", 1, false]
[204, "nose", "a", 1, false]
[205, "bed", "a", 1, false]
[206, "whale", "a", 1, true]
[207, "jacket", "a", 1, true]
[208, "shirt", "a", 1, true]
[209, "hippo", "a", 1, true]
[210, "beach", "a", 1, false]
[211, "egg", "an", 1, false]
[212, "face", "a", 1, false]
[213, "cookie", "a", 1, true]
[214, "cheese", "a", 1, true]
[215, "ice", "", 1, false]
[216, "cream", "a", 1, true]
[217, "cone", "a", 1, false]
[218, "drum", "a", 1, false]
[219, "circle", "a", 1, true]
[220, "spoon", "a", 1, false]
[221, "worm", "a", 1, false]
[222, "spider", "a", 1, true]
[223, "web", "a", 1, false]
[224, "bridge", "a", 1, true]
[225, "bone", "a", 1, false]
[226, "grapes", "", 1, true]
[227, "bell", "a", 1, false]
[228, "truck", "a", 1, true]
[229, "grass", "", 1, true]
[230, "monkey", "a", 1, true]
[231, "bread", "a", 1, true]
[232, "ears", "", 1, false]
[233, "bowl", "a", 1, false]
[234, "bat", "a", 1, false]
[235, "clock", "a", 1, true]
[236, "doll", "a", 1, false]
[237, "orange", "an", 1, true]
[238, "bike", "a", 1, false]
[239, "pen", "a", 1, false]
[240, "seashell", "a", 1, true]
[241, "cloud", "a", 1, true]
[242, "bear", "a", 1, false]
[243, "corn", "", 1, false]
[244, "glasses", "", 1, true]
[245, "blocks", "", 1, true]
[246, "car<NAME>", "a", 1, true]
[247, "turtle", "a", 1, true]
[248, "pencil", "a", 1, false]
[249, "dinosaur", "a", 1, true]
[250, "head", "a", 1, false]
[251, "lamp", "a", 1, false]
[252, "snowman", "a", 1, true]
[253, "ant", "an", 1, false]
[254, "giraffe", "a", 1, true]
[255, "cupcake", "a", 1, true]
[256, "leaf", "a", 1, false]
[257, "bunk", "a", 1, false]
[258, "snail", "a", 1, true]
[259, "baby", "a", 1, false]
[260, "balloon", "a", 1, true]
[261, "bus", "a", 1, false]
[262, "cherry", "a", 1, true]
[263, "football", "a", 1, true]
[264, "branch", "a", 1, true]
[265, "robot", "a", 1, true]
[266, "laptop", "a", 1, true]
[267, "pil<NAME>", "a", 1, true]
[268, "monitor", "a", 1, true]
[269, "dinner", "a", 1, true]
[270, "bottle", "a", 1, false]
[271, "tomato", "a", 1, true]
[272, "butter", "", 1, true]
[273, "salami", "a", 1, true]
[274, "pancake", "a", 1, true]
[275, "waiter", "a", 1, true]
[276, "omelet", "", 1, true]
[277, "keyboard", "", 1, true]
[278, "coffee", "", 1, true]
[279, "adapter", "", 1, true]
[280, "webcam", "", 1, true]
[281, "window", "a", 1, true]
[282, "drill", "a", 1, true]
[283, "pliers", "", 1, true]
[284, "shotgun", "a", 1, true]
[285, "shield", "a", 1, true]
[286, "sword", "a", 1, true]
[287, "catapult", "a", 1, true]
[288, "carpet", "a", 1, true]
[289, "tennis", "", 1, true]
[290, "racket", "a", 1, true]
[291, "stick", "a", 1, true]
[292, "speaker", "a", 1, true]
[293, "church", "a", 1, true]
[294, "light", "", 1, true]
[295, "stereo", "a", 1, true]
[296, "<NAME>", "a", 1, true]
[297, "dragon", "a", 1, true]
[298, "guitar", "a", 1, true]
[299, "arrow", "an", 1, true]
[300, "pants", "", 1, true]
[301, "eyebrow", "an", 1, true]
[302, "umbrella", "an", 1, true]
[303, "wheel", "a", 1, true]
[304, "snail", "a", 1, true]
[305, "<NAME>", "a", 1, true]
[306, "sneeze", "a", 1, true]
[307, "dwarf", "a", 1, true]
[308, "<NAME>", "a", 1, true]
[309, "police", "", 1, true]
[310, "<NAME>man", "a", 1, true]
[311, "cable", "a", 1, true]
[312, "printer", "a", 1, true]
[313, "trophy", "a", 1, true]
[314, "Earth", "the", 1, true]
[315, "Saturn", "the", 1, true]
[316, "Europe", "the", 1, true]
[317, "flamingo", "a", 1, true]
[318, "volcano", "a", 1, true]
[319, "badge", "a", 1, true]
[320, "mirror", "a", 1, true]
[321, "shadow", "a", 1, true]
[322, "windmill", "a", 1, true]
[323, "shampoo", "", 1, true]
[324, "website", "a", 1, true]
[325, "children", "", 1, true]
[326, "blushing", "", 1, true]
[327, "tattoo", "a", 1, true]
[328, "piercing", "a", 1, true]
[329, "teacher", "a", 1, true]
[330, "gasoline", "", 1, true]
[331, "koala", "a", 1, true]
[332, "panda", "a", 1, true]
[333, "penguin", "a", 1, true]
[334, "shopping", "", 1, true]
[335, "brick", "a", 1, true]
[336, "necklace", "a", 1, true]
[337, "surprise", "", 1, true]
[338, "shoes", "", 1, true]
[339, "group", "a", 1, true]
[340, "selfie", "", 1, true]
[341, "plant", "a", 1, true]
[342, "toilet", "a", 1, true]
[343, "study", "a", 1, true]
[344, "kitchen", "a", 1, true]
[345, "towel", "a", 1, true]
[346, "hyena", "a", 1, true]
[347, "<NAME>", "", 1, true]
[348, "eyeliner", "", 1, true]
[349, "makeup", "", 1, true]
[350, "lipstick", "", 1, true]
[351, "fridge", "a", 1, true]
[352, "movie", "a", 1, true]
[353, "sleeve", "a", 1, true]
[354, "<NAME>", "", 1, true]
[355, "trashcan", "a", 1, true]
[356, "elevator", "an", 1, true]
[357, "dagger", "a", 1, true]
[358, "Titanic", "the", 1, true]
[359, "d<NAME>ning", "", 1, true]
[360, "iceberg", "an", 1, true]
[361, "colors", "", 1, true]
[362, "river", "a", 1, true]
[363, "wizard", "a", 1, true]
[364, "witch", "a", 1, true]
[365, "captain", "a", 1, true]
[366, "pillar", "a", 1, true]
[367, "donut", "a", 1, true]
[368, "lantern", "a", 1, true]
] | true | # id, word, prefix, difficulty, active
# difficulty not yet implemented
exports.wordList = -> [
[0, "rabbit", "a", 1, true]
[1, "strawberry", "a", 1, false]
[2, "crazy", "", 1, false]
[3, "painting", "a", 1, true]
[4, "fence", "a", 1, true]
[5, "horse", "a", 1, true]
[6, "door", "a", 1, false]
[7, "song", "a", 1, false]
[8, "trip", "", 1, false]
[9, "backbone", "a", 1, false]
[10, "bomb", "a", 1, false]
[11, "treasure", "a", 1, true]
[12, "garbage", "", 1, true]
[13, "park", "a", 1, false]
[14, "pirate", "a", 1, true]
[15, "ski", "a", 1, false]
[16, "state", "a", 1, true]
[17, "whistle", "a", 1, true]
[18, "palace", "a", 1, true]
[19, "baseball", "a", 1, true]
[20, "coal", "", 1, false]
[21, "queen", "a", 1, true]
[22, "domPI:NAME:<NAME>END_PI", "", 1, true]
[23, "photo", "a", 1, true]
[24, "computer", "a", 1, true]
[25, "hockey", "a", 1, true]
[26, "aircraft", "an", 1, true]
[27, "hot", "", 1, false]
[28, "dog", "a", 1, false]
[29, "salt", "", 1, false]
[30, "PI:NAME:<NAME>END_PI", "", 1, true]
[31, "key", "a", 1, false]
[32, "iPad", "an", 1, true]
[33, "frog", "a", 1, false]
[34, "lPI:NAME:<NAME>END_PI mower", "a", 1, false]
[35, "PI:NAME:<NAME>END_PI", "a", 1, true]
[36, "cake", "a", 1, false]
[37, "circPI:NAME:<NAME>END_PI", "a", 1, true]
[38, "battery", "a", 1, true]
[39, "PI:NAME:<NAME>END_PI", "a", 1, true]
[40, "PI:NAME:<NAME>END_PI", "a", 1, true]
[41, "password", "PI:PASSWORD:<PASSWORD>END_PI", 1, true]
[42, "bicycle", "a", 1, true]
[43, "skate", "a", 1, false]
[44, "electricity", "", 1, false]
[45, "lightsaber", "a", 1, false]
[46, "thief", "a", 1, true]
[47, "teapot", "a", 1, true]
[48, "spring", "", 1, true]
[49, "nature", "", 1, true]
[50, "shallow", "", 1, false]
[51, "toast", "a", 1, true]
[52, "outside", "", 1, true]
[53, "America", "", 1, true]
[54, "man", "a", 1, false]
[55, "bowtie", "a", 1, true]
[56, "half", "", 1, false]
[57, "spare", "", 1, false]
[58, "wax", "", 1, false]
[59, "lightbulb", "a", 1, false]
[60, "chicken", "a", 1, true]
[61, "music", "", 1, true]
[62, "sailboat", "a", 1, true]
[63, "popsicle", "a", 1, true]
[64, "brain", "a", 1, true]
[65, "birthday", "a", 1, true]
[66, "skirt", "a", 1, false]
[67, "knee", "a", 1, false]
[68, "pineapple", "a", 1, false]
[69, "sprinkler", "a", 1, false]
[70, "money", "a", 1, true]
[71, "lighthouse", "a", 1, false]
[72, "doormat", "a", 1, true]
[73, "face", "a", 1, false]
[74, "flute", "a", 1, true]
[75, "rug", "a", 1, false]
[76, "snowball", "a", 1, true]
[77, "purse", "a", 1, true]
[78, "owl", "an", 1, false]
[79, "gate", "a", 1, false]
[80, "suitcase", "a", 1, true]
[81, "stomach", "a", 1, true]
[82, "doghouse", "a", 1, true]
[83, "bathroom", "a", 1, true]
[84, "peach", "a", 1, true]
[85, "newspaper", "a", 1, false]
[86, "hook", "a", 1, false]
[87, "school", "a", 1, true]
[88, "beaver", "a", 1, true]
[89, "PI:NAME:<NAME>END_PIries", "", 1, true]
[90, "beehive", "a", 1, true]
[91, "beach", "a", 1, true]
[92, "artist", "an", 1, true]
[93, "flagpole", "a", 1, true]
[94, "camera", "a", 1, true]
[95, "hairdryer", "a", 1, false]
[96, "mushroom", "a", 1, true]
[97, "toe", "a", 1, false]
[98, "pretzel", "a", 1, true]
[99, "tv", "a", 1, false]
[100, "PI:NAME:<NAME>END_PI", "", 1, true]
[101, "chalk", "a", 1, true]
[102, "PI:NAME:<NAME>END_PI", "a", 1, true]
[103, "soda", "a", 1, false]
[104, "chin", "a", 1, false]
[105, "swing", "a", 1, true]
[106, "garden", "a", 1, true]
[107, "ticket", "a", 1, true]
[108, "boot", "a", 1, false]
[109, "PI:NAME:<NAME>END_PI", "a", 1, true]
[110, "rain", "", 1, false]
[111, "clam", "a", 1, false]
[112, "treehouse", "a", 1, false]
[113, "rocket", "a", 1, true]
[114, "fur", "a", 1, false]
[115, "fish", "a", 1, false]
[116, "rainbow", "a", 1, true]
[117, "happy", "", 1, true]
[118, "fist", "a", 1, false]
[119, "base", "a", 1, false]
[120, "storm", "a", 1, true]
[121, "mitPI:NAME:<NAME>END_PI", "a", 1, true]
[122, "nail", "a", 1, false]
[123, "sheep", "a", 1, true]
[124, "traffic light", "a", 1, false]
[125, "coconut", "a", 1, true]
[126, "helmet", "a", 1, true]
[127, "ring", "a", 1, false]
[128, "seesaw", "a", 1, true]
[129, "plate", "a", 1, true]
[130, "hammer", "a", 1, true]
[131, "bell", "a", 1, false]
[132, "street", "", 1, true]
[133, "roof", "a", 1, false]
[134, "cheek", "a", 1, true]
[135, "phone", "a", 1, true]
[136, "PI:NAME:<NAME>END_PI", "a", 1, false]
[137, "snowflake", "a", 1, false]
[138, "flashlight", "a", 1, false]
[139, "muffin", "a", 1, true]
[140, "sunflower", "a", 1, false]
[141, "tophat", "a", 1, true]
[142, "pool", "a", 1, false]
[143, "tusk", "a", 1, false]
[144, "radish", "a", 1, true]
[145, "peanut", "a", 1, true]
[146, "chair", "a", 1, true]
[147, "poodle", "a", 1, true]
[148, "potato", "a", 1, true]
[149, "shark", "a", 1, true]
[150, "jaws", "a", 1, false]
[151, "waist", "a", 1, true]
[152, "spoon", "a", 1, true]
[153, "bottle", "a", 1, true]
[154, "mail", "", 1, false]
[155, "crab", "a", 1, false]
[156, "ice", "", 1, false]
[157, "lawn", "a", 1, false]
[158, "bubble", "a", 1, true]
[159, "pencil", "a", 1, true]
[160, "hamburger", "a", 1, false]
[161, "corner", "a", 1, true]
[162, "PI:NAME:<NAME>END_PIcorn", "", 1, true]
[163, "starfish", "a", 1, true]
[164, "octopus", "an", 1, true]
[165, "desk", "an", 1, false]
[166, "pie", "a", 1, false]
[167, "kitten", "a", 1, true]
[168, "Sun", "the", 1, false]
[169, "PI:NAME:<NAME>END_PI", "", 1, true]
[170, "cup", "a", 1, false]
[171, "ghost", "a", 1, true]
[172, "flower", "a", 1, true]
[173, "cow", "a", 1, false]
[174, "banana", "a", 1, true]
[175, "bug", "a", 1, false]
[176, "book", "a", 1, false]
[177, "jar", "a", 1, false]
[178, "snake", "a", 1, true]
[179, "tree", "a", 1, false]
[180, "lips", "a", 1, false]
[181, "apple", "an", 1, true]
[182, "socks", "", 1, true]
[183, "swing", "a", 1, true]
[184, "coat", "a", 1, false]
[185, "shoe", "a", 1, false]
[186, "water", "", 1, true]
[187, "heart", "a", 1, true]
[188, "ocean", "an", 1, true]
[189, "kite", "a", 1, false]
[190, "mouth", "a", 1, true]
[191, "milk", "a", 1, false]
[192, "duck", "a", 1, false]
[193, "eyes", "", 1, false]
[194, "bird", "a", 1, false]
[195, "boy", "a", 1, false]
[196, "person", "a", 1, true]
[197, "man", "a", 1, false]
[198, "woman", "a", 1, true]
[199, "girl", "a", 1, false]
[200, "mouse", "a", 1, true]
[201, "ball", "a", 1, false]
[202, "house", "a", 1, true]
[203, "star", "a", 1, false]
[204, "nose", "a", 1, false]
[205, "bed", "a", 1, false]
[206, "whale", "a", 1, true]
[207, "jacket", "a", 1, true]
[208, "shirt", "a", 1, true]
[209, "hippo", "a", 1, true]
[210, "beach", "a", 1, false]
[211, "egg", "an", 1, false]
[212, "face", "a", 1, false]
[213, "cookie", "a", 1, true]
[214, "cheese", "a", 1, true]
[215, "ice", "", 1, false]
[216, "cream", "a", 1, true]
[217, "cone", "a", 1, false]
[218, "drum", "a", 1, false]
[219, "circle", "a", 1, true]
[220, "spoon", "a", 1, false]
[221, "worm", "a", 1, false]
[222, "spider", "a", 1, true]
[223, "web", "a", 1, false]
[224, "bridge", "a", 1, true]
[225, "bone", "a", 1, false]
[226, "grapes", "", 1, true]
[227, "bell", "a", 1, false]
[228, "truck", "a", 1, true]
[229, "grass", "", 1, true]
[230, "monkey", "a", 1, true]
[231, "bread", "a", 1, true]
[232, "ears", "", 1, false]
[233, "bowl", "a", 1, false]
[234, "bat", "a", 1, false]
[235, "clock", "a", 1, true]
[236, "doll", "a", 1, false]
[237, "orange", "an", 1, true]
[238, "bike", "a", 1, false]
[239, "pen", "a", 1, false]
[240, "seashell", "a", 1, true]
[241, "cloud", "a", 1, true]
[242, "bear", "a", 1, false]
[243, "corn", "", 1, false]
[244, "glasses", "", 1, true]
[245, "blocks", "", 1, true]
[246, "carPI:NAME:<NAME>END_PI", "a", 1, true]
[247, "turtle", "a", 1, true]
[248, "pencil", "a", 1, false]
[249, "dinosaur", "a", 1, true]
[250, "head", "a", 1, false]
[251, "lamp", "a", 1, false]
[252, "snowman", "a", 1, true]
[253, "ant", "an", 1, false]
[254, "giraffe", "a", 1, true]
[255, "cupcake", "a", 1, true]
[256, "leaf", "a", 1, false]
[257, "bunk", "a", 1, false]
[258, "snail", "a", 1, true]
[259, "baby", "a", 1, false]
[260, "balloon", "a", 1, true]
[261, "bus", "a", 1, false]
[262, "cherry", "a", 1, true]
[263, "football", "a", 1, true]
[264, "branch", "a", 1, true]
[265, "robot", "a", 1, true]
[266, "laptop", "a", 1, true]
[267, "pilPI:NAME:<NAME>END_PI", "a", 1, true]
[268, "monitor", "a", 1, true]
[269, "dinner", "a", 1, true]
[270, "bottle", "a", 1, false]
[271, "tomato", "a", 1, true]
[272, "butter", "", 1, true]
[273, "salami", "a", 1, true]
[274, "pancake", "a", 1, true]
[275, "waiter", "a", 1, true]
[276, "omelet", "", 1, true]
[277, "keyboard", "", 1, true]
[278, "coffee", "", 1, true]
[279, "adapter", "", 1, true]
[280, "webcam", "", 1, true]
[281, "window", "a", 1, true]
[282, "drill", "a", 1, true]
[283, "pliers", "", 1, true]
[284, "shotgun", "a", 1, true]
[285, "shield", "a", 1, true]
[286, "sword", "a", 1, true]
[287, "catapult", "a", 1, true]
[288, "carpet", "a", 1, true]
[289, "tennis", "", 1, true]
[290, "racket", "a", 1, true]
[291, "stick", "a", 1, true]
[292, "speaker", "a", 1, true]
[293, "church", "a", 1, true]
[294, "light", "", 1, true]
[295, "stereo", "a", 1, true]
[296, "PI:NAME:<NAME>END_PI", "a", 1, true]
[297, "dragon", "a", 1, true]
[298, "guitar", "a", 1, true]
[299, "arrow", "an", 1, true]
[300, "pants", "", 1, true]
[301, "eyebrow", "an", 1, true]
[302, "umbrella", "an", 1, true]
[303, "wheel", "a", 1, true]
[304, "snail", "a", 1, true]
[305, "PI:NAME:<NAME>END_PI", "a", 1, true]
[306, "sneeze", "a", 1, true]
[307, "dwarf", "a", 1, true]
[308, "PI:NAME:<NAME>END_PI", "a", 1, true]
[309, "police", "", 1, true]
[310, "PI:NAME:<NAME>END_PIman", "a", 1, true]
[311, "cable", "a", 1, true]
[312, "printer", "a", 1, true]
[313, "trophy", "a", 1, true]
[314, "Earth", "the", 1, true]
[315, "Saturn", "the", 1, true]
[316, "Europe", "the", 1, true]
[317, "flamingo", "a", 1, true]
[318, "volcano", "a", 1, true]
[319, "badge", "a", 1, true]
[320, "mirror", "a", 1, true]
[321, "shadow", "a", 1, true]
[322, "windmill", "a", 1, true]
[323, "shampoo", "", 1, true]
[324, "website", "a", 1, true]
[325, "children", "", 1, true]
[326, "blushing", "", 1, true]
[327, "tattoo", "a", 1, true]
[328, "piercing", "a", 1, true]
[329, "teacher", "a", 1, true]
[330, "gasoline", "", 1, true]
[331, "koala", "a", 1, true]
[332, "panda", "a", 1, true]
[333, "penguin", "a", 1, true]
[334, "shopping", "", 1, true]
[335, "brick", "a", 1, true]
[336, "necklace", "a", 1, true]
[337, "surprise", "", 1, true]
[338, "shoes", "", 1, true]
[339, "group", "a", 1, true]
[340, "selfie", "", 1, true]
[341, "plant", "a", 1, true]
[342, "toilet", "a", 1, true]
[343, "study", "a", 1, true]
[344, "kitchen", "a", 1, true]
[345, "towel", "a", 1, true]
[346, "hyena", "a", 1, true]
[347, "PI:NAME:<NAME>END_PI", "", 1, true]
[348, "eyeliner", "", 1, true]
[349, "makeup", "", 1, true]
[350, "lipstick", "", 1, true]
[351, "fridge", "a", 1, true]
[352, "movie", "a", 1, true]
[353, "sleeve", "a", 1, true]
[354, "PI:NAME:<NAME>END_PI", "", 1, true]
[355, "trashcan", "a", 1, true]
[356, "elevator", "an", 1, true]
[357, "dagger", "a", 1, true]
[358, "Titanic", "the", 1, true]
[359, "dPI:NAME:<NAME>END_PIning", "", 1, true]
[360, "iceberg", "an", 1, true]
[361, "colors", "", 1, true]
[362, "river", "a", 1, true]
[363, "wizard", "a", 1, true]
[364, "witch", "a", 1, true]
[365, "captain", "a", 1, true]
[366, "pillar", "a", 1, true]
[367, "donut", "a", 1, true]
[368, "lantern", "a", 1, true]
] |
[
{
"context": "NOT_NEEDED')\n\t\t.then ->\n\t\t\tWidget.create({ name: 'wodget', qty: 50, tags: ['cool']})\n\n\tit 'should do a rei",
"end": 2543,
"score": 0.8406292796134949,
"start": 2537,
"tag": "USERNAME",
"value": "wodget"
},
{
"context": "ig.execute()\n\t\t.then ->\n\t\t\tWidget... | test/migration.coffee | wcjohnson/ormojo-elasticsearch | 0 | { expect } = require 'chai'
{ ESBackend: es_backend } = require '..'
es_client = require './es_client'
ormojo = require 'ormojo'
Blackbird = require 'blackbird-promises'
makeCorpus = ->
logger = if '--ormojo-trace' in process.argv then console.log.bind(console) else ->
new ormojo.Corpus({
Promise: {
resolve: (x) -> Blackbird.resolve(x)
reject: (x) -> Blackbird.reject(x)
all: (x) -> Blackbird.all(x)
}
log: {
trace: logger
}
backends: {
'main': new es_backend(es_client)
}
})
makeModel = (corpus, modified) ->
fields = {
id: { type: ormojo.STRING }
name: { type: ormojo.STRING, defaultValue: 'nameless' }
timestamp: { type: ormojo.DATE, defaultValue: -> new Date }
url: {
type: ormojo.STRING
elasticsearch: {
mapping: { index: 'not_analyzed' }
}
}
qty: { type: ormojo.INTEGER, defaultValue: -> 1 + 1 }
tags: {
type: ormojo.ARRAY(ormojo.STRING)
defaultValue: -> []
elasticsearch: {
mapping: {
fields: {
raw: {
type: 'string'
index: 'not_analyzed'
}
}
}
}
}
}
if modified then fields['extra'] = { type: ormojo.STRING, defaultValue: 'extraData' }
Widget = corpus.createModel({
name: 'widget'
fields
})
Widget.forBackend('main', {
index: 'widget'
type: 'test'
filter: {
autocomplete_filter: {
type: 'edge_ngram',
min_gram: 1,
max_gram: 10
}
}
analyzer: {
autocomplete: {
type: 'custom',
tokenizer: 'standard',
filter: [ 'lowercase', 'autocomplete_filter' ]
}
}
})
describe 'migration tests: ', ->
it 'should delete all indices from prior tests', ->
es_client.indices.delete({
index: 'widget_ormojo*'
ignore: [404]
})
it 'should have static migration plan', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
console.dir plan[0].targetSettings, { depth: 50 }
it 'should do a create migration', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('CREATE')
mig.execute()
it 'should report repeated migration as unneded', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('NOT_NEEDED')
.then ->
Widget.create({ name: 'wodget', qty: 50, tags: ['cool']})
it 'should do a reindex migration', ->
corpus = makeCorpus()
Widget = makeModel(corpus, true)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('REINDEX')
mig.execute()
.then ->
Widget.create({ name: 'whatsit', qty: 50000, tags:['unCool'], extra: '150'})
| 207804 | { expect } = require 'chai'
{ ESBackend: es_backend } = require '..'
es_client = require './es_client'
ormojo = require 'ormojo'
Blackbird = require 'blackbird-promises'
makeCorpus = ->
logger = if '--ormojo-trace' in process.argv then console.log.bind(console) else ->
new ormojo.Corpus({
Promise: {
resolve: (x) -> Blackbird.resolve(x)
reject: (x) -> Blackbird.reject(x)
all: (x) -> Blackbird.all(x)
}
log: {
trace: logger
}
backends: {
'main': new es_backend(es_client)
}
})
makeModel = (corpus, modified) ->
fields = {
id: { type: ormojo.STRING }
name: { type: ormojo.STRING, defaultValue: 'nameless' }
timestamp: { type: ormojo.DATE, defaultValue: -> new Date }
url: {
type: ormojo.STRING
elasticsearch: {
mapping: { index: 'not_analyzed' }
}
}
qty: { type: ormojo.INTEGER, defaultValue: -> 1 + 1 }
tags: {
type: ormojo.ARRAY(ormojo.STRING)
defaultValue: -> []
elasticsearch: {
mapping: {
fields: {
raw: {
type: 'string'
index: 'not_analyzed'
}
}
}
}
}
}
if modified then fields['extra'] = { type: ormojo.STRING, defaultValue: 'extraData' }
Widget = corpus.createModel({
name: 'widget'
fields
})
Widget.forBackend('main', {
index: 'widget'
type: 'test'
filter: {
autocomplete_filter: {
type: 'edge_ngram',
min_gram: 1,
max_gram: 10
}
}
analyzer: {
autocomplete: {
type: 'custom',
tokenizer: 'standard',
filter: [ 'lowercase', 'autocomplete_filter' ]
}
}
})
describe 'migration tests: ', ->
it 'should delete all indices from prior tests', ->
es_client.indices.delete({
index: 'widget_ormojo*'
ignore: [404]
})
it 'should have static migration plan', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
console.dir plan[0].targetSettings, { depth: 50 }
it 'should do a create migration', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('CREATE')
mig.execute()
it 'should report repeated migration as unneded', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('NOT_NEEDED')
.then ->
Widget.create({ name: 'wodget', qty: 50, tags: ['cool']})
it 'should do a reindex migration', ->
corpus = makeCorpus()
Widget = makeModel(corpus, true)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('REINDEX')
mig.execute()
.then ->
Widget.create({ name: '<NAME>it', qty: 50000, tags:['unCool'], extra: '150'})
| true | { expect } = require 'chai'
{ ESBackend: es_backend } = require '..'
es_client = require './es_client'
ormojo = require 'ormojo'
Blackbird = require 'blackbird-promises'
makeCorpus = ->
logger = if '--ormojo-trace' in process.argv then console.log.bind(console) else ->
new ormojo.Corpus({
Promise: {
resolve: (x) -> Blackbird.resolve(x)
reject: (x) -> Blackbird.reject(x)
all: (x) -> Blackbird.all(x)
}
log: {
trace: logger
}
backends: {
'main': new es_backend(es_client)
}
})
makeModel = (corpus, modified) ->
fields = {
id: { type: ormojo.STRING }
name: { type: ormojo.STRING, defaultValue: 'nameless' }
timestamp: { type: ormojo.DATE, defaultValue: -> new Date }
url: {
type: ormojo.STRING
elasticsearch: {
mapping: { index: 'not_analyzed' }
}
}
qty: { type: ormojo.INTEGER, defaultValue: -> 1 + 1 }
tags: {
type: ormojo.ARRAY(ormojo.STRING)
defaultValue: -> []
elasticsearch: {
mapping: {
fields: {
raw: {
type: 'string'
index: 'not_analyzed'
}
}
}
}
}
}
if modified then fields['extra'] = { type: ormojo.STRING, defaultValue: 'extraData' }
Widget = corpus.createModel({
name: 'widget'
fields
})
Widget.forBackend('main', {
index: 'widget'
type: 'test'
filter: {
autocomplete_filter: {
type: 'edge_ngram',
min_gram: 1,
max_gram: 10
}
}
analyzer: {
autocomplete: {
type: 'custom',
tokenizer: 'standard',
filter: [ 'lowercase', 'autocomplete_filter' ]
}
}
})
describe 'migration tests: ', ->
it 'should delete all indices from prior tests', ->
es_client.indices.delete({
index: 'widget_ormojo*'
ignore: [404]
})
it 'should have static migration plan', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
console.dir plan[0].targetSettings, { depth: 50 }
it 'should do a create migration', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('CREATE')
mig.execute()
it 'should report repeated migration as unneded', ->
corpus = makeCorpus()
Widget = makeModel(corpus)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('NOT_NEEDED')
.then ->
Widget.create({ name: 'wodget', qty: 50, tags: ['cool']})
it 'should do a reindex migration', ->
corpus = makeCorpus()
Widget = makeModel(corpus, true)
mig = corpus.getBackend('main').getMigration()
mig.prepare()
.then ->
plan = mig.getMigrationPlan()
expect(plan[0].strategy).to.equal('REINDEX')
mig.execute()
.then ->
Widget.create({ name: 'PI:NAME:<NAME>END_PIit', qty: 50000, tags:['unCool'], extra: '150'})
|
[
{
"context": "tainers.length == 0\n matches = line.match(@graphMatchRe)\n if matches\n rootGraph = new",
"end": 13801,
"score": 0.9363806843757629,
"start": 13788,
"tag": "USERNAME",
"value": "@graphMatchRe"
},
{
"context": "rs[0])\n else\n ... | src/coffee/canviz.coffee | mokemokechicken/CanvizPlain | 3 | class CanvizTokenizer
constructor: (@str) ->
takeChars: (num) ->
num = 1 if !num
tokens = []
while (num--)
matches = @str.match(/^(\S+)\s*/)
if matches
@str = @str.substr(matches[0].length)
tokens.push(matches[1])
else
tokens.push(false)
if 1 == tokens.length
return tokens[0]
else
return tokens
takeNumber: (num) ->
num = 1 if !num
if 1 == num
return Number(@takeChars())
else
tokens = @takeChars(num)
while num--
tokens[num] = Number(tokens[num])
return tokens
takeString: () ->
byteCount = Number(@takeChars())
charCount = 0
return false if '-' != @str.charAt(0)
while 0 < byteCount
++charCount
charCode = @str.charCodeAt(charCount)
if 0x80 > charCode
--byteCount
else if 0x800 > charCode
byteCount -= 2
else
byteCount -= 3
str = @str.substr(1, charCount)
@str = @str.substr(1 + charCount).replace(/^\s+/, '')
return str
class CanvizEntity
constructor: (@defaultAttrHashName, @name, @canviz, @rootGraph, @parentGraph, @immediateGraph) ->
@attrs = {}
@drawAttrs = {}
initBB: () ->
matches = @getAttr('pos').match(/([0-9.]+),([0-9.]+)/)
x = Math.round(matches[1])
y = Math.round(@canviz.height - matches[2])
@bbRect = new Rect(x, y, x, y)
getAttr: (attrName, escString=false) ->
attrValue = @attrs[attrName]
if not attrValue?
graph = @parentGraph
while graph?
attrValue = graph[@defaultAttrHashName][attrName]
if not attrValue?
graph = graph.parentGraph
else
break
if attrValue and escString
attrValue = attrValue.replace @escStringMatchRe, (match, p1) =>
switch p1
when 'N', 'E' then return @name
when 'T' then return @tailNode
when 'H' then return @headNode
when 'G' then return @immediateGraph.name
when 'L' then return @getAttr('label', true)
return match
return attrValue
draw: (ctx, ctxScale, redrawCanvasOnly) ->
if !redrawCanvasOnly
@initBB()
bbDiv = document.createElement('div')
@canviz.elements.appendChild(bbDiv)
for _, command of @drawAttrs
# command = drawAttr.value
tokenizer = new CanvizTokenizer(command)
token = tokenizer.takeChars()
if token
dashStyle = 'solid'
ctx.save()
while token
switch token
when 'E', 'e' # unfilled ellipse
filled = ('E' == token)
cx = tokenizer.takeNumber()
cy = @canviz.height - tokenizer.takeNumber()
rx = tokenizer.takeNumber()
ry = tokenizer.takeNumber()
path = new Ellipse(cx, cy, rx, ry)
when 'P', 'p', 'L'
filled = ('P' == token)
closed = ('L' != token);
numPoints = tokenizer.takeNumber()
tokens = tokenizer.takeNumber(2 * numPoints)
path = new Path()
#for (i = 2; i < 2 * numPoints; i += 2)
for i in [2...(2*numPoints)] by 2
path.addBezier([
new Point(tokens[i - 2], @canviz.height - tokens[i - 1])
new Point(tokens[i], @canviz.height - tokens[i + 1])
])
if closed
path.addBezier([
new Point(tokens[2 * numPoints - 2], @canviz.height - tokens[2 * numPoints - 1])
new Point(tokens[0], @canviz.height - tokens[1])
])
when 'B', 'b' # unfilled b-spline
filled = ('b' == token)
numPoints = tokenizer.takeNumber()
tokens = tokenizer.takeNumber(2 * numPoints); # points
path = new Path()
for i in [2...(2*numPoints)] by 6
path.addBezier([
new Point(tokens[i - 2], @canviz.height - tokens[i - 1])
new Point(tokens[i], @canviz.height - tokens[i + 1])
new Point(tokens[i + 2], @canviz.height - tokens[i + 3])
new Point(tokens[i + 4], @canviz.height - tokens[i + 5])
])
when 'I' # image
l = tokenizer.takeNumber()
b = @canviz.height - tokenizer.takeNumber()
w = tokenizer.takeNumber()
h = tokenizer.takeNumber()
src = tokenizer.takeString()
if !@canviz.images[src]
@canviz.images[src] = new CanvizImage(@canviz, src)
@canviz.images[src].draw(ctx, l, b - h, w, h)
when 'T' # text
l = Math.round(ctxScale * tokenizer.takeNumber() + @canviz.padding)
t = Math.round(ctxScale * @canviz.height + 2 * @canviz.padding - (ctxScale * (tokenizer.takeNumber() + @canviz.bbScale * fontSize) + @canviz.padding))
textAlign = tokenizer.takeNumber()
textWidth = Math.round(ctxScale * tokenizer.takeNumber())
str = tokenizer.takeString()
if !redrawCanvasOnly and !/^\s*$/.test(str)
#str = escapeHTML(str)
loop
matches = str.match(/[ ]([ ]+)/)
if matches
spaces = ' '
spaces += ' ' for _ in [0..matches[1].length.times]
str = str.replace(/[ ] +/, spaces)
break unless matches
href = @getAttr('URL', true) || @getAttr('href', true)
if href
target = @getAttr('target', true) || '_self'
tooltip = @getAttr('tooltip', true) || @getAttr('label', true)
text = document.createElement("a")
text.href = href
text.target = target
text.title = tooltip
for attrName in ['onclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout']
attrValue = @getAttr(attrName, true)
if attrValue
text.writeAttribute(attrName, attrValue)
text.textDecoration = 'none'
else
text = document.createElement("span") # new Element('span')
text.innerText = str
ts = text.style
ts.fontSize = Math.round(fontSize * ctxScale * @canviz.bbScale) + 'px'
ts.fontFamily = fontFamily
ts.color = strokeColor.textColor
ts.position = 'absolute'
ts.textAlign = if (-1 == textAlign) then 'left' else if (1 == textAlign) then 'right' else 'center'
ts.left = (l - (1 + textAlign) * textWidth) + 'px'
ts.top = t + 'px'
ts.width = (2 * textWidth) + 'px'
ts.opacity = strokeColor.opacity if 1 != strokeColor.opacity
@canviz.elements.appendChild(text)
when 'C', 'c'
fill = ('C' == token)
color = @parseColor(tokenizer.takeString())
if fill
fillColor = color
ctx.fillStyle = color.canvasColor
else
strokeColor = color
ctx.strokeStyle = color.canvasColor
when 'F' # // set font
fontSize = tokenizer.takeNumber()
fontFamily = tokenizer.takeString()
switch fontFamily
when 'Times-Roman' then fontFamily = 'Times New Roman'
when 'Courier' then fontFamily = 'Courier New'
when 'Helvetica' then fontFamily = 'Arial'
when 'S' # // set style
style = tokenizer.takeString()
switch style
when 'solid', 'filled' then 1 # nothing
when 'dashed', 'dotted' then dashStyle = style
when 'bold' then ctx.lineWidth = 2
else
matches = style.match(/^setlinewidth\((.*)\)$/)
if matches
ctx.lineWidth = Number(matches[1])
else
debug('unknown style ' + style)
else
debug('unknown token ' + token)
return
if path
@canviz.drawPath(ctx, path, filled, dashStyle)
@bbRect.expandToInclude(path.getBB()) if !redrawCanvasOnly
path = undefined
token = tokenizer.takeChars()
if !redrawCanvasOnly
bbDiv.position = 'absolute'
bbDiv.left = Math.round(ctxScale * @bbRect.l + @canviz.padding) + 'px'
bbDiv.top = Math.round(ctxScale * @bbRect.t + @canviz.padding) + 'px'
bbDiv.width = Math.round(ctxScale * @bbRect.getWidth()) + 'px'
bbDiv.height = Math.round(ctxScale * @bbRect.getHeight()) + 'px'
ctx.restore()
parseColor: (color) ->
parsedColor = {opacity: 1}
# // rgb/rgba
if /^#(?:[0-9a-f]{2}\s*){3,4}$/i.test(color)
return @canviz.parseHexColor(color)
# // hsv
matches = color.match(/^(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)$/)
if matches
parsedColor.canvasColor = parsedColor.textColor = @canviz.hsvToRgbColor(matches[1], matches[2], matches[3])
return parsedColor
# // named color
colorScheme = @getAttr('colorscheme') || 'X11'
colorName = color
matches = color.match(/^\/(.*)\/(.*)$/)
if matches
if matches[1]
colorScheme = matches[1]
colorName = matches[2]
else
matches = color.match(/^\/(.*)$/)
if matches
colorScheme = 'X11'
colorName = matches[1]
colorName = colorName.toLowerCase()
colorSchemeName = colorScheme.toLowerCase()
colorSchemeData = Canviz.colors[colorSchemeName]
if colorSchemeData
colorData = colorSchemeData[colorName]
if colorData
return @canviz.parseHexColor('#' + colorData)
colorData = Canviz.colors['fallback'][colorName]
if colorData
return @canviz.parseHexColor('#' + colorData)
if !colorSchemeData
debug('unknown color scheme ' + colorScheme)
# // unknown
debug('unknown color ' + color + '; color scheme is ' + colorScheme)
parsedColor.canvasColor = parsedColor.textColor = '#000000'
return parsedColor
class CanvizNode extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph) ->
super('nodeAttrs', name, canviz, rootGraph, parentGraph, parentGraph)
escStringMatchRe: /\\([NGL])/g
#
class CanvizEdge extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph, @tailNode, @headNode) ->
super('edgeAttrs', name, canviz, rootGraph, parentGraph, parentGraph)
escStringMatchRe: /\\([EGTHL])/g
class CanvizGraph extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph) ->
super('attrs', name, canviz, rootGraph, parentGraph, this)
@nodeAttrs = {}
@edgeAttrs = {}
@nodes = []
@edges = []
@subgraphs = []
initBB: () ->
coords = @getAttr('bb').split(',')
@bbRect = new Rect(coords[0], @canviz.height - coords[1], coords[2], @canviz.height - coords[3])
draw: (ctx, ctxScale, redrawCanvasOnly) ->
super(ctx, ctxScale, redrawCanvasOnly)
for type in [@subgraphs, @nodes, @edges]
for entity in type
entity.draw(ctx, ctxScale, redrawCanvasOnly)
escStringMatchRe: /\\([GL])/g
class Canviz
@maxXdotVersion: "1.2"
@colors:
fallback:
black:'000000'
lightgrey:'d3d3d3'
white:'ffffff'
constructor: (container, url, urlParams) ->
@canvas = document.createElement('canvas')
@canvas.style.position = "absolute"
Canviz.canvasCounter ?= 0
@canvas.id = 'canviz_canvas_' + (++Canviz.canvasCounter)
@elements = document.createElement('div')
@elements.style.position = "absolute"
@container = document.getElementById(container)
@container.style.position = "relative"
@container.appendChild(@canvas)
@container.appendChild(@elements)
@ctx = @canvas.getContext('2d')
@scale = 1
@padding = 8
@dashLength = 6
@dotSpacing = 4
@graphs = []
@images = {}
@numImages = 0
@numImagesFinished = 0
@imagePath = ""
@idMatch = '([a-zA-Z\u0080-\uFFFF_][0-9a-zA-Z\u0080-\uFFFF_]*|-?(?:\\.\\d+|\\d+(?:\\.\\d*)?)|"(?:\\\\"|[^"])*"|<(?:<[^>]*>|[^<>]+?)+>)'
@nodeIdMatch = @idMatch + '(?::' + @idMatch + ')?(?::' + @idMatch + ')?'
@graphMatchRe = new RegExp('^(strict\\s+)?(graph|digraph)(?:\\s+' + @idMatch + ')?\\s*{$', 'i')
@subgraphMatchRe = new RegExp('^(?:subgraph\\s+)?' + @idMatch + '?\\s*{$', 'i')
@nodeMatchRe = new RegExp('^(' + @nodeIdMatch + ')\\s+\\[(.+)\\];$')
@edgeMatchRe = new RegExp('^(' + @nodeIdMatch + '\\s*-[->]\\s*' + @nodeIdMatch + ')\\s+\\[(.+)\\];$')
@attrMatchRe = new RegExp('^' + @idMatch + '=' + @idMatch + '(?:[,\\s]+|$)')
setScale: (@scale) ->
setImagePath: (@imagePath) ->
parse: (xdot) ->
@graphs = []
@width = 0
@height = 0
@maxWidth = false
@maxHeight = false
@bbEnlarge = false
@bbScale = 1
@dpi = 96
@bgcolor = opacity: 1
@bgcolor.canvasColor = @bgcolor.textColor = '#ffffff'
lines = xdot.split(/\r?\n/)
i = 0
containers = []
while i < lines.length
line = lines[i++].replace(/^\s+/, '')
if '' != line and '#' != line.substr(0, 1)
while i < lines.length and ';' != (lastChar = line.substr(line.length - 1, line.length)) and '{' != lastChar and '}' != lastChar
if '\\' == lastChar
line = line.substr(0, line.length - 1)
line += lines[i++]
if containers.length == 0
matches = line.match(@graphMatchRe)
if matches
rootGraph = new CanvizGraph(matches[3], this)
containers.unshift(rootGraph)
containers[0].strict = not (not matches[1])
containers[0].type = if 'graph' == matches[2] then 'undirected' else 'directed'
containers[0].attrs.xdotversion = '1.0'
containers[0].attrs.bb ?= '0,0,500,500'
@graphs.push(containers[0])
else
matches = line.match(@subgraphMatchRe)
if matches
containers.unshift(new CanvizGraph(matches[1], this, rootGraph, containers[0]))
containers[1].subgraphs.push containers[0]
if matches
else if "}" == line
containers.shift()
break if 0 == containers.length
else
matches = line.match(@nodeMatchRe)
if matches
entityName = matches[2]
attrs = matches[5]
drawAttrHash = containers[0].drawAttrs
isGraph = false
switch entityName
when 'graph'
attrHash = containers[0].attrs
isGraph = true
when 'node' then attrHash = containers[0].nodeAttrs
when 'edge' then attrHash = containers[0].edgeAttrs
else
entity = new CanvizNode(entityName, this, rootGraph, containers[0])
attrHash = entity.attrs
drawAttrHash = entity.drawAttrs
containers[0].nodes.push(entity)
else
matches = line.match(@edgeMatchRe)
if matches
entityName = matches[1]
attrs = matches[8]
entity = new CanvizEdge(entityName, this, rootGraph, containers[0], matches[2], matches[5])
attrHash = entity.attrs
drawAttrHash = entity.drawAttrs
containers[0].edges.push(entity)
while matches
break if 0 == attrs.length
matches = attrs.match(@attrMatchRe)
if matches
attrs = attrs.substr(matches[0].length)
attrName = matches[1]
attrValue = @unescape(matches[2])
if /^_.*draw_$/.test(attrName)
drawAttrHash[attrName] = attrValue
else
attrHash[attrName] = attrValue
if isGraph and 1 == containers.length
switch attrName
when 'bb'
bb = attrValue.split(/,/)
@width = Number(bb[2])
@height = Number(bb[3])
when 'bgcolor' then @bgcolor = rootGraph.parseColor(attrValue)
when 'dpi' then @dpi = attrValue
when 'size'
size = attrValue.match(/^(\d+|\d*(?:\.\d+)),\s*(\d+|\d*(?:\.\d+))(!?)$/)
if size
@maxWidth = 72 * Number(size[1])
@maxHeight = 72 * Number(size[2])
@bbEnlarge = '!' == size[3]
when 'xdotversion'
if 0 > @versionCompare(Canviz.maxXdotVersion, attrHash['xdotversion'])
1
@draw()
draw: (redrawCanvasOnly) ->
redrawCanvasOnly ?= false
ctxScale = @scale * @dpi / 72
width = Math.round(ctxScale * @width + 2 * @padding)
height = Math.round(ctxScale * @height + 2 * @padding)
if !redrawCanvasOnly
@canvas.width = width
@canvas.height = height
@canvas.style.width = "#{width}px"
@canvas.style.height = "#{height}px"
@container.style.width = "#{width}px"
while (@elements.firstChild)
@elements.removeChild(@elements.firstChild)
@ctx.save()
@ctx.lineCap = 'round'
@ctx.fillStyle = @bgcolor.canvasColor
@ctx.fillRect(0, 0, width, height)
@ctx.translate(@padding, @padding)
@ctx.scale(ctxScale, ctxScale)
@graphs[0].draw(@ctx, ctxScale, redrawCanvasOnly)
@ctx.restore()
drawPath: (ctx, path, filled, dashStyle) ->
if (filled)
ctx.beginPath()
path.makePath(ctx)
ctx.fill()
if ctx.fillStyle != ctx.strokeStyle or not filled
switch dashStyle
when 'dashed'
ctx.beginPath()
path.makeDashedPath(ctx, @dashLength)
when 'dotted'
oldLineWidth = ctx.lineWidth
ctx.lineWidth *= 2
ctx.beginPath()
path.makeDottedPath(ctx, @dotSpacing)
else
if not filled
ctx.beginPath()
path.makePath(ctx)
ctx.stroke()
ctx.lineWidth = oldLineWidth if oldLineWidth
unescape: (str) ->
matches = str.match(/^"(.*)"$/)
if (matches)
return matches[1].replace(/\\"/g, '"')
else
return str
parseHexColor: (color) ->
matches = color.match(/^#([0-9a-f]{2})\s*([0-9a-f]{2})\s*([0-9a-f]{2})\s*([0-9a-f]{2})?$/i)
if matches
canvasColor; textColor = '#' + matches[1] + matches[2] + matches[3]; opacity = 1
if (matches[4]) # rgba
opacity = parseInt(matches[4], 16) / 255
canvasColor = 'rgba(' + parseInt(matches[1], 16) + ',' + parseInt(matches[2], 16) + ',' + parseInt(matches[3], 16) + ',' + opacity + ')'
else # rgb
canvasColor = textColor
return {canvasColor: canvasColor, textColor: textColor, opacity: opacity}
hsvToRgbColor: (h, s, v) ->
h *= 360
i = Math.floor(h / 60) % 6
f = h / 60 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
switch (i)
when 0 then r = v; g = t; b = p
when 1 then r = q; g = v; b = p
when 2 then r = p; g = v; b = t
when 3 then r = p; g = q; b = v
when 4 then r = t; g = p; b = v
when 5 then r = v; g = p; b = q
return 'rgb(' + Math.round(255 * r) + ',' + Math.round(255 * g) + ',' + Math.round(255 * b) + ')'
versionCompare: (a, b) ->
a = a.split('.')
b = b.split('.')
while (a.length or b.length)
a1 = if a.length then a.shift() else 0
b1 = if b.length then b.shift() else 0
return -1 if (a1 < b1)
return 1 if (a1 > b1)
return 0
class CanvizImage
constructor: (@canviz, src) ->
++@canviz.numImages
@finished = @loaded = false
@img = new Image()
@img.onload = @onLoad.bind(this)
@img.onerror = @onFinish.bind(this)
@img.onabort = @onFinish.bind(this)
@img.src = @canviz.imagePath + src
onLoad: ->
@loaded = true
@onFinish()
onFinish: ->
@finished = true
++@canviz.numImagesFinished
if @canviz.numImages == @canviz.numImagesFinished
@canviz.draw(true)
draw: (ctx, l, t, w, h) ->
if @finished
if @loaded
ctx.drawImage(@img, l, t, w, h)
else
debug("can't load image " + @img.src)
@drawBrokenImage(ctx, l, t, w, h)
drawBrokenImage: (ctx, l, t, w, h) ->
ctx.save()
ctx.beginPath()
new Rect(l, t, l + w, t + w).draw(ctx)
ctx.moveTo(l, t)
ctx.lineTo(l + w, t + w)
ctx.moveTo(l + w, t)
ctx.lineTo(l, t + h)
ctx.strokeStyle = '#f00'
ctx.lineWidth = 1
ctx.stroke()
ctx.restore()
##########################################################
# $Id: path.js 262 2009-05-19 11:55:24Z ryandesign.com $
##########################################################
class Point
constructor: (@x, @y) ->
offset: (dx, dy) ->
@x += dx
@y += dy
distanceFrom: (point) ->
dx = @x - point.x
dy = @y - point.y
Math.sqrt(dx * dx + dy * dy)
makePath: (ctx) ->
ctx.moveTo(@x, @y)
ctx.lineTo(@x + 0.001, @y)
############### Path.js
class Bezier
constructor: (@points) ->
@order = points.length
reset: () ->
p = Bezier.prototype
@controlPolygonLength = p.controlPolygonLength
@chordLength = p.chordLength
@triangle = p.triangle
@chordPoints = p.chordPoints
@coefficients = p.coefficients
offset: (dx, dy) ->
for point in @points
point.offset(dx, dy)
@reset()
getBB: ->
return undefined if !@order
p = @points[0]
l = r = p.x
t = b = p.y
for point in @points
l = Math.min(l, point.x)
t = Math.min(t, point.y)
r = Math.max(r, point.x)
b = Math.max(b, point.y)
rect = new Rect(l, t, r, b)
return (@getBB = -> rect)()
isPointInBB: (x, y, tolerance) ->
tolerance ?= 0
bb = @getBB()
if (0 < tolerance)
bb = clone(bb)
bb.inset(-tolerance, -tolerance)
!(x < bb.l || x > bb.r || y < bb.t || y > bb.b)
isPointOnBezier: (x, y, tolerance=0) ->
return false if !@isPointInBB(x, y, tolerance)
segments = @chordPoints()
p1 = segments[0].p
for i in [1...segments.length]
p2 = segments[i].p
x1 = p1.x
y1 = p1.y
x2 = p2.x
y2 = p2.y
bb = new Rect(x1, y1, x2, y2)
if bb.isPointInBB(x, y, tolerance)
twice_area = Math.abs(x1 * y2 + x2 * y + x * y1 - x2 * y1 - x * y2 - x1 * y)
base = p1.distanceFrom(p2)
height = twice_area / base
return true if height <= tolerance
p1 = p2
return false
# # Based on Oliver Steele's bezier.js library.
controlPolygonLength: ->
len = 0
for i in [1...@order]
len += @points[i - 1].distanceFrom(@points[i])
(@controlPolygonLength = -> len)()
# # Based on Oliver Steele's bezier.js library.
chordLength: ->
len = @points[0].distanceFrom(@points[@order - 1])
(@chordLength = -> len)()
# # From Oliver Steele's bezier.js library.
triangle: ->
upper = @points
m = [upper]
for i in [1...@order]
lower = []
for j in [0...(@order-i)]
c0 = upper[j]
c1 = upper[j + 1]
lower[j] = new Point((c0.x + c1.x) / 2, (c0.y + c1.y) / 2)
m.push(lower)
upper = lower
(@triangle = -> m)()
# # Based on Oliver Steele's bezier.js library.
triangleAtT: (t) ->
s = 1 - t
upper = @points
m = [upper]
for i in [1...@order]
lower = []
for j in [0...(@order-i)]
c0 = upper[j]
c1 = upper[j + 1]
lower[j] = new Point(c0.x * s + c1.x * t, c0.y * s + c1.y * t)
m.push(lower)
upper = lower
return m
# Returns two beziers resulting from splitting @bezier at t=0.5.
# Based on Oliver Steele's bezier.js library.
split: (t=0.5) ->
m = if (0.5 == t) then @triangle() else @triangleAtT(t)
leftPoints = new Array(@order)
rightPoints = new Array(@order)
for i in [1...@order]
leftPoints[i] = m[i][0]
rightPoints[i] = m[@order - 1 - i][i]
return {left: new Bezier(leftPoints), right: new Bezier(rightPoints)}
# Returns a bezier which is the portion of @bezier from t1 to t2.
# Thanks to Peter Zin on comp.graphics.algorithms.
mid: (t1, t2) ->
@split(t2).left.split(t1 / t2).right
# Returns points (and their corresponding times in the bezier) that form
# an approximate polygonal representation of the bezier.
# Based on the algorithm described in Jeremy Gibbons' dashed.ps.gz
chordPoints: ->
p = [{tStart: 0, tEnd: 0, dt: 0, p: @points[0]}].concat(@_chordPoints(0, 1))
(@chordPoints = -> p)()
_chordPoints: (tStart, tEnd) ->
tolerance = 0.001
dt = tEnd - tStart
if @controlPolygonLength() <= (1 + tolerance) * @chordLength()
return [{tStart: tStart, tEnd: tEnd, dt: dt, p: @points[@order - 1]}]
else
tMid = tStart + dt / 2
halves = @split()
return halves.left._chordPoints(tStart, tMid).concat(halves.right._chordPoints(tMid, tEnd))
# Returns an array of times between 0 and 1 that mark the bezier evenly
# in space.
# Based in part on the algorithm described in Jeremy Gibbons' dashed.ps.gz
markedEvery: (distance, firstDistance) ->
nextDistance = firstDistance || distance
segments = @chordPoints()
times = []
t = 0; # time
for i in [1...segments.length]
segment = segments[i]
segment.length = segment.p.distanceFrom(segments[i - 1].p)
if 0 == segment.length
t += segment.dt
else
dt = nextDistance / segment.length * segment.dt
segment.remainingLength = segment.length
while segment.remainingLength >= nextDistance
segment.remainingLength -= nextDistance
t += dt
times.push(t)
if distance != nextDistance
nextDistance = distance
dt = nextDistance / segment.length * segment.dt
nextDistance -= segment.remainingLength
t = segment.tEnd
return {times: times, nextDistance: nextDistance}
# Return the coefficients of the polynomials for x and y in t.
# From Oliver Steele's bezier.js library.
coefficients: ->
# @function deals with polynomials, represented as
# arrays of coefficients. p[i] is the coefficient of n^i.
# p0, p1 => p0 + (p1 - p0) * n
# side-effects (denormalizes) p0, for convienence
interpolate = (p0, p1) ->
p0.push(0)
p = new Array(p0.length)
p[0] = p0[0]
for i in [0...p1.length]
p[i + 1] = p0[i + 1] + p1[i] - p0[i]
p
# folds +interpolate+ across a graph whose fringe is
# the polynomial elements of +ns+, and returns its TOP
collapse = (ns) ->
while ns.length > 1
ps = new Array(ns.length-1)
for i in [0...(ns.length-1)]
ps[i] = interpolate(ns[i], ns[i + 1])
ns = ps
return ns[0]
# xps and yps are arrays of polynomials --- concretely realized
# as arrays of arrays
xps = []
yps = []
for pt in @points
xps.push([pt.x])
yps.push([pt.y])
result = {xs: collapse(xps), ys: collapse(yps)}
return (@coefficients = ->result)()
# Return the point at time t.
# From Oliver Steele's bezier.js library.
pointAtT: (t) ->
c = @coefficients()
[cx, cy] = [c.xs, c.ys]
# evaluate cx[0] + cx[1]t +cx[2]t^2 ....
# optimization: start from the end, to save one
# muliplicate per order (we never need an explicit t^n)
# optimization: special-case the last element
# to save a multiply-add
x = cx[cx.length - 1]; y = cy[cy.length - 1];
for i in [cx.length..0]
x = x * t + cx[i]
y = y * t + cy[i]
new Point(x, y)
# Render the Bezier to a WHATWG 2D canvas context.
# Based on Oliver Steele's bezier.js library.
makePath: (ctx, moveTo=true) ->
ctx.moveTo(@points[0].x, @points[0].y) if (moveTo)
fn = @pathCommands[@order]
if fn
coords = []
for i in [(if 1 == @order then 0 else 1)...@points.length]
coords.push(@points[i].x)
coords.push(@points[i].y)
fn.apply(ctx, coords)
# Wrapper functions to work around Safari, in which, up to at least 2.0.3,
# fn.apply isn't defined on the context primitives.
# Based on Oliver Steele's bezier.js library.
pathCommands: [
null,
# @will have an effect if there's a line thickness or end cap.
(x, y) -> @lineTo(x + 0.001, y)
(x, y) -> @lineTo(x, y)
(x1, y1, x2, y2) -> @quadraticCurveTo(x1, y1, x2, y2)
(x1, y1, x2, y2, x3, y3) -> @bezierCurveTo(x1, y1, x2, y2, x3, y3)
]
makeDashedPath: (ctx, dashLength, firstDistance, drawFirst=true) ->
firstDistance = dashLength if !firstDistance
markedEvery = @markedEvery(dashLength, firstDistance)
markedEvery.times.unshift(0) if (drawFirst)
drawLast = (markedEvery.times.length % 2)
markedEvery.times.push(1) if drawLast
for i in [1...(markedEvery.times.length)] by 2
@mid(markedEvery.times[i - 1], markedEvery.times[i]).makePath(ctx)
return {firstDistance: markedEvery.nextDistance, drawFirst: drawLast}
makeDottedPath: (ctx, dotSpacing, firstDistance) ->
firstDistance = dotSpacing if !firstDistance
markedEvery = @markedEvery(dotSpacing, firstDistance)
markedEvery.times.unshift(0) if dotSpacing == firstDistance
for t in markedEvery.times
@pointAtT(t).makePath(ctx)
return markedEvery.nextDistance
class Path
constructor: (@segments=[]) ->
setupSegments: ->
# Based on Oliver Steele's bezier.js library.
addBezier: (pointsOrBezier) ->
@segments.push(if pointsOrBezier instanceof Array then new Bezier(pointsOrBezier) else pointsOrBezier)
offset: (dx, dy) ->
@setupSegments() if 0 == @segments.length
for segment in @segments
segment.offset(dx, dy)
getBB: ->
@setupSegments() if 0 == @segments.length
p = @segments[0].points[0]
l = r = p.x
t = b = p.y
for segment in @segments
for point in segment.points
l = Math.min(l, point.x)
t = Math.min(t, point.y)
r = Math.max(r, point.x)
b = Math.max(b, point.y)
rect = new Rect(l, t, r, b);
return (@getBB = -> rect)()
isPointInBB: (x, y, tolerance=0) ->
bb = @getBB()
if 0 < tolerance
bb = clone(bb)
bb.inset(-tolerance, -tolerance)
return !(x < bb.l || x > bb.r || y < bb.t || y > bb.b)
isPointOnPath: (x, y, tolerance=0) ->
return false if !@isPointInBB(x, y, tolerance)
result = false;
for segment in @segments
if segment.isPointOnBezier(x, y, tolerance)
result = true
throw $break
return result
isPointInPath: (x, y) -> false
# Based on Oliver Steele's bezier.js library.
makePath: (ctx) ->
@setupSegments() if 0 == @segments.length
moveTo = true
for segment in @segments
segment.makePath(ctx, moveTo)
moveTo = false
makeDashedPath: (ctx, dashLength, firstDistance, drawFirst) ->
@setupSegments() if 0 == @segments.length
info =
drawFirst: if !drawFirst? then true else drawFirst
firstDistance: firstDistance || dashLength
for segment in @segments
info = segment.makeDashedPath(ctx, dashLength, info.firstDistance, info.drawFirst)
makeDottedPath: (ctx, dotSpacing, firstDistance) ->
@setupSegments() if 0 == @segments.length
firstDistance = dotSpacing if !firstDistance
for segment in @segments
firstDistance = segment.makeDottedPath(ctx, dotSpacing, firstDistance)
class Polygon extends Path
constructor: (@points=[]) -> super()
setupSegments: ->
for p, i in @points
next = i + 1
next = 0 if @points.length == next
@addBezier([p, @points[next]])
class Rect extends Polygon
constructor: (@l, @t, @r, @b) -> super()
inset: (ix, iy) ->
@l += ix
@t += iy
@r -= ix
@b -= iy
return this
expandToInclude: (rect) ->
@l = Math.min(@l, rect.l)
@t = Math.min(@t, rect.t)
@r = Math.max(@r, rect.r)
@b = Math.max(@b, rect.b)
getWidth: -> @r - @l
getHeight: -> @b - @t
setupSegments: ->
w = @getWidth()
h = @getHeight()
@points = [
new Point(@l, @t)
new Point(@l + w, @t)
new Point(@l + w, @t + h)
new Point(@l, @t + h)
]
super()
class Ellipse extends Path
KAPPA: 0.5522847498,
constructor: (@cx, @cy, @rx, @ry) -> super()
setupSegments: ->
@addBezier([
new Point(@cx, @cy - @ry)
new Point(@cx + @KAPPA * @rx, @cy - @ry)
new Point(@cx + @rx, @cy - @KAPPA * @ry)
new Point(@cx + @rx, @cy)
])
@addBezier([
new Point(@cx + @rx, @cy)
new Point(@cx + @rx, @cy + @KAPPA * @ry)
new Point(@cx + @KAPPA * @rx, @cy + @ry)
new Point(@cx, @cy + @ry)
])
@addBezier([
new Point(@cx, @cy + @ry)
new Point(@cx - @KAPPA * @rx, @cy + @ry)
new Point(@cx - @rx, @cy + @KAPPA * @ry)
new Point(@cx - @rx, @cy)
]);
@addBezier([
new Point(@cx - @rx, @cy)
new Point(@cx - @rx, @cy - @KAPPA * @ry)
new Point(@cx - @KAPPA * @rx, @cy - @ry)
new Point(@cx, @cy - @ry)
])
escapeHTML = (str) ->
div = document.createElement('div')
div.appendChild(document.createTextNode(str))
div.innerHTML
debug = (str) ->
console.log str
clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
#/*
# * This file is part of Canviz. See http://www.canviz.org/
# * $Id: x11colors.js 246 2008-12-27 08:36:24Z ryandesign.com $
# */
Canviz.colors.x11 =
aliceblue:'f0f8ff'
antiquewhite:'faebd7'
antiquewhite1:'ffefdb'
antiquewhite2:'eedfcc'
antiquewhite3:'cdc0b0'
antiquewhite4:'8b8378'
aquamarine:'7fffd4'
aquamarine1:'7fffd4'
aquamarine2:'76eec6'
aquamarine3:'66cdaa'
aquamarine4:'458b74'
azure:'f0ffff'
azure1:'f0ffff'
azure2:'e0eeee'
azure3:'c1cdcd'
azure4:'838b8b'
beige:'f5f5dc'
bisque:'ffe4c4'
bisque1:'ffe4c4'
bisque2:'eed5b7'
bisque3:'cdb79e'
bisque4:'8b7d6b'
black:'000000'
blanchedalmond:'ffebcd'
blue:'0000ff'
blue1:'0000ff'
blue2:'0000ee'
blue3:'0000cd'
blue4:'00008b'
blueviolet:'8a2be2'
brown:'a52a2a'
brown1:'ff4040'
brown2:'ee3b3b'
brown3:'cd3333'
brown4:'8b2323'
burlywood:'deb887'
burlywood1:'ffd39b'
burlywood2:'eec591'
burlywood3:'cdaa7d'
burlywood4:'8b7355'
cadetblue:'5f9ea0'
cadetblue1:'98f5ff'
cadetblue2:'8ee5ee'
cadetblue3:'7ac5cd'
cadetblue4:'53868b'
chartreuse:'7fff00'
chartreuse1:'7fff00'
chartreuse2:'76ee00'
chartreuse3:'66cd00'
chartreuse4:'458b00'
chocolate:'d2691e'
chocolate1:'ff7f24'
chocolate2:'ee7621'
chocolate3:'cd661d'
chocolate4:'8b4513'
coral:'ff7f50'
coral1:'ff7256'
coral2:'ee6a50'
coral3:'cd5b45'
coral4:'8b3e2f'
cornflowerblue:'6495ed'
cornsilk:'fff8dc'
cornsilk1:'fff8dc'
cornsilk2:'eee8cd'
cornsilk3:'cdc8b1'
cornsilk4:'8b8878'
crimson:'dc143c'
cyan:'00ffff'
cyan1:'00ffff'
cyan2:'00eeee'
cyan3:'00cdcd'
cyan4:'008b8b'
darkgoldenrod:'b8860b'
darkgoldenrod1:'ffb90f'
darkgoldenrod2:'eead0e'
darkgoldenrod3:'cd950c'
darkgoldenrod4:'8b6508'
darkgreen:'006400'
darkkhaki:'bdb76b'
darkolivegreen:'556b2f'
darkolivegreen1:'caff70'
darkolivegreen2:'bcee68'
darkolivegreen3:'a2cd5a'
darkolivegreen4:'6e8b3d'
darkorange:'ff8c00'
darkorange1:'ff7f00'
darkorange2:'ee7600'
darkorange3:'cd6600'
darkorange4:'8b4500'
darkorchid:'9932cc'
darkorchid1:'bf3eff'
darkorchid2:'b23aee'
darkorchid3:'9a32cd'
darkorchid4:'68228b'
darksalmon:'e9967a'
darkseagreen:'8fbc8f'
darkseagreen1:'c1ffc1'
darkseagreen2:'b4eeb4'
darkseagreen3:'9bcd9b'
darkseagreen4:'698b69'
darkslateblue:'483d8b'
darkslategray:'2f4f4f'
darkslategray1:'97ffff'
darkslategray2:'8deeee'
darkslategray3:'79cdcd'
darkslategray4:'528b8b'
darkslategrey:'2f4f4f'
darkturquoise:'00ced1'
darkviolet:'9400d3'
deeppink:'ff1493'
deeppink1:'ff1493'
deeppink2:'ee1289'
deeppink3:'cd1076'
deeppink4:'8b0a50'
deepskyblue:'00bfff'
deepskyblue1:'00bfff'
deepskyblue2:'00b2ee'
deepskyblue3:'009acd'
deepskyblue4:'00688b'
dimgray:'696969'
dimgrey:'696969'
dodgerblue:'1e90ff'
dodgerblue1:'1e90ff'
dodgerblue2:'1c86ee'
dodgerblue3:'1874cd'
dodgerblue4:'104e8b'
firebrick:'b22222'
firebrick1:'ff3030'
firebrick2:'ee2c2c'
firebrick3:'cd2626'
firebrick4:'8b1a1a'
floralwhite:'fffaf0'
forestgreen:'228b22'
gainsboro:'dcdcdc'
ghostwhite:'f8f8ff'
gold:'ffd700'
gold1:'ffd700'
gold2:'eec900'
gold3:'cdad00'
gold4:'8b7500'
goldenrod:'daa520'
goldenrod1:'ffc125'
goldenrod2:'eeb422'
goldenrod3:'cd9b1d'
goldenrod4:'8b6914'
gray:'c0c0c0'
gray0:'000000'
gray1:'030303'
gray10:'1a1a1a'
gray100:'ffffff'
gray11:'1c1c1c'
gray12:'1f1f1f'
gray13:'212121'
gray14:'242424'
gray15:'262626'
gray16:'292929'
gray17:'2b2b2b'
gray18:'2e2e2e'
gray19:'303030'
gray2:'050505'
gray20:'333333'
gray21:'363636'
gray22:'383838'
gray23:'3b3b3b'
gray24:'3d3d3d'
gray25:'404040'
gray26:'424242'
gray27:'454545'
gray28:'474747'
gray29:'4a4a4a'
gray3:'080808'
gray30:'4d4d4d'
gray31:'4f4f4f'
gray32:'525252'
gray33:'545454'
gray34:'575757'
gray35:'595959'
gray36:'5c5c5c'
gray37:'5e5e5e'
gray38:'616161'
gray39:'636363'
gray4:'0a0a0a'
gray40:'666666'
gray41:'696969'
gray42:'6b6b6b'
gray43:'6e6e6e'
gray44:'707070'
gray45:'737373'
gray46:'757575'
gray47:'787878'
gray48:'7a7a7a'
gray49:'7d7d7d'
gray5:'0d0d0d'
gray50:'7f7f7f'
gray51:'828282'
gray52:'858585'
gray53:'878787'
gray54:'8a8a8a'
gray55:'8c8c8c'
gray56:'8f8f8f'
gray57:'919191'
gray58:'949494'
gray59:'969696'
gray6:'0f0f0f'
gray60:'999999'
gray61:'9c9c9c'
gray62:'9e9e9e'
gray63:'a1a1a1'
gray64:'a3a3a3'
gray65:'a6a6a6'
gray66:'a8a8a8'
gray67:'ababab'
gray68:'adadad'
gray69:'b0b0b0'
gray7:'121212'
gray70:'b3b3b3'
gray71:'b5b5b5'
gray72:'b8b8b8'
gray73:'bababa'
gray74:'bdbdbd'
gray75:'bfbfbf'
gray76:'c2c2c2'
gray77:'c4c4c4'
gray78:'c7c7c7'
gray79:'c9c9c9'
gray8:'141414'
gray80:'cccccc'
gray81:'cfcfcf'
gray82:'d1d1d1'
gray83:'d4d4d4'
gray84:'d6d6d6'
gray85:'d9d9d9'
gray86:'dbdbdb'
gray87:'dedede'
gray88:'e0e0e0'
gray89:'e3e3e3'
gray9:'171717'
gray90:'e5e5e5'
gray91:'e8e8e8'
gray92:'ebebeb'
gray93:'ededed'
gray94:'f0f0f0'
gray95:'f2f2f2'
gray96:'f5f5f5'
gray97:'f7f7f7'
gray98:'fafafa'
gray99:'fcfcfc'
green:'00ff00'
green1:'00ff00'
green2:'00ee00'
green3:'00cd00'
green4:'008b00'
greenyellow:'adff2f'
grey:'c0c0c0'
grey0:'000000'
grey1:'030303'
grey10:'1a1a1a'
grey100:'ffffff'
grey11:'1c1c1c'
grey12:'1f1f1f'
grey13:'212121'
grey14:'242424'
grey15:'262626'
grey16:'292929'
grey17:'2b2b2b'
grey18:'2e2e2e'
grey19:'303030'
grey2:'050505'
grey20:'333333'
grey21:'363636'
grey22:'383838'
grey23:'3b3b3b'
grey24:'3d3d3d'
grey25:'404040'
grey26:'424242'
grey27:'454545'
grey28:'474747'
grey29:'4a4a4a'
grey3:'080808'
grey30:'4d4d4d'
grey31:'4f4f4f'
grey32:'525252'
grey33:'545454'
grey34:'575757'
grey35:'595959'
grey36:'5c5c5c'
grey37:'5e5e5e'
grey38:'616161'
grey39:'636363'
grey4:'0a0a0a'
grey40:'666666'
grey41:'696969'
grey42:'6b6b6b'
grey43:'6e6e6e'
grey44:'707070'
grey45:'737373'
grey46:'757575'
grey47:'787878'
grey48:'7a7a7a'
grey49:'7d7d7d'
grey5:'0d0d0d'
grey50:'7f7f7f'
grey51:'828282'
grey52:'858585'
grey53:'878787'
grey54:'8a8a8a'
grey55:'8c8c8c'
grey56:'8f8f8f'
grey57:'919191'
grey58:'949494'
grey59:'969696'
grey6:'0f0f0f'
grey60:'999999'
grey61:'9c9c9c'
grey62:'9e9e9e'
grey63:'a1a1a1'
grey64:'a3a3a3'
grey65:'a6a6a6'
grey66:'a8a8a8'
grey67:'ababab'
grey68:'adadad'
grey69:'b0b0b0'
grey7:'121212'
grey70:'b3b3b3'
grey71:'b5b5b5'
grey72:'b8b8b8'
grey73:'bababa'
grey74:'bdbdbd'
grey75:'bfbfbf'
grey76:'c2c2c2'
grey77:'c4c4c4'
grey78:'c7c7c7'
grey79:'c9c9c9'
grey8:'141414'
grey80:'cccccc'
grey81:'cfcfcf'
grey82:'d1d1d1'
grey83:'d4d4d4'
grey84:'d6d6d6'
grey85:'d9d9d9'
grey86:'dbdbdb'
grey87:'dedede'
grey88:'e0e0e0'
grey89:'e3e3e3'
grey9:'171717'
grey90:'e5e5e5'
grey91:'e8e8e8'
grey92:'ebebeb'
grey93:'ededed'
grey94:'f0f0f0'
grey95:'f2f2f2'
grey96:'f5f5f5'
grey97:'f7f7f7'
grey98:'fafafa'
grey99:'fcfcfc'
honeydew:'f0fff0'
honeydew1:'f0fff0'
honeydew2:'e0eee0'
honeydew3:'c1cdc1'
honeydew4:'838b83'
hotpink:'ff69b4'
hotpink1:'ff6eb4'
hotpink2:'ee6aa7'
hotpink3:'cd6090'
hotpink4:'8b3a62'
indianred:'cd5c5c'
indianred1:'ff6a6a'
indianred2:'ee6363'
indianred3:'cd5555'
indianred4:'8b3a3a'
indigo:'4b0082'
invis:'fffffe00'
ivory:'fffff0'
ivory1:'fffff0'
ivory2:'eeeee0'
ivory3:'cdcdc1'
ivory4:'8b8b83'
khaki:'f0e68c'
khaki1:'fff68f'
khaki2:'eee685'
khaki3:'cdc673'
khaki4:'8b864e'
lavender:'e6e6fa'
lavenderblush:'fff0f5'
lavenderblush1:'fff0f5'
lavenderblush2:'eee0e5'
lavenderblush3:'cdc1c5'
lavenderblush4:'8b8386'
lawngreen:'7cfc00'
lemonchiffon:'fffacd'
lemonchiffon1:'fffacd'
lemonchiffon2:'eee9bf'
lemonchiffon3:'cdc9a5'
lemonchiffon4:'8b8970'
lightblue:'add8e6'
lightblue1:'bfefff'
lightblue2:'b2dfee'
lightblue3:'9ac0cd'
lightblue4:'68838b'
lightcoral:'f08080'
lightcyan:'e0ffff'
lightcyan1:'e0ffff'
lightcyan2:'d1eeee'
lightcyan3:'b4cdcd'
lightcyan4:'7a8b8b'
lightgoldenrod:'eedd82'
lightgoldenrod1:'ffec8b'
lightgoldenrod2:'eedc82'
lightgoldenrod3:'cdbe70'
lightgoldenrod4:'8b814c'
lightgoldenrodyellow:'fafad2'
lightgray:'d3d3d3'
lightgrey:'d3d3d3'
lightpink:'ffb6c1'
lightpink1:'ffaeb9'
lightpink2:'eea2ad'
lightpink3:'cd8c95'
lightpink4:'8b5f65'
lightsalmon:'ffa07a'
lightsalmon1:'ffa07a'
lightsalmon2:'ee9572'
lightsalmon3:'cd8162'
lightsalmon4:'8b5742'
lightseagreen:'20b2aa'
lightskyblue:'87cefa'
lightskyblue1:'b0e2ff'
lightskyblue2:'a4d3ee'
lightskyblue3:'8db6cd'
lightskyblue4:'607b8b'
lightslateblue:'8470ff'
lightslategray:'778899'
lightslategrey:'778899'
lightsteelblue:'b0c4de'
lightsteelblue1:'cae1ff'
lightsteelblue2:'bcd2ee'
lightsteelblue3:'a2b5cd'
lightsteelblue4:'6e7b8b'
lightyellow:'ffffe0'
lightyellow1:'ffffe0'
lightyellow2:'eeeed1'
lightyellow3:'cdcdb4'
lightyellow4:'8b8b7a'
limegreen:'32cd32'
linen:'faf0e6'
magenta:'ff00ff'
magenta1:'ff00ff'
magenta2:'ee00ee'
magenta3:'cd00cd'
magenta4:'8b008b'
maroon:'b03060'
maroon1:'ff34b3'
maroon2:'ee30a7'
maroon3:'cd2990'
maroon4:'8b1c62'
mediumaquamarine:'66cdaa'
mediumblue:'0000cd'
mediumorchid:'ba55d3'
mediumorchid1:'e066ff'
mediumorchid2:'d15fee'
mediumorchid3:'b452cd'
mediumorchid4:'7a378b'
mediumpurple:'9370db'
mediumpurple1:'ab82ff'
mediumpurple2:'9f79ee'
mediumpurple3:'8968cd'
mediumpurple4:'5d478b'
mediumseagreen:'3cb371'
mediumslateblue:'7b68ee'
mediumspringgreen:'00fa9a'
mediumturquoise:'48d1cc'
mediumvioletred:'c71585'
midnightblue:'191970'
mintcream:'f5fffa'
mistyrose:'ffe4e1'
mistyrose1:'ffe4e1'
mistyrose2:'eed5d2'
mistyrose3:'cdb7b5'
mistyrose4:'8b7d7b'
moccasin:'ffe4b5'
navajowhite:'ffdead'
navajowhite1:'ffdead'
navajowhite2:'eecfa1'
navajowhite3:'cdb38b'
navajowhite4:'8b795e'
navy:'000080'
navyblue:'000080'
none:'fffffe00'
oldlace:'fdf5e6'
olivedrab:'6b8e23'
olivedrab1:'c0ff3e'
olivedrab2:'b3ee3a'
olivedrab3:'9acd32'
olivedrab4:'698b22'
orange:'ffa500'
orange1:'ffa500'
orange2:'ee9a00'
orange3:'cd8500'
orange4:'8b5a00'
orangered:'ff4500'
orangered1:'ff4500'
orangered2:'ee4000'
orangered3:'cd3700'
orangered4:'8b2500'
orchid:'da70d6'
orchid1:'ff83fa'
orchid2:'ee7ae9'
orchid3:'cd69c9'
orchid4:'8b4789'
palegoldenrod:'eee8aa'
palegreen:'98fb98'
palegreen1:'9aff9a'
palegreen2:'90ee90'
palegreen3:'7ccd7c'
palegreen4:'548b54'
paleturquoise:'afeeee'
paleturquoise1:'bbffff'
paleturquoise2:'aeeeee'
paleturquoise3:'96cdcd'
paleturquoise4:'668b8b'
palevioletred:'db7093'
palevioletred1:'ff82ab'
palevioletred2:'ee799f'
palevioletred3:'cd6889'
palevioletred4:'8b475d'
papayawhip:'ffefd5'
peachpuff:'ffdab9'
peachpuff1:'ffdab9'
peachpuff2:'eecbad'
peachpuff3:'cdaf95'
peachpuff4:'8b7765'
peru:'cd853f'
pink:'ffc0cb'
pink1:'ffb5c5'
pink2:'eea9b8'
pink3:'cd919e'
pink4:'8b636c'
plum:'dda0dd'
plum1:'ffbbff'
plum2:'eeaeee'
plum3:'cd96cd'
plum4:'8b668b'
powderblue:'b0e0e6'
purple:'a020f0'
purple1:'9b30ff'
purple2:'912cee'
purple3:'7d26cd'
purple4:'551a8b'
red:'ff0000'
red1:'ff0000'
red2:'ee0000'
red3:'cd0000'
red4:'8b0000'
rosybrown:'bc8f8f'
rosybrown1:'ffc1c1'
rosybrown2:'eeb4b4'
rosybrown3:'cd9b9b'
rosybrown4:'8b6969'
royalblue:'4169e1'
royalblue1:'4876ff'
royalblue2:'436eee'
royalblue3:'3a5fcd'
royalblue4:'27408b'
saddlebrown:'8b4513'
salmon:'fa8072'
salmon1:'ff8c69'
salmon2:'ee8262'
salmon3:'cd7054'
salmon4:'8b4c39'
sandybrown:'f4a460'
seagreen:'2e8b57'
seagreen1:'54ff9f'
seagreen2:'4eee94'
seagreen3:'43cd80'
seagreen4:'2e8b57'
seashell:'fff5ee'
seashell1:'fff5ee'
seashell2:'eee5de'
seashell3:'cdc5bf'
seashell4:'8b8682'
sienna:'a0522d'
sienna1:'ff8247'
sienna2:'ee7942'
sienna3:'cd6839'
sienna4:'8b4726'
skyblue:'87ceeb'
skyblue1:'87ceff'
skyblue2:'7ec0ee'
skyblue3:'6ca6cd'
skyblue4:'4a708b'
slateblue:'6a5acd'
slateblue1:'836fff'
slateblue2:'7a67ee'
slateblue3:'6959cd'
slateblue4:'473c8b'
slategray:'708090'
slategray1:'c6e2ff'
slategray2:'b9d3ee'
slategray3:'9fb6cd'
slategray4:'6c7b8b'
slategrey:'708090'
snow:'fffafa'
snow1:'fffafa'
snow2:'eee9e9'
snow3:'cdc9c9'
snow4:'8b8989'
springgreen:'00ff7f'
springgreen1:'00ff7f'
springgreen2:'00ee76'
springgreen3:'00cd66'
springgreen4:'008b45'
steelblue:'4682b4'
steelblue1:'63b8ff'
steelblue2:'5cacee'
steelblue3:'4f94cd'
steelblue4:'36648b'
tan:'d2b48c'
tan1:'ffa54f'
tan2:'ee9a49'
tan3:'cd853f'
tan4:'8b5a2b'
thistle:'d8bfd8'
thistle1:'ffe1ff'
thistle2:'eed2ee'
thistle3:'cdb5cd'
thistle4:'8b7b8b'
tomato:'ff6347'
tomato1:'ff6347'
tomato2:'ee5c42'
tomato3:'cd4f39'
tomato4:'8b3626'
transparent:'fffffe00'
turquoise:'40e0d0'
turquoise1:'00f5ff'
turquoise2:'00e5ee'
turquoise3:'00c5cd'
turquoise4:'00868b'
violet:'ee82ee'
violetred:'d02090'
violetred1:'ff3e96'
violetred2:'ee3a8c'
violetred3:'cd3278'
violetred4:'8b2252'
wheat:'f5deb3'
wheat1:'ffe7ba'
wheat2:'eed8ae'
wheat3:'cdba96'
wheat4:'8b7e66'
white:'ffffff'
whitesmoke:'f5f5f5'
yellow:'ffff00'
yellow1:'ffff00'
yellow2:'eeee00'
yellow3:'cdcd00'
yellow4:'8b8b00'
yellowgreen:'9acd32'
window.Canviz = Canviz
| 22764 | class CanvizTokenizer
constructor: (@str) ->
takeChars: (num) ->
num = 1 if !num
tokens = []
while (num--)
matches = @str.match(/^(\S+)\s*/)
if matches
@str = @str.substr(matches[0].length)
tokens.push(matches[1])
else
tokens.push(false)
if 1 == tokens.length
return tokens[0]
else
return tokens
takeNumber: (num) ->
num = 1 if !num
if 1 == num
return Number(@takeChars())
else
tokens = @takeChars(num)
while num--
tokens[num] = Number(tokens[num])
return tokens
takeString: () ->
byteCount = Number(@takeChars())
charCount = 0
return false if '-' != @str.charAt(0)
while 0 < byteCount
++charCount
charCode = @str.charCodeAt(charCount)
if 0x80 > charCode
--byteCount
else if 0x800 > charCode
byteCount -= 2
else
byteCount -= 3
str = @str.substr(1, charCount)
@str = @str.substr(1 + charCount).replace(/^\s+/, '')
return str
class CanvizEntity
constructor: (@defaultAttrHashName, @name, @canviz, @rootGraph, @parentGraph, @immediateGraph) ->
@attrs = {}
@drawAttrs = {}
initBB: () ->
matches = @getAttr('pos').match(/([0-9.]+),([0-9.]+)/)
x = Math.round(matches[1])
y = Math.round(@canviz.height - matches[2])
@bbRect = new Rect(x, y, x, y)
getAttr: (attrName, escString=false) ->
attrValue = @attrs[attrName]
if not attrValue?
graph = @parentGraph
while graph?
attrValue = graph[@defaultAttrHashName][attrName]
if not attrValue?
graph = graph.parentGraph
else
break
if attrValue and escString
attrValue = attrValue.replace @escStringMatchRe, (match, p1) =>
switch p1
when 'N', 'E' then return @name
when 'T' then return @tailNode
when 'H' then return @headNode
when 'G' then return @immediateGraph.name
when 'L' then return @getAttr('label', true)
return match
return attrValue
draw: (ctx, ctxScale, redrawCanvasOnly) ->
if !redrawCanvasOnly
@initBB()
bbDiv = document.createElement('div')
@canviz.elements.appendChild(bbDiv)
for _, command of @drawAttrs
# command = drawAttr.value
tokenizer = new CanvizTokenizer(command)
token = tokenizer.takeChars()
if token
dashStyle = 'solid'
ctx.save()
while token
switch token
when 'E', 'e' # unfilled ellipse
filled = ('E' == token)
cx = tokenizer.takeNumber()
cy = @canviz.height - tokenizer.takeNumber()
rx = tokenizer.takeNumber()
ry = tokenizer.takeNumber()
path = new Ellipse(cx, cy, rx, ry)
when 'P', 'p', 'L'
filled = ('P' == token)
closed = ('L' != token);
numPoints = tokenizer.takeNumber()
tokens = tokenizer.takeNumber(2 * numPoints)
path = new Path()
#for (i = 2; i < 2 * numPoints; i += 2)
for i in [2...(2*numPoints)] by 2
path.addBezier([
new Point(tokens[i - 2], @canviz.height - tokens[i - 1])
new Point(tokens[i], @canviz.height - tokens[i + 1])
])
if closed
path.addBezier([
new Point(tokens[2 * numPoints - 2], @canviz.height - tokens[2 * numPoints - 1])
new Point(tokens[0], @canviz.height - tokens[1])
])
when 'B', 'b' # unfilled b-spline
filled = ('b' == token)
numPoints = tokenizer.takeNumber()
tokens = tokenizer.takeNumber(2 * numPoints); # points
path = new Path()
for i in [2...(2*numPoints)] by 6
path.addBezier([
new Point(tokens[i - 2], @canviz.height - tokens[i - 1])
new Point(tokens[i], @canviz.height - tokens[i + 1])
new Point(tokens[i + 2], @canviz.height - tokens[i + 3])
new Point(tokens[i + 4], @canviz.height - tokens[i + 5])
])
when 'I' # image
l = tokenizer.takeNumber()
b = @canviz.height - tokenizer.takeNumber()
w = tokenizer.takeNumber()
h = tokenizer.takeNumber()
src = tokenizer.takeString()
if !@canviz.images[src]
@canviz.images[src] = new CanvizImage(@canviz, src)
@canviz.images[src].draw(ctx, l, b - h, w, h)
when 'T' # text
l = Math.round(ctxScale * tokenizer.takeNumber() + @canviz.padding)
t = Math.round(ctxScale * @canviz.height + 2 * @canviz.padding - (ctxScale * (tokenizer.takeNumber() + @canviz.bbScale * fontSize) + @canviz.padding))
textAlign = tokenizer.takeNumber()
textWidth = Math.round(ctxScale * tokenizer.takeNumber())
str = tokenizer.takeString()
if !redrawCanvasOnly and !/^\s*$/.test(str)
#str = escapeHTML(str)
loop
matches = str.match(/[ ]([ ]+)/)
if matches
spaces = ' '
spaces += ' ' for _ in [0..matches[1].length.times]
str = str.replace(/[ ] +/, spaces)
break unless matches
href = @getAttr('URL', true) || @getAttr('href', true)
if href
target = @getAttr('target', true) || '_self'
tooltip = @getAttr('tooltip', true) || @getAttr('label', true)
text = document.createElement("a")
text.href = href
text.target = target
text.title = tooltip
for attrName in ['onclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout']
attrValue = @getAttr(attrName, true)
if attrValue
text.writeAttribute(attrName, attrValue)
text.textDecoration = 'none'
else
text = document.createElement("span") # new Element('span')
text.innerText = str
ts = text.style
ts.fontSize = Math.round(fontSize * ctxScale * @canviz.bbScale) + 'px'
ts.fontFamily = fontFamily
ts.color = strokeColor.textColor
ts.position = 'absolute'
ts.textAlign = if (-1 == textAlign) then 'left' else if (1 == textAlign) then 'right' else 'center'
ts.left = (l - (1 + textAlign) * textWidth) + 'px'
ts.top = t + 'px'
ts.width = (2 * textWidth) + 'px'
ts.opacity = strokeColor.opacity if 1 != strokeColor.opacity
@canviz.elements.appendChild(text)
when 'C', 'c'
fill = ('C' == token)
color = @parseColor(tokenizer.takeString())
if fill
fillColor = color
ctx.fillStyle = color.canvasColor
else
strokeColor = color
ctx.strokeStyle = color.canvasColor
when 'F' # // set font
fontSize = tokenizer.takeNumber()
fontFamily = tokenizer.takeString()
switch fontFamily
when 'Times-Roman' then fontFamily = 'Times New Roman'
when 'Courier' then fontFamily = 'Courier New'
when 'Helvetica' then fontFamily = 'Arial'
when 'S' # // set style
style = tokenizer.takeString()
switch style
when 'solid', 'filled' then 1 # nothing
when 'dashed', 'dotted' then dashStyle = style
when 'bold' then ctx.lineWidth = 2
else
matches = style.match(/^setlinewidth\((.*)\)$/)
if matches
ctx.lineWidth = Number(matches[1])
else
debug('unknown style ' + style)
else
debug('unknown token ' + token)
return
if path
@canviz.drawPath(ctx, path, filled, dashStyle)
@bbRect.expandToInclude(path.getBB()) if !redrawCanvasOnly
path = undefined
token = tokenizer.takeChars()
if !redrawCanvasOnly
bbDiv.position = 'absolute'
bbDiv.left = Math.round(ctxScale * @bbRect.l + @canviz.padding) + 'px'
bbDiv.top = Math.round(ctxScale * @bbRect.t + @canviz.padding) + 'px'
bbDiv.width = Math.round(ctxScale * @bbRect.getWidth()) + 'px'
bbDiv.height = Math.round(ctxScale * @bbRect.getHeight()) + 'px'
ctx.restore()
parseColor: (color) ->
parsedColor = {opacity: 1}
# // rgb/rgba
if /^#(?:[0-9a-f]{2}\s*){3,4}$/i.test(color)
return @canviz.parseHexColor(color)
# // hsv
matches = color.match(/^(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)$/)
if matches
parsedColor.canvasColor = parsedColor.textColor = @canviz.hsvToRgbColor(matches[1], matches[2], matches[3])
return parsedColor
# // named color
colorScheme = @getAttr('colorscheme') || 'X11'
colorName = color
matches = color.match(/^\/(.*)\/(.*)$/)
if matches
if matches[1]
colorScheme = matches[1]
colorName = matches[2]
else
matches = color.match(/^\/(.*)$/)
if matches
colorScheme = 'X11'
colorName = matches[1]
colorName = colorName.toLowerCase()
colorSchemeName = colorScheme.toLowerCase()
colorSchemeData = Canviz.colors[colorSchemeName]
if colorSchemeData
colorData = colorSchemeData[colorName]
if colorData
return @canviz.parseHexColor('#' + colorData)
colorData = Canviz.colors['fallback'][colorName]
if colorData
return @canviz.parseHexColor('#' + colorData)
if !colorSchemeData
debug('unknown color scheme ' + colorScheme)
# // unknown
debug('unknown color ' + color + '; color scheme is ' + colorScheme)
parsedColor.canvasColor = parsedColor.textColor = '#000000'
return parsedColor
class CanvizNode extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph) ->
super('nodeAttrs', name, canviz, rootGraph, parentGraph, parentGraph)
escStringMatchRe: /\\([NGL])/g
#
class CanvizEdge extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph, @tailNode, @headNode) ->
super('edgeAttrs', name, canviz, rootGraph, parentGraph, parentGraph)
escStringMatchRe: /\\([EGTHL])/g
class CanvizGraph extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph) ->
super('attrs', name, canviz, rootGraph, parentGraph, this)
@nodeAttrs = {}
@edgeAttrs = {}
@nodes = []
@edges = []
@subgraphs = []
initBB: () ->
coords = @getAttr('bb').split(',')
@bbRect = new Rect(coords[0], @canviz.height - coords[1], coords[2], @canviz.height - coords[3])
draw: (ctx, ctxScale, redrawCanvasOnly) ->
super(ctx, ctxScale, redrawCanvasOnly)
for type in [@subgraphs, @nodes, @edges]
for entity in type
entity.draw(ctx, ctxScale, redrawCanvasOnly)
escStringMatchRe: /\\([GL])/g
class Canviz
@maxXdotVersion: "1.2"
@colors:
fallback:
black:'000000'
lightgrey:'d3d3d3'
white:'ffffff'
constructor: (container, url, urlParams) ->
@canvas = document.createElement('canvas')
@canvas.style.position = "absolute"
Canviz.canvasCounter ?= 0
@canvas.id = 'canviz_canvas_' + (++Canviz.canvasCounter)
@elements = document.createElement('div')
@elements.style.position = "absolute"
@container = document.getElementById(container)
@container.style.position = "relative"
@container.appendChild(@canvas)
@container.appendChild(@elements)
@ctx = @canvas.getContext('2d')
@scale = 1
@padding = 8
@dashLength = 6
@dotSpacing = 4
@graphs = []
@images = {}
@numImages = 0
@numImagesFinished = 0
@imagePath = ""
@idMatch = '([a-zA-Z\u0080-\uFFFF_][0-9a-zA-Z\u0080-\uFFFF_]*|-?(?:\\.\\d+|\\d+(?:\\.\\d*)?)|"(?:\\\\"|[^"])*"|<(?:<[^>]*>|[^<>]+?)+>)'
@nodeIdMatch = @idMatch + '(?::' + @idMatch + ')?(?::' + @idMatch + ')?'
@graphMatchRe = new RegExp('^(strict\\s+)?(graph|digraph)(?:\\s+' + @idMatch + ')?\\s*{$', 'i')
@subgraphMatchRe = new RegExp('^(?:subgraph\\s+)?' + @idMatch + '?\\s*{$', 'i')
@nodeMatchRe = new RegExp('^(' + @nodeIdMatch + ')\\s+\\[(.+)\\];$')
@edgeMatchRe = new RegExp('^(' + @nodeIdMatch + '\\s*-[->]\\s*' + @nodeIdMatch + ')\\s+\\[(.+)\\];$')
@attrMatchRe = new RegExp('^' + @idMatch + '=' + @idMatch + '(?:[,\\s]+|$)')
setScale: (@scale) ->
setImagePath: (@imagePath) ->
parse: (xdot) ->
@graphs = []
@width = 0
@height = 0
@maxWidth = false
@maxHeight = false
@bbEnlarge = false
@bbScale = 1
@dpi = 96
@bgcolor = opacity: 1
@bgcolor.canvasColor = @bgcolor.textColor = '#ffffff'
lines = xdot.split(/\r?\n/)
i = 0
containers = []
while i < lines.length
line = lines[i++].replace(/^\s+/, '')
if '' != line and '#' != line.substr(0, 1)
while i < lines.length and ';' != (lastChar = line.substr(line.length - 1, line.length)) and '{' != lastChar and '}' != lastChar
if '\\' == lastChar
line = line.substr(0, line.length - 1)
line += lines[i++]
if containers.length == 0
matches = line.match(@graphMatchRe)
if matches
rootGraph = new CanvizGraph(matches[3], this)
containers.unshift(rootGraph)
containers[0].strict = not (not matches[1])
containers[0].type = if 'graph' == matches[2] then 'undirected' else 'directed'
containers[0].attrs.xdotversion = '1.0'
containers[0].attrs.bb ?= '0,0,500,500'
@graphs.push(containers[0])
else
matches = line.match(@subgraphMatchRe)
if matches
containers.unshift(new CanvizGraph(matches[1], this, rootGraph, containers[0]))
containers[1].subgraphs.push containers[0]
if matches
else if "}" == line
containers.shift()
break if 0 == containers.length
else
matches = line.match(@nodeMatchRe)
if matches
entityName = matches[2]
attrs = matches[5]
drawAttrHash = containers[0].drawAttrs
isGraph = false
switch entityName
when 'graph'
attrHash = containers[0].attrs
isGraph = true
when 'node' then attrHash = containers[0].nodeAttrs
when 'edge' then attrHash = containers[0].edgeAttrs
else
entity = new CanvizNode(entityName, this, rootGraph, containers[0])
attrHash = entity.attrs
drawAttrHash = entity.drawAttrs
containers[0].nodes.push(entity)
else
matches = line.match(@edgeMatchRe)
if matches
entityName = matches[1]
attrs = matches[8]
entity = new CanvizEdge(entityName, this, rootGraph, containers[0], matches[2], matches[5])
attrHash = entity.attrs
drawAttrHash = entity.drawAttrs
containers[0].edges.push(entity)
while matches
break if 0 == attrs.length
matches = attrs.match(@attrMatchRe)
if matches
attrs = attrs.substr(matches[0].length)
attrName = matches[1]
attrValue = @unescape(matches[2])
if /^_.*draw_$/.test(attrName)
drawAttrHash[attrName] = attrValue
else
attrHash[attrName] = attrValue
if isGraph and 1 == containers.length
switch attrName
when 'bb'
bb = attrValue.split(/,/)
@width = Number(bb[2])
@height = Number(bb[3])
when 'bgcolor' then @bgcolor = rootGraph.parseColor(attrValue)
when 'dpi' then @dpi = attrValue
when 'size'
size = attrValue.match(/^(\d+|\d*(?:\.\d+)),\s*(\d+|\d*(?:\.\d+))(!?)$/)
if size
@maxWidth = 72 * Number(size[1])
@maxHeight = 72 * Number(size[2])
@bbEnlarge = '!' == size[3]
when 'xdotversion'
if 0 > @versionCompare(Canviz.maxXdotVersion, attrHash['xdotversion'])
1
@draw()
draw: (redrawCanvasOnly) ->
redrawCanvasOnly ?= false
ctxScale = @scale * @dpi / 72
width = Math.round(ctxScale * @width + 2 * @padding)
height = Math.round(ctxScale * @height + 2 * @padding)
if !redrawCanvasOnly
@canvas.width = width
@canvas.height = height
@canvas.style.width = "#{width}px"
@canvas.style.height = "#{height}px"
@container.style.width = "#{width}px"
while (@elements.firstChild)
@elements.removeChild(@elements.firstChild)
@ctx.save()
@ctx.lineCap = 'round'
@ctx.fillStyle = @bgcolor.canvasColor
@ctx.fillRect(0, 0, width, height)
@ctx.translate(@padding, @padding)
@ctx.scale(ctxScale, ctxScale)
@graphs[0].draw(@ctx, ctxScale, redrawCanvasOnly)
@ctx.restore()
drawPath: (ctx, path, filled, dashStyle) ->
if (filled)
ctx.beginPath()
path.makePath(ctx)
ctx.fill()
if ctx.fillStyle != ctx.strokeStyle or not filled
switch dashStyle
when 'dashed'
ctx.beginPath()
path.makeDashedPath(ctx, @dashLength)
when 'dotted'
oldLineWidth = ctx.lineWidth
ctx.lineWidth *= 2
ctx.beginPath()
path.makeDottedPath(ctx, @dotSpacing)
else
if not filled
ctx.beginPath()
path.makePath(ctx)
ctx.stroke()
ctx.lineWidth = oldLineWidth if oldLineWidth
unescape: (str) ->
matches = str.match(/^"(.*)"$/)
if (matches)
return matches[1].replace(/\\"/g, '"')
else
return str
parseHexColor: (color) ->
matches = color.match(/^#([0-9a-f]{2})\s*([0-9a-f]{2})\s*([0-9a-f]{2})\s*([0-9a-f]{2})?$/i)
if matches
canvasColor; textColor = '#' + matches[1] + matches[2] + matches[3]; opacity = 1
if (matches[4]) # rgba
opacity = parseInt(matches[4], 16) / 255
canvasColor = 'rgba(' + parseInt(matches[1], 16) + ',' + parseInt(matches[2], 16) + ',' + parseInt(matches[3], 16) + ',' + opacity + ')'
else # rgb
canvasColor = textColor
return {canvasColor: canvasColor, textColor: textColor, opacity: opacity}
hsvToRgbColor: (h, s, v) ->
h *= 360
i = Math.floor(h / 60) % 6
f = h / 60 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
switch (i)
when 0 then r = v; g = t; b = p
when 1 then r = q; g = v; b = p
when 2 then r = p; g = v; b = t
when 3 then r = p; g = q; b = v
when 4 then r = t; g = p; b = v
when 5 then r = v; g = p; b = q
return 'rgb(' + Math.round(255 * r) + ',' + Math.round(255 * g) + ',' + Math.round(255 * b) + ')'
versionCompare: (a, b) ->
a = a.split('.')
b = b.split('.')
while (a.length or b.length)
a1 = if a.length then a.shift() else 0
b1 = if b.length then b.shift() else 0
return -1 if (a1 < b1)
return 1 if (a1 > b1)
return 0
class CanvizImage
constructor: (@canviz, src) ->
++@canviz.numImages
@finished = @loaded = false
@img = new Image()
@img.onload = @onLoad.bind(this)
@img.onerror = @onFinish.bind(this)
@img.onabort = @onFinish.bind(this)
@img.src = @canviz.imagePath + src
onLoad: ->
@loaded = true
@onFinish()
onFinish: ->
@finished = true
++@canviz.numImagesFinished
if @canviz.numImages == @canviz.numImagesFinished
@canviz.draw(true)
draw: (ctx, l, t, w, h) ->
if @finished
if @loaded
ctx.drawImage(@img, l, t, w, h)
else
debug("can't load image " + @img.src)
@drawBrokenImage(ctx, l, t, w, h)
drawBrokenImage: (ctx, l, t, w, h) ->
ctx.save()
ctx.beginPath()
new Rect(l, t, l + w, t + w).draw(ctx)
ctx.moveTo(l, t)
ctx.lineTo(l + w, t + w)
ctx.moveTo(l + w, t)
ctx.lineTo(l, t + h)
ctx.strokeStyle = '#f00'
ctx.lineWidth = 1
ctx.stroke()
ctx.restore()
##########################################################
# $Id: path.js 262 2009-05-19 11:55:24Z <EMAIL> $
##########################################################
class Point
constructor: (@x, @y) ->
offset: (dx, dy) ->
@x += dx
@y += dy
distanceFrom: (point) ->
dx = @x - point.x
dy = @y - point.y
Math.sqrt(dx * dx + dy * dy)
makePath: (ctx) ->
ctx.moveTo(@x, @y)
ctx.lineTo(@x + 0.001, @y)
############### Path.js
class Bezier
constructor: (@points) ->
@order = points.length
reset: () ->
p = Bezier.prototype
@controlPolygonLength = p.controlPolygonLength
@chordLength = p.chordLength
@triangle = p.triangle
@chordPoints = p.chordPoints
@coefficients = p.coefficients
offset: (dx, dy) ->
for point in @points
point.offset(dx, dy)
@reset()
getBB: ->
return undefined if !@order
p = @points[0]
l = r = p.x
t = b = p.y
for point in @points
l = Math.min(l, point.x)
t = Math.min(t, point.y)
r = Math.max(r, point.x)
b = Math.max(b, point.y)
rect = new Rect(l, t, r, b)
return (@getBB = -> rect)()
isPointInBB: (x, y, tolerance) ->
tolerance ?= 0
bb = @getBB()
if (0 < tolerance)
bb = clone(bb)
bb.inset(-tolerance, -tolerance)
!(x < bb.l || x > bb.r || y < bb.t || y > bb.b)
isPointOnBezier: (x, y, tolerance=0) ->
return false if !@isPointInBB(x, y, tolerance)
segments = @chordPoints()
p1 = segments[0].p
for i in [1...segments.length]
p2 = segments[i].p
x1 = p1.x
y1 = p1.y
x2 = p2.x
y2 = p2.y
bb = new Rect(x1, y1, x2, y2)
if bb.isPointInBB(x, y, tolerance)
twice_area = Math.abs(x1 * y2 + x2 * y + x * y1 - x2 * y1 - x * y2 - x1 * y)
base = p1.distanceFrom(p2)
height = twice_area / base
return true if height <= tolerance
p1 = p2
return false
# # Based on Oliver Steele's bezier.js library.
controlPolygonLength: ->
len = 0
for i in [1...@order]
len += @points[i - 1].distanceFrom(@points[i])
(@controlPolygonLength = -> len)()
# # Based on Oliver Steele's bezier.js library.
chordLength: ->
len = @points[0].distanceFrom(@points[@order - 1])
(@chordLength = -> len)()
# # From Oliver Steele's bezier.js library.
triangle: ->
upper = @points
m = [upper]
for i in [1...@order]
lower = []
for j in [0...(@order-i)]
c0 = upper[j]
c1 = upper[j + 1]
lower[j] = new Point((c0.x + c1.x) / 2, (c0.y + c1.y) / 2)
m.push(lower)
upper = lower
(@triangle = -> m)()
# # Based on Oliver Steele's bezier.js library.
triangleAtT: (t) ->
s = 1 - t
upper = @points
m = [upper]
for i in [1...@order]
lower = []
for j in [0...(@order-i)]
c0 = upper[j]
c1 = upper[j + 1]
lower[j] = new Point(c0.x * s + c1.x * t, c0.y * s + c1.y * t)
m.push(lower)
upper = lower
return m
# Returns two beziers resulting from splitting @bezier at t=0.5.
# Based on Oliver Steele's bezier.js library.
split: (t=0.5) ->
m = if (0.5 == t) then @triangle() else @triangleAtT(t)
leftPoints = new Array(@order)
rightPoints = new Array(@order)
for i in [1...@order]
leftPoints[i] = m[i][0]
rightPoints[i] = m[@order - 1 - i][i]
return {left: new Bezier(leftPoints), right: new Bezier(rightPoints)}
# Returns a bezier which is the portion of @bezier from t1 to t2.
# Thanks to <NAME> on comp.graphics.algorithms.
mid: (t1, t2) ->
@split(t2).left.split(t1 / t2).right
# Returns points (and their corresponding times in the bezier) that form
# an approximate polygonal representation of the bezier.
# Based on the algorithm described in <NAME>' dashed.ps.gz
chordPoints: ->
p = [{tStart: 0, tEnd: 0, dt: 0, p: @points[0]}].concat(@_chordPoints(0, 1))
(@chordPoints = -> p)()
_chordPoints: (tStart, tEnd) ->
tolerance = 0.001
dt = tEnd - tStart
if @controlPolygonLength() <= (1 + tolerance) * @chordLength()
return [{tStart: tStart, tEnd: tEnd, dt: dt, p: @points[@order - 1]}]
else
tMid = tStart + dt / 2
halves = @split()
return halves.left._chordPoints(tStart, tMid).concat(halves.right._chordPoints(tMid, tEnd))
# Returns an array of times between 0 and 1 that mark the bezier evenly
# in space.
# Based in part on the algorithm described in <NAME>' dashed.ps.gz
markedEvery: (distance, firstDistance) ->
nextDistance = firstDistance || distance
segments = @chordPoints()
times = []
t = 0; # time
for i in [1...segments.length]
segment = segments[i]
segment.length = segment.p.distanceFrom(segments[i - 1].p)
if 0 == segment.length
t += segment.dt
else
dt = nextDistance / segment.length * segment.dt
segment.remainingLength = segment.length
while segment.remainingLength >= nextDistance
segment.remainingLength -= nextDistance
t += dt
times.push(t)
if distance != nextDistance
nextDistance = distance
dt = nextDistance / segment.length * segment.dt
nextDistance -= segment.remainingLength
t = segment.tEnd
return {times: times, nextDistance: nextDistance}
# Return the coefficients of the polynomials for x and y in t.
# From <NAME>'s bezier.js library.
coefficients: ->
# @function deals with polynomials, represented as
# arrays of coefficients. p[i] is the coefficient of n^i.
# p0, p1 => p0 + (p1 - p0) * n
# side-effects (denormalizes) p0, for convienence
interpolate = (p0, p1) ->
p0.push(0)
p = new Array(p0.length)
p[0] = p0[0]
for i in [0...p1.length]
p[i + 1] = p0[i + 1] + p1[i] - p0[i]
p
# folds +interpolate+ across a graph whose fringe is
# the polynomial elements of +ns+, and returns its TOP
collapse = (ns) ->
while ns.length > 1
ps = new Array(ns.length-1)
for i in [0...(ns.length-1)]
ps[i] = interpolate(ns[i], ns[i + 1])
ns = ps
return ns[0]
# xps and yps are arrays of polynomials --- concretely realized
# as arrays of arrays
xps = []
yps = []
for pt in @points
xps.push([pt.x])
yps.push([pt.y])
result = {xs: collapse(xps), ys: collapse(yps)}
return (@coefficients = ->result)()
# Return the point at time t.
# From <NAME>'s bezier.js library.
pointAtT: (t) ->
c = @coefficients()
[cx, cy] = [c.xs, c.ys]
# evaluate cx[0] + cx[1]t +cx[2]t^2 ....
# optimization: start from the end, to save one
# muliplicate per order (we never need an explicit t^n)
# optimization: special-case the last element
# to save a multiply-add
x = cx[cx.length - 1]; y = cy[cy.length - 1];
for i in [cx.length..0]
x = x * t + cx[i]
y = y * t + cy[i]
new Point(x, y)
# Render the Bezier to a WHATWG 2D canvas context.
# Based on Oliver Steele's bezier.js library.
makePath: (ctx, moveTo=true) ->
ctx.moveTo(@points[0].x, @points[0].y) if (moveTo)
fn = @pathCommands[@order]
if fn
coords = []
for i in [(if 1 == @order then 0 else 1)...@points.length]
coords.push(@points[i].x)
coords.push(@points[i].y)
fn.apply(ctx, coords)
# Wrapper functions to work around Safari, in which, up to at least 2.0.3,
# fn.apply isn't defined on the context primitives.
# Based on Oliver Steele's bezier.js library.
pathCommands: [
null,
# @will have an effect if there's a line thickness or end cap.
(x, y) -> @lineTo(x + 0.001, y)
(x, y) -> @lineTo(x, y)
(x1, y1, x2, y2) -> @quadraticCurveTo(x1, y1, x2, y2)
(x1, y1, x2, y2, x3, y3) -> @bezierCurveTo(x1, y1, x2, y2, x3, y3)
]
makeDashedPath: (ctx, dashLength, firstDistance, drawFirst=true) ->
firstDistance = dashLength if !firstDistance
markedEvery = @markedEvery(dashLength, firstDistance)
markedEvery.times.unshift(0) if (drawFirst)
drawLast = (markedEvery.times.length % 2)
markedEvery.times.push(1) if drawLast
for i in [1...(markedEvery.times.length)] by 2
@mid(markedEvery.times[i - 1], markedEvery.times[i]).makePath(ctx)
return {firstDistance: markedEvery.nextDistance, drawFirst: drawLast}
makeDottedPath: (ctx, dotSpacing, firstDistance) ->
firstDistance = dotSpacing if !firstDistance
markedEvery = @markedEvery(dotSpacing, firstDistance)
markedEvery.times.unshift(0) if dotSpacing == firstDistance
for t in markedEvery.times
@pointAtT(t).makePath(ctx)
return markedEvery.nextDistance
class Path
constructor: (@segments=[]) ->
setupSegments: ->
# Based on Oliver Steele's bezier.js library.
addBezier: (pointsOrBezier) ->
@segments.push(if pointsOrBezier instanceof Array then new Bezier(pointsOrBezier) else pointsOrBezier)
offset: (dx, dy) ->
@setupSegments() if 0 == @segments.length
for segment in @segments
segment.offset(dx, dy)
getBB: ->
@setupSegments() if 0 == @segments.length
p = @segments[0].points[0]
l = r = p.x
t = b = p.y
for segment in @segments
for point in segment.points
l = Math.min(l, point.x)
t = Math.min(t, point.y)
r = Math.max(r, point.x)
b = Math.max(b, point.y)
rect = new Rect(l, t, r, b);
return (@getBB = -> rect)()
isPointInBB: (x, y, tolerance=0) ->
bb = @getBB()
if 0 < tolerance
bb = clone(bb)
bb.inset(-tolerance, -tolerance)
return !(x < bb.l || x > bb.r || y < bb.t || y > bb.b)
isPointOnPath: (x, y, tolerance=0) ->
return false if !@isPointInBB(x, y, tolerance)
result = false;
for segment in @segments
if segment.isPointOnBezier(x, y, tolerance)
result = true
throw $break
return result
isPointInPath: (x, y) -> false
# Based on <NAME>'s bezier.js library.
makePath: (ctx) ->
@setupSegments() if 0 == @segments.length
moveTo = true
for segment in @segments
segment.makePath(ctx, moveTo)
moveTo = false
makeDashedPath: (ctx, dashLength, firstDistance, drawFirst) ->
@setupSegments() if 0 == @segments.length
info =
drawFirst: if !drawFirst? then true else drawFirst
firstDistance: firstDistance || dashLength
for segment in @segments
info = segment.makeDashedPath(ctx, dashLength, info.firstDistance, info.drawFirst)
makeDottedPath: (ctx, dotSpacing, firstDistance) ->
@setupSegments() if 0 == @segments.length
firstDistance = dotSpacing if !firstDistance
for segment in @segments
firstDistance = segment.makeDottedPath(ctx, dotSpacing, firstDistance)
class Polygon extends Path
constructor: (@points=[]) -> super()
setupSegments: ->
for p, i in @points
next = i + 1
next = 0 if @points.length == next
@addBezier([p, @points[next]])
class Rect extends Polygon
constructor: (@l, @t, @r, @b) -> super()
inset: (ix, iy) ->
@l += ix
@t += iy
@r -= ix
@b -= iy
return this
expandToInclude: (rect) ->
@l = Math.min(@l, rect.l)
@t = Math.min(@t, rect.t)
@r = Math.max(@r, rect.r)
@b = Math.max(@b, rect.b)
getWidth: -> @r - @l
getHeight: -> @b - @t
setupSegments: ->
w = @getWidth()
h = @getHeight()
@points = [
new Point(@l, @t)
new Point(@l + w, @t)
new Point(@l + w, @t + h)
new Point(@l, @t + h)
]
super()
class Ellipse extends Path
KAPPA: 0.5522847498,
constructor: (@cx, @cy, @rx, @ry) -> super()
setupSegments: ->
@addBezier([
new Point(@cx, @cy - @ry)
new Point(@cx + @KAPPA * @rx, @cy - @ry)
new Point(@cx + @rx, @cy - @KAPPA * @ry)
new Point(@cx + @rx, @cy)
])
@addBezier([
new Point(@cx + @rx, @cy)
new Point(@cx + @rx, @cy + @KAPPA * @ry)
new Point(@cx + @KAPPA * @rx, @cy + @ry)
new Point(@cx, @cy + @ry)
])
@addBezier([
new Point(@cx, @cy + @ry)
new Point(@cx - @KAPPA * @rx, @cy + @ry)
new Point(@cx - @rx, @cy + @KAPPA * @ry)
new Point(@cx - @rx, @cy)
]);
@addBezier([
new Point(@cx - @rx, @cy)
new Point(@cx - @rx, @cy - @KAPPA * @ry)
new Point(@cx - @KAPPA * @rx, @cy - @ry)
new Point(@cx, @cy - @ry)
])
escapeHTML = (str) ->
div = document.createElement('div')
div.appendChild(document.createTextNode(str))
div.innerHTML
debug = (str) ->
console.log str
clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
#/*
# * This file is part of Canviz. See http://www.canviz.org/
# * $Id: x11colors.js 246 2008-12-27 08:36:24Z ryandesign.com $
# */
Canviz.colors.x11 =
aliceblue:'f0f8ff'
antiquewhite:'faebd7'
antiquewhite1:'ffefdb'
antiquewhite2:'eedfcc'
antiquewhite3:'cdc0b0'
antiquewhite4:'8b8378'
aquamarine:'7fffd4'
aquamarine1:'7fffd4'
aquamarine2:'76eec6'
aquamarine3:'66cdaa'
aquamarine4:'458b74'
azure:'f0ffff'
azure1:'f0ffff'
azure2:'e0eeee'
azure3:'c1cdcd'
azure4:'838b8b'
beige:'f5f5dc'
bisque:'ffe4c4'
bisque1:'ffe4c4'
bisque2:'eed5b7'
bisque3:'cdb79e'
bisque4:'8b7d6b'
black:'000000'
blanchedalmond:'ffebcd'
blue:'0000ff'
blue1:'0000ff'
blue2:'0000ee'
blue3:'0000cd'
blue4:'00008b'
blueviolet:'8a2be2'
brown:'a52a2a'
brown1:'ff4040'
brown2:'ee3b3b'
brown3:'cd3333'
brown4:'8b2323'
burlywood:'deb887'
burlywood1:'ffd39b'
burlywood2:'eec591'
burlywood3:'cdaa7d'
burlywood4:'8b7355'
cadetblue:'5f9ea0'
cadetblue1:'98f5ff'
cadetblue2:'8ee5ee'
cadetblue3:'7ac5cd'
cadetblue4:'53868b'
chartreuse:'7fff00'
chartreuse1:'7fff00'
chartreuse2:'76ee00'
chartreuse3:'66cd00'
chartreuse4:'458b00'
chocolate:'d2691e'
chocolate1:'ff7f24'
chocolate2:'ee7621'
chocolate3:'cd661d'
chocolate4:'8b4513'
coral:'ff7f50'
coral1:'ff7256'
coral2:'ee6a50'
coral3:'cd5b45'
coral4:'8b3e2f'
cornflowerblue:'6495ed'
cornsilk:'fff8dc'
cornsilk1:'fff8dc'
cornsilk2:'eee8cd'
cornsilk3:'cdc8b1'
cornsilk4:'8b8878'
crimson:'dc143c'
cyan:'00ffff'
cyan1:'00ffff'
cyan2:'00eeee'
cyan3:'00cdcd'
cyan4:'008b8b'
darkgoldenrod:'b8860b'
darkgoldenrod1:'ffb90f'
darkgoldenrod2:'eead0e'
darkgoldenrod3:'cd950c'
darkgoldenrod4:'8b6508'
darkgreen:'006400'
darkkhaki:'bdb76b'
darkolivegreen:'556b2f'
darkolivegreen1:'caff70'
darkolivegreen2:'bcee68'
darkolivegreen3:'a2cd5a'
darkolivegreen4:'6e8b3d'
darkorange:'ff8c00'
darkorange1:'ff7f00'
darkorange2:'ee7600'
darkorange3:'cd6600'
darkorange4:'8b4500'
darkorchid:'9932cc'
darkorchid1:'bf3eff'
darkorchid2:'b23aee'
darkorchid3:'9a32cd'
darkorchid4:'68228b'
darksalmon:'e9967a'
darkseagreen:'8fbc8f'
darkseagreen1:'c1ffc1'
darkseagreen2:'b4eeb4'
darkseagreen3:'9bcd9b'
darkseagreen4:'698b69'
darkslateblue:'483d8b'
darkslategray:'2f4f4f'
darkslategray1:'97ffff'
darkslategray2:'8deeee'
darkslategray3:'79cdcd'
darkslategray4:'528b8b'
darkslategrey:'2f4f4f'
darkturquoise:'00ced1'
darkviolet:'9400d3'
deeppink:'ff1493'
deeppink1:'ff1493'
deeppink2:'ee1289'
deeppink3:'cd1076'
deeppink4:'8b0a50'
deepskyblue:'00bfff'
deepskyblue1:'00bfff'
deepskyblue2:'00b2ee'
deepskyblue3:'009acd'
deepskyblue4:'00688b'
dimgray:'696969'
dimgrey:'696969'
dodgerblue:'1e90ff'
dodgerblue1:'1e90ff'
dodgerblue2:'1c86ee'
dodgerblue3:'1874cd'
dodgerblue4:'104e8b'
firebrick:'b22222'
firebrick1:'ff3030'
firebrick2:'ee2c2c'
firebrick3:'cd2626'
firebrick4:'8b1a1a'
floralwhite:'fffaf0'
forestgreen:'228b22'
gainsboro:'dcdcdc'
ghostwhite:'f8f8ff'
gold:'ffd700'
gold1:'ffd700'
gold2:'eec900'
gold3:'cdad00'
gold4:'8b7500'
goldenrod:'daa520'
goldenrod1:'ffc125'
goldenrod2:'eeb422'
goldenrod3:'cd9b1d'
goldenrod4:'8b6914'
gray:'c0c0c0'
gray0:'000000'
gray1:'030303'
gray10:'1a1a1a'
gray100:'ffffff'
gray11:'1c1c1c'
gray12:'1f1f1f'
gray13:'212121'
gray14:'242424'
gray15:'262626'
gray16:'292929'
gray17:'2b2b2b'
gray18:'2e2e2e'
gray19:'303030'
gray2:'050505'
gray20:'333333'
gray21:'363636'
gray22:'383838'
gray23:'3b3b3b'
gray24:'3d3d3d'
gray25:'404040'
gray26:'424242'
gray27:'454545'
gray28:'474747'
gray29:'4a4a4a'
gray3:'080808'
gray30:'4d4d4d'
gray31:'4f4f4f'
gray32:'525252'
gray33:'545454'
gray34:'575757'
gray35:'595959'
gray36:'5c5c5c'
gray37:'5e5e5e'
gray38:'616161'
gray39:'636363'
gray4:'0a0a0a'
gray40:'666666'
gray41:'696969'
gray42:'6b6b6b'
gray43:'6e6e6e'
gray44:'707070'
gray45:'737373'
gray46:'757575'
gray47:'787878'
gray48:'7a7a7a'
gray49:'7d7d7d'
gray5:'0d0d0d'
gray50:'7f7f7f'
gray51:'828282'
gray52:'858585'
gray53:'878787'
gray54:'8a8a8a'
gray55:'8c8c8c'
gray56:'8f8f8f'
gray57:'919191'
gray58:'949494'
gray59:'969696'
gray6:'0f0f0f'
gray60:'999999'
gray61:'9c9c9c'
gray62:'9e9e9e'
gray63:'a1a1a1'
gray64:'a3a3a3'
gray65:'a6a6a6'
gray66:'a8a8a8'
gray67:'ababab'
gray68:'adadad'
gray69:'b0b0b0'
gray7:'121212'
gray70:'b3b3b3'
gray71:'b5b5b5'
gray72:'b8b8b8'
gray73:'bababa'
gray74:'bdbdbd'
gray75:'bfbfbf'
gray76:'c2c2c2'
gray77:'c4c4c4'
gray78:'c7c7c7'
gray79:'c9c9c9'
gray8:'141414'
gray80:'cccccc'
gray81:'cfcfcf'
gray82:'d1d1d1'
gray83:'d4d4d4'
gray84:'d6d6d6'
gray85:'d9d9d9'
gray86:'dbdbdb'
gray87:'dedede'
gray88:'e0e0e0'
gray89:'e3e3e3'
gray9:'171717'
gray90:'e5e5e5'
gray91:'e8e8e8'
gray92:'ebebeb'
gray93:'ededed'
gray94:'f0f0f0'
gray95:'f2f2f2'
gray96:'f5f5f5'
gray97:'f7f7f7'
gray98:'fafafa'
gray99:'fcfcfc'
green:'00ff00'
green1:'00ff00'
green2:'00ee00'
green3:'00cd00'
green4:'008b00'
greenyellow:'adff2f'
grey:'c0c0c0'
grey0:'000000'
grey1:'030303'
grey10:'1a1a1a'
grey100:'ffffff'
grey11:'1c1c1c'
grey12:'1f1f1f'
grey13:'212121'
grey14:'242424'
grey15:'262626'
grey16:'292929'
grey17:'2b2b2b'
grey18:'2e2e2e'
grey19:'303030'
grey2:'050505'
grey20:'333333'
grey21:'363636'
grey22:'383838'
grey23:'3b3b3b'
grey24:'3d3d3d'
grey25:'404040'
grey26:'424242'
grey27:'454545'
grey28:'474747'
grey29:'4a4a4a'
grey3:'080808'
grey30:'4d4d4d'
grey31:'4f4f4f'
grey32:'525252'
grey33:'545454'
grey34:'575757'
grey35:'595959'
grey36:'5c5c5c'
grey37:'5e5e5e'
grey38:'616161'
grey39:'636363'
grey4:'0a0a0a'
grey40:'666666'
grey41:'696969'
grey42:'6b6b6b'
grey43:'6e6e6e'
grey44:'707070'
grey45:'737373'
grey46:'757575'
grey47:'787878'
grey48:'7a7a7a'
grey49:'7d7d7d'
grey5:'0d0d0d'
grey50:'7f7f7f'
grey51:'828282'
grey52:'858585'
grey53:'878787'
grey54:'8a8a8a'
grey55:'8c8c8c'
grey56:'8f8f8f'
grey57:'919191'
grey58:'949494'
grey59:'969696'
grey6:'0f0f0f'
grey60:'999999'
grey61:'9c9c9c'
grey62:'9e9e9e'
grey63:'a1a1a1'
grey64:'a3a3a3'
grey65:'a6a6a6'
grey66:'a8a8a8'
grey67:'ababab'
grey68:'adadad'
grey69:'b0b0b0'
grey7:'121212'
grey70:'b3b3b3'
grey71:'b5b5b5'
grey72:'b8b8b8'
grey73:'bababa'
grey74:'bdbdbd'
grey75:'bfbfbf'
grey76:'c2c2c2'
grey77:'c4c4c4'
grey78:'c7c7c7'
grey79:'c9c9c9'
grey8:'141414'
grey80:'cccccc'
grey81:'cfcfcf'
grey82:'d1d1d1'
grey83:'d4d4d4'
grey84:'d6d6d6'
grey85:'d9d9d9'
grey86:'dbdbdb'
grey87:'dedede'
grey88:'e0e0e0'
grey89:'e3e3e3'
grey9:'171717'
grey90:'e5e5e5'
grey91:'e8e8e8'
grey92:'ebebeb'
grey93:'ededed'
grey94:'f0f0f0'
grey95:'f2f2f2'
grey96:'f5f5f5'
grey97:'f7f7f7'
grey98:'fafafa'
grey99:'fcfcfc'
honeydew:'f0fff0'
honeydew1:'f0fff0'
honeydew2:'e0eee0'
honeydew3:'c1cdc1'
honeydew4:'838b83'
hotpink:'ff69b4'
hotpink1:'ff6eb4'
hotpink2:'ee6aa7'
hotpink3:'cd6090'
hotpink4:'8b3a62'
indianred:'cd5c5c'
indianred1:'ff6a6a'
indianred2:'ee6363'
indianred3:'cd5555'
indianred4:'8b3a3a'
indigo:'4b0082'
invis:'fffffe00'
ivory:'fffff0'
ivory1:'fffff0'
ivory2:'eeeee0'
ivory3:'cdcdc1'
ivory4:'8b8b83'
khaki:'f0e68c'
khaki1:'fff68f'
khaki2:'eee685'
khaki3:'cdc673'
khaki4:'8b864e'
lavender:'e6e6fa'
lavenderblush:'fff0f5'
lavenderblush1:'fff0f5'
lavenderblush2:'eee0e5'
lavenderblush3:'cdc1c5'
lavenderblush4:'8b8386'
lawngreen:'7cfc00'
lemonchiffon:'fffacd'
lemonchiffon1:'fffacd'
lemonchiffon2:'eee9bf'
lemonchiffon3:'cdc9a5'
lemonchiffon4:'8b8970'
lightblue:'add8e6'
lightblue1:'bfefff'
lightblue2:'b2dfee'
lightblue3:'9ac0cd'
lightblue4:'68838b'
lightcoral:'f08080'
lightcyan:'e0ffff'
lightcyan1:'e0ffff'
lightcyan2:'d1eeee'
lightcyan3:'b4cdcd'
lightcyan4:'7a8b8b'
lightgoldenrod:'eedd82'
lightgoldenrod1:'ffec8b'
lightgoldenrod2:'eedc82'
lightgoldenrod3:'cdbe70'
lightgoldenrod4:'8b814c'
lightgoldenrodyellow:'fafad2'
lightgray:'d3d3d3'
lightgrey:'d3d3d3'
lightpink:'ffb6c1'
lightpink1:'ffaeb9'
lightpink2:'eea2ad'
lightpink3:'cd8c95'
lightpink4:'8b5f65'
lightsalmon:'ffa07a'
lightsalmon1:'ffa07a'
lightsalmon2:'ee9572'
lightsalmon3:'cd8162'
lightsalmon4:'8b5742'
lightseagreen:'20b2aa'
lightskyblue:'87cefa'
lightskyblue1:'b0e2ff'
lightskyblue2:'a4d3ee'
lightskyblue3:'8db6cd'
lightskyblue4:'607b8b'
lightslateblue:'8470ff'
lightslategray:'778899'
lightslategrey:'778899'
lightsteelblue:'b0c4de'
lightsteelblue1:'cae1ff'
lightsteelblue2:'bcd2ee'
lightsteelblue3:'a2b5cd'
lightsteelblue4:'6e7b8b'
lightyellow:'ffffe0'
lightyellow1:'ffffe0'
lightyellow2:'eeeed1'
lightyellow3:'cdcdb4'
lightyellow4:'8b8b7a'
limegreen:'32cd32'
linen:'faf0e6'
magenta:'ff00ff'
magenta1:'ff00ff'
magenta2:'ee00ee'
magenta3:'cd00cd'
magenta4:'8b008b'
maroon:'b03060'
maroon1:'ff34b3'
maroon2:'ee30a7'
maroon3:'cd2990'
maroon4:'8b1c62'
mediumaquamarine:'66cdaa'
mediumblue:'0000cd'
mediumorchid:'ba55d3'
mediumorchid1:'e066ff'
mediumorchid2:'d15fee'
mediumorchid3:'b452cd'
mediumorchid4:'7a378b'
mediumpurple:'9370db'
mediumpurple1:'ab82ff'
mediumpurple2:'9f79ee'
mediumpurple3:'8968cd'
mediumpurple4:'5d478b'
mediumseagreen:'3cb371'
mediumslateblue:'7b68ee'
mediumspringgreen:'00fa9a'
mediumturquoise:'48d1cc'
mediumvioletred:'c71585'
midnightblue:'191970'
mintcream:'f5fffa'
mistyrose:'ffe4e1'
mistyrose1:'ffe4e1'
mistyrose2:'eed5d2'
mistyrose3:'cdb7b5'
mistyrose4:'8b7d7b'
moccasin:'ffe4b5'
navajowhite:'ffdead'
navajowhite1:'ffdead'
navajowhite2:'eecfa1'
navajowhite3:'cdb38b'
navajowhite4:'8b795e'
navy:'000080'
navyblue:'000080'
none:'fffffe00'
oldlace:'fdf5e6'
olivedrab:'6b8e23'
olivedrab1:'c0ff3e'
olivedrab2:'b3ee3a'
olivedrab3:'9acd32'
olivedrab4:'698b22'
orange:'ffa500'
orange1:'ffa500'
orange2:'ee9a00'
orange3:'cd8500'
orange4:'8b5a00'
orangered:'ff4500'
orangered1:'ff4500'
orangered2:'ee4000'
orangered3:'cd3700'
orangered4:'8b2500'
orchid:'da70d6'
orchid1:'ff83fa'
orchid2:'ee7ae9'
orchid3:'cd69c9'
orchid4:'8b4789'
palegoldenrod:'eee8aa'
palegreen:'98fb98'
palegreen1:'9aff9a'
palegreen2:'90ee90'
palegreen3:'7ccd7c'
palegreen4:'548b54'
paleturquoise:'afeeee'
paleturquoise1:'bbffff'
paleturquoise2:'aeeeee'
paleturquoise3:'96cdcd'
paleturquoise4:'668b8b'
palevioletred:'db7093'
palevioletred1:'ff82ab'
palevioletred2:'ee799f'
palevioletred3:'cd6889'
palevioletred4:'8b475d'
papayawhip:'ffefd5'
peachpuff:'ffdab9'
peachpuff1:'ffdab9'
peachpuff2:'eecbad'
peachpuff3:'cdaf95'
peachpuff4:'8b7765'
peru:'cd853f'
pink:'ffc0cb'
pink1:'ffb5c5'
pink2:'eea9b8'
pink3:'cd919e'
pink4:'8b636c'
plum:'dda0dd'
plum1:'ffbbff'
plum2:'eeaeee'
plum3:'cd96cd'
plum4:'8b668b'
powderblue:'b0e0e6'
purple:'a020f0'
purple1:'9b30ff'
purple2:'912cee'
purple3:'7d26cd'
purple4:'551a8b'
red:'ff0000'
red1:'ff0000'
red2:'ee0000'
red3:'cd0000'
red4:'8b0000'
rosybrown:'bc8f8f'
rosybrown1:'ffc1c1'
rosybrown2:'eeb4b4'
rosybrown3:'cd9b9b'
rosybrown4:'8b6969'
royalblue:'4169e1'
royalblue1:'4876ff'
royalblue2:'436eee'
royalblue3:'3a5fcd'
royalblue4:'27408b'
saddlebrown:'8b4513'
salmon:'fa8072'
salmon1:'ff8c69'
salmon2:'ee8262'
salmon3:'cd7054'
salmon4:'8b4c39'
sandybrown:'f4a460'
seagreen:'2e8b57'
seagreen1:'54ff9f'
seagreen2:'4eee94'
seagreen3:'43cd80'
seagreen4:'2e8b57'
seashell:'fff5ee'
seashell1:'fff5ee'
seashell2:'eee5de'
seashell3:'cdc5bf'
seashell4:'8b8682'
sienna:'a0522d'
sienna1:'ff8247'
sienna2:'ee7942'
sienna3:'cd6839'
sienna4:'8b4726'
skyblue:'87ceeb'
skyblue1:'87ceff'
skyblue2:'7ec0ee'
skyblue3:'6ca6cd'
skyblue4:'4a708b'
slateblue:'6a5acd'
slateblue1:'836fff'
slateblue2:'7a67ee'
slateblue3:'6959cd'
slateblue4:'473c8b'
slategray:'708090'
slategray1:'c6e2ff'
slategray2:'b9d3ee'
slategray3:'9fb6cd'
slategray4:'6c7b8b'
slategrey:'708090'
snow:'fffafa'
snow1:'fffafa'
snow2:'eee9e9'
snow3:'cdc9c9'
snow4:'8b8989'
springgreen:'00ff7f'
springgreen1:'00ff7f'
springgreen2:'00ee76'
springgreen3:'00cd66'
springgreen4:'008b45'
steelblue:'4682b4'
steelblue1:'63b8ff'
steelblue2:'5cacee'
steelblue3:'4f94cd'
steelblue4:'36648b'
tan:'d2b48c'
tan1:'ffa54f'
tan2:'ee9a49'
tan3:'cd853f'
tan4:'8b5a2b'
thistle:'d8bfd8'
thistle1:'ffe1ff'
thistle2:'eed2ee'
thistle3:'cdb5cd'
thistle4:'8b7b8b'
tomato:'ff6347'
tomato1:'ff6347'
tomato2:'ee5c42'
tomato3:'cd4f39'
tomato4:'8b3626'
transparent:'fffffe00'
turquoise:'40e0d0'
turquoise1:'00f5ff'
turquoise2:'00e5ee'
turquoise3:'00c5cd'
turquoise4:'00868b'
violet:'ee82ee'
violetred:'d02090'
violetred1:'ff3e96'
violetred2:'ee3a8c'
violetred3:'cd3278'
violetred4:'8b2252'
wheat:'f5deb3'
wheat1:'ffe7ba'
wheat2:'eed8ae'
wheat3:'cdba96'
wheat4:'8b7e66'
white:'ffffff'
whitesmoke:'f5f5f5'
yellow:'ffff00'
yellow1:'ffff00'
yellow2:'eeee00'
yellow3:'cdcd00'
yellow4:'8b8b00'
yellowgreen:'9acd32'
window.Canviz = Canviz
| true | class CanvizTokenizer
constructor: (@str) ->
takeChars: (num) ->
num = 1 if !num
tokens = []
while (num--)
matches = @str.match(/^(\S+)\s*/)
if matches
@str = @str.substr(matches[0].length)
tokens.push(matches[1])
else
tokens.push(false)
if 1 == tokens.length
return tokens[0]
else
return tokens
takeNumber: (num) ->
num = 1 if !num
if 1 == num
return Number(@takeChars())
else
tokens = @takeChars(num)
while num--
tokens[num] = Number(tokens[num])
return tokens
takeString: () ->
byteCount = Number(@takeChars())
charCount = 0
return false if '-' != @str.charAt(0)
while 0 < byteCount
++charCount
charCode = @str.charCodeAt(charCount)
if 0x80 > charCode
--byteCount
else if 0x800 > charCode
byteCount -= 2
else
byteCount -= 3
str = @str.substr(1, charCount)
@str = @str.substr(1 + charCount).replace(/^\s+/, '')
return str
class CanvizEntity
constructor: (@defaultAttrHashName, @name, @canviz, @rootGraph, @parentGraph, @immediateGraph) ->
@attrs = {}
@drawAttrs = {}
initBB: () ->
matches = @getAttr('pos').match(/([0-9.]+),([0-9.]+)/)
x = Math.round(matches[1])
y = Math.round(@canviz.height - matches[2])
@bbRect = new Rect(x, y, x, y)
getAttr: (attrName, escString=false) ->
attrValue = @attrs[attrName]
if not attrValue?
graph = @parentGraph
while graph?
attrValue = graph[@defaultAttrHashName][attrName]
if not attrValue?
graph = graph.parentGraph
else
break
if attrValue and escString
attrValue = attrValue.replace @escStringMatchRe, (match, p1) =>
switch p1
when 'N', 'E' then return @name
when 'T' then return @tailNode
when 'H' then return @headNode
when 'G' then return @immediateGraph.name
when 'L' then return @getAttr('label', true)
return match
return attrValue
draw: (ctx, ctxScale, redrawCanvasOnly) ->
if !redrawCanvasOnly
@initBB()
bbDiv = document.createElement('div')
@canviz.elements.appendChild(bbDiv)
for _, command of @drawAttrs
# command = drawAttr.value
tokenizer = new CanvizTokenizer(command)
token = tokenizer.takeChars()
if token
dashStyle = 'solid'
ctx.save()
while token
switch token
when 'E', 'e' # unfilled ellipse
filled = ('E' == token)
cx = tokenizer.takeNumber()
cy = @canviz.height - tokenizer.takeNumber()
rx = tokenizer.takeNumber()
ry = tokenizer.takeNumber()
path = new Ellipse(cx, cy, rx, ry)
when 'P', 'p', 'L'
filled = ('P' == token)
closed = ('L' != token);
numPoints = tokenizer.takeNumber()
tokens = tokenizer.takeNumber(2 * numPoints)
path = new Path()
#for (i = 2; i < 2 * numPoints; i += 2)
for i in [2...(2*numPoints)] by 2
path.addBezier([
new Point(tokens[i - 2], @canviz.height - tokens[i - 1])
new Point(tokens[i], @canviz.height - tokens[i + 1])
])
if closed
path.addBezier([
new Point(tokens[2 * numPoints - 2], @canviz.height - tokens[2 * numPoints - 1])
new Point(tokens[0], @canviz.height - tokens[1])
])
when 'B', 'b' # unfilled b-spline
filled = ('b' == token)
numPoints = tokenizer.takeNumber()
tokens = tokenizer.takeNumber(2 * numPoints); # points
path = new Path()
for i in [2...(2*numPoints)] by 6
path.addBezier([
new Point(tokens[i - 2], @canviz.height - tokens[i - 1])
new Point(tokens[i], @canviz.height - tokens[i + 1])
new Point(tokens[i + 2], @canviz.height - tokens[i + 3])
new Point(tokens[i + 4], @canviz.height - tokens[i + 5])
])
when 'I' # image
l = tokenizer.takeNumber()
b = @canviz.height - tokenizer.takeNumber()
w = tokenizer.takeNumber()
h = tokenizer.takeNumber()
src = tokenizer.takeString()
if !@canviz.images[src]
@canviz.images[src] = new CanvizImage(@canviz, src)
@canviz.images[src].draw(ctx, l, b - h, w, h)
when 'T' # text
l = Math.round(ctxScale * tokenizer.takeNumber() + @canviz.padding)
t = Math.round(ctxScale * @canviz.height + 2 * @canviz.padding - (ctxScale * (tokenizer.takeNumber() + @canviz.bbScale * fontSize) + @canviz.padding))
textAlign = tokenizer.takeNumber()
textWidth = Math.round(ctxScale * tokenizer.takeNumber())
str = tokenizer.takeString()
if !redrawCanvasOnly and !/^\s*$/.test(str)
#str = escapeHTML(str)
loop
matches = str.match(/[ ]([ ]+)/)
if matches
spaces = ' '
spaces += ' ' for _ in [0..matches[1].length.times]
str = str.replace(/[ ] +/, spaces)
break unless matches
href = @getAttr('URL', true) || @getAttr('href', true)
if href
target = @getAttr('target', true) || '_self'
tooltip = @getAttr('tooltip', true) || @getAttr('label', true)
text = document.createElement("a")
text.href = href
text.target = target
text.title = tooltip
for attrName in ['onclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout']
attrValue = @getAttr(attrName, true)
if attrValue
text.writeAttribute(attrName, attrValue)
text.textDecoration = 'none'
else
text = document.createElement("span") # new Element('span')
text.innerText = str
ts = text.style
ts.fontSize = Math.round(fontSize * ctxScale * @canviz.bbScale) + 'px'
ts.fontFamily = fontFamily
ts.color = strokeColor.textColor
ts.position = 'absolute'
ts.textAlign = if (-1 == textAlign) then 'left' else if (1 == textAlign) then 'right' else 'center'
ts.left = (l - (1 + textAlign) * textWidth) + 'px'
ts.top = t + 'px'
ts.width = (2 * textWidth) + 'px'
ts.opacity = strokeColor.opacity if 1 != strokeColor.opacity
@canviz.elements.appendChild(text)
when 'C', 'c'
fill = ('C' == token)
color = @parseColor(tokenizer.takeString())
if fill
fillColor = color
ctx.fillStyle = color.canvasColor
else
strokeColor = color
ctx.strokeStyle = color.canvasColor
when 'F' # // set font
fontSize = tokenizer.takeNumber()
fontFamily = tokenizer.takeString()
switch fontFamily
when 'Times-Roman' then fontFamily = 'Times New Roman'
when 'Courier' then fontFamily = 'Courier New'
when 'Helvetica' then fontFamily = 'Arial'
when 'S' # // set style
style = tokenizer.takeString()
switch style
when 'solid', 'filled' then 1 # nothing
when 'dashed', 'dotted' then dashStyle = style
when 'bold' then ctx.lineWidth = 2
else
matches = style.match(/^setlinewidth\((.*)\)$/)
if matches
ctx.lineWidth = Number(matches[1])
else
debug('unknown style ' + style)
else
debug('unknown token ' + token)
return
if path
@canviz.drawPath(ctx, path, filled, dashStyle)
@bbRect.expandToInclude(path.getBB()) if !redrawCanvasOnly
path = undefined
token = tokenizer.takeChars()
if !redrawCanvasOnly
bbDiv.position = 'absolute'
bbDiv.left = Math.round(ctxScale * @bbRect.l + @canviz.padding) + 'px'
bbDiv.top = Math.round(ctxScale * @bbRect.t + @canviz.padding) + 'px'
bbDiv.width = Math.round(ctxScale * @bbRect.getWidth()) + 'px'
bbDiv.height = Math.round(ctxScale * @bbRect.getHeight()) + 'px'
ctx.restore()
parseColor: (color) ->
parsedColor = {opacity: 1}
# // rgb/rgba
if /^#(?:[0-9a-f]{2}\s*){3,4}$/i.test(color)
return @canviz.parseHexColor(color)
# // hsv
matches = color.match(/^(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)$/)
if matches
parsedColor.canvasColor = parsedColor.textColor = @canviz.hsvToRgbColor(matches[1], matches[2], matches[3])
return parsedColor
# // named color
colorScheme = @getAttr('colorscheme') || 'X11'
colorName = color
matches = color.match(/^\/(.*)\/(.*)$/)
if matches
if matches[1]
colorScheme = matches[1]
colorName = matches[2]
else
matches = color.match(/^\/(.*)$/)
if matches
colorScheme = 'X11'
colorName = matches[1]
colorName = colorName.toLowerCase()
colorSchemeName = colorScheme.toLowerCase()
colorSchemeData = Canviz.colors[colorSchemeName]
if colorSchemeData
colorData = colorSchemeData[colorName]
if colorData
return @canviz.parseHexColor('#' + colorData)
colorData = Canviz.colors['fallback'][colorName]
if colorData
return @canviz.parseHexColor('#' + colorData)
if !colorSchemeData
debug('unknown color scheme ' + colorScheme)
# // unknown
debug('unknown color ' + color + '; color scheme is ' + colorScheme)
parsedColor.canvasColor = parsedColor.textColor = '#000000'
return parsedColor
class CanvizNode extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph) ->
super('nodeAttrs', name, canviz, rootGraph, parentGraph, parentGraph)
escStringMatchRe: /\\([NGL])/g
#
class CanvizEdge extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph, @tailNode, @headNode) ->
super('edgeAttrs', name, canviz, rootGraph, parentGraph, parentGraph)
escStringMatchRe: /\\([EGTHL])/g
class CanvizGraph extends CanvizEntity
constructor: (name, canviz, rootGraph, parentGraph) ->
super('attrs', name, canviz, rootGraph, parentGraph, this)
@nodeAttrs = {}
@edgeAttrs = {}
@nodes = []
@edges = []
@subgraphs = []
initBB: () ->
coords = @getAttr('bb').split(',')
@bbRect = new Rect(coords[0], @canviz.height - coords[1], coords[2], @canviz.height - coords[3])
draw: (ctx, ctxScale, redrawCanvasOnly) ->
super(ctx, ctxScale, redrawCanvasOnly)
for type in [@subgraphs, @nodes, @edges]
for entity in type
entity.draw(ctx, ctxScale, redrawCanvasOnly)
escStringMatchRe: /\\([GL])/g
class Canviz
@maxXdotVersion: "1.2"
@colors:
fallback:
black:'000000'
lightgrey:'d3d3d3'
white:'ffffff'
constructor: (container, url, urlParams) ->
@canvas = document.createElement('canvas')
@canvas.style.position = "absolute"
Canviz.canvasCounter ?= 0
@canvas.id = 'canviz_canvas_' + (++Canviz.canvasCounter)
@elements = document.createElement('div')
@elements.style.position = "absolute"
@container = document.getElementById(container)
@container.style.position = "relative"
@container.appendChild(@canvas)
@container.appendChild(@elements)
@ctx = @canvas.getContext('2d')
@scale = 1
@padding = 8
@dashLength = 6
@dotSpacing = 4
@graphs = []
@images = {}
@numImages = 0
@numImagesFinished = 0
@imagePath = ""
@idMatch = '([a-zA-Z\u0080-\uFFFF_][0-9a-zA-Z\u0080-\uFFFF_]*|-?(?:\\.\\d+|\\d+(?:\\.\\d*)?)|"(?:\\\\"|[^"])*"|<(?:<[^>]*>|[^<>]+?)+>)'
@nodeIdMatch = @idMatch + '(?::' + @idMatch + ')?(?::' + @idMatch + ')?'
@graphMatchRe = new RegExp('^(strict\\s+)?(graph|digraph)(?:\\s+' + @idMatch + ')?\\s*{$', 'i')
@subgraphMatchRe = new RegExp('^(?:subgraph\\s+)?' + @idMatch + '?\\s*{$', 'i')
@nodeMatchRe = new RegExp('^(' + @nodeIdMatch + ')\\s+\\[(.+)\\];$')
@edgeMatchRe = new RegExp('^(' + @nodeIdMatch + '\\s*-[->]\\s*' + @nodeIdMatch + ')\\s+\\[(.+)\\];$')
@attrMatchRe = new RegExp('^' + @idMatch + '=' + @idMatch + '(?:[,\\s]+|$)')
setScale: (@scale) ->
setImagePath: (@imagePath) ->
parse: (xdot) ->
@graphs = []
@width = 0
@height = 0
@maxWidth = false
@maxHeight = false
@bbEnlarge = false
@bbScale = 1
@dpi = 96
@bgcolor = opacity: 1
@bgcolor.canvasColor = @bgcolor.textColor = '#ffffff'
lines = xdot.split(/\r?\n/)
i = 0
containers = []
while i < lines.length
line = lines[i++].replace(/^\s+/, '')
if '' != line and '#' != line.substr(0, 1)
while i < lines.length and ';' != (lastChar = line.substr(line.length - 1, line.length)) and '{' != lastChar and '}' != lastChar
if '\\' == lastChar
line = line.substr(0, line.length - 1)
line += lines[i++]
if containers.length == 0
matches = line.match(@graphMatchRe)
if matches
rootGraph = new CanvizGraph(matches[3], this)
containers.unshift(rootGraph)
containers[0].strict = not (not matches[1])
containers[0].type = if 'graph' == matches[2] then 'undirected' else 'directed'
containers[0].attrs.xdotversion = '1.0'
containers[0].attrs.bb ?= '0,0,500,500'
@graphs.push(containers[0])
else
matches = line.match(@subgraphMatchRe)
if matches
containers.unshift(new CanvizGraph(matches[1], this, rootGraph, containers[0]))
containers[1].subgraphs.push containers[0]
if matches
else if "}" == line
containers.shift()
break if 0 == containers.length
else
matches = line.match(@nodeMatchRe)
if matches
entityName = matches[2]
attrs = matches[5]
drawAttrHash = containers[0].drawAttrs
isGraph = false
switch entityName
when 'graph'
attrHash = containers[0].attrs
isGraph = true
when 'node' then attrHash = containers[0].nodeAttrs
when 'edge' then attrHash = containers[0].edgeAttrs
else
entity = new CanvizNode(entityName, this, rootGraph, containers[0])
attrHash = entity.attrs
drawAttrHash = entity.drawAttrs
containers[0].nodes.push(entity)
else
matches = line.match(@edgeMatchRe)
if matches
entityName = matches[1]
attrs = matches[8]
entity = new CanvizEdge(entityName, this, rootGraph, containers[0], matches[2], matches[5])
attrHash = entity.attrs
drawAttrHash = entity.drawAttrs
containers[0].edges.push(entity)
while matches
break if 0 == attrs.length
matches = attrs.match(@attrMatchRe)
if matches
attrs = attrs.substr(matches[0].length)
attrName = matches[1]
attrValue = @unescape(matches[2])
if /^_.*draw_$/.test(attrName)
drawAttrHash[attrName] = attrValue
else
attrHash[attrName] = attrValue
if isGraph and 1 == containers.length
switch attrName
when 'bb'
bb = attrValue.split(/,/)
@width = Number(bb[2])
@height = Number(bb[3])
when 'bgcolor' then @bgcolor = rootGraph.parseColor(attrValue)
when 'dpi' then @dpi = attrValue
when 'size'
size = attrValue.match(/^(\d+|\d*(?:\.\d+)),\s*(\d+|\d*(?:\.\d+))(!?)$/)
if size
@maxWidth = 72 * Number(size[1])
@maxHeight = 72 * Number(size[2])
@bbEnlarge = '!' == size[3]
when 'xdotversion'
if 0 > @versionCompare(Canviz.maxXdotVersion, attrHash['xdotversion'])
1
@draw()
draw: (redrawCanvasOnly) ->
redrawCanvasOnly ?= false
ctxScale = @scale * @dpi / 72
width = Math.round(ctxScale * @width + 2 * @padding)
height = Math.round(ctxScale * @height + 2 * @padding)
if !redrawCanvasOnly
@canvas.width = width
@canvas.height = height
@canvas.style.width = "#{width}px"
@canvas.style.height = "#{height}px"
@container.style.width = "#{width}px"
while (@elements.firstChild)
@elements.removeChild(@elements.firstChild)
@ctx.save()
@ctx.lineCap = 'round'
@ctx.fillStyle = @bgcolor.canvasColor
@ctx.fillRect(0, 0, width, height)
@ctx.translate(@padding, @padding)
@ctx.scale(ctxScale, ctxScale)
@graphs[0].draw(@ctx, ctxScale, redrawCanvasOnly)
@ctx.restore()
drawPath: (ctx, path, filled, dashStyle) ->
if (filled)
ctx.beginPath()
path.makePath(ctx)
ctx.fill()
if ctx.fillStyle != ctx.strokeStyle or not filled
switch dashStyle
when 'dashed'
ctx.beginPath()
path.makeDashedPath(ctx, @dashLength)
when 'dotted'
oldLineWidth = ctx.lineWidth
ctx.lineWidth *= 2
ctx.beginPath()
path.makeDottedPath(ctx, @dotSpacing)
else
if not filled
ctx.beginPath()
path.makePath(ctx)
ctx.stroke()
ctx.lineWidth = oldLineWidth if oldLineWidth
unescape: (str) ->
matches = str.match(/^"(.*)"$/)
if (matches)
return matches[1].replace(/\\"/g, '"')
else
return str
parseHexColor: (color) ->
matches = color.match(/^#([0-9a-f]{2})\s*([0-9a-f]{2})\s*([0-9a-f]{2})\s*([0-9a-f]{2})?$/i)
if matches
canvasColor; textColor = '#' + matches[1] + matches[2] + matches[3]; opacity = 1
if (matches[4]) # rgba
opacity = parseInt(matches[4], 16) / 255
canvasColor = 'rgba(' + parseInt(matches[1], 16) + ',' + parseInt(matches[2], 16) + ',' + parseInt(matches[3], 16) + ',' + opacity + ')'
else # rgb
canvasColor = textColor
return {canvasColor: canvasColor, textColor: textColor, opacity: opacity}
hsvToRgbColor: (h, s, v) ->
h *= 360
i = Math.floor(h / 60) % 6
f = h / 60 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
switch (i)
when 0 then r = v; g = t; b = p
when 1 then r = q; g = v; b = p
when 2 then r = p; g = v; b = t
when 3 then r = p; g = q; b = v
when 4 then r = t; g = p; b = v
when 5 then r = v; g = p; b = q
return 'rgb(' + Math.round(255 * r) + ',' + Math.round(255 * g) + ',' + Math.round(255 * b) + ')'
versionCompare: (a, b) ->
a = a.split('.')
b = b.split('.')
while (a.length or b.length)
a1 = if a.length then a.shift() else 0
b1 = if b.length then b.shift() else 0
return -1 if (a1 < b1)
return 1 if (a1 > b1)
return 0
class CanvizImage
constructor: (@canviz, src) ->
++@canviz.numImages
@finished = @loaded = false
@img = new Image()
@img.onload = @onLoad.bind(this)
@img.onerror = @onFinish.bind(this)
@img.onabort = @onFinish.bind(this)
@img.src = @canviz.imagePath + src
onLoad: ->
@loaded = true
@onFinish()
onFinish: ->
@finished = true
++@canviz.numImagesFinished
if @canviz.numImages == @canviz.numImagesFinished
@canviz.draw(true)
draw: (ctx, l, t, w, h) ->
if @finished
if @loaded
ctx.drawImage(@img, l, t, w, h)
else
debug("can't load image " + @img.src)
@drawBrokenImage(ctx, l, t, w, h)
drawBrokenImage: (ctx, l, t, w, h) ->
ctx.save()
ctx.beginPath()
new Rect(l, t, l + w, t + w).draw(ctx)
ctx.moveTo(l, t)
ctx.lineTo(l + w, t + w)
ctx.moveTo(l + w, t)
ctx.lineTo(l, t + h)
ctx.strokeStyle = '#f00'
ctx.lineWidth = 1
ctx.stroke()
ctx.restore()
##########################################################
# $Id: path.js 262 2009-05-19 11:55:24Z PI:EMAIL:<EMAIL>END_PI $
##########################################################
class Point
constructor: (@x, @y) ->
offset: (dx, dy) ->
@x += dx
@y += dy
distanceFrom: (point) ->
dx = @x - point.x
dy = @y - point.y
Math.sqrt(dx * dx + dy * dy)
makePath: (ctx) ->
ctx.moveTo(@x, @y)
ctx.lineTo(@x + 0.001, @y)
############### Path.js
class Bezier
constructor: (@points) ->
@order = points.length
reset: () ->
p = Bezier.prototype
@controlPolygonLength = p.controlPolygonLength
@chordLength = p.chordLength
@triangle = p.triangle
@chordPoints = p.chordPoints
@coefficients = p.coefficients
offset: (dx, dy) ->
for point in @points
point.offset(dx, dy)
@reset()
getBB: ->
return undefined if !@order
p = @points[0]
l = r = p.x
t = b = p.y
for point in @points
l = Math.min(l, point.x)
t = Math.min(t, point.y)
r = Math.max(r, point.x)
b = Math.max(b, point.y)
rect = new Rect(l, t, r, b)
return (@getBB = -> rect)()
isPointInBB: (x, y, tolerance) ->
tolerance ?= 0
bb = @getBB()
if (0 < tolerance)
bb = clone(bb)
bb.inset(-tolerance, -tolerance)
!(x < bb.l || x > bb.r || y < bb.t || y > bb.b)
isPointOnBezier: (x, y, tolerance=0) ->
return false if !@isPointInBB(x, y, tolerance)
segments = @chordPoints()
p1 = segments[0].p
for i in [1...segments.length]
p2 = segments[i].p
x1 = p1.x
y1 = p1.y
x2 = p2.x
y2 = p2.y
bb = new Rect(x1, y1, x2, y2)
if bb.isPointInBB(x, y, tolerance)
twice_area = Math.abs(x1 * y2 + x2 * y + x * y1 - x2 * y1 - x * y2 - x1 * y)
base = p1.distanceFrom(p2)
height = twice_area / base
return true if height <= tolerance
p1 = p2
return false
# # Based on Oliver Steele's bezier.js library.
controlPolygonLength: ->
len = 0
for i in [1...@order]
len += @points[i - 1].distanceFrom(@points[i])
(@controlPolygonLength = -> len)()
# # Based on Oliver Steele's bezier.js library.
chordLength: ->
len = @points[0].distanceFrom(@points[@order - 1])
(@chordLength = -> len)()
# # From Oliver Steele's bezier.js library.
triangle: ->
upper = @points
m = [upper]
for i in [1...@order]
lower = []
for j in [0...(@order-i)]
c0 = upper[j]
c1 = upper[j + 1]
lower[j] = new Point((c0.x + c1.x) / 2, (c0.y + c1.y) / 2)
m.push(lower)
upper = lower
(@triangle = -> m)()
# # Based on Oliver Steele's bezier.js library.
triangleAtT: (t) ->
s = 1 - t
upper = @points
m = [upper]
for i in [1...@order]
lower = []
for j in [0...(@order-i)]
c0 = upper[j]
c1 = upper[j + 1]
lower[j] = new Point(c0.x * s + c1.x * t, c0.y * s + c1.y * t)
m.push(lower)
upper = lower
return m
# Returns two beziers resulting from splitting @bezier at t=0.5.
# Based on Oliver Steele's bezier.js library.
split: (t=0.5) ->
m = if (0.5 == t) then @triangle() else @triangleAtT(t)
leftPoints = new Array(@order)
rightPoints = new Array(@order)
for i in [1...@order]
leftPoints[i] = m[i][0]
rightPoints[i] = m[@order - 1 - i][i]
return {left: new Bezier(leftPoints), right: new Bezier(rightPoints)}
# Returns a bezier which is the portion of @bezier from t1 to t2.
# Thanks to PI:NAME:<NAME>END_PI on comp.graphics.algorithms.
mid: (t1, t2) ->
@split(t2).left.split(t1 / t2).right
# Returns points (and their corresponding times in the bezier) that form
# an approximate polygonal representation of the bezier.
# Based on the algorithm described in PI:NAME:<NAME>END_PI' dashed.ps.gz
chordPoints: ->
p = [{tStart: 0, tEnd: 0, dt: 0, p: @points[0]}].concat(@_chordPoints(0, 1))
(@chordPoints = -> p)()
_chordPoints: (tStart, tEnd) ->
tolerance = 0.001
dt = tEnd - tStart
if @controlPolygonLength() <= (1 + tolerance) * @chordLength()
return [{tStart: tStart, tEnd: tEnd, dt: dt, p: @points[@order - 1]}]
else
tMid = tStart + dt / 2
halves = @split()
return halves.left._chordPoints(tStart, tMid).concat(halves.right._chordPoints(tMid, tEnd))
# Returns an array of times between 0 and 1 that mark the bezier evenly
# in space.
# Based in part on the algorithm described in PI:NAME:<NAME>END_PI' dashed.ps.gz
markedEvery: (distance, firstDistance) ->
nextDistance = firstDistance || distance
segments = @chordPoints()
times = []
t = 0; # time
for i in [1...segments.length]
segment = segments[i]
segment.length = segment.p.distanceFrom(segments[i - 1].p)
if 0 == segment.length
t += segment.dt
else
dt = nextDistance / segment.length * segment.dt
segment.remainingLength = segment.length
while segment.remainingLength >= nextDistance
segment.remainingLength -= nextDistance
t += dt
times.push(t)
if distance != nextDistance
nextDistance = distance
dt = nextDistance / segment.length * segment.dt
nextDistance -= segment.remainingLength
t = segment.tEnd
return {times: times, nextDistance: nextDistance}
# Return the coefficients of the polynomials for x and y in t.
# From PI:NAME:<NAME>END_PI's bezier.js library.
coefficients: ->
# @function deals with polynomials, represented as
# arrays of coefficients. p[i] is the coefficient of n^i.
# p0, p1 => p0 + (p1 - p0) * n
# side-effects (denormalizes) p0, for convienence
interpolate = (p0, p1) ->
p0.push(0)
p = new Array(p0.length)
p[0] = p0[0]
for i in [0...p1.length]
p[i + 1] = p0[i + 1] + p1[i] - p0[i]
p
# folds +interpolate+ across a graph whose fringe is
# the polynomial elements of +ns+, and returns its TOP
collapse = (ns) ->
while ns.length > 1
ps = new Array(ns.length-1)
for i in [0...(ns.length-1)]
ps[i] = interpolate(ns[i], ns[i + 1])
ns = ps
return ns[0]
# xps and yps are arrays of polynomials --- concretely realized
# as arrays of arrays
xps = []
yps = []
for pt in @points
xps.push([pt.x])
yps.push([pt.y])
result = {xs: collapse(xps), ys: collapse(yps)}
return (@coefficients = ->result)()
# Return the point at time t.
# From PI:NAME:<NAME>END_PI's bezier.js library.
pointAtT: (t) ->
c = @coefficients()
[cx, cy] = [c.xs, c.ys]
# evaluate cx[0] + cx[1]t +cx[2]t^2 ....
# optimization: start from the end, to save one
# muliplicate per order (we never need an explicit t^n)
# optimization: special-case the last element
# to save a multiply-add
x = cx[cx.length - 1]; y = cy[cy.length - 1];
for i in [cx.length..0]
x = x * t + cx[i]
y = y * t + cy[i]
new Point(x, y)
# Render the Bezier to a WHATWG 2D canvas context.
# Based on Oliver Steele's bezier.js library.
makePath: (ctx, moveTo=true) ->
ctx.moveTo(@points[0].x, @points[0].y) if (moveTo)
fn = @pathCommands[@order]
if fn
coords = []
for i in [(if 1 == @order then 0 else 1)...@points.length]
coords.push(@points[i].x)
coords.push(@points[i].y)
fn.apply(ctx, coords)
# Wrapper functions to work around Safari, in which, up to at least 2.0.3,
# fn.apply isn't defined on the context primitives.
# Based on Oliver Steele's bezier.js library.
pathCommands: [
null,
# @will have an effect if there's a line thickness or end cap.
(x, y) -> @lineTo(x + 0.001, y)
(x, y) -> @lineTo(x, y)
(x1, y1, x2, y2) -> @quadraticCurveTo(x1, y1, x2, y2)
(x1, y1, x2, y2, x3, y3) -> @bezierCurveTo(x1, y1, x2, y2, x3, y3)
]
makeDashedPath: (ctx, dashLength, firstDistance, drawFirst=true) ->
firstDistance = dashLength if !firstDistance
markedEvery = @markedEvery(dashLength, firstDistance)
markedEvery.times.unshift(0) if (drawFirst)
drawLast = (markedEvery.times.length % 2)
markedEvery.times.push(1) if drawLast
for i in [1...(markedEvery.times.length)] by 2
@mid(markedEvery.times[i - 1], markedEvery.times[i]).makePath(ctx)
return {firstDistance: markedEvery.nextDistance, drawFirst: drawLast}
makeDottedPath: (ctx, dotSpacing, firstDistance) ->
firstDistance = dotSpacing if !firstDistance
markedEvery = @markedEvery(dotSpacing, firstDistance)
markedEvery.times.unshift(0) if dotSpacing == firstDistance
for t in markedEvery.times
@pointAtT(t).makePath(ctx)
return markedEvery.nextDistance
class Path
constructor: (@segments=[]) ->
setupSegments: ->
# Based on Oliver Steele's bezier.js library.
addBezier: (pointsOrBezier) ->
@segments.push(if pointsOrBezier instanceof Array then new Bezier(pointsOrBezier) else pointsOrBezier)
offset: (dx, dy) ->
@setupSegments() if 0 == @segments.length
for segment in @segments
segment.offset(dx, dy)
getBB: ->
@setupSegments() if 0 == @segments.length
p = @segments[0].points[0]
l = r = p.x
t = b = p.y
for segment in @segments
for point in segment.points
l = Math.min(l, point.x)
t = Math.min(t, point.y)
r = Math.max(r, point.x)
b = Math.max(b, point.y)
rect = new Rect(l, t, r, b);
return (@getBB = -> rect)()
isPointInBB: (x, y, tolerance=0) ->
bb = @getBB()
if 0 < tolerance
bb = clone(bb)
bb.inset(-tolerance, -tolerance)
return !(x < bb.l || x > bb.r || y < bb.t || y > bb.b)
isPointOnPath: (x, y, tolerance=0) ->
return false if !@isPointInBB(x, y, tolerance)
result = false;
for segment in @segments
if segment.isPointOnBezier(x, y, tolerance)
result = true
throw $break
return result
isPointInPath: (x, y) -> false
# Based on PI:NAME:<NAME>END_PI's bezier.js library.
makePath: (ctx) ->
@setupSegments() if 0 == @segments.length
moveTo = true
for segment in @segments
segment.makePath(ctx, moveTo)
moveTo = false
makeDashedPath: (ctx, dashLength, firstDistance, drawFirst) ->
@setupSegments() if 0 == @segments.length
info =
drawFirst: if !drawFirst? then true else drawFirst
firstDistance: firstDistance || dashLength
for segment in @segments
info = segment.makeDashedPath(ctx, dashLength, info.firstDistance, info.drawFirst)
makeDottedPath: (ctx, dotSpacing, firstDistance) ->
@setupSegments() if 0 == @segments.length
firstDistance = dotSpacing if !firstDistance
for segment in @segments
firstDistance = segment.makeDottedPath(ctx, dotSpacing, firstDistance)
class Polygon extends Path
constructor: (@points=[]) -> super()
setupSegments: ->
for p, i in @points
next = i + 1
next = 0 if @points.length == next
@addBezier([p, @points[next]])
class Rect extends Polygon
constructor: (@l, @t, @r, @b) -> super()
inset: (ix, iy) ->
@l += ix
@t += iy
@r -= ix
@b -= iy
return this
expandToInclude: (rect) ->
@l = Math.min(@l, rect.l)
@t = Math.min(@t, rect.t)
@r = Math.max(@r, rect.r)
@b = Math.max(@b, rect.b)
getWidth: -> @r - @l
getHeight: -> @b - @t
setupSegments: ->
w = @getWidth()
h = @getHeight()
@points = [
new Point(@l, @t)
new Point(@l + w, @t)
new Point(@l + w, @t + h)
new Point(@l, @t + h)
]
super()
class Ellipse extends Path
KAPPA: 0.5522847498,
constructor: (@cx, @cy, @rx, @ry) -> super()
setupSegments: ->
@addBezier([
new Point(@cx, @cy - @ry)
new Point(@cx + @KAPPA * @rx, @cy - @ry)
new Point(@cx + @rx, @cy - @KAPPA * @ry)
new Point(@cx + @rx, @cy)
])
@addBezier([
new Point(@cx + @rx, @cy)
new Point(@cx + @rx, @cy + @KAPPA * @ry)
new Point(@cx + @KAPPA * @rx, @cy + @ry)
new Point(@cx, @cy + @ry)
])
@addBezier([
new Point(@cx, @cy + @ry)
new Point(@cx - @KAPPA * @rx, @cy + @ry)
new Point(@cx - @rx, @cy + @KAPPA * @ry)
new Point(@cx - @rx, @cy)
]);
@addBezier([
new Point(@cx - @rx, @cy)
new Point(@cx - @rx, @cy - @KAPPA * @ry)
new Point(@cx - @KAPPA * @rx, @cy - @ry)
new Point(@cx, @cy - @ry)
])
escapeHTML = (str) ->
div = document.createElement('div')
div.appendChild(document.createTextNode(str))
div.innerHTML
debug = (str) ->
console.log str
clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
#/*
# * This file is part of Canviz. See http://www.canviz.org/
# * $Id: x11colors.js 246 2008-12-27 08:36:24Z ryandesign.com $
# */
Canviz.colors.x11 =
aliceblue:'f0f8ff'
antiquewhite:'faebd7'
antiquewhite1:'ffefdb'
antiquewhite2:'eedfcc'
antiquewhite3:'cdc0b0'
antiquewhite4:'8b8378'
aquamarine:'7fffd4'
aquamarine1:'7fffd4'
aquamarine2:'76eec6'
aquamarine3:'66cdaa'
aquamarine4:'458b74'
azure:'f0ffff'
azure1:'f0ffff'
azure2:'e0eeee'
azure3:'c1cdcd'
azure4:'838b8b'
beige:'f5f5dc'
bisque:'ffe4c4'
bisque1:'ffe4c4'
bisque2:'eed5b7'
bisque3:'cdb79e'
bisque4:'8b7d6b'
black:'000000'
blanchedalmond:'ffebcd'
blue:'0000ff'
blue1:'0000ff'
blue2:'0000ee'
blue3:'0000cd'
blue4:'00008b'
blueviolet:'8a2be2'
brown:'a52a2a'
brown1:'ff4040'
brown2:'ee3b3b'
brown3:'cd3333'
brown4:'8b2323'
burlywood:'deb887'
burlywood1:'ffd39b'
burlywood2:'eec591'
burlywood3:'cdaa7d'
burlywood4:'8b7355'
cadetblue:'5f9ea0'
cadetblue1:'98f5ff'
cadetblue2:'8ee5ee'
cadetblue3:'7ac5cd'
cadetblue4:'53868b'
chartreuse:'7fff00'
chartreuse1:'7fff00'
chartreuse2:'76ee00'
chartreuse3:'66cd00'
chartreuse4:'458b00'
chocolate:'d2691e'
chocolate1:'ff7f24'
chocolate2:'ee7621'
chocolate3:'cd661d'
chocolate4:'8b4513'
coral:'ff7f50'
coral1:'ff7256'
coral2:'ee6a50'
coral3:'cd5b45'
coral4:'8b3e2f'
cornflowerblue:'6495ed'
cornsilk:'fff8dc'
cornsilk1:'fff8dc'
cornsilk2:'eee8cd'
cornsilk3:'cdc8b1'
cornsilk4:'8b8878'
crimson:'dc143c'
cyan:'00ffff'
cyan1:'00ffff'
cyan2:'00eeee'
cyan3:'00cdcd'
cyan4:'008b8b'
darkgoldenrod:'b8860b'
darkgoldenrod1:'ffb90f'
darkgoldenrod2:'eead0e'
darkgoldenrod3:'cd950c'
darkgoldenrod4:'8b6508'
darkgreen:'006400'
darkkhaki:'bdb76b'
darkolivegreen:'556b2f'
darkolivegreen1:'caff70'
darkolivegreen2:'bcee68'
darkolivegreen3:'a2cd5a'
darkolivegreen4:'6e8b3d'
darkorange:'ff8c00'
darkorange1:'ff7f00'
darkorange2:'ee7600'
darkorange3:'cd6600'
darkorange4:'8b4500'
darkorchid:'9932cc'
darkorchid1:'bf3eff'
darkorchid2:'b23aee'
darkorchid3:'9a32cd'
darkorchid4:'68228b'
darksalmon:'e9967a'
darkseagreen:'8fbc8f'
darkseagreen1:'c1ffc1'
darkseagreen2:'b4eeb4'
darkseagreen3:'9bcd9b'
darkseagreen4:'698b69'
darkslateblue:'483d8b'
darkslategray:'2f4f4f'
darkslategray1:'97ffff'
darkslategray2:'8deeee'
darkslategray3:'79cdcd'
darkslategray4:'528b8b'
darkslategrey:'2f4f4f'
darkturquoise:'00ced1'
darkviolet:'9400d3'
deeppink:'ff1493'
deeppink1:'ff1493'
deeppink2:'ee1289'
deeppink3:'cd1076'
deeppink4:'8b0a50'
deepskyblue:'00bfff'
deepskyblue1:'00bfff'
deepskyblue2:'00b2ee'
deepskyblue3:'009acd'
deepskyblue4:'00688b'
dimgray:'696969'
dimgrey:'696969'
dodgerblue:'1e90ff'
dodgerblue1:'1e90ff'
dodgerblue2:'1c86ee'
dodgerblue3:'1874cd'
dodgerblue4:'104e8b'
firebrick:'b22222'
firebrick1:'ff3030'
firebrick2:'ee2c2c'
firebrick3:'cd2626'
firebrick4:'8b1a1a'
floralwhite:'fffaf0'
forestgreen:'228b22'
gainsboro:'dcdcdc'
ghostwhite:'f8f8ff'
gold:'ffd700'
gold1:'ffd700'
gold2:'eec900'
gold3:'cdad00'
gold4:'8b7500'
goldenrod:'daa520'
goldenrod1:'ffc125'
goldenrod2:'eeb422'
goldenrod3:'cd9b1d'
goldenrod4:'8b6914'
gray:'c0c0c0'
gray0:'000000'
gray1:'030303'
gray10:'1a1a1a'
gray100:'ffffff'
gray11:'1c1c1c'
gray12:'1f1f1f'
gray13:'212121'
gray14:'242424'
gray15:'262626'
gray16:'292929'
gray17:'2b2b2b'
gray18:'2e2e2e'
gray19:'303030'
gray2:'050505'
gray20:'333333'
gray21:'363636'
gray22:'383838'
gray23:'3b3b3b'
gray24:'3d3d3d'
gray25:'404040'
gray26:'424242'
gray27:'454545'
gray28:'474747'
gray29:'4a4a4a'
gray3:'080808'
gray30:'4d4d4d'
gray31:'4f4f4f'
gray32:'525252'
gray33:'545454'
gray34:'575757'
gray35:'595959'
gray36:'5c5c5c'
gray37:'5e5e5e'
gray38:'616161'
gray39:'636363'
gray4:'0a0a0a'
gray40:'666666'
gray41:'696969'
gray42:'6b6b6b'
gray43:'6e6e6e'
gray44:'707070'
gray45:'737373'
gray46:'757575'
gray47:'787878'
gray48:'7a7a7a'
gray49:'7d7d7d'
gray5:'0d0d0d'
gray50:'7f7f7f'
gray51:'828282'
gray52:'858585'
gray53:'878787'
gray54:'8a8a8a'
gray55:'8c8c8c'
gray56:'8f8f8f'
gray57:'919191'
gray58:'949494'
gray59:'969696'
gray6:'0f0f0f'
gray60:'999999'
gray61:'9c9c9c'
gray62:'9e9e9e'
gray63:'a1a1a1'
gray64:'a3a3a3'
gray65:'a6a6a6'
gray66:'a8a8a8'
gray67:'ababab'
gray68:'adadad'
gray69:'b0b0b0'
gray7:'121212'
gray70:'b3b3b3'
gray71:'b5b5b5'
gray72:'b8b8b8'
gray73:'bababa'
gray74:'bdbdbd'
gray75:'bfbfbf'
gray76:'c2c2c2'
gray77:'c4c4c4'
gray78:'c7c7c7'
gray79:'c9c9c9'
gray8:'141414'
gray80:'cccccc'
gray81:'cfcfcf'
gray82:'d1d1d1'
gray83:'d4d4d4'
gray84:'d6d6d6'
gray85:'d9d9d9'
gray86:'dbdbdb'
gray87:'dedede'
gray88:'e0e0e0'
gray89:'e3e3e3'
gray9:'171717'
gray90:'e5e5e5'
gray91:'e8e8e8'
gray92:'ebebeb'
gray93:'ededed'
gray94:'f0f0f0'
gray95:'f2f2f2'
gray96:'f5f5f5'
gray97:'f7f7f7'
gray98:'fafafa'
gray99:'fcfcfc'
green:'00ff00'
green1:'00ff00'
green2:'00ee00'
green3:'00cd00'
green4:'008b00'
greenyellow:'adff2f'
grey:'c0c0c0'
grey0:'000000'
grey1:'030303'
grey10:'1a1a1a'
grey100:'ffffff'
grey11:'1c1c1c'
grey12:'1f1f1f'
grey13:'212121'
grey14:'242424'
grey15:'262626'
grey16:'292929'
grey17:'2b2b2b'
grey18:'2e2e2e'
grey19:'303030'
grey2:'050505'
grey20:'333333'
grey21:'363636'
grey22:'383838'
grey23:'3b3b3b'
grey24:'3d3d3d'
grey25:'404040'
grey26:'424242'
grey27:'454545'
grey28:'474747'
grey29:'4a4a4a'
grey3:'080808'
grey30:'4d4d4d'
grey31:'4f4f4f'
grey32:'525252'
grey33:'545454'
grey34:'575757'
grey35:'595959'
grey36:'5c5c5c'
grey37:'5e5e5e'
grey38:'616161'
grey39:'636363'
grey4:'0a0a0a'
grey40:'666666'
grey41:'696969'
grey42:'6b6b6b'
grey43:'6e6e6e'
grey44:'707070'
grey45:'737373'
grey46:'757575'
grey47:'787878'
grey48:'7a7a7a'
grey49:'7d7d7d'
grey5:'0d0d0d'
grey50:'7f7f7f'
grey51:'828282'
grey52:'858585'
grey53:'878787'
grey54:'8a8a8a'
grey55:'8c8c8c'
grey56:'8f8f8f'
grey57:'919191'
grey58:'949494'
grey59:'969696'
grey6:'0f0f0f'
grey60:'999999'
grey61:'9c9c9c'
grey62:'9e9e9e'
grey63:'a1a1a1'
grey64:'a3a3a3'
grey65:'a6a6a6'
grey66:'a8a8a8'
grey67:'ababab'
grey68:'adadad'
grey69:'b0b0b0'
grey7:'121212'
grey70:'b3b3b3'
grey71:'b5b5b5'
grey72:'b8b8b8'
grey73:'bababa'
grey74:'bdbdbd'
grey75:'bfbfbf'
grey76:'c2c2c2'
grey77:'c4c4c4'
grey78:'c7c7c7'
grey79:'c9c9c9'
grey8:'141414'
grey80:'cccccc'
grey81:'cfcfcf'
grey82:'d1d1d1'
grey83:'d4d4d4'
grey84:'d6d6d6'
grey85:'d9d9d9'
grey86:'dbdbdb'
grey87:'dedede'
grey88:'e0e0e0'
grey89:'e3e3e3'
grey9:'171717'
grey90:'e5e5e5'
grey91:'e8e8e8'
grey92:'ebebeb'
grey93:'ededed'
grey94:'f0f0f0'
grey95:'f2f2f2'
grey96:'f5f5f5'
grey97:'f7f7f7'
grey98:'fafafa'
grey99:'fcfcfc'
honeydew:'f0fff0'
honeydew1:'f0fff0'
honeydew2:'e0eee0'
honeydew3:'c1cdc1'
honeydew4:'838b83'
hotpink:'ff69b4'
hotpink1:'ff6eb4'
hotpink2:'ee6aa7'
hotpink3:'cd6090'
hotpink4:'8b3a62'
indianred:'cd5c5c'
indianred1:'ff6a6a'
indianred2:'ee6363'
indianred3:'cd5555'
indianred4:'8b3a3a'
indigo:'4b0082'
invis:'fffffe00'
ivory:'fffff0'
ivory1:'fffff0'
ivory2:'eeeee0'
ivory3:'cdcdc1'
ivory4:'8b8b83'
khaki:'f0e68c'
khaki1:'fff68f'
khaki2:'eee685'
khaki3:'cdc673'
khaki4:'8b864e'
lavender:'e6e6fa'
lavenderblush:'fff0f5'
lavenderblush1:'fff0f5'
lavenderblush2:'eee0e5'
lavenderblush3:'cdc1c5'
lavenderblush4:'8b8386'
lawngreen:'7cfc00'
lemonchiffon:'fffacd'
lemonchiffon1:'fffacd'
lemonchiffon2:'eee9bf'
lemonchiffon3:'cdc9a5'
lemonchiffon4:'8b8970'
lightblue:'add8e6'
lightblue1:'bfefff'
lightblue2:'b2dfee'
lightblue3:'9ac0cd'
lightblue4:'68838b'
lightcoral:'f08080'
lightcyan:'e0ffff'
lightcyan1:'e0ffff'
lightcyan2:'d1eeee'
lightcyan3:'b4cdcd'
lightcyan4:'7a8b8b'
lightgoldenrod:'eedd82'
lightgoldenrod1:'ffec8b'
lightgoldenrod2:'eedc82'
lightgoldenrod3:'cdbe70'
lightgoldenrod4:'8b814c'
lightgoldenrodyellow:'fafad2'
lightgray:'d3d3d3'
lightgrey:'d3d3d3'
lightpink:'ffb6c1'
lightpink1:'ffaeb9'
lightpink2:'eea2ad'
lightpink3:'cd8c95'
lightpink4:'8b5f65'
lightsalmon:'ffa07a'
lightsalmon1:'ffa07a'
lightsalmon2:'ee9572'
lightsalmon3:'cd8162'
lightsalmon4:'8b5742'
lightseagreen:'20b2aa'
lightskyblue:'87cefa'
lightskyblue1:'b0e2ff'
lightskyblue2:'a4d3ee'
lightskyblue3:'8db6cd'
lightskyblue4:'607b8b'
lightslateblue:'8470ff'
lightslategray:'778899'
lightslategrey:'778899'
lightsteelblue:'b0c4de'
lightsteelblue1:'cae1ff'
lightsteelblue2:'bcd2ee'
lightsteelblue3:'a2b5cd'
lightsteelblue4:'6e7b8b'
lightyellow:'ffffe0'
lightyellow1:'ffffe0'
lightyellow2:'eeeed1'
lightyellow3:'cdcdb4'
lightyellow4:'8b8b7a'
limegreen:'32cd32'
linen:'faf0e6'
magenta:'ff00ff'
magenta1:'ff00ff'
magenta2:'ee00ee'
magenta3:'cd00cd'
magenta4:'8b008b'
maroon:'b03060'
maroon1:'ff34b3'
maroon2:'ee30a7'
maroon3:'cd2990'
maroon4:'8b1c62'
mediumaquamarine:'66cdaa'
mediumblue:'0000cd'
mediumorchid:'ba55d3'
mediumorchid1:'e066ff'
mediumorchid2:'d15fee'
mediumorchid3:'b452cd'
mediumorchid4:'7a378b'
mediumpurple:'9370db'
mediumpurple1:'ab82ff'
mediumpurple2:'9f79ee'
mediumpurple3:'8968cd'
mediumpurple4:'5d478b'
mediumseagreen:'3cb371'
mediumslateblue:'7b68ee'
mediumspringgreen:'00fa9a'
mediumturquoise:'48d1cc'
mediumvioletred:'c71585'
midnightblue:'191970'
mintcream:'f5fffa'
mistyrose:'ffe4e1'
mistyrose1:'ffe4e1'
mistyrose2:'eed5d2'
mistyrose3:'cdb7b5'
mistyrose4:'8b7d7b'
moccasin:'ffe4b5'
navajowhite:'ffdead'
navajowhite1:'ffdead'
navajowhite2:'eecfa1'
navajowhite3:'cdb38b'
navajowhite4:'8b795e'
navy:'000080'
navyblue:'000080'
none:'fffffe00'
oldlace:'fdf5e6'
olivedrab:'6b8e23'
olivedrab1:'c0ff3e'
olivedrab2:'b3ee3a'
olivedrab3:'9acd32'
olivedrab4:'698b22'
orange:'ffa500'
orange1:'ffa500'
orange2:'ee9a00'
orange3:'cd8500'
orange4:'8b5a00'
orangered:'ff4500'
orangered1:'ff4500'
orangered2:'ee4000'
orangered3:'cd3700'
orangered4:'8b2500'
orchid:'da70d6'
orchid1:'ff83fa'
orchid2:'ee7ae9'
orchid3:'cd69c9'
orchid4:'8b4789'
palegoldenrod:'eee8aa'
palegreen:'98fb98'
palegreen1:'9aff9a'
palegreen2:'90ee90'
palegreen3:'7ccd7c'
palegreen4:'548b54'
paleturquoise:'afeeee'
paleturquoise1:'bbffff'
paleturquoise2:'aeeeee'
paleturquoise3:'96cdcd'
paleturquoise4:'668b8b'
palevioletred:'db7093'
palevioletred1:'ff82ab'
palevioletred2:'ee799f'
palevioletred3:'cd6889'
palevioletred4:'8b475d'
papayawhip:'ffefd5'
peachpuff:'ffdab9'
peachpuff1:'ffdab9'
peachpuff2:'eecbad'
peachpuff3:'cdaf95'
peachpuff4:'8b7765'
peru:'cd853f'
pink:'ffc0cb'
pink1:'ffb5c5'
pink2:'eea9b8'
pink3:'cd919e'
pink4:'8b636c'
plum:'dda0dd'
plum1:'ffbbff'
plum2:'eeaeee'
plum3:'cd96cd'
plum4:'8b668b'
powderblue:'b0e0e6'
purple:'a020f0'
purple1:'9b30ff'
purple2:'912cee'
purple3:'7d26cd'
purple4:'551a8b'
red:'ff0000'
red1:'ff0000'
red2:'ee0000'
red3:'cd0000'
red4:'8b0000'
rosybrown:'bc8f8f'
rosybrown1:'ffc1c1'
rosybrown2:'eeb4b4'
rosybrown3:'cd9b9b'
rosybrown4:'8b6969'
royalblue:'4169e1'
royalblue1:'4876ff'
royalblue2:'436eee'
royalblue3:'3a5fcd'
royalblue4:'27408b'
saddlebrown:'8b4513'
salmon:'fa8072'
salmon1:'ff8c69'
salmon2:'ee8262'
salmon3:'cd7054'
salmon4:'8b4c39'
sandybrown:'f4a460'
seagreen:'2e8b57'
seagreen1:'54ff9f'
seagreen2:'4eee94'
seagreen3:'43cd80'
seagreen4:'2e8b57'
seashell:'fff5ee'
seashell1:'fff5ee'
seashell2:'eee5de'
seashell3:'cdc5bf'
seashell4:'8b8682'
sienna:'a0522d'
sienna1:'ff8247'
sienna2:'ee7942'
sienna3:'cd6839'
sienna4:'8b4726'
skyblue:'87ceeb'
skyblue1:'87ceff'
skyblue2:'7ec0ee'
skyblue3:'6ca6cd'
skyblue4:'4a708b'
slateblue:'6a5acd'
slateblue1:'836fff'
slateblue2:'7a67ee'
slateblue3:'6959cd'
slateblue4:'473c8b'
slategray:'708090'
slategray1:'c6e2ff'
slategray2:'b9d3ee'
slategray3:'9fb6cd'
slategray4:'6c7b8b'
slategrey:'708090'
snow:'fffafa'
snow1:'fffafa'
snow2:'eee9e9'
snow3:'cdc9c9'
snow4:'8b8989'
springgreen:'00ff7f'
springgreen1:'00ff7f'
springgreen2:'00ee76'
springgreen3:'00cd66'
springgreen4:'008b45'
steelblue:'4682b4'
steelblue1:'63b8ff'
steelblue2:'5cacee'
steelblue3:'4f94cd'
steelblue4:'36648b'
tan:'d2b48c'
tan1:'ffa54f'
tan2:'ee9a49'
tan3:'cd853f'
tan4:'8b5a2b'
thistle:'d8bfd8'
thistle1:'ffe1ff'
thistle2:'eed2ee'
thistle3:'cdb5cd'
thistle4:'8b7b8b'
tomato:'ff6347'
tomato1:'ff6347'
tomato2:'ee5c42'
tomato3:'cd4f39'
tomato4:'8b3626'
transparent:'fffffe00'
turquoise:'40e0d0'
turquoise1:'00f5ff'
turquoise2:'00e5ee'
turquoise3:'00c5cd'
turquoise4:'00868b'
violet:'ee82ee'
violetred:'d02090'
violetred1:'ff3e96'
violetred2:'ee3a8c'
violetred3:'cd3278'
violetred4:'8b2252'
wheat:'f5deb3'
wheat1:'ffe7ba'
wheat2:'eed8ae'
wheat3:'cdba96'
wheat4:'8b7e66'
white:'ffffff'
whitesmoke:'f5f5f5'
yellow:'ffff00'
yellow1:'ffff00'
yellow2:'eeee00'
yellow3:'cdcd00'
yellow4:'8b8b00'
yellowgreen:'9acd32'
window.Canviz = Canviz
|
[
{
"context": "vel\nlevels.level_middle =\n\n type: 'Map'\n name: 'middle'\n x: 0\n y: 0\n width: 300\n height: 200\n\n offs",
"end": 67,
"score": 0.6779714226722717,
"start": 61,
"tag": "NAME",
"value": "middle"
}
] | js/coffee/level_middle.coffee | wjagodfrey/spaceJoust | 0 | # middle level
levels.level_middle =
type: 'Map'
name: 'middle'
x: 0
y: 0
width: 300
height: 200
offsetX: 0
offsetY: 0
winner: ''
render: cq()
onEnd: (type) -> #WIP
console.log 'ENDS'
onBuild: ->
vars = {}
# Foreground
# @foreground = {}
# Midground
@midground =
# EDGES
top: new entity.Boundary 0, 0, 300, 4
bottom: new entity.Boundary 0, 196, 300, 4
left: new entity.Boundary 0, 0, 4, 200
right: new entity.Boundary 296, 0, 4, 200
# SPAWNS
# red
spawn_red: new entity.PlayerSpawn 50, 52, 'Red'
# blue
spawn_blue: new entity.PlayerSpawn 230, 52, 'Blue'
# BOUNDARIES
row1_left: new entity.Boundary 40, 55, 60, 4
row1_right: new entity.Boundary 200, 55, 60, 4
row1_barrier_middle: new entity.Boundary 148, 50, 4, 25
row1_barrier_right: new entity.Boundary 200, 59, 4, 15
row1_barrier_left: new entity.Boundary 96, 59, 4, 15
row2_middle: new entity.Boundary 115, 110, 70, 4
row2_left: new entity.Boundary 30, 110, 50, 4
row2_right: new entity.Boundary 220, 110, 50, 4
# LASERS AND BUTTONS
# top laser/button combo
laser_1_right: new entity.Laser 152, 55, 48, 15, false, '#21b2b4'
laser_1_left: new entity.Laser 100, 55, 48, 15, false, '#21b2b4'
laser_1_button: new entity.Button 148, 108
, ->
level.midground.laser_1_right.on = true
level.midground.laser_1_left.on = true
, ->
level.midground.laser_1_right.on = false
level.midground.laser_1_left.on = false
, true, '#21b2b4'
# top laser/button combo
laser_2_middle: new entity.Laser 148, 4, 4, 46, false
laser_2_right_button: new entity.Button 204, 53
, ->
vars.laser_2_right_button =
level.midground.laser_2_middle.on = true
, ->
vars.laser_2_right_button = false
if !vars.laser_2_left_button
level.midground.laser_2_middle.on = false
, true
laser_2_left_button: new entity.Button 92, 53
, ->
vars.laser_2_left_button =
level.midground.laser_2_middle.on = true
, ->
vars.laser_2_left_button = false
if !vars.laser_2_right_button
level.midground.laser_2_middle.on = false
, true
slime: new entity.Slime @, 23
# Item Spawner
@spawner = new Item_Spawner(@midground, [
'Bomb'
['Bomb', true, false],
['Bomb', false, true],
['Bomb', true, true]
'NoWingsEnemy'
'AddLife'
], @width, @height, 10)
for i, source of [players, @midground, @foreground]
for ii, ent of source
ent?.onBuild?(@)
shake:
shaking: false
speed: 3
dir:
x: 1
y: 1
dist:
x: 6
y: 3
timeout: {}
start: (duration = 300) ->
@timeout?()
@shaking = true
@timeout = setFrameTimeout =>
@shaking = false
, duration
update: ->
if @shaking
if Math.abs(level.offsetX) >= @dist.x
@dir.x *= -1
if Math.abs(level.offsetY) >= @dist.y
@dir.y *= -1
level.offsetX += @speed * @dir.x
level.offsetY += @speed * @dir.y
else
level.offsetX = 0
level.offsetY = 0
blinkUpdates: []
addBlinkUpdate: (x, y, text, red) ->
@blinkUpdates.push
x: Math.round(x)
y: Math.round(y)
text: text
alpha: 1
red: red
container: @blinkUpdates
update: ->
@y -= 0.8
@alpha -= 0.02
if @alpha <= 0
@container.splice(
@container.indexOf(@)
1
)
draw: (ctx) ->
ctx
.save()
.globalAlpha(@alpha)
.font('Helvetica')
.textBaseline('top')
.textAlign('center')
.fillStyle(if @red then '#e00005' else '#79df06')
.fillText(@text, @x, @y)
.restore()
update: ->
@render.canvas.width = @width
@render.canvas.height = @height
if players.blue.lives is 0 then @winner = 'Red'
if players.red.lives is 0 then @winner = 'Blue'
if players.red.lives is 0 and players.blue.lives is 0
@winner = 'draw'
level.shake.update()
for update in @blinkUpdates
update?.update()
drawBackground: ->
@render
.save()
.fillStyle('#383838')
.fillRect(0,0, @width,@height)
.restore()
drawMidground: ->
@render
.save()
for i, ent of @midground
ent.update?()
ent.draw?(@render)
@render.restore()
drawForeground: ->
@render
.save()
for i, ent of @foreground
ent.update?()
ent.draw?(@render)
@render.restore()
for update in @blinkUpdates
update.draw @render
reset: ->
console.log @
for name, ent of @midground
delete @midground
delete @spawner
clearFrameTimeouts()
@winner = ''
@shake.shaking = false
@onBuild() | 99574 | # middle level
levels.level_middle =
type: 'Map'
name: '<NAME>'
x: 0
y: 0
width: 300
height: 200
offsetX: 0
offsetY: 0
winner: ''
render: cq()
onEnd: (type) -> #WIP
console.log 'ENDS'
onBuild: ->
vars = {}
# Foreground
# @foreground = {}
# Midground
@midground =
# EDGES
top: new entity.Boundary 0, 0, 300, 4
bottom: new entity.Boundary 0, 196, 300, 4
left: new entity.Boundary 0, 0, 4, 200
right: new entity.Boundary 296, 0, 4, 200
# SPAWNS
# red
spawn_red: new entity.PlayerSpawn 50, 52, 'Red'
# blue
spawn_blue: new entity.PlayerSpawn 230, 52, 'Blue'
# BOUNDARIES
row1_left: new entity.Boundary 40, 55, 60, 4
row1_right: new entity.Boundary 200, 55, 60, 4
row1_barrier_middle: new entity.Boundary 148, 50, 4, 25
row1_barrier_right: new entity.Boundary 200, 59, 4, 15
row1_barrier_left: new entity.Boundary 96, 59, 4, 15
row2_middle: new entity.Boundary 115, 110, 70, 4
row2_left: new entity.Boundary 30, 110, 50, 4
row2_right: new entity.Boundary 220, 110, 50, 4
# LASERS AND BUTTONS
# top laser/button combo
laser_1_right: new entity.Laser 152, 55, 48, 15, false, '#21b2b4'
laser_1_left: new entity.Laser 100, 55, 48, 15, false, '#21b2b4'
laser_1_button: new entity.Button 148, 108
, ->
level.midground.laser_1_right.on = true
level.midground.laser_1_left.on = true
, ->
level.midground.laser_1_right.on = false
level.midground.laser_1_left.on = false
, true, '#21b2b4'
# top laser/button combo
laser_2_middle: new entity.Laser 148, 4, 4, 46, false
laser_2_right_button: new entity.Button 204, 53
, ->
vars.laser_2_right_button =
level.midground.laser_2_middle.on = true
, ->
vars.laser_2_right_button = false
if !vars.laser_2_left_button
level.midground.laser_2_middle.on = false
, true
laser_2_left_button: new entity.Button 92, 53
, ->
vars.laser_2_left_button =
level.midground.laser_2_middle.on = true
, ->
vars.laser_2_left_button = false
if !vars.laser_2_right_button
level.midground.laser_2_middle.on = false
, true
slime: new entity.Slime @, 23
# Item Spawner
@spawner = new Item_Spawner(@midground, [
'Bomb'
['Bomb', true, false],
['Bomb', false, true],
['Bomb', true, true]
'NoWingsEnemy'
'AddLife'
], @width, @height, 10)
for i, source of [players, @midground, @foreground]
for ii, ent of source
ent?.onBuild?(@)
shake:
shaking: false
speed: 3
dir:
x: 1
y: 1
dist:
x: 6
y: 3
timeout: {}
start: (duration = 300) ->
@timeout?()
@shaking = true
@timeout = setFrameTimeout =>
@shaking = false
, duration
update: ->
if @shaking
if Math.abs(level.offsetX) >= @dist.x
@dir.x *= -1
if Math.abs(level.offsetY) >= @dist.y
@dir.y *= -1
level.offsetX += @speed * @dir.x
level.offsetY += @speed * @dir.y
else
level.offsetX = 0
level.offsetY = 0
blinkUpdates: []
addBlinkUpdate: (x, y, text, red) ->
@blinkUpdates.push
x: Math.round(x)
y: Math.round(y)
text: text
alpha: 1
red: red
container: @blinkUpdates
update: ->
@y -= 0.8
@alpha -= 0.02
if @alpha <= 0
@container.splice(
@container.indexOf(@)
1
)
draw: (ctx) ->
ctx
.save()
.globalAlpha(@alpha)
.font('Helvetica')
.textBaseline('top')
.textAlign('center')
.fillStyle(if @red then '#e00005' else '#79df06')
.fillText(@text, @x, @y)
.restore()
update: ->
@render.canvas.width = @width
@render.canvas.height = @height
if players.blue.lives is 0 then @winner = 'Red'
if players.red.lives is 0 then @winner = 'Blue'
if players.red.lives is 0 and players.blue.lives is 0
@winner = 'draw'
level.shake.update()
for update in @blinkUpdates
update?.update()
drawBackground: ->
@render
.save()
.fillStyle('#383838')
.fillRect(0,0, @width,@height)
.restore()
drawMidground: ->
@render
.save()
for i, ent of @midground
ent.update?()
ent.draw?(@render)
@render.restore()
drawForeground: ->
@render
.save()
for i, ent of @foreground
ent.update?()
ent.draw?(@render)
@render.restore()
for update in @blinkUpdates
update.draw @render
reset: ->
console.log @
for name, ent of @midground
delete @midground
delete @spawner
clearFrameTimeouts()
@winner = ''
@shake.shaking = false
@onBuild() | true | # middle level
levels.level_middle =
type: 'Map'
name: 'PI:NAME:<NAME>END_PI'
x: 0
y: 0
width: 300
height: 200
offsetX: 0
offsetY: 0
winner: ''
render: cq()
onEnd: (type) -> #WIP
console.log 'ENDS'
onBuild: ->
vars = {}
# Foreground
# @foreground = {}
# Midground
@midground =
# EDGES
top: new entity.Boundary 0, 0, 300, 4
bottom: new entity.Boundary 0, 196, 300, 4
left: new entity.Boundary 0, 0, 4, 200
right: new entity.Boundary 296, 0, 4, 200
# SPAWNS
# red
spawn_red: new entity.PlayerSpawn 50, 52, 'Red'
# blue
spawn_blue: new entity.PlayerSpawn 230, 52, 'Blue'
# BOUNDARIES
row1_left: new entity.Boundary 40, 55, 60, 4
row1_right: new entity.Boundary 200, 55, 60, 4
row1_barrier_middle: new entity.Boundary 148, 50, 4, 25
row1_barrier_right: new entity.Boundary 200, 59, 4, 15
row1_barrier_left: new entity.Boundary 96, 59, 4, 15
row2_middle: new entity.Boundary 115, 110, 70, 4
row2_left: new entity.Boundary 30, 110, 50, 4
row2_right: new entity.Boundary 220, 110, 50, 4
# LASERS AND BUTTONS
# top laser/button combo
laser_1_right: new entity.Laser 152, 55, 48, 15, false, '#21b2b4'
laser_1_left: new entity.Laser 100, 55, 48, 15, false, '#21b2b4'
laser_1_button: new entity.Button 148, 108
, ->
level.midground.laser_1_right.on = true
level.midground.laser_1_left.on = true
, ->
level.midground.laser_1_right.on = false
level.midground.laser_1_left.on = false
, true, '#21b2b4'
# top laser/button combo
laser_2_middle: new entity.Laser 148, 4, 4, 46, false
laser_2_right_button: new entity.Button 204, 53
, ->
vars.laser_2_right_button =
level.midground.laser_2_middle.on = true
, ->
vars.laser_2_right_button = false
if !vars.laser_2_left_button
level.midground.laser_2_middle.on = false
, true
laser_2_left_button: new entity.Button 92, 53
, ->
vars.laser_2_left_button =
level.midground.laser_2_middle.on = true
, ->
vars.laser_2_left_button = false
if !vars.laser_2_right_button
level.midground.laser_2_middle.on = false
, true
slime: new entity.Slime @, 23
# Item Spawner
@spawner = new Item_Spawner(@midground, [
'Bomb'
['Bomb', true, false],
['Bomb', false, true],
['Bomb', true, true]
'NoWingsEnemy'
'AddLife'
], @width, @height, 10)
for i, source of [players, @midground, @foreground]
for ii, ent of source
ent?.onBuild?(@)
shake:
shaking: false
speed: 3
dir:
x: 1
y: 1
dist:
x: 6
y: 3
timeout: {}
start: (duration = 300) ->
@timeout?()
@shaking = true
@timeout = setFrameTimeout =>
@shaking = false
, duration
update: ->
if @shaking
if Math.abs(level.offsetX) >= @dist.x
@dir.x *= -1
if Math.abs(level.offsetY) >= @dist.y
@dir.y *= -1
level.offsetX += @speed * @dir.x
level.offsetY += @speed * @dir.y
else
level.offsetX = 0
level.offsetY = 0
blinkUpdates: []
addBlinkUpdate: (x, y, text, red) ->
@blinkUpdates.push
x: Math.round(x)
y: Math.round(y)
text: text
alpha: 1
red: red
container: @blinkUpdates
update: ->
@y -= 0.8
@alpha -= 0.02
if @alpha <= 0
@container.splice(
@container.indexOf(@)
1
)
draw: (ctx) ->
ctx
.save()
.globalAlpha(@alpha)
.font('Helvetica')
.textBaseline('top')
.textAlign('center')
.fillStyle(if @red then '#e00005' else '#79df06')
.fillText(@text, @x, @y)
.restore()
update: ->
@render.canvas.width = @width
@render.canvas.height = @height
if players.blue.lives is 0 then @winner = 'Red'
if players.red.lives is 0 then @winner = 'Blue'
if players.red.lives is 0 and players.blue.lives is 0
@winner = 'draw'
level.shake.update()
for update in @blinkUpdates
update?.update()
drawBackground: ->
@render
.save()
.fillStyle('#383838')
.fillRect(0,0, @width,@height)
.restore()
drawMidground: ->
@render
.save()
for i, ent of @midground
ent.update?()
ent.draw?(@render)
@render.restore()
drawForeground: ->
@render
.save()
for i, ent of @foreground
ent.update?()
ent.draw?(@render)
@render.restore()
for update in @blinkUpdates
update.draw @render
reset: ->
console.log @
for name, ent of @midground
delete @midground
delete @spawner
clearFrameTimeouts()
@winner = ''
@shake.shaking = false
@onBuild() |
[
{
"context": "export default\n name: 'Uranus'\n type: 'planet'\n radius: 25362\n mass: 86.8103",
"end": 30,
"score": 0.9996359348297119,
"start": 24,
"tag": "NAME",
"value": "Uranus"
},
{
"context": "04240589}\n satellites:\n titania:\n name: 'Titania'\n type: 'moon... | src/data/bodies/uranus.coffee | skepticalimagination/solaris-model | 5 | export default
name: 'Uranus'
type: 'planet'
radius: 25362
mass: 86.8103e24
tilt: 97.86
elements:
format: 'jpl-1800-2050'
base: {a: 19.18916464, e: 0.04725744, i: 0.77263783, L: 313.23810451, lp: 170.95427630, node: 74.01692503}
cy: {a: -0.00196176, e: -0.00004397, i: -0.00242939, L: 428.48202785, lp: 0.40805281, node: 0.04240589}
satellites:
titania:
name: 'Titania'
type: 'moon'
radius: 788.9
mass: 35.27e20
elements:
format: 'jpl-satellites-table'
base: {a: 436300, e: 0.0011, i: 0.079, L: 408.785, lp: 384.171, node: 99.771}
day: {M: 41.3514246}
| 53714 | export default
name: '<NAME>'
type: 'planet'
radius: 25362
mass: 86.8103e24
tilt: 97.86
elements:
format: 'jpl-1800-2050'
base: {a: 19.18916464, e: 0.04725744, i: 0.77263783, L: 313.23810451, lp: 170.95427630, node: 74.01692503}
cy: {a: -0.00196176, e: -0.00004397, i: -0.00242939, L: 428.48202785, lp: 0.40805281, node: 0.04240589}
satellites:
titania:
name: '<NAME>'
type: 'moon'
radius: 788.9
mass: 35.27e20
elements:
format: 'jpl-satellites-table'
base: {a: 436300, e: 0.0011, i: 0.079, L: 408.785, lp: 384.171, node: 99.771}
day: {M: 41.3514246}
| true | export default
name: 'PI:NAME:<NAME>END_PI'
type: 'planet'
radius: 25362
mass: 86.8103e24
tilt: 97.86
elements:
format: 'jpl-1800-2050'
base: {a: 19.18916464, e: 0.04725744, i: 0.77263783, L: 313.23810451, lp: 170.95427630, node: 74.01692503}
cy: {a: -0.00196176, e: -0.00004397, i: -0.00242939, L: 428.48202785, lp: 0.40805281, node: 0.04240589}
satellites:
titania:
name: 'PI:NAME:<NAME>END_PI'
type: 'moon'
radius: 788.9
mass: 35.27e20
elements:
format: 'jpl-satellites-table'
base: {a: 436300, e: 0.0011, i: 0.079, L: 408.785, lp: 384.171, node: 99.771}
day: {M: 41.3514246}
|
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998855590820312,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/resources.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/resources.coffee
###
taiga = @.taiga
class ResourcesService extends taiga.Service
urls = {
"auth": "/auth"
"auth-register": "/auth/register"
"invitations": "/invitations"
"permissions": "/permissions"
"roles": "/roles"
"projects": "/projects"
"memberships": "/memberships"
"notify-policies": "/notify-policies"
"bulk-create-memberships": "/memberships/bulk_create"
"milestones": "/milestones"
"userstories": "/userstories"
"bulk-create-us": "/userstories/bulk_create"
"bulk-update-us-backlog-order": "/userstories/bulk_update_backlog_order"
"bulk-update-us-sprint-order": "/userstories/bulk_update_sprint_order"
"bulk-update-us-kanban-order": "/userstories/bulk_update_kanban_order"
"userstories-restore": "/userstories/%s/restore"
"tasks": "/tasks"
"bulk-create-tasks": "/tasks/bulk_create"
"bulk-update-task-taskboard-order": "/tasks/bulk_update_taskboard_order"
"tasks-restore": "/tasks/%s/restore"
"issues": "/issues"
"bulk-create-issues": "/issues/bulk_create"
"issues-restore": "/issues/%s/restore"
"wiki": "/wiki"
"wiki-restore": "/wiki/%s/restore"
"wiki-links": "/wiki-links"
"choices/userstory-statuses": "/userstory-statuses"
"choices/userstory-statuses/bulk-update-order": "/userstory-statuses/bulk_update_order"
"choices/points": "/points"
"choices/points/bulk-update-order": "/points/bulk_update_order"
"choices/task-statuses": "/task-statuses"
"choices/task-statuses/bulk-update-order": "/task-statuses/bulk_update_order"
"choices/issue-statuses": "/issue-statuses"
"choices/issue-statuses/bulk-update-order": "/issue-statuses/bulk_update_order"
"choices/issue-types": "/issue-types"
"choices/issue-types/bulk-update-order": "/issue-types/bulk_update_order"
"choices/priorities": "/priorities"
"choices/priorities/bulk-update-order": "/priorities/bulk_update_order"
"choices/severities": "/severities"
"choices/severities/bulk-update-order": "/severities/bulk_update_order"
"search": "/search"
"sites": "/sites"
"project-templates": "/project-templates"
"site-members": "/site-members"
"site-projects": "/site-projects"
"users": "/users"
"users-password-recovery": "/users/password_recovery"
"users-change-password-from-recovery": "/users/change_password_from_recovery"
"users-change-password": "/users/change_password"
"users-change-email": "/users/change_email"
"users-cancel-account": "/users/cancel"
"user-storage": "/user-storage"
"resolver": "/resolver"
"userstory-statuses": "/userstory-statuses"
"points": "/points"
"task-statuses": "/task-statuses"
"issue-statuses": "/issue-statuses"
"issue-types": "/issue-types"
"priorities": "/priorities"
"severities": "/severities"
"project-modules": "/projects/%s/modules"
# History
"history/us": "/history/userstory"
"history/issue": "/history/issue"
"history/task": "/history/task"
"history/wiki": "/history/wiki"
# Attachments
"attachments/us": "/userstories/attachments"
"attachments/issue": "/issues/attachments"
"attachments/task": "/tasks/attachments"
"attachments/wiki_page": "/wiki/attachments"
# Feedback
"feedback": "/feedback"
}
# Initialize api urls service
initUrls = ($log, $urls) ->
$log.debug "Initialize api urls"
$urls.update(urls)
# Initialize resources service populating it with methods
# defined in separated files.
initResources = ($log, $rs) ->
$log.debug "Initialize resources"
providers = _.toArray(arguments).slice(2)
for provider in providers
provider($rs)
module = angular.module("taigaResources", ["taigaBase"])
module.service("$tgResources", ResourcesService)
# Module entry point
module.run(["$log", "$tgUrls", initUrls])
module.run([
"$log",
"$tgResources",
"$tgProjectsResourcesProvider",
"$tgMembershipsResourcesProvider",
"$tgNotifyPoliciesResourcesProvider",
"$tgInvitationsResourcesProvider",
"$tgRolesResourcesProvider",
"$tgUserSettingsResourcesProvider",
"$tgSprintsResourcesProvider",
"$tgUserstoriesResourcesProvider",
"$tgTasksResourcesProvider",
"$tgIssuesResourcesProvider",
"$tgWikiResourcesProvider",
"$tgSearchResourcesProvider",
"$tgAttachmentsResourcesProvider",
"$tgMdRenderResourcesProvider",
"$tgHistoryResourcesProvider",
"$tgKanbanResourcesProvider",
"$tgModulesResourcesProvider",
initResources
])
| 30525 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/resources.coffee
###
taiga = @.taiga
class ResourcesService extends taiga.Service
urls = {
"auth": "/auth"
"auth-register": "/auth/register"
"invitations": "/invitations"
"permissions": "/permissions"
"roles": "/roles"
"projects": "/projects"
"memberships": "/memberships"
"notify-policies": "/notify-policies"
"bulk-create-memberships": "/memberships/bulk_create"
"milestones": "/milestones"
"userstories": "/userstories"
"bulk-create-us": "/userstories/bulk_create"
"bulk-update-us-backlog-order": "/userstories/bulk_update_backlog_order"
"bulk-update-us-sprint-order": "/userstories/bulk_update_sprint_order"
"bulk-update-us-kanban-order": "/userstories/bulk_update_kanban_order"
"userstories-restore": "/userstories/%s/restore"
"tasks": "/tasks"
"bulk-create-tasks": "/tasks/bulk_create"
"bulk-update-task-taskboard-order": "/tasks/bulk_update_taskboard_order"
"tasks-restore": "/tasks/%s/restore"
"issues": "/issues"
"bulk-create-issues": "/issues/bulk_create"
"issues-restore": "/issues/%s/restore"
"wiki": "/wiki"
"wiki-restore": "/wiki/%s/restore"
"wiki-links": "/wiki-links"
"choices/userstory-statuses": "/userstory-statuses"
"choices/userstory-statuses/bulk-update-order": "/userstory-statuses/bulk_update_order"
"choices/points": "/points"
"choices/points/bulk-update-order": "/points/bulk_update_order"
"choices/task-statuses": "/task-statuses"
"choices/task-statuses/bulk-update-order": "/task-statuses/bulk_update_order"
"choices/issue-statuses": "/issue-statuses"
"choices/issue-statuses/bulk-update-order": "/issue-statuses/bulk_update_order"
"choices/issue-types": "/issue-types"
"choices/issue-types/bulk-update-order": "/issue-types/bulk_update_order"
"choices/priorities": "/priorities"
"choices/priorities/bulk-update-order": "/priorities/bulk_update_order"
"choices/severities": "/severities"
"choices/severities/bulk-update-order": "/severities/bulk_update_order"
"search": "/search"
"sites": "/sites"
"project-templates": "/project-templates"
"site-members": "/site-members"
"site-projects": "/site-projects"
"users": "/users"
"users-password-recovery": "/users/password_recovery"
"users-change-password-from-recovery": "/users/change_password_from_recovery"
"users-change-password": "/users/change_password"
"users-change-email": "/users/change_email"
"users-cancel-account": "/users/cancel"
"user-storage": "/user-storage"
"resolver": "/resolver"
"userstory-statuses": "/userstory-statuses"
"points": "/points"
"task-statuses": "/task-statuses"
"issue-statuses": "/issue-statuses"
"issue-types": "/issue-types"
"priorities": "/priorities"
"severities": "/severities"
"project-modules": "/projects/%s/modules"
# History
"history/us": "/history/userstory"
"history/issue": "/history/issue"
"history/task": "/history/task"
"history/wiki": "/history/wiki"
# Attachments
"attachments/us": "/userstories/attachments"
"attachments/issue": "/issues/attachments"
"attachments/task": "/tasks/attachments"
"attachments/wiki_page": "/wiki/attachments"
# Feedback
"feedback": "/feedback"
}
# Initialize api urls service
initUrls = ($log, $urls) ->
$log.debug "Initialize api urls"
$urls.update(urls)
# Initialize resources service populating it with methods
# defined in separated files.
initResources = ($log, $rs) ->
$log.debug "Initialize resources"
providers = _.toArray(arguments).slice(2)
for provider in providers
provider($rs)
module = angular.module("taigaResources", ["taigaBase"])
module.service("$tgResources", ResourcesService)
# Module entry point
module.run(["$log", "$tgUrls", initUrls])
module.run([
"$log",
"$tgResources",
"$tgProjectsResourcesProvider",
"$tgMembershipsResourcesProvider",
"$tgNotifyPoliciesResourcesProvider",
"$tgInvitationsResourcesProvider",
"$tgRolesResourcesProvider",
"$tgUserSettingsResourcesProvider",
"$tgSprintsResourcesProvider",
"$tgUserstoriesResourcesProvider",
"$tgTasksResourcesProvider",
"$tgIssuesResourcesProvider",
"$tgWikiResourcesProvider",
"$tgSearchResourcesProvider",
"$tgAttachmentsResourcesProvider",
"$tgMdRenderResourcesProvider",
"$tgHistoryResourcesProvider",
"$tgKanbanResourcesProvider",
"$tgModulesResourcesProvider",
initResources
])
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/resources.coffee
###
taiga = @.taiga
class ResourcesService extends taiga.Service
urls = {
"auth": "/auth"
"auth-register": "/auth/register"
"invitations": "/invitations"
"permissions": "/permissions"
"roles": "/roles"
"projects": "/projects"
"memberships": "/memberships"
"notify-policies": "/notify-policies"
"bulk-create-memberships": "/memberships/bulk_create"
"milestones": "/milestones"
"userstories": "/userstories"
"bulk-create-us": "/userstories/bulk_create"
"bulk-update-us-backlog-order": "/userstories/bulk_update_backlog_order"
"bulk-update-us-sprint-order": "/userstories/bulk_update_sprint_order"
"bulk-update-us-kanban-order": "/userstories/bulk_update_kanban_order"
"userstories-restore": "/userstories/%s/restore"
"tasks": "/tasks"
"bulk-create-tasks": "/tasks/bulk_create"
"bulk-update-task-taskboard-order": "/tasks/bulk_update_taskboard_order"
"tasks-restore": "/tasks/%s/restore"
"issues": "/issues"
"bulk-create-issues": "/issues/bulk_create"
"issues-restore": "/issues/%s/restore"
"wiki": "/wiki"
"wiki-restore": "/wiki/%s/restore"
"wiki-links": "/wiki-links"
"choices/userstory-statuses": "/userstory-statuses"
"choices/userstory-statuses/bulk-update-order": "/userstory-statuses/bulk_update_order"
"choices/points": "/points"
"choices/points/bulk-update-order": "/points/bulk_update_order"
"choices/task-statuses": "/task-statuses"
"choices/task-statuses/bulk-update-order": "/task-statuses/bulk_update_order"
"choices/issue-statuses": "/issue-statuses"
"choices/issue-statuses/bulk-update-order": "/issue-statuses/bulk_update_order"
"choices/issue-types": "/issue-types"
"choices/issue-types/bulk-update-order": "/issue-types/bulk_update_order"
"choices/priorities": "/priorities"
"choices/priorities/bulk-update-order": "/priorities/bulk_update_order"
"choices/severities": "/severities"
"choices/severities/bulk-update-order": "/severities/bulk_update_order"
"search": "/search"
"sites": "/sites"
"project-templates": "/project-templates"
"site-members": "/site-members"
"site-projects": "/site-projects"
"users": "/users"
"users-password-recovery": "/users/password_recovery"
"users-change-password-from-recovery": "/users/change_password_from_recovery"
"users-change-password": "/users/change_password"
"users-change-email": "/users/change_email"
"users-cancel-account": "/users/cancel"
"user-storage": "/user-storage"
"resolver": "/resolver"
"userstory-statuses": "/userstory-statuses"
"points": "/points"
"task-statuses": "/task-statuses"
"issue-statuses": "/issue-statuses"
"issue-types": "/issue-types"
"priorities": "/priorities"
"severities": "/severities"
"project-modules": "/projects/%s/modules"
# History
"history/us": "/history/userstory"
"history/issue": "/history/issue"
"history/task": "/history/task"
"history/wiki": "/history/wiki"
# Attachments
"attachments/us": "/userstories/attachments"
"attachments/issue": "/issues/attachments"
"attachments/task": "/tasks/attachments"
"attachments/wiki_page": "/wiki/attachments"
# Feedback
"feedback": "/feedback"
}
# Initialize api urls service
initUrls = ($log, $urls) ->
$log.debug "Initialize api urls"
$urls.update(urls)
# Initialize resources service populating it with methods
# defined in separated files.
initResources = ($log, $rs) ->
$log.debug "Initialize resources"
providers = _.toArray(arguments).slice(2)
for provider in providers
provider($rs)
module = angular.module("taigaResources", ["taigaBase"])
module.service("$tgResources", ResourcesService)
# Module entry point
module.run(["$log", "$tgUrls", initUrls])
module.run([
"$log",
"$tgResources",
"$tgProjectsResourcesProvider",
"$tgMembershipsResourcesProvider",
"$tgNotifyPoliciesResourcesProvider",
"$tgInvitationsResourcesProvider",
"$tgRolesResourcesProvider",
"$tgUserSettingsResourcesProvider",
"$tgSprintsResourcesProvider",
"$tgUserstoriesResourcesProvider",
"$tgTasksResourcesProvider",
"$tgIssuesResourcesProvider",
"$tgWikiResourcesProvider",
"$tgSearchResourcesProvider",
"$tgAttachmentsResourcesProvider",
"$tgMdRenderResourcesProvider",
"$tgHistoryResourcesProvider",
"$tgKanbanResourcesProvider",
"$tgModulesResourcesProvider",
initResources
])
|
[
{
"context": "###\n@fileoverview\n\nCreated by Davide on 1/31/18.\n###\n\nrequire 'coffeescript/register'\n",
"end": 36,
"score": 0.9997639656066895,
"start": 30,
"tag": "NAME",
"value": "Davide"
}
] | js/atom-macros/test/macros.spec.coffee | pokemoncentral/wiki-util | 1 | ###
@fileoverview
Created by Davide on 1/31/18.
###
require 'coffeescript/register'
should = require 'chai'
.should()
runMacros = require '../lib/run-macro'
badHTML = '''
<small>small text</small>
<big>big text</big>
first line<br>second line
'''
goodHTML = '''
<span class="text-small">small text</span>
<span class="text-big">big text</span>
first line<div>second line</div>
'''
luaModule = '''
local ms = require('Modulo:MiniSprite')
local txt = require('Modulo:Wikilib/strings')
local c = mw.loadData('Modulo:Colore/data')
'''
luaSource = '''
local ms = require('MiniSprite')
local txt = require('Wikilib-strings')
local c = require("Colore-data")
'''
luaDict = '''
{{-start-}}
\'''Modulo:Test\'''
local ms = require('Modulo:MiniSprite')
local txt = require('Modulo:Wikilib/strings')
local c = mw.loadData('Modulo:Colore/data')
{{-stop-}}
'''
badWikicode = '''
{{colore pcwiki}}
{{colore pcwiki dark}}
{{p|Luxio}}
{{template call}}
'''
goodWikicode = '''
{{#invoke: colore | pcwiki}}
{{#invoke: colore | pcwiki | dark}}
[[Luxio]]
{{template call}}
'''
basicBehavior = (source, expected, macroName) ->
() ->
result = runMacros.applyMacro source, macroName
result.should.equal expected
basicBehaviorMatch = (source, expected, macroName, pattern) ->
() ->
matches = expected.match new RegExp pattern, 'g'
result = runMacros.applyMacro source, macroName
matches.every (match) -> result.should.contain match
basicBehaviorFilename = (source, expected, macroName, filename) ->
() ->
result = runMacros.applyMacro source, macroName, filename
result.should.equal expected
idempotence = (source, macroName, filename) ->
() ->
once = runMacros.applyMacro source, macroName, filename
twice = runMacros.applyMacro once, macroName, filename
once.should.equal twice
describe 'big', () ->
it 'should turn big tags to span class="text-big"', \
basicBehaviorMatch badHTML, goodHTML, 'big', \
'<span class="text-big">.+</span>'
it 'should be idempotent', \
idempotence badHTML, 'big'
describe 'br', () ->
it 'should turn br tags to div', \
basicBehaviorMatch badHTML, goodHTML, 'br', '.*<div>.+</div>'
it 'should be idempotent', \
idempotence badHTML, 'br'
describe 'colore', () ->
it 'should turn colore template to colore modules', \
basicBehaviorMatch badWikicode, goodWikicode, 'colore', \
/\{\{#invoke: colore \| .+\}\}/
it 'should be idempotent', \
idempotence badWikicode, 'colore'
describe 'p', () ->
it 'should turn p template to plain links', \
basicBehaviorMatch badWikicode, goodWikicode, 'p', /\[\[.+\]\]/
it 'should be idempotent', \
idempotence badWikicode, 'p'
describe 'small', () ->
it 'should turn small tags to span class="text-small"', \
basicBehaviorMatch badHTML, goodHTML, 'small', \
'<span class="text-small">.+</span>'
it 'should be idempotent', \
idempotence badHTML, 'small'
describe 'tags', () ->
it 'should turn all tags to a better version', \
basicBehavior badHTML, goodHTML, 'tags'
it 'should be idempotent', \
idempotence badHTML, 'tags'
describe 'toLua', () ->
it 'should change module names and remove mw.loadData', \
basicBehavior luaModule, luaSource, 'toLua'
it 'should be idempotent', \
idempotence luaModule, 'toLua'
describe 'toModule', () ->
it 'should prepend Module and insert mw.loadData for double quotes', \
basicBehavior luaSource, luaModule, 'toModule'
it 'should be idempotent', \
idempotence luaSource, 'toModule'
describe 'wikicode', () ->
it 'should turn the wikicode to a better version', \
basicBehavior badWikicode, goodWikicode, 'wikicode'
it 'should be idempotent', \
idempotence badWikicode, 'wikicode'
describe 'moduleToDict', () ->
it 'should turn the scributo to an uploadable dict', \
basicBehaviorFilename luaModule, luaDict, 'moduleToDict', 'Test.lua'
it 'should be idempotent', \
idempotence luaModule, 'moduleToDict', 'Test.lua'
| 181061 | ###
@fileoverview
Created by <NAME> on 1/31/18.
###
require 'coffeescript/register'
should = require 'chai'
.should()
runMacros = require '../lib/run-macro'
badHTML = '''
<small>small text</small>
<big>big text</big>
first line<br>second line
'''
goodHTML = '''
<span class="text-small">small text</span>
<span class="text-big">big text</span>
first line<div>second line</div>
'''
luaModule = '''
local ms = require('Modulo:MiniSprite')
local txt = require('Modulo:Wikilib/strings')
local c = mw.loadData('Modulo:Colore/data')
'''
luaSource = '''
local ms = require('MiniSprite')
local txt = require('Wikilib-strings')
local c = require("Colore-data")
'''
luaDict = '''
{{-start-}}
\'''Modulo:Test\'''
local ms = require('Modulo:MiniSprite')
local txt = require('Modulo:Wikilib/strings')
local c = mw.loadData('Modulo:Colore/data')
{{-stop-}}
'''
badWikicode = '''
{{colore pcwiki}}
{{colore pcwiki dark}}
{{p|Luxio}}
{{template call}}
'''
goodWikicode = '''
{{#invoke: colore | pcwiki}}
{{#invoke: colore | pcwiki | dark}}
[[Luxio]]
{{template call}}
'''
basicBehavior = (source, expected, macroName) ->
() ->
result = runMacros.applyMacro source, macroName
result.should.equal expected
basicBehaviorMatch = (source, expected, macroName, pattern) ->
() ->
matches = expected.match new RegExp pattern, 'g'
result = runMacros.applyMacro source, macroName
matches.every (match) -> result.should.contain match
basicBehaviorFilename = (source, expected, macroName, filename) ->
() ->
result = runMacros.applyMacro source, macroName, filename
result.should.equal expected
idempotence = (source, macroName, filename) ->
() ->
once = runMacros.applyMacro source, macroName, filename
twice = runMacros.applyMacro once, macroName, filename
once.should.equal twice
describe 'big', () ->
it 'should turn big tags to span class="text-big"', \
basicBehaviorMatch badHTML, goodHTML, 'big', \
'<span class="text-big">.+</span>'
it 'should be idempotent', \
idempotence badHTML, 'big'
describe 'br', () ->
it 'should turn br tags to div', \
basicBehaviorMatch badHTML, goodHTML, 'br', '.*<div>.+</div>'
it 'should be idempotent', \
idempotence badHTML, 'br'
describe 'colore', () ->
it 'should turn colore template to colore modules', \
basicBehaviorMatch badWikicode, goodWikicode, 'colore', \
/\{\{#invoke: colore \| .+\}\}/
it 'should be idempotent', \
idempotence badWikicode, 'colore'
describe 'p', () ->
it 'should turn p template to plain links', \
basicBehaviorMatch badWikicode, goodWikicode, 'p', /\[\[.+\]\]/
it 'should be idempotent', \
idempotence badWikicode, 'p'
describe 'small', () ->
it 'should turn small tags to span class="text-small"', \
basicBehaviorMatch badHTML, goodHTML, 'small', \
'<span class="text-small">.+</span>'
it 'should be idempotent', \
idempotence badHTML, 'small'
describe 'tags', () ->
it 'should turn all tags to a better version', \
basicBehavior badHTML, goodHTML, 'tags'
it 'should be idempotent', \
idempotence badHTML, 'tags'
describe 'toLua', () ->
it 'should change module names and remove mw.loadData', \
basicBehavior luaModule, luaSource, 'toLua'
it 'should be idempotent', \
idempotence luaModule, 'toLua'
describe 'toModule', () ->
it 'should prepend Module and insert mw.loadData for double quotes', \
basicBehavior luaSource, luaModule, 'toModule'
it 'should be idempotent', \
idempotence luaSource, 'toModule'
describe 'wikicode', () ->
it 'should turn the wikicode to a better version', \
basicBehavior badWikicode, goodWikicode, 'wikicode'
it 'should be idempotent', \
idempotence badWikicode, 'wikicode'
describe 'moduleToDict', () ->
it 'should turn the scributo to an uploadable dict', \
basicBehaviorFilename luaModule, luaDict, 'moduleToDict', 'Test.lua'
it 'should be idempotent', \
idempotence luaModule, 'moduleToDict', 'Test.lua'
| true | ###
@fileoverview
Created by PI:NAME:<NAME>END_PI on 1/31/18.
###
require 'coffeescript/register'
should = require 'chai'
.should()
runMacros = require '../lib/run-macro'
badHTML = '''
<small>small text</small>
<big>big text</big>
first line<br>second line
'''
goodHTML = '''
<span class="text-small">small text</span>
<span class="text-big">big text</span>
first line<div>second line</div>
'''
luaModule = '''
local ms = require('Modulo:MiniSprite')
local txt = require('Modulo:Wikilib/strings')
local c = mw.loadData('Modulo:Colore/data')
'''
luaSource = '''
local ms = require('MiniSprite')
local txt = require('Wikilib-strings')
local c = require("Colore-data")
'''
luaDict = '''
{{-start-}}
\'''Modulo:Test\'''
local ms = require('Modulo:MiniSprite')
local txt = require('Modulo:Wikilib/strings')
local c = mw.loadData('Modulo:Colore/data')
{{-stop-}}
'''
badWikicode = '''
{{colore pcwiki}}
{{colore pcwiki dark}}
{{p|Luxio}}
{{template call}}
'''
goodWikicode = '''
{{#invoke: colore | pcwiki}}
{{#invoke: colore | pcwiki | dark}}
[[Luxio]]
{{template call}}
'''
basicBehavior = (source, expected, macroName) ->
() ->
result = runMacros.applyMacro source, macroName
result.should.equal expected
basicBehaviorMatch = (source, expected, macroName, pattern) ->
() ->
matches = expected.match new RegExp pattern, 'g'
result = runMacros.applyMacro source, macroName
matches.every (match) -> result.should.contain match
basicBehaviorFilename = (source, expected, macroName, filename) ->
() ->
result = runMacros.applyMacro source, macroName, filename
result.should.equal expected
idempotence = (source, macroName, filename) ->
() ->
once = runMacros.applyMacro source, macroName, filename
twice = runMacros.applyMacro once, macroName, filename
once.should.equal twice
describe 'big', () ->
it 'should turn big tags to span class="text-big"', \
basicBehaviorMatch badHTML, goodHTML, 'big', \
'<span class="text-big">.+</span>'
it 'should be idempotent', \
idempotence badHTML, 'big'
describe 'br', () ->
it 'should turn br tags to div', \
basicBehaviorMatch badHTML, goodHTML, 'br', '.*<div>.+</div>'
it 'should be idempotent', \
idempotence badHTML, 'br'
describe 'colore', () ->
it 'should turn colore template to colore modules', \
basicBehaviorMatch badWikicode, goodWikicode, 'colore', \
/\{\{#invoke: colore \| .+\}\}/
it 'should be idempotent', \
idempotence badWikicode, 'colore'
describe 'p', () ->
it 'should turn p template to plain links', \
basicBehaviorMatch badWikicode, goodWikicode, 'p', /\[\[.+\]\]/
it 'should be idempotent', \
idempotence badWikicode, 'p'
describe 'small', () ->
it 'should turn small tags to span class="text-small"', \
basicBehaviorMatch badHTML, goodHTML, 'small', \
'<span class="text-small">.+</span>'
it 'should be idempotent', \
idempotence badHTML, 'small'
describe 'tags', () ->
it 'should turn all tags to a better version', \
basicBehavior badHTML, goodHTML, 'tags'
it 'should be idempotent', \
idempotence badHTML, 'tags'
describe 'toLua', () ->
it 'should change module names and remove mw.loadData', \
basicBehavior luaModule, luaSource, 'toLua'
it 'should be idempotent', \
idempotence luaModule, 'toLua'
describe 'toModule', () ->
it 'should prepend Module and insert mw.loadData for double quotes', \
basicBehavior luaSource, luaModule, 'toModule'
it 'should be idempotent', \
idempotence luaSource, 'toModule'
describe 'wikicode', () ->
it 'should turn the wikicode to a better version', \
basicBehavior badWikicode, goodWikicode, 'wikicode'
it 'should be idempotent', \
idempotence badWikicode, 'wikicode'
describe 'moduleToDict', () ->
it 'should turn the scributo to an uploadable dict', \
basicBehaviorFilename luaModule, luaDict, 'moduleToDict', 'Test.lua'
it 'should be idempotent', \
idempotence luaModule, 'moduleToDict', 'Test.lua'
|
[
{
"context": "ess page > 0 and page <= 30\n\n mainFilterKeys = ['_roomId', 'isDirectMessage', '_storyId']\n\n mainFilters =",
"end": 936,
"score": 0.9278910160064697,
"start": 930,
"tag": "KEY",
"value": "roomId"
},
{
"context": "0 and page <= 30\n\n mainFilterKeys = ['_roomId', '... | talk-api2x/server/searchers/favorite.coffee | ikingye/talk-os | 3,084 | Promise = require 'bluebird'
_ = require 'lodash'
Err = require 'err1st'
util = require '../util'
{limbo} = require '../components'
{
FavoriteModel
SearchFavoriteModel
} = limbo.use 'talk'
_combileFilter = (filter, clause, children) ->
if filter.bool?[clause]
filter.bool[clause].push children
else if filter.bool
filter.bool[clause] = [children]
else
_filter = filter
filter = bool: {}
filter.bool[clause] = [_filter, children]
filter
_generalQueryDsl = (req) ->
{
_teamId
keyword
_sessionUserId
limit
page
_creatorId
_creatorIds
_toId
_toIds
_roomId # Room filter
isDirectMessage # Only return the direct messages
_storyId
type
sort
} = req.get()
limit or= 10
page or= 1
page = parseInt page
type or= 'general'
return Promise.reject(new Err('OUT_OF_SEARCH_RANGE')) unless page > 0 and page <= 30
mainFilterKeys = ['_roomId', 'isDirectMessage', '_storyId']
mainFilters = mainFilterKeys.filter (key) -> req.get key
return Promise.reject(new Err('PARAMS_CONFLICT', mainFilterKeys)) if mainFilters.length > 1
keyword = keyword?.trim()
keyword = keyword[..20] if keyword?.length > 20
# Need team scope
$filter = Promise.resolve
bool:
must: [
term: _teamId: _teamId
,
term: _favoritedById: _sessionUserId
]
if isDirectMessage # Filter only direct message
$filter = $filter.then (filter) -> _combileFilter filter, 'must', exists: field: '_toId'
else if _roomId # Filter by room id
$filter = $filter.then (filter) -> _combileFilter filter, 'must', term: _roomId: _roomId
else if _storyId
$filter = $filter.then (filter) -> _combileFilter filter, 'must', term: _storyId: _storyId
# Add creator filter on general filters
if _creatorId
$filter = $filter.then (filter) ->
creatorFilter = term: _creatorId: _creatorId
_combileFilter filter, 'must', creatorFilter
else if _creatorIds
$filter = $filter.then (filter) ->
creatorFilter = terms: _creatorId: _creatorIds
_combileFilter filter, 'must', creatorFilter
# Add to filter on general filters
if _toId
$filter = $filter.then (filter) ->
toFilter = term: _toId: _toId
_combileFilter filter, 'must', toFilter
else if _toIds
$filter = $filter.then (filter) ->
toFilter = terms: _toId: _toIds
_combileFilter filter, 'must', toFilter
# Build the query DSL
$queryDsl = $filter.then (filter) ->
queryDsl =
size: limit
from: limit * (page - 1)
highlight:
fields:
'body': {}
'attachments.data.title': {}
'attachments.data.text': {}
'attachments.data.fileName': {}
query:
filtered:
filter: filter
query:
query_string:
fields: [
'body'
'attachments.data.title'
'attachments.data.text'
'attachments.data.fileName'
]
query: keyword or '*' # Search for all when the keyword is not defined
queryDsl.sort = sort if sort
queryDsl.sort = createdAt: order: 'desc' unless sort or keyword
queryDsl
_typeDsls =
general: _generalQueryDsl
file: (req, res, callback) ->
{fileCategory} = req.get()
switch fileCategory
when 'image' then fileCategories = ['image']
when 'document' then fileCategories = ['text', 'pdf', 'message']
when 'media' then fileCategories = ['audio', 'video']
when 'other' then fileCategories = ['application', 'font']
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
# Generate file filter
fileFilter =
bool:
must: [
term: 'attachments.category': 'file'
]
if fileCategories
fileFilter.bool.must.push terms: 'attachments.data.fileCategory': fileCategories
# Combine with general filter
filter = _combileFilter filter, 'must', fileFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.fileName'] # Only search for the fileName
queryDsl
thirdapp: (req, res, callback) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
appFilter =
bool:
must: [
term: 'attachments.category': 'quote'
,
term: 'attachments.data.category': 'thirdapp'
]
filter = _combileFilter filter, 'must', appFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['body', 'attachments.data.title', 'attachments.data.text']
queryDsl
url: (req) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
urlFilter =
bool:
must: [
term: 'attachments.category': 'quote'
,
term: 'attachments.data.category': 'url'
]
filter = _combileFilter filter, 'must', urlFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
rtf: (req) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
rtfFilter =
bool:
must: [
term: 'attachments.category': 'rtf'
]
filter = _combileFilter filter, 'must', rtfFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
snippet: (req) ->
{codeType} = req.get()
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
snippetFilter =
bool:
must: [
term: "attachments.category": "snippet"
]
if codeType
snippetFilter.bool.must.push term: "attachments.data.codeType": codeType
filter = _combileFilter filter, 'must', snippetFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
###*
* Only messages send from user to user
* @param {Request} req
* @return {Promise} queryDsl
###
message: (req) ->
_typeDsls.general(req).then (queryDsl) ->
queryDsl.query.filtered.query.query_string.fields = ['body']
queryDsl
###*
* Search for messages
* @param {Request} req
* @param {Response} res
* @param {Function} callback
* @return {Promise} data - Response data
###
exports.search = (req, res, callback) ->
{type} = req.get()
type or= 'general'
return callback(new Err('PARAMS_INVALID', "type #{type} is not defined")) unless _typeDsls[type]
$queryDsl = _typeDsls[type] req
$searchResult = $queryDsl.then (queryDsl) ->
SearchFavoriteModel.searchAsync queryDsl.query, queryDsl
.then (searchResult) ->
throw new Err('SEARCH_FAILED') unless searchResult?.hits?.hits
searchResult
$resData = $searchResult.then (searchResult) ->
resData =
total: searchResult.hits.total
favorites: []
_favoriteIds = searchResult.hits.hits.map (hit) -> hit._id
favoriteHash = {}
Promise.resolve()
.then -> FavoriteModel.findByIdsAsync _favoriteIds
.map (favorite) -> favoriteHash["#{favorite._id}"] = favorite.toJSON()
.then ->
resData.favorites = searchResult.hits.hits.map (hit) ->
return false unless favoriteHash[hit._id]
favorite = favoriteHash[hit._id]
favorite.highlight = hit.highlight
favorite._score = hit._score
favorite
.filter (favorite) -> favorite
resData
$resData.nodeify callback
| 73479 | Promise = require 'bluebird'
_ = require 'lodash'
Err = require 'err1st'
util = require '../util'
{limbo} = require '../components'
{
FavoriteModel
SearchFavoriteModel
} = limbo.use 'talk'
_combileFilter = (filter, clause, children) ->
if filter.bool?[clause]
filter.bool[clause].push children
else if filter.bool
filter.bool[clause] = [children]
else
_filter = filter
filter = bool: {}
filter.bool[clause] = [_filter, children]
filter
_generalQueryDsl = (req) ->
{
_teamId
keyword
_sessionUserId
limit
page
_creatorId
_creatorIds
_toId
_toIds
_roomId # Room filter
isDirectMessage # Only return the direct messages
_storyId
type
sort
} = req.get()
limit or= 10
page or= 1
page = parseInt page
type or= 'general'
return Promise.reject(new Err('OUT_OF_SEARCH_RANGE')) unless page > 0 and page <= 30
mainFilterKeys = ['_<KEY>', '<KEY>DirectMessage', '_storyId']
mainFilters = mainFilterKeys.filter (key) -> req.get key
return Promise.reject(new Err('PARAMS_CONFLICT', mainFilterKeys)) if mainFilters.length > 1
keyword = keyword?.trim()
keyword = keyword[..20] if keyword?.length > 20
# Need team scope
$filter = Promise.resolve
bool:
must: [
term: _teamId: _teamId
,
term: _favoritedById: _sessionUserId
]
if isDirectMessage # Filter only direct message
$filter = $filter.then (filter) -> _combileFilter filter, 'must', exists: field: '_toId'
else if _roomId # Filter by room id
$filter = $filter.then (filter) -> _combileFilter filter, 'must', term: _roomId: _roomId
else if _storyId
$filter = $filter.then (filter) -> _combileFilter filter, 'must', term: _storyId: _storyId
# Add creator filter on general filters
if _creatorId
$filter = $filter.then (filter) ->
creatorFilter = term: _creatorId: _creatorId
_combileFilter filter, 'must', creatorFilter
else if _creatorIds
$filter = $filter.then (filter) ->
creatorFilter = terms: _creatorId: _creatorIds
_combileFilter filter, 'must', creatorFilter
# Add to filter on general filters
if _toId
$filter = $filter.then (filter) ->
toFilter = term: _toId: _toId
_combileFilter filter, 'must', toFilter
else if _toIds
$filter = $filter.then (filter) ->
toFilter = terms: _toId: _toIds
_combileFilter filter, 'must', toFilter
# Build the query DSL
$queryDsl = $filter.then (filter) ->
queryDsl =
size: limit
from: limit * (page - 1)
highlight:
fields:
'body': {}
'attachments.data.title': {}
'attachments.data.text': {}
'attachments.data.fileName': {}
query:
filtered:
filter: filter
query:
query_string:
fields: [
'body'
'attachments.data.title'
'attachments.data.text'
'attachments.data.fileName'
]
query: keyword or '*' # Search for all when the keyword is not defined
queryDsl.sort = sort if sort
queryDsl.sort = createdAt: order: 'desc' unless sort or keyword
queryDsl
_typeDsls =
general: _generalQueryDsl
file: (req, res, callback) ->
{fileCategory} = req.get()
switch fileCategory
when 'image' then fileCategories = ['image']
when 'document' then fileCategories = ['text', 'pdf', 'message']
when 'media' then fileCategories = ['audio', 'video']
when 'other' then fileCategories = ['application', 'font']
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
# Generate file filter
fileFilter =
bool:
must: [
term: 'attachments.category': 'file'
]
if fileCategories
fileFilter.bool.must.push terms: 'attachments.data.fileCategory': fileCategories
# Combine with general filter
filter = _combileFilter filter, 'must', fileFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.fileName'] # Only search for the fileName
queryDsl
thirdapp: (req, res, callback) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
appFilter =
bool:
must: [
term: 'attachments.category': 'quote'
,
term: 'attachments.data.category': 'thirdapp'
]
filter = _combileFilter filter, 'must', appFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['body', 'attachments.data.title', 'attachments.data.text']
queryDsl
url: (req) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
urlFilter =
bool:
must: [
term: 'attachments.category': 'quote'
,
term: 'attachments.data.category': 'url'
]
filter = _combileFilter filter, 'must', urlFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
rtf: (req) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
rtfFilter =
bool:
must: [
term: 'attachments.category': 'rtf'
]
filter = _combileFilter filter, 'must', rtfFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
snippet: (req) ->
{codeType} = req.get()
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
snippetFilter =
bool:
must: [
term: "attachments.category": "snippet"
]
if codeType
snippetFilter.bool.must.push term: "attachments.data.codeType": codeType
filter = _combileFilter filter, 'must', snippetFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
###*
* Only messages send from user to user
* @param {Request} req
* @return {Promise} queryDsl
###
message: (req) ->
_typeDsls.general(req).then (queryDsl) ->
queryDsl.query.filtered.query.query_string.fields = ['body']
queryDsl
###*
* Search for messages
* @param {Request} req
* @param {Response} res
* @param {Function} callback
* @return {Promise} data - Response data
###
exports.search = (req, res, callback) ->
{type} = req.get()
type or= 'general'
return callback(new Err('PARAMS_INVALID', "type #{type} is not defined")) unless _typeDsls[type]
$queryDsl = _typeDsls[type] req
$searchResult = $queryDsl.then (queryDsl) ->
SearchFavoriteModel.searchAsync queryDsl.query, queryDsl
.then (searchResult) ->
throw new Err('SEARCH_FAILED') unless searchResult?.hits?.hits
searchResult
$resData = $searchResult.then (searchResult) ->
resData =
total: searchResult.hits.total
favorites: []
_favoriteIds = searchResult.hits.hits.map (hit) -> hit._id
favoriteHash = {}
Promise.resolve()
.then -> FavoriteModel.findByIdsAsync _favoriteIds
.map (favorite) -> favoriteHash["#{favorite._id}"] = favorite.toJSON()
.then ->
resData.favorites = searchResult.hits.hits.map (hit) ->
return false unless favoriteHash[hit._id]
favorite = favoriteHash[hit._id]
favorite.highlight = hit.highlight
favorite._score = hit._score
favorite
.filter (favorite) -> favorite
resData
$resData.nodeify callback
| true | Promise = require 'bluebird'
_ = require 'lodash'
Err = require 'err1st'
util = require '../util'
{limbo} = require '../components'
{
FavoriteModel
SearchFavoriteModel
} = limbo.use 'talk'
_combileFilter = (filter, clause, children) ->
if filter.bool?[clause]
filter.bool[clause].push children
else if filter.bool
filter.bool[clause] = [children]
else
_filter = filter
filter = bool: {}
filter.bool[clause] = [_filter, children]
filter
_generalQueryDsl = (req) ->
{
_teamId
keyword
_sessionUserId
limit
page
_creatorId
_creatorIds
_toId
_toIds
_roomId # Room filter
isDirectMessage # Only return the direct messages
_storyId
type
sort
} = req.get()
limit or= 10
page or= 1
page = parseInt page
type or= 'general'
return Promise.reject(new Err('OUT_OF_SEARCH_RANGE')) unless page > 0 and page <= 30
mainFilterKeys = ['_PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PIDirectMessage', '_storyId']
mainFilters = mainFilterKeys.filter (key) -> req.get key
return Promise.reject(new Err('PARAMS_CONFLICT', mainFilterKeys)) if mainFilters.length > 1
keyword = keyword?.trim()
keyword = keyword[..20] if keyword?.length > 20
# Need team scope
$filter = Promise.resolve
bool:
must: [
term: _teamId: _teamId
,
term: _favoritedById: _sessionUserId
]
if isDirectMessage # Filter only direct message
$filter = $filter.then (filter) -> _combileFilter filter, 'must', exists: field: '_toId'
else if _roomId # Filter by room id
$filter = $filter.then (filter) -> _combileFilter filter, 'must', term: _roomId: _roomId
else if _storyId
$filter = $filter.then (filter) -> _combileFilter filter, 'must', term: _storyId: _storyId
# Add creator filter on general filters
if _creatorId
$filter = $filter.then (filter) ->
creatorFilter = term: _creatorId: _creatorId
_combileFilter filter, 'must', creatorFilter
else if _creatorIds
$filter = $filter.then (filter) ->
creatorFilter = terms: _creatorId: _creatorIds
_combileFilter filter, 'must', creatorFilter
# Add to filter on general filters
if _toId
$filter = $filter.then (filter) ->
toFilter = term: _toId: _toId
_combileFilter filter, 'must', toFilter
else if _toIds
$filter = $filter.then (filter) ->
toFilter = terms: _toId: _toIds
_combileFilter filter, 'must', toFilter
# Build the query DSL
$queryDsl = $filter.then (filter) ->
queryDsl =
size: limit
from: limit * (page - 1)
highlight:
fields:
'body': {}
'attachments.data.title': {}
'attachments.data.text': {}
'attachments.data.fileName': {}
query:
filtered:
filter: filter
query:
query_string:
fields: [
'body'
'attachments.data.title'
'attachments.data.text'
'attachments.data.fileName'
]
query: keyword or '*' # Search for all when the keyword is not defined
queryDsl.sort = sort if sort
queryDsl.sort = createdAt: order: 'desc' unless sort or keyword
queryDsl
_typeDsls =
general: _generalQueryDsl
file: (req, res, callback) ->
{fileCategory} = req.get()
switch fileCategory
when 'image' then fileCategories = ['image']
when 'document' then fileCategories = ['text', 'pdf', 'message']
when 'media' then fileCategories = ['audio', 'video']
when 'other' then fileCategories = ['application', 'font']
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
# Generate file filter
fileFilter =
bool:
must: [
term: 'attachments.category': 'file'
]
if fileCategories
fileFilter.bool.must.push terms: 'attachments.data.fileCategory': fileCategories
# Combine with general filter
filter = _combileFilter filter, 'must', fileFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.fileName'] # Only search for the fileName
queryDsl
thirdapp: (req, res, callback) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
appFilter =
bool:
must: [
term: 'attachments.category': 'quote'
,
term: 'attachments.data.category': 'thirdapp'
]
filter = _combileFilter filter, 'must', appFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['body', 'attachments.data.title', 'attachments.data.text']
queryDsl
url: (req) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
urlFilter =
bool:
must: [
term: 'attachments.category': 'quote'
,
term: 'attachments.data.category': 'url'
]
filter = _combileFilter filter, 'must', urlFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
rtf: (req) ->
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
rtfFilter =
bool:
must: [
term: 'attachments.category': 'rtf'
]
filter = _combileFilter filter, 'must', rtfFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
snippet: (req) ->
{codeType} = req.get()
_typeDsls.general(req).then (queryDsl) ->
{filter, query} = queryDsl.query.filtered
snippetFilter =
bool:
must: [
term: "attachments.category": "snippet"
]
if codeType
snippetFilter.bool.must.push term: "attachments.data.codeType": codeType
filter = _combileFilter filter, 'must', snippetFilter
queryDsl.query.filtered.filter = filter
queryDsl.query.filtered.query.query_string.fields = ['attachments.data.title', 'attachments.data.text']
queryDsl
###*
* Only messages send from user to user
* @param {Request} req
* @return {Promise} queryDsl
###
message: (req) ->
_typeDsls.general(req).then (queryDsl) ->
queryDsl.query.filtered.query.query_string.fields = ['body']
queryDsl
###*
* Search for messages
* @param {Request} req
* @param {Response} res
* @param {Function} callback
* @return {Promise} data - Response data
###
exports.search = (req, res, callback) ->
{type} = req.get()
type or= 'general'
return callback(new Err('PARAMS_INVALID', "type #{type} is not defined")) unless _typeDsls[type]
$queryDsl = _typeDsls[type] req
$searchResult = $queryDsl.then (queryDsl) ->
SearchFavoriteModel.searchAsync queryDsl.query, queryDsl
.then (searchResult) ->
throw new Err('SEARCH_FAILED') unless searchResult?.hits?.hits
searchResult
$resData = $searchResult.then (searchResult) ->
resData =
total: searchResult.hits.total
favorites: []
_favoriteIds = searchResult.hits.hits.map (hit) -> hit._id
favoriteHash = {}
Promise.resolve()
.then -> FavoriteModel.findByIdsAsync _favoriteIds
.map (favorite) -> favoriteHash["#{favorite._id}"] = favorite.toJSON()
.then ->
resData.favorites = searchResult.hits.hits.map (hit) ->
return false unless favoriteHash[hit._id]
favorite = favoriteHash[hit._id]
favorite.highlight = hit.highlight
favorite._score = hit._score
favorite
.filter (favorite) -> favorite
resData
$resData.nodeify callback
|
[
{
"context": "#\n# input.coffee\n#\n# Copyright (c) 2014, Daniel Ellermann\n#\n# Permission is hereby granted, free of charge,",
"end": 57,
"score": 0.9997028112411499,
"start": 41,
"tag": "NAME",
"value": "Daniel Ellermann"
}
] | coffee/input.coffee | dellermann/js-calc | 0 | #
# input.coffee
#
# Copyright (c) 2014, Daniel Ellermann
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
class Input
#-- Class variables ---------------------------
# The maximum number of characters that may be entered.
#
@MAX_INPUT_LENGTH: 15
#-- Constructor -------------------------------
# Creates an empty calculator input.
#
constructor: ->
@clear()
#-- Public methods ----------------------------
# Adds the given digit to the input.
#
# @param [Number|String] digit the digit that should be added
# @return [Input] this instance for method chaining
#
addDigit: (digit) ->
input = @input
@input = input + digit if input.length <= Input.MAX_INPUT_LENGTH
this
# Adds a decimal point to the input. The decimal point is added if not
# already done.
#
# @return [Input] this instance for method chaining
#
addPoint: ->
input = @input
input = '0' unless input
@input = input + '.' if input.indexOf('.') < 0
this
# Clears the input and resets the negative flag.
#
# @return [Input] this instance for method chaining
#
clear: ->
@input = ''
@negative = false
this
# Deletes the last character from input.
#
# @return [Input] this instance for method chaining
#
deleteLastChar: ->
input = @input
n = input.length
input = input.substring(0, n - 1) if n > 0
input = '' if input is '0'
@input = input
this
# Sets the input to the given number.
#
# @param [Number] number the given number
# @return [Input] this instance for method chaining
#
setNumber: (number) ->
if number is 0
@input = ''
@negative = false
else
negative = false
if number < 0
negative = true
number *= -1
@input = String(number)
@negative = negative
this
# Toggles the negative flag. If the input is empty the flag is unchanged.
#
# @return [Boolean] the new state of the negative flag
#
toggleNegative: ->
@negative = not @negative unless @input is ''
# Converts the input to a number.
#
# @return [Number] the numeric representation of the input
#
toNumber: ->
input = @input
input = 0 if input is ''
value = parseFloat input
value *= -1 if @negative
value
| 65157 | #
# input.coffee
#
# Copyright (c) 2014, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
class Input
#-- Class variables ---------------------------
# The maximum number of characters that may be entered.
#
@MAX_INPUT_LENGTH: 15
#-- Constructor -------------------------------
# Creates an empty calculator input.
#
constructor: ->
@clear()
#-- Public methods ----------------------------
# Adds the given digit to the input.
#
# @param [Number|String] digit the digit that should be added
# @return [Input] this instance for method chaining
#
addDigit: (digit) ->
input = @input
@input = input + digit if input.length <= Input.MAX_INPUT_LENGTH
this
# Adds a decimal point to the input. The decimal point is added if not
# already done.
#
# @return [Input] this instance for method chaining
#
addPoint: ->
input = @input
input = '0' unless input
@input = input + '.' if input.indexOf('.') < 0
this
# Clears the input and resets the negative flag.
#
# @return [Input] this instance for method chaining
#
clear: ->
@input = ''
@negative = false
this
# Deletes the last character from input.
#
# @return [Input] this instance for method chaining
#
deleteLastChar: ->
input = @input
n = input.length
input = input.substring(0, n - 1) if n > 0
input = '' if input is '0'
@input = input
this
# Sets the input to the given number.
#
# @param [Number] number the given number
# @return [Input] this instance for method chaining
#
setNumber: (number) ->
if number is 0
@input = ''
@negative = false
else
negative = false
if number < 0
negative = true
number *= -1
@input = String(number)
@negative = negative
this
# Toggles the negative flag. If the input is empty the flag is unchanged.
#
# @return [Boolean] the new state of the negative flag
#
toggleNegative: ->
@negative = not @negative unless @input is ''
# Converts the input to a number.
#
# @return [Number] the numeric representation of the input
#
toNumber: ->
input = @input
input = 0 if input is ''
value = parseFloat input
value *= -1 if @negative
value
| true | #
# input.coffee
#
# Copyright (c) 2014, PI:NAME:<NAME>END_PI
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
class Input
#-- Class variables ---------------------------
# The maximum number of characters that may be entered.
#
@MAX_INPUT_LENGTH: 15
#-- Constructor -------------------------------
# Creates an empty calculator input.
#
constructor: ->
@clear()
#-- Public methods ----------------------------
# Adds the given digit to the input.
#
# @param [Number|String] digit the digit that should be added
# @return [Input] this instance for method chaining
#
addDigit: (digit) ->
input = @input
@input = input + digit if input.length <= Input.MAX_INPUT_LENGTH
this
# Adds a decimal point to the input. The decimal point is added if not
# already done.
#
# @return [Input] this instance for method chaining
#
addPoint: ->
input = @input
input = '0' unless input
@input = input + '.' if input.indexOf('.') < 0
this
# Clears the input and resets the negative flag.
#
# @return [Input] this instance for method chaining
#
clear: ->
@input = ''
@negative = false
this
# Deletes the last character from input.
#
# @return [Input] this instance for method chaining
#
deleteLastChar: ->
input = @input
n = input.length
input = input.substring(0, n - 1) if n > 0
input = '' if input is '0'
@input = input
this
# Sets the input to the given number.
#
# @param [Number] number the given number
# @return [Input] this instance for method chaining
#
setNumber: (number) ->
if number is 0
@input = ''
@negative = false
else
negative = false
if number < 0
negative = true
number *= -1
@input = String(number)
@negative = negative
this
# Toggles the negative flag. If the input is empty the flag is unchanged.
#
# @return [Boolean] the new state of the negative flag
#
toggleNegative: ->
@negative = not @negative unless @input is ''
# Converts the input to a number.
#
# @return [Number] the numeric representation of the input
#
toNumber: ->
input = @input
input = 0 if input is ''
value = parseFloat input
value *= -1 if @negative
value
|
[
{
"context": " await @call \"#{tmpdir}/my_module.js\", my_key: 'my value'\n result.should.containEql my_key: 'my value",
"end": 964,
"score": 0.773995041847229,
"start": 959,
"tag": "KEY",
"value": "value"
},
{
"context": " await @call \"#{tmpdir}/my_module.js\", my_key: 'my val... | packages/core/test/actions/call.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 0 |
nikita = require '../../src'
registry = require '../../src/registry'
{tags, config} = require '../test'
they = require('mocha-they')(config)
describe 'actions.call', ->
return unless tags.api
it 'call action from global registry', ->
try
await nikita.call ->
registry.register 'my_function', ({config}) ->
pass_a_key: config.a_key
await nikita.call ->
{pass_a_key} = await nikita.my_function a_key: 'a value'
pass_a_key.should.eql 'a value'
finally ->
nikita.call ->
registry.unregister 'my_function'
they 'call a module exporting a function', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = ({config}) => {
return config
}
'''
target: "#{tmpdir}/my_module.js"
result = await @call "#{tmpdir}/my_module.js", my_key: 'my value'
result.should.containEql my_key: 'my value'
they 'call a module exporting an object', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = {
metadata: {
header: 'hello'
},
handler: ({config, metadata}) => {
return {config, metadata}
}
}
'''
target: "#{tmpdir}/my_module.js"
{config, metadata} = await @call "#{tmpdir}/my_module.js", my_key: 'my value'
config.should.containEql
my_key: 'my value'
metadata.should.containEql
header: 'hello'
module: "#{tmpdir}/my_module.js"
they 'call a module dont overwrite argument', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = {
metadata: {
argument_to_config: 'a_boolean',
definitions: {
config: {
type: 'object',
properties: {
a_boolean: {
type: 'boolean',
default: true
}
}
}
}
},
handler: ({config, metadata}) => {
return {config, metadata}
}
}
'''
target: "#{tmpdir}/my_module.js"
{config, metadata} = await @call "#{tmpdir}/my_module.js"
config.should.eql
a_boolean: true
metadata.should.containEql
argument: undefined
| 29365 |
nikita = require '../../src'
registry = require '../../src/registry'
{tags, config} = require '../test'
they = require('mocha-they')(config)
describe 'actions.call', ->
return unless tags.api
it 'call action from global registry', ->
try
await nikita.call ->
registry.register 'my_function', ({config}) ->
pass_a_key: config.a_key
await nikita.call ->
{pass_a_key} = await nikita.my_function a_key: 'a value'
pass_a_key.should.eql 'a value'
finally ->
nikita.call ->
registry.unregister 'my_function'
they 'call a module exporting a function', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = ({config}) => {
return config
}
'''
target: "#{tmpdir}/my_module.js"
result = await @call "#{tmpdir}/my_module.js", my_key: 'my <KEY>'
result.should.containEql my_key: 'my value'
they 'call a module exporting an object', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = {
metadata: {
header: 'hello'
},
handler: ({config, metadata}) => {
return {config, metadata}
}
}
'''
target: "#{tmpdir}/my_module.js"
{config, metadata} = await @call "#{tmpdir}/my_module.js", my_key: 'my <KEY>'
config.should.containEql
my_key: 'my <KEY>'
metadata.should.containEql
header: 'hello'
module: "#{tmpdir}/my_module.js"
they 'call a module dont overwrite argument', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = {
metadata: {
argument_to_config: 'a_boolean',
definitions: {
config: {
type: 'object',
properties: {
a_boolean: {
type: 'boolean',
default: true
}
}
}
}
},
handler: ({config, metadata}) => {
return {config, metadata}
}
}
'''
target: "#{tmpdir}/my_module.js"
{config, metadata} = await @call "#{tmpdir}/my_module.js"
config.should.eql
a_boolean: true
metadata.should.containEql
argument: undefined
| true |
nikita = require '../../src'
registry = require '../../src/registry'
{tags, config} = require '../test'
they = require('mocha-they')(config)
describe 'actions.call', ->
return unless tags.api
it 'call action from global registry', ->
try
await nikita.call ->
registry.register 'my_function', ({config}) ->
pass_a_key: config.a_key
await nikita.call ->
{pass_a_key} = await nikita.my_function a_key: 'a value'
pass_a_key.should.eql 'a value'
finally ->
nikita.call ->
registry.unregister 'my_function'
they 'call a module exporting a function', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = ({config}) => {
return config
}
'''
target: "#{tmpdir}/my_module.js"
result = await @call "#{tmpdir}/my_module.js", my_key: 'my PI:KEY:<KEY>END_PI'
result.should.containEql my_key: 'my value'
they 'call a module exporting an object', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = {
metadata: {
header: 'hello'
},
handler: ({config, metadata}) => {
return {config, metadata}
}
}
'''
target: "#{tmpdir}/my_module.js"
{config, metadata} = await @call "#{tmpdir}/my_module.js", my_key: 'my PI:KEY:<KEY>END_PI'
config.should.containEql
my_key: 'my PI:KEY:<KEY>END_PI'
metadata.should.containEql
header: 'hello'
module: "#{tmpdir}/my_module.js"
they 'call a module dont overwrite argument', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
await @fs.base.writeFile
content: '''
module.exports = {
metadata: {
argument_to_config: 'a_boolean',
definitions: {
config: {
type: 'object',
properties: {
a_boolean: {
type: 'boolean',
default: true
}
}
}
}
},
handler: ({config, metadata}) => {
return {config, metadata}
}
}
'''
target: "#{tmpdir}/my_module.js"
{config, metadata} = await @call "#{tmpdir}/my_module.js"
config.should.eql
a_boolean: true
metadata.should.containEql
argument: undefined
|
[
{
"context": "\nemp = require '../exports/emp'\n\nbash_path_key = 'emp-debugger.path'\npid = null\nnpid = null\nnode_name = null\n\nemp_app",
"end": 185,
"score": 0.9977811574935913,
"start": 168,
"tag": "KEY",
"value": "emp-debugger.path"
},
{
"context": "conf 中\n# emp_app_ ='iewp'... | lib/emp_app/emp_app_manage.coffee | jcrom/emp-debugger | 2 | {BufferedProcess,Emitter} = require 'atom'
path = require 'path'
fs = require 'fs'
c_process = require 'child_process'
emp = require '../exports/emp'
bash_path_key = 'emp-debugger.path'
pid = null
npid = null
node_name = null
emp_app_view = null
app_state = false
connect_state = false
emp_app_start_script='iewp'
emp_front_app_start_script='/public/simulator'
emp_app_make_cmd='make'
emp_app_config_cmd='configure'
emp_app_config_arg= ['--with-debug']
emp_import_menu = '[{App_name, _}|_]=ewp_app_manager:all_apps(),ewp_channel_util:import_menu(App_name).'
emp_c_make = '[{App_name, _}|_]=ewp_app_manager:all_apps(), ewp:c_app(App_name).'
emp_get_app_name = '[{A, _}|_]=ewp_app_manager:all_apps(), A.'
parser_beam_epath = path.join(__dirname, '../../erl_util/')
# 定义编译文件到 atom conf 中
# emp_app_ ='iewp'
# EMP_MAKE_CMD_KEY = 'emp-debugger.emp-make'
# EMP_STAET_SCRIPT_KEY = 'emp-debugger.emp-start-script'
# EMP_CONFIG_KEY = 'emp-debugger.emp-config'
# EMP_CONFIG_ARG_KEY = 'emp-debugger.emp-config-arg'
module.exports =
class emp_app
project_path: null
erl_project: true
constructor: (tmp_emp_app_view)->
@project_path = atom.project.getPaths()[0]
emp_app_view = tmp_emp_app_view
unless atom.config.get(emp.EMP_MAKE_CMD_KEY)
atom.config.set(emp.EMP_MAKE_CMD_KEY, emp_app_make_cmd)
# else
# emp_app_make_cmd = tmp_emp_make
unless atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
atom.config.set(emp.EMP_STAET_SCRIPT_KEY, emp_app_start_script)
unless atom.config.get(emp.EMP_STAET_FRONT_SCRIPT_KEY)
atom.config.set(emp.EMP_STAET_FRONT_SCRIPT_KEY, emp_front_app_start_script)
# else
# emp_app_start_script = tmp_emp_start_sc
unless atom.config.get(emp.EMP_CONFIG_KEY)
atom.config.set(emp.EMP_CONFIG_KEY, emp_app_config_cmd)
# else
# emp_app_config_cmd = tmp_emp_config_sc
# app_state = false
unless atom.config.get(emp.EMP_CONFIG_ARG_KEY)
atom.config.set(emp.EMP_CONFIG_ARG_KEY, emp_app_config_arg)
unless atom.config.get(emp.EMP_IMPORT_MENU_KEY)
atom.config.set(emp.EMP_IMPORT_MENU_KEY, emp_import_menu)
unless atom.config.get(emp.EMP_CMAKE_KEY)
atom.config.set(emp.EMP_CMAKE_KEY, emp_c_make)
# console.log "project_path:#{@project_path}"
@initial_path()
make_app: ->
# console.log "make"
make_str = atom.config.get(emp.EMP_MAKE_CMD_KEY)
cwd = atom.project.getPaths()[0]
# console.log cwd
c_process.exec make_str, cwd:cwd, (error, stdout, stderr) ->
if (error instanceof Error)
# throw error
console.warn error.message
show_error("Make error ~")
# console.log "compile:#{error}"
# console.log "compile:#{stdout}"
format_stdout(stdout)
format_stderr(stderr)
emp_app_view.hide_loading()
config_app: ->
# console.log "config"
conf_file = atom.config.get(emp.EMP_CONFIG_KEY)
conf_ags = atom.config.get(emp.EMP_CONFIG_ARG_KEY)
# console.log conf_ags
cwd = atom.project.getPaths()[0]
conf_f_p = path.join cwd, conf_file
# console.log conf_f_p
f_state = fs.existsSync conf_f_p
# console.log f_state
# console.log cwd
try
if f_state
conf_stat = fs.statSync(conf_f_p).mode & 0o0777
if conf_stat < 457
fs.chmodSync(conf_f_p, 493)
script_file = atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
script_path = path.join cwd, script_file
# console.log script_path
if fs.existsSync script_path
script_stat = fs.statSync(script_path).mode & 0o0777
if script_stat < 457
fs.chmodSync(conf_f_p, 493)
catch e
console.error e
if f_state
c_process.execFile conf_f_p, conf_ags, cwd:cwd, (error, stdout, stderr) ->
if (error instanceof Error)
# throw error
console.warn error.message
emp.show_error("Configure app error ~")
format_stdout(stdout)
format_stderr(stderr)
emp_app_view.hide_loading()
else
emp.show_error("Configure app error ~")
run_app: ->
# console.log "run"
script_file = atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
script_exc = './' +script_file
cwd = atom.project.getPaths()[0]
script_path = path.join cwd, script_file
# console.log script_path
f_state = fs.existsSync script_path
# console.log f_state
# console.log cwd
# console.log script_exc
# console.log cwd
if f_state
if pid
tmp_pid = pid
pid = null
tmp_pid.kill()
# stdout = (data) ->
# console.log data
# # console.info data.binarySlice()
# stderr = (data) ->
# console.error data.binarySlice()
# exit = (code) ->
# console.log "exit"
# app_state = false
# # pid.stdin.write('q().\r\n')
# # set_app_stat(false)
# pid.stdin.end()
# emp_app_view.refresh_app_st(app_state)
# console.warn "close over:#{code}"
# pid = new BufferedProcess({command:script_exc, args:[], options:{cwd:cwd}, stdout:stdout, stderr:stderr, exit:exit})
pid = c_process.spawn script_exc, [], {cwd:cwd, env: process.env}
app_state = true
set_app_stat(true)
pid.stdout.on 'data', (data) ->
console.info data.binarySlice()
# pid.stdout.pipe process.stdout
pid.stderr.on 'data', (data) ->
console.error data.binarySlice()
pid.on 'SIGINT', (data) ->
console.log "-------------------------"
console.log data
pid.on 'close', (code) ->
app_state = false
# pid.stdin.write('q().\r\n')
# set_app_stat(false)
pid.stdin.end()
pid = null
emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
else
emp.show_error("Run app error ~")
run_front_app: ->
# console.log "run"
script_file = atom.config.get(emp.EMP_STAET_FRONT_SCRIPT_KEY)
script_exc = '.' +script_file
cwd = atom.project.getPaths()[0]
script_path = path.join cwd, script_file
# console.log script_path
f_state = fs.existsSync script_path
if f_state
if pid
tmp_pid = pid
pid = null
tmp_pid.kill()
# pid = new BufferedProcess({command:script_exc, args:[], options:{cwd:cwd}, stdout:stdout, stderr:stderr, exit:exit})
pid = c_process.spawn script_exc, [], {cwd:cwd, env: process.env}
app_state = true
set_app_stat(true)
pid.stdout.on 'data', (data) ->
console.info data.binarySlice()
# pid.stdout.pipe process.stdout
pid.stderr.on 'data', (data) ->
console.error data.binarySlice()
pid.on 'SIGINT', (data) ->
console.log "-------------------------"
console.log data
pid.on 'close', (code) ->
app_state = false
# pid.stdin.write('q().\r\n')
# set_app_stat(false)
pid.stdin.end()
pid = null
emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
else
emp.show_error("Run app error ~")
# test: ({command, args, options, stdout, stderr, exit}={}) ->
# @emitter = new Emitter
# options ?= {}
# # Related to joyent/node#2318
# if process.platform is 'win32'
# # Quote all arguments and escapes inner quotes
# if args?
# cmdArgs = args.filter (arg) -> arg?
# cmdArgs = cmdArgs.map (arg) =>
# if @isExplorerCommand(command) and /^\/[a-zA-Z]+,.*$/.test(arg)
# # Don't wrap /root,C:\folder style arguments to explorer calls in
# # quotes since they will not be interpreted correctly if they are
# arg
# else
# "\"#{arg.toString().replace(/"/g, '\\"')}\""
# else
# cmdArgs = []
# if /\s/.test(command)
# cmdArgs.unshift("\"#{command}\"")
# else
# cmdArgs.unshift(command)
# cmdArgs = ['/s', '/c', "\"#{cmdArgs.join(' ')}\""]
# cmdOptions = _.clone(options)
# cmdOptions.windowsVerbatimArguments = true
# @process = ChildProcess.spawn(@getCmdPath(), cmdArgs, cmdOptions)
# else
# console.log command
# console.log args
# console.log options
# @process = c_process.spawn(command, args, options)
# @killed = false
stop_app: ->
# console.log "stop"
if app_state
app_state = false
set_app_stat(false)
if pid
pid.kill()
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
run_erl: (erl_str) ->
# console.log "erl:#{erl_str}"
if app_state
if pid
# pid.stdin.resume()
pid.stdin.write(erl_str+'\n')
# pid.stdin.end()
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
connect_node: (tmp_node_name, node_cookie, fa_view)->
node_name = tmp_node_name
atom.project.emp_node_name = tmp_node_name
console.log "node_name:#{node_name}, cookie:#{node_cookie}"
# console.log "-------"
unless node_cookie.match(/\-setcookie/ig)
node_cookie = " -setcookie " +node_cookie
# console.log "------zzz-:#{node_cookie}"
check_flag = ''
unless node_cookie.match(/\-sname|\-name/ig)
# console.log emp.mk_node_name()
tmp_obj = emp.mk_node_name(node_name)
# console.log tmp_obj
check_flag = tmp_obj.name
node_cookie = node_cookie+tmp_obj.node_name
t_erl = '-pa '+parser_beam_epath+node_cookie
re_arg = ["-run", "#{emp.parser_beam_file_mod}", "connect_node", ""+node_name, ""+check_flag]
re_arg = re_arg.concat(t_erl.replace(/\s+/ig, " ").split(" "))
cwd = atom.project.getPaths()[0]
# console.log t_erl
# console.log re_arg
if npid
tmp_pid = npid
npid = null
tmp_pid.kill()
npid = c_process.spawn "erl", re_arg, {cwd:cwd}
connect_state = true
set_node_stat(true)
npid.stdout.on 'data', (data) ->
console.info data.binarySlice()
npid.stderr.on 'data', (data) ->
err_msg = data.binarySlice()
if err_msg is "error_" + check_flag
console.error "Connect remote error"
connect_state = false
set_node_stat(false)
fa_view.refresh_node_st(connect_state)
else
console.error data.binarySlice()
npid.on 'close', (code) ->
connect_state = false
console.log "close -------"
# npid.stdin.write('q().\r\n')
npid.stdin.end()
npid = null
# emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
disconnect_node: ->
if connect_state
if npid
npid.kill()
run_nerl: (erl_str) ->
if connect_state
if npid
if erl_str.match(/^[\w\d]*:[\w\d]*/ig)
erl_str = "#{emp.parser_beam_file_mod}:run_in_remote(\'#{node_name}\', \"#{erl_str}\")."
console.log "erl:#{erl_str}"
npid.stdin.write(erl_str+'\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
make_app_runtime_node: ->
emp_c_make_node = "#{emp.parser_beam_file_mod}:node_fun_call(\'#{node_name}\', node_cmake)."
@run_to_node(emp_c_make_node)
import_menu_node: ->
emp_c_make_node = "#{emp.parser_beam_file_mod}:node_fun_call(\'#{node_name}\', node_import)."
@run_to_node(emp.EMP_IMPORT_MENU_KEY)
make_app_runtime: ->
@run_from_conf(emp.EMP_CMAKE_KEY)
import_menu: ->
@run_from_conf(emp.EMP_IMPORT_MENU_KEY)
run_from_conf: (key)->
erl_str = atom.config.get(key)
# console.log erl_str
if app_state
if pid
# pid.stdin.resume()
pid.stdin.write(erl_str+'\n')
# pid.stdin.end()
# pid.stdin.write('\r\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
run_to_node: (erl_str)->
# ewp_app_manager:all_apps().
if connect_state
if npid
npid.stdin.write(erl_str+'\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
get_app_state: ->
return app_state
initial_path: ->
os_platform = emp.get_emp_os()
# console.log os_platform
if os_platform is emp.OS_DARWIN or os_platform is emp.OS_LINUX
bash_path = atom.config.get(bash_path_key)
# console.log bash_path
# console.log process.env[OS_PATH]
if bash_path is undefined
exportsCommand = process.env.SHELL + " -lc export"
# console.log exportsCommand
# Run the command and update the local process environment:
c_process.exec exportsCommand, (error, stdout, stderr) ->
for definition in stdout.trim().split('\n')
[key, value] = definition.split('=', 2)
key = key.trim().split(" ").pop()
# console.log "key:#{key}, value:#{value}"
unless key isnt emp.OS_PATH
process.env[key] = value
atom.config.set(bash_path_key, value)
else
process.env[emp.OS_PATH] = bash_path
check_project: ->
console.log "checking ~"
do_test: ->
pid = c_process.spawn 'erl', ['-setcookie',' ewpcool', ' -sname', ' test1']
pid.stdout.on 'data', (data) ->
console.log "stdout: #{data}"
pid.stderr.on 'data', (data) ->
console.log "stderr: #{data}"
pid.on 'close', (code) ->
console.log "close: #{code}"
pid.stdin.end()
pid = null
console.log pid
do_send: (str)->
console.log "do_else"
# pid.stdin.write("io:format(\"test ~n\",[]).\r\n")
pid.stdin.write('io:format("test ~n",[]). \n')
# pid.stdin.write("1.")
# pid.stdin.write("q().")
format_stdout = (stdout)->
unless !stdout
for log in stdout.trim().split('\n')
console.info log
format_stderr = (stdout)->
unless !stdout
for log in stdout.trim().split('\n')
console.error log
set_app_stat = (state)->
# console.log "set stat :#{state}"
if state
atom.project.emp_app_pid = pid
else
atom.project.emp_app_pid = null
atom.project.emp_app_state = state
set_node_stat = (state) ->
if state
atom.project.emp_node_pid = npid
else
atom.project.emp_node_pid = null
atom.project.emp_node_state = state
| 212000 | {BufferedProcess,Emitter} = require 'atom'
path = require 'path'
fs = require 'fs'
c_process = require 'child_process'
emp = require '../exports/emp'
bash_path_key = '<KEY>'
pid = null
npid = null
node_name = null
emp_app_view = null
app_state = false
connect_state = false
emp_app_start_script='iewp'
emp_front_app_start_script='/public/simulator'
emp_app_make_cmd='make'
emp_app_config_cmd='configure'
emp_app_config_arg= ['--with-debug']
emp_import_menu = '[{App_name, _}|_]=ewp_app_manager:all_apps(),ewp_channel_util:import_menu(App_name).'
emp_c_make = '[{App_name, _}|_]=ewp_app_manager:all_apps(), ewp:c_app(App_name).'
emp_get_app_name = '[{A, _}|_]=ewp_app_manager:all_apps(), A.'
parser_beam_epath = path.join(__dirname, '../../erl_util/')
# 定义编译文件到 atom conf 中
# emp_app_ ='iewp'
# EMP_MAKE_CMD_KEY = '<KEY>'
# EMP_STAET_SCRIPT_KEY = '<KEY>'
# EMP_CONFIG_KEY = '<KEY>'
# EMP_CONFIG_ARG_KEY = '<KEY>'
module.exports =
class emp_app
project_path: null
erl_project: true
constructor: (tmp_emp_app_view)->
@project_path = atom.project.getPaths()[0]
emp_app_view = tmp_emp_app_view
unless atom.config.get(emp.EMP_MAKE_CMD_KEY)
atom.config.set(emp.EMP_MAKE_CMD_KEY, emp_app_make_cmd)
# else
# emp_app_make_cmd = tmp_emp_make
unless atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
atom.config.set(emp.EMP_STAET_SCRIPT_KEY, emp_app_start_script)
unless atom.config.get(emp.EMP_STAET_FRONT_SCRIPT_KEY)
atom.config.set(emp.EMP_STAET_FRONT_SCRIPT_KEY, emp_front_app_start_script)
# else
# emp_app_start_script = tmp_emp_start_sc
unless atom.config.get(emp.EMP_CONFIG_KEY)
atom.config.set(emp.EMP_CONFIG_KEY, emp_app_config_cmd)
# else
# emp_app_config_cmd = tmp_emp_config_sc
# app_state = false
unless atom.config.get(emp.EMP_CONFIG_ARG_KEY)
atom.config.set(emp.EMP_CONFIG_ARG_KEY, emp_app_config_arg)
unless atom.config.get(emp.EMP_IMPORT_MENU_KEY)
atom.config.set(emp.EMP_IMPORT_MENU_KEY, emp_import_menu)
unless atom.config.get(emp.EMP_CMAKE_KEY)
atom.config.set(emp.EMP_CMAKE_KEY, emp_c_make)
# console.log "project_path:#{@project_path}"
@initial_path()
make_app: ->
# console.log "make"
make_str = atom.config.get(emp.EMP_MAKE_CMD_KEY)
cwd = atom.project.getPaths()[0]
# console.log cwd
c_process.exec make_str, cwd:cwd, (error, stdout, stderr) ->
if (error instanceof Error)
# throw error
console.warn error.message
show_error("Make error ~")
# console.log "compile:#{error}"
# console.log "compile:#{stdout}"
format_stdout(stdout)
format_stderr(stderr)
emp_app_view.hide_loading()
config_app: ->
# console.log "config"
conf_file = atom.config.get(emp.EMP_CONFIG_KEY)
conf_ags = atom.config.get(emp.EMP_CONFIG_ARG_KEY)
# console.log conf_ags
cwd = atom.project.getPaths()[0]
conf_f_p = path.join cwd, conf_file
# console.log conf_f_p
f_state = fs.existsSync conf_f_p
# console.log f_state
# console.log cwd
try
if f_state
conf_stat = fs.statSync(conf_f_p).mode & 0o0777
if conf_stat < 457
fs.chmodSync(conf_f_p, 493)
script_file = atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
script_path = path.join cwd, script_file
# console.log script_path
if fs.existsSync script_path
script_stat = fs.statSync(script_path).mode & 0o0777
if script_stat < 457
fs.chmodSync(conf_f_p, 493)
catch e
console.error e
if f_state
c_process.execFile conf_f_p, conf_ags, cwd:cwd, (error, stdout, stderr) ->
if (error instanceof Error)
# throw error
console.warn error.message
emp.show_error("Configure app error ~")
format_stdout(stdout)
format_stderr(stderr)
emp_app_view.hide_loading()
else
emp.show_error("Configure app error ~")
run_app: ->
# console.log "run"
script_file = atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
script_exc = './' +script_file
cwd = atom.project.getPaths()[0]
script_path = path.join cwd, script_file
# console.log script_path
f_state = fs.existsSync script_path
# console.log f_state
# console.log cwd
# console.log script_exc
# console.log cwd
if f_state
if pid
tmp_pid = pid
pid = null
tmp_pid.kill()
# stdout = (data) ->
# console.log data
# # console.info data.binarySlice()
# stderr = (data) ->
# console.error data.binarySlice()
# exit = (code) ->
# console.log "exit"
# app_state = false
# # pid.stdin.write('q().\r\n')
# # set_app_stat(false)
# pid.stdin.end()
# emp_app_view.refresh_app_st(app_state)
# console.warn "close over:#{code}"
# pid = new BufferedProcess({command:script_exc, args:[], options:{cwd:cwd}, stdout:stdout, stderr:stderr, exit:exit})
pid = c_process.spawn script_exc, [], {cwd:cwd, env: process.env}
app_state = true
set_app_stat(true)
pid.stdout.on 'data', (data) ->
console.info data.binarySlice()
# pid.stdout.pipe process.stdout
pid.stderr.on 'data', (data) ->
console.error data.binarySlice()
pid.on 'SIGINT', (data) ->
console.log "-------------------------"
console.log data
pid.on 'close', (code) ->
app_state = false
# pid.stdin.write('q().\r\n')
# set_app_stat(false)
pid.stdin.end()
pid = null
emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
else
emp.show_error("Run app error ~")
run_front_app: ->
# console.log "run"
script_file = atom.config.get(emp.EMP_STAET_FRONT_SCRIPT_KEY)
script_exc = '.' +script_file
cwd = atom.project.getPaths()[0]
script_path = path.join cwd, script_file
# console.log script_path
f_state = fs.existsSync script_path
if f_state
if pid
tmp_pid = pid
pid = null
tmp_pid.kill()
# pid = new BufferedProcess({command:script_exc, args:[], options:{cwd:cwd}, stdout:stdout, stderr:stderr, exit:exit})
pid = c_process.spawn script_exc, [], {cwd:cwd, env: process.env}
app_state = true
set_app_stat(true)
pid.stdout.on 'data', (data) ->
console.info data.binarySlice()
# pid.stdout.pipe process.stdout
pid.stderr.on 'data', (data) ->
console.error data.binarySlice()
pid.on 'SIGINT', (data) ->
console.log "-------------------------"
console.log data
pid.on 'close', (code) ->
app_state = false
# pid.stdin.write('q().\r\n')
# set_app_stat(false)
pid.stdin.end()
pid = null
emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
else
emp.show_error("Run app error ~")
# test: ({command, args, options, stdout, stderr, exit}={}) ->
# @emitter = new Emitter
# options ?= {}
# # Related to joyent/node#2318
# if process.platform is 'win32'
# # Quote all arguments and escapes inner quotes
# if args?
# cmdArgs = args.filter (arg) -> arg?
# cmdArgs = cmdArgs.map (arg) =>
# if @isExplorerCommand(command) and /^\/[a-zA-Z]+,.*$/.test(arg)
# # Don't wrap /root,C:\folder style arguments to explorer calls in
# # quotes since they will not be interpreted correctly if they are
# arg
# else
# "\"#{arg.toString().replace(/"/g, '\\"')}\""
# else
# cmdArgs = []
# if /\s/.test(command)
# cmdArgs.unshift("\"#{command}\"")
# else
# cmdArgs.unshift(command)
# cmdArgs = ['/s', '/c', "\"#{cmdArgs.join(' ')}\""]
# cmdOptions = _.clone(options)
# cmdOptions.windowsVerbatimArguments = true
# @process = ChildProcess.spawn(@getCmdPath(), cmdArgs, cmdOptions)
# else
# console.log command
# console.log args
# console.log options
# @process = c_process.spawn(command, args, options)
# @killed = false
stop_app: ->
# console.log "stop"
if app_state
app_state = false
set_app_stat(false)
if pid
pid.kill()
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
run_erl: (erl_str) ->
# console.log "erl:#{erl_str}"
if app_state
if pid
# pid.stdin.resume()
pid.stdin.write(erl_str+'\n')
# pid.stdin.end()
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
connect_node: (tmp_node_name, node_cookie, fa_view)->
node_name = tmp_node_name
atom.project.emp_node_name = tmp_node_name
console.log "node_name:#{node_name}, cookie:#{node_cookie}"
# console.log "-------"
unless node_cookie.match(/\-setcookie/ig)
node_cookie = " -setcookie " +node_cookie
# console.log "------zzz-:#{node_cookie}"
check_flag = ''
unless node_cookie.match(/\-sname|\-name/ig)
# console.log emp.mk_node_name()
tmp_obj = emp.mk_node_name(node_name)
# console.log tmp_obj
check_flag = tmp_obj.name
node_cookie = node_cookie+tmp_obj.node_name
t_erl = '-pa '+parser_beam_epath+node_cookie
re_arg = ["-run", "#{emp.parser_beam_file_mod}", "connect_node", ""+node_name, ""+check_flag]
re_arg = re_arg.concat(t_erl.replace(/\s+/ig, " ").split(" "))
cwd = atom.project.getPaths()[0]
# console.log t_erl
# console.log re_arg
if npid
tmp_pid = npid
npid = null
tmp_pid.kill()
npid = c_process.spawn "erl", re_arg, {cwd:cwd}
connect_state = true
set_node_stat(true)
npid.stdout.on 'data', (data) ->
console.info data.binarySlice()
npid.stderr.on 'data', (data) ->
err_msg = data.binarySlice()
if err_msg is "error_" + check_flag
console.error "Connect remote error"
connect_state = false
set_node_stat(false)
fa_view.refresh_node_st(connect_state)
else
console.error data.binarySlice()
npid.on 'close', (code) ->
connect_state = false
console.log "close -------"
# npid.stdin.write('q().\r\n')
npid.stdin.end()
npid = null
# emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
disconnect_node: ->
if connect_state
if npid
npid.kill()
run_nerl: (erl_str) ->
if connect_state
if npid
if erl_str.match(/^[\w\d]*:[\w\d]*/ig)
erl_str = "#{emp.parser_beam_file_mod}:run_in_remote(\'#{node_name}\', \"#{erl_str}\")."
console.log "erl:#{erl_str}"
npid.stdin.write(erl_str+'\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
make_app_runtime_node: ->
emp_c_make_node = "#{emp.parser_beam_file_mod}:node_fun_call(\'#{node_name}\', node_cmake)."
@run_to_node(emp_c_make_node)
import_menu_node: ->
emp_c_make_node = "#{emp.parser_beam_file_mod}:node_fun_call(\'#{node_name}\', node_import)."
@run_to_node(emp.EMP_IMPORT_MENU_KEY)
make_app_runtime: ->
@run_from_conf(emp.EMP_CMAKE_KEY)
import_menu: ->
@run_from_conf(emp.EMP_IMPORT_MENU_KEY)
run_from_conf: (key)->
erl_str = atom.config.get(key)
# console.log erl_str
if app_state
if pid
# pid.stdin.resume()
pid.stdin.write(erl_str+'\n')
# pid.stdin.end()
# pid.stdin.write('\r\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
run_to_node: (erl_str)->
# ewp_app_manager:all_apps().
if connect_state
if npid
npid.stdin.write(erl_str+'\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
get_app_state: ->
return app_state
initial_path: ->
os_platform = emp.get_emp_os()
# console.log os_platform
if os_platform is emp.OS_DARWIN or os_platform is emp.OS_LINUX
bash_path = atom.config.get(bash_path_key)
# console.log bash_path
# console.log process.env[OS_PATH]
if bash_path is undefined
exportsCommand = process.env.SHELL + " -lc export"
# console.log exportsCommand
# Run the command and update the local process environment:
c_process.exec exportsCommand, (error, stdout, stderr) ->
for definition in stdout.trim().split('\n')
[key, value] = definition.split('=', 2)
key = key.trim().split(" ").pop()
# console.log "key:#{key}, value:#{value}"
unless key isnt emp.OS_PATH
process.env[key] = value
atom.config.set(bash_path_key, value)
else
process.env[emp.OS_PATH] = bash_path
check_project: ->
console.log "checking ~"
do_test: ->
pid = c_process.spawn 'erl', ['-setcookie',' ewpcool', ' -sname', ' test1']
pid.stdout.on 'data', (data) ->
console.log "stdout: #{data}"
pid.stderr.on 'data', (data) ->
console.log "stderr: #{data}"
pid.on 'close', (code) ->
console.log "close: #{code}"
pid.stdin.end()
pid = null
console.log pid
do_send: (str)->
console.log "do_else"
# pid.stdin.write("io:format(\"test ~n\",[]).\r\n")
pid.stdin.write('io:format("test ~n",[]). \n')
# pid.stdin.write("1.")
# pid.stdin.write("q().")
format_stdout = (stdout)->
unless !stdout
for log in stdout.trim().split('\n')
console.info log
format_stderr = (stdout)->
unless !stdout
for log in stdout.trim().split('\n')
console.error log
set_app_stat = (state)->
# console.log "set stat :#{state}"
if state
atom.project.emp_app_pid = pid
else
atom.project.emp_app_pid = null
atom.project.emp_app_state = state
set_node_stat = (state) ->
if state
atom.project.emp_node_pid = npid
else
atom.project.emp_node_pid = null
atom.project.emp_node_state = state
| true | {BufferedProcess,Emitter} = require 'atom'
path = require 'path'
fs = require 'fs'
c_process = require 'child_process'
emp = require '../exports/emp'
bash_path_key = 'PI:KEY:<KEY>END_PI'
pid = null
npid = null
node_name = null
emp_app_view = null
app_state = false
connect_state = false
emp_app_start_script='iewp'
emp_front_app_start_script='/public/simulator'
emp_app_make_cmd='make'
emp_app_config_cmd='configure'
emp_app_config_arg= ['--with-debug']
emp_import_menu = '[{App_name, _}|_]=ewp_app_manager:all_apps(),ewp_channel_util:import_menu(App_name).'
emp_c_make = '[{App_name, _}|_]=ewp_app_manager:all_apps(), ewp:c_app(App_name).'
emp_get_app_name = '[{A, _}|_]=ewp_app_manager:all_apps(), A.'
parser_beam_epath = path.join(__dirname, '../../erl_util/')
# 定义编译文件到 atom conf 中
# emp_app_ ='iewp'
# EMP_MAKE_CMD_KEY = 'PI:KEY:<KEY>END_PI'
# EMP_STAET_SCRIPT_KEY = 'PI:KEY:<KEY>END_PI'
# EMP_CONFIG_KEY = 'PI:KEY:<KEY>END_PI'
# EMP_CONFIG_ARG_KEY = 'PI:KEY:<KEY>END_PI'
module.exports =
class emp_app
project_path: null
erl_project: true
constructor: (tmp_emp_app_view)->
@project_path = atom.project.getPaths()[0]
emp_app_view = tmp_emp_app_view
unless atom.config.get(emp.EMP_MAKE_CMD_KEY)
atom.config.set(emp.EMP_MAKE_CMD_KEY, emp_app_make_cmd)
# else
# emp_app_make_cmd = tmp_emp_make
unless atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
atom.config.set(emp.EMP_STAET_SCRIPT_KEY, emp_app_start_script)
unless atom.config.get(emp.EMP_STAET_FRONT_SCRIPT_KEY)
atom.config.set(emp.EMP_STAET_FRONT_SCRIPT_KEY, emp_front_app_start_script)
# else
# emp_app_start_script = tmp_emp_start_sc
unless atom.config.get(emp.EMP_CONFIG_KEY)
atom.config.set(emp.EMP_CONFIG_KEY, emp_app_config_cmd)
# else
# emp_app_config_cmd = tmp_emp_config_sc
# app_state = false
unless atom.config.get(emp.EMP_CONFIG_ARG_KEY)
atom.config.set(emp.EMP_CONFIG_ARG_KEY, emp_app_config_arg)
unless atom.config.get(emp.EMP_IMPORT_MENU_KEY)
atom.config.set(emp.EMP_IMPORT_MENU_KEY, emp_import_menu)
unless atom.config.get(emp.EMP_CMAKE_KEY)
atom.config.set(emp.EMP_CMAKE_KEY, emp_c_make)
# console.log "project_path:#{@project_path}"
@initial_path()
make_app: ->
# console.log "make"
make_str = atom.config.get(emp.EMP_MAKE_CMD_KEY)
cwd = atom.project.getPaths()[0]
# console.log cwd
c_process.exec make_str, cwd:cwd, (error, stdout, stderr) ->
if (error instanceof Error)
# throw error
console.warn error.message
show_error("Make error ~")
# console.log "compile:#{error}"
# console.log "compile:#{stdout}"
format_stdout(stdout)
format_stderr(stderr)
emp_app_view.hide_loading()
config_app: ->
# console.log "config"
conf_file = atom.config.get(emp.EMP_CONFIG_KEY)
conf_ags = atom.config.get(emp.EMP_CONFIG_ARG_KEY)
# console.log conf_ags
cwd = atom.project.getPaths()[0]
conf_f_p = path.join cwd, conf_file
# console.log conf_f_p
f_state = fs.existsSync conf_f_p
# console.log f_state
# console.log cwd
try
if f_state
conf_stat = fs.statSync(conf_f_p).mode & 0o0777
if conf_stat < 457
fs.chmodSync(conf_f_p, 493)
script_file = atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
script_path = path.join cwd, script_file
# console.log script_path
if fs.existsSync script_path
script_stat = fs.statSync(script_path).mode & 0o0777
if script_stat < 457
fs.chmodSync(conf_f_p, 493)
catch e
console.error e
if f_state
c_process.execFile conf_f_p, conf_ags, cwd:cwd, (error, stdout, stderr) ->
if (error instanceof Error)
# throw error
console.warn error.message
emp.show_error("Configure app error ~")
format_stdout(stdout)
format_stderr(stderr)
emp_app_view.hide_loading()
else
emp.show_error("Configure app error ~")
run_app: ->
# console.log "run"
script_file = atom.config.get(emp.EMP_STAET_SCRIPT_KEY)
script_exc = './' +script_file
cwd = atom.project.getPaths()[0]
script_path = path.join cwd, script_file
# console.log script_path
f_state = fs.existsSync script_path
# console.log f_state
# console.log cwd
# console.log script_exc
# console.log cwd
if f_state
if pid
tmp_pid = pid
pid = null
tmp_pid.kill()
# stdout = (data) ->
# console.log data
# # console.info data.binarySlice()
# stderr = (data) ->
# console.error data.binarySlice()
# exit = (code) ->
# console.log "exit"
# app_state = false
# # pid.stdin.write('q().\r\n')
# # set_app_stat(false)
# pid.stdin.end()
# emp_app_view.refresh_app_st(app_state)
# console.warn "close over:#{code}"
# pid = new BufferedProcess({command:script_exc, args:[], options:{cwd:cwd}, stdout:stdout, stderr:stderr, exit:exit})
pid = c_process.spawn script_exc, [], {cwd:cwd, env: process.env}
app_state = true
set_app_stat(true)
pid.stdout.on 'data', (data) ->
console.info data.binarySlice()
# pid.stdout.pipe process.stdout
pid.stderr.on 'data', (data) ->
console.error data.binarySlice()
pid.on 'SIGINT', (data) ->
console.log "-------------------------"
console.log data
pid.on 'close', (code) ->
app_state = false
# pid.stdin.write('q().\r\n')
# set_app_stat(false)
pid.stdin.end()
pid = null
emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
else
emp.show_error("Run app error ~")
run_front_app: ->
# console.log "run"
script_file = atom.config.get(emp.EMP_STAET_FRONT_SCRIPT_KEY)
script_exc = '.' +script_file
cwd = atom.project.getPaths()[0]
script_path = path.join cwd, script_file
# console.log script_path
f_state = fs.existsSync script_path
if f_state
if pid
tmp_pid = pid
pid = null
tmp_pid.kill()
# pid = new BufferedProcess({command:script_exc, args:[], options:{cwd:cwd}, stdout:stdout, stderr:stderr, exit:exit})
pid = c_process.spawn script_exc, [], {cwd:cwd, env: process.env}
app_state = true
set_app_stat(true)
pid.stdout.on 'data', (data) ->
console.info data.binarySlice()
# pid.stdout.pipe process.stdout
pid.stderr.on 'data', (data) ->
console.error data.binarySlice()
pid.on 'SIGINT', (data) ->
console.log "-------------------------"
console.log data
pid.on 'close', (code) ->
app_state = false
# pid.stdin.write('q().\r\n')
# set_app_stat(false)
pid.stdin.end()
pid = null
emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
else
emp.show_error("Run app error ~")
# test: ({command, args, options, stdout, stderr, exit}={}) ->
# @emitter = new Emitter
# options ?= {}
# # Related to joyent/node#2318
# if process.platform is 'win32'
# # Quote all arguments and escapes inner quotes
# if args?
# cmdArgs = args.filter (arg) -> arg?
# cmdArgs = cmdArgs.map (arg) =>
# if @isExplorerCommand(command) and /^\/[a-zA-Z]+,.*$/.test(arg)
# # Don't wrap /root,C:\folder style arguments to explorer calls in
# # quotes since they will not be interpreted correctly if they are
# arg
# else
# "\"#{arg.toString().replace(/"/g, '\\"')}\""
# else
# cmdArgs = []
# if /\s/.test(command)
# cmdArgs.unshift("\"#{command}\"")
# else
# cmdArgs.unshift(command)
# cmdArgs = ['/s', '/c', "\"#{cmdArgs.join(' ')}\""]
# cmdOptions = _.clone(options)
# cmdOptions.windowsVerbatimArguments = true
# @process = ChildProcess.spawn(@getCmdPath(), cmdArgs, cmdOptions)
# else
# console.log command
# console.log args
# console.log options
# @process = c_process.spawn(command, args, options)
# @killed = false
stop_app: ->
# console.log "stop"
if app_state
app_state = false
set_app_stat(false)
if pid
pid.kill()
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
run_erl: (erl_str) ->
# console.log "erl:#{erl_str}"
if app_state
if pid
# pid.stdin.resume()
pid.stdin.write(erl_str+'\n')
# pid.stdin.end()
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
connect_node: (tmp_node_name, node_cookie, fa_view)->
node_name = tmp_node_name
atom.project.emp_node_name = tmp_node_name
console.log "node_name:#{node_name}, cookie:#{node_cookie}"
# console.log "-------"
unless node_cookie.match(/\-setcookie/ig)
node_cookie = " -setcookie " +node_cookie
# console.log "------zzz-:#{node_cookie}"
check_flag = ''
unless node_cookie.match(/\-sname|\-name/ig)
# console.log emp.mk_node_name()
tmp_obj = emp.mk_node_name(node_name)
# console.log tmp_obj
check_flag = tmp_obj.name
node_cookie = node_cookie+tmp_obj.node_name
t_erl = '-pa '+parser_beam_epath+node_cookie
re_arg = ["-run", "#{emp.parser_beam_file_mod}", "connect_node", ""+node_name, ""+check_flag]
re_arg = re_arg.concat(t_erl.replace(/\s+/ig, " ").split(" "))
cwd = atom.project.getPaths()[0]
# console.log t_erl
# console.log re_arg
if npid
tmp_pid = npid
npid = null
tmp_pid.kill()
npid = c_process.spawn "erl", re_arg, {cwd:cwd}
connect_state = true
set_node_stat(true)
npid.stdout.on 'data', (data) ->
console.info data.binarySlice()
npid.stderr.on 'data', (data) ->
err_msg = data.binarySlice()
if err_msg is "error_" + check_flag
console.error "Connect remote error"
connect_state = false
set_node_stat(false)
fa_view.refresh_node_st(connect_state)
else
console.error data.binarySlice()
npid.on 'close', (code) ->
connect_state = false
console.log "close -------"
# npid.stdin.write('q().\r\n')
npid.stdin.end()
npid = null
# emp_app_view.refresh_app_st(app_state)
console.warn "close over:#{code}"
disconnect_node: ->
if connect_state
if npid
npid.kill()
run_nerl: (erl_str) ->
if connect_state
if npid
if erl_str.match(/^[\w\d]*:[\w\d]*/ig)
erl_str = "#{emp.parser_beam_file_mod}:run_in_remote(\'#{node_name}\', \"#{erl_str}\")."
console.log "erl:#{erl_str}"
npid.stdin.write(erl_str+'\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
make_app_runtime_node: ->
emp_c_make_node = "#{emp.parser_beam_file_mod}:node_fun_call(\'#{node_name}\', node_cmake)."
@run_to_node(emp_c_make_node)
import_menu_node: ->
emp_c_make_node = "#{emp.parser_beam_file_mod}:node_fun_call(\'#{node_name}\', node_import)."
@run_to_node(emp.EMP_IMPORT_MENU_KEY)
make_app_runtime: ->
@run_from_conf(emp.EMP_CMAKE_KEY)
import_menu: ->
@run_from_conf(emp.EMP_IMPORT_MENU_KEY)
run_from_conf: (key)->
erl_str = atom.config.get(key)
# console.log erl_str
if app_state
if pid
# pid.stdin.resume()
pid.stdin.write(erl_str+'\n')
# pid.stdin.end()
# pid.stdin.write('\r\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
run_to_node: (erl_str)->
# ewp_app_manager:all_apps().
if connect_state
if npid
npid.stdin.write(erl_str+'\n')
else
emp.show_error("no Pid ~")
else
emp.show_error("The app is not running ~")
get_app_state: ->
return app_state
initial_path: ->
os_platform = emp.get_emp_os()
# console.log os_platform
if os_platform is emp.OS_DARWIN or os_platform is emp.OS_LINUX
bash_path = atom.config.get(bash_path_key)
# console.log bash_path
# console.log process.env[OS_PATH]
if bash_path is undefined
exportsCommand = process.env.SHELL + " -lc export"
# console.log exportsCommand
# Run the command and update the local process environment:
c_process.exec exportsCommand, (error, stdout, stderr) ->
for definition in stdout.trim().split('\n')
[key, value] = definition.split('=', 2)
key = key.trim().split(" ").pop()
# console.log "key:#{key}, value:#{value}"
unless key isnt emp.OS_PATH
process.env[key] = value
atom.config.set(bash_path_key, value)
else
process.env[emp.OS_PATH] = bash_path
check_project: ->
console.log "checking ~"
do_test: ->
pid = c_process.spawn 'erl', ['-setcookie',' ewpcool', ' -sname', ' test1']
pid.stdout.on 'data', (data) ->
console.log "stdout: #{data}"
pid.stderr.on 'data', (data) ->
console.log "stderr: #{data}"
pid.on 'close', (code) ->
console.log "close: #{code}"
pid.stdin.end()
pid = null
console.log pid
do_send: (str)->
console.log "do_else"
# pid.stdin.write("io:format(\"test ~n\",[]).\r\n")
pid.stdin.write('io:format("test ~n",[]). \n')
# pid.stdin.write("1.")
# pid.stdin.write("q().")
format_stdout = (stdout)->
unless !stdout
for log in stdout.trim().split('\n')
console.info log
format_stderr = (stdout)->
unless !stdout
for log in stdout.trim().split('\n')
console.error log
set_app_stat = (state)->
# console.log "set stat :#{state}"
if state
atom.project.emp_app_pid = pid
else
atom.project.emp_app_pid = null
atom.project.emp_app_state = state
set_node_stat = (state) ->
if state
atom.project.emp_node_pid = npid
else
atom.project.emp_node_pid = null
atom.project.emp_node_state = state
|
[
{
"context": "ouchdb.user:u\", \"auth\").reply 201,\n username: \"u\"\n password: \"p\"\n email: \"u@p.me\"\n\n return\n",
"end": 195,
"score": 0.9807816743850708,
"start": 194,
"tag": "USERNAME",
"value": "u"
},
{
"context": "uth\").reply 201,\n username: \"u\"\n pas... | deps/npm/test/tap/login-always-auth.coffee | lxe/io.coffee | 0 | mocks = (server) ->
server.filteringRequestBody (r) ->
"auth" if r.match(/\"_id\":\"org\.couchdb\.user:u\"/)
server.put("/-/user/org.couchdb.user:u", "auth").reply 201,
username: "u"
password: "p"
email: "u@p.me"
return
fs = require("fs")
path = require("path")
rimraf = require("rimraf")
mr = require("npm-registry-mock")
test = require("tap").test
common = require("../common-tap.js")
opts = cwd: __dirname
outfile = path.resolve(__dirname, "_npmrc")
responses =
Username: "u\n"
Password: "p\n"
Email: "u@p.me\n"
test "npm login", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=false/, "always-auth is scoped and false (by default)"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "npm login --always-auth", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
"--always-auth"
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=true/, "always-auth is scoped and true"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "npm login --no-always-auth", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
"--no-always-auth"
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=false/, "always-auth is scoped and false"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "cleanup", (t) ->
rimraf.sync outfile
t.pass "cleaned up"
t.end()
return
| 86800 | mocks = (server) ->
server.filteringRequestBody (r) ->
"auth" if r.match(/\"_id\":\"org\.couchdb\.user:u\"/)
server.put("/-/user/org.couchdb.user:u", "auth").reply 201,
username: "u"
password: "<PASSWORD>"
email: "<EMAIL>"
return
fs = require("fs")
path = require("path")
rimraf = require("rimraf")
mr = require("npm-registry-mock")
test = require("tap").test
common = require("../common-tap.js")
opts = cwd: __dirname
outfile = path.resolve(__dirname, "_npmrc")
responses =
Username: "u\n"
Password: "<PASSWORD>"
Email: "u@p.me\n"
test "npm login", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=false/, "always-auth is scoped and false (by default)"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "npm login --always-auth", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
"--always-auth"
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=true/, "always-auth is scoped and true"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "npm login --no-always-auth", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
"--no-always-auth"
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=false/, "always-auth is scoped and false"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "cleanup", (t) ->
rimraf.sync outfile
t.pass "cleaned up"
t.end()
return
| true | mocks = (server) ->
server.filteringRequestBody (r) ->
"auth" if r.match(/\"_id\":\"org\.couchdb\.user:u\"/)
server.put("/-/user/org.couchdb.user:u", "auth").reply 201,
username: "u"
password: "PI:PASSWORD:<PASSWORD>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
return
fs = require("fs")
path = require("path")
rimraf = require("rimraf")
mr = require("npm-registry-mock")
test = require("tap").test
common = require("../common-tap.js")
opts = cwd: __dirname
outfile = path.resolve(__dirname, "_npmrc")
responses =
Username: "u\n"
Password: "PI:PASSWORD:<PASSWORD>END_PI"
Email: "u@p.me\n"
test "npm login", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=false/, "always-auth is scoped and false (by default)"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "npm login --always-auth", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
"--always-auth"
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=true/, "always-auth is scoped and true"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "npm login --no-always-auth", (t) ->
mr
port: common.port
mocks: mocks
, (s) ->
runner = common.npm([
"login"
"--registry"
common.registry
"--loglevel"
"silent"
"--userconfig"
outfile
"--no-always-auth"
], opts, (err, code) ->
t.notOk code, "exited OK"
t.notOk err, "no error output"
config = fs.readFileSync(outfile, "utf8")
t.like config, /:always-auth=false/, "always-auth is scoped and false"
s.close()
rimraf outfile, (err) ->
t.ifError err, "removed config file OK"
t.end()
return
return
)
o = ""
e = ""
remaining = Object.keys(responses).length
runner.stdout.on "data", (chunk) ->
remaining--
o += chunk
label = chunk.toString("utf8").split(":")[0]
runner.stdin.write responses[label]
runner.stdin.end() if remaining is 0
return
runner.stderr.on "data", (chunk) ->
e += chunk
return
return
return
test "cleanup", (t) ->
rimraf.sync outfile
t.pass "cleaned up"
t.end()
return
|
[
{
"context": "rs\n\t\tLogger.module(\"IO\").log \"DECODED TOKEN ID: #{socket.decoded_token.d.id.blue}\"\n\n\t\tsavePlayerCount(++pl",
"end": 3800,
"score": 0.5184482932090759,
"start": 3794,
"tag": "KEY",
"value": "socket"
},
{
"context": "IO\").log \"DECODED TOKEN ID: #{socket.decod... | server/single_player.coffee | willroberts/duelyst | 0 | ###
Game Server Pieces
###
fs = require 'fs'
os = require 'os'
util = require 'util'
_ = require 'underscore'
colors = require 'colors' # used for console message coloring
jwt = require 'jsonwebtoken'
io = require 'socket.io'
ioJwt = require 'socketio-jwt'
Promise = require 'bluebird'
kue = require 'kue'
moment = require 'moment'
request = require 'superagent'
# Our modules
shutdown = require './shutdown'
StarterAI = require './ai/starter_ai'
SDK = require '../app/sdk.coffee'
Logger = require '../app/common/logger.coffee'
EVENTS = require '../app/common/event_types'
UtilsGameSession = require '../app/common/utils/utils_game_session.coffee'
exceptionReporter = require '@counterplay/exception-reporter'
# lib Modules
Consul = require './lib/consul'
# Configuration object
config = require '../config/config.js'
env = config.get('env')
firebaseToken = config.get('firebaseToken')
# Boots up a basic HTTP server on port 8080
# Responds to /health endpoint with status 200
# Otherwise responds with status 404
Logger = require '../app/common/logger.coffee'
CONFIG = require '../app/common/config'
http = require 'http'
url = require 'url'
Promise = require 'bluebird'
# perform DNS health check
dnsHealthCheck = () ->
if config.isDevelopment()
return Promise.resolve({healthy: true})
nodename = "#{config.get('env')}-#{os.hostname().split('.')[0]}"
return Consul.kv.get("nodes/#{nodename}/dns_name")
.then (dnsName) ->
return new Promise (resolve, reject) ->
request.get("https://#{dnsName}/health")
.end (err, res) ->
if err
return resolve({dnsName: dnsName, healthy: false})
if res? && res.status == 200
return resolve({dnsName: dnsName, healthy: true})
return ({dnsName: dnsName, healthy: false})
.catch (e) ->
return {healthy: false}
# create http server and respond to /health requests
server = http.createServer (req, res) ->
pathname = url.parse(req.url).pathname
if pathname == '/health'
Logger.module("GAME SERVER").debug "HTTP Health Ping"
res.statusCode = 200
res.write JSON.stringify({players: playerCount, games: gameCount})
res.end()
else
res.statusCode = 404
res.end()
# io server setup, binds to http server
io = require('socket.io')().listen(server, {
cors: {
origin: "*"
}
})
io.use(
ioJwt.authorize(
secret:firebaseToken
timeout: 15000
)
)
module.exports = io
server.listen config.get('game_port'), () ->
Logger.module("AI SERVER").log "AI Server <b>#{os.hostname()}</b> started."
# redis
{Redis, Jobs, GameManager} = require './redis/'
# server id for this game server
serverId = os.hostname()
# the 'games' hash maps game IDs to References for those games
games = {}
# save some basic stats about this server into redis
playerCount = 0
gameCount = 0
# turn times
MAX_TURN_TIME = (CONFIG.TURN_DURATION + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0
MAX_TURN_TIME_INACTIVE = (CONFIG.TURN_DURATION_INACTIVE + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0
savePlayerCount = (playerCount) ->
Redis.hsetAsync("servers:#{serverId}", "players", playerCount)
saveGameCount = (gameCount) ->
Redis.hsetAsync("servers:#{serverId}", "games", gameCount)
# error 'domain' to deal with io.sockets uncaught errors
d = require('domain').create()
d.on 'error', shutdown.errorShutdown
d.add(io.sockets)
# health ping on socket namespace /health
healthPing = io
.of '/health'
.on 'connection', (socket) ->
socket.on 'ping', () ->
Logger.module("GAME SERVER").debug "socket.io Health Ping"
socket.emit 'pong'
# run main io.sockets inside of the domain
d.run () ->
io.sockets.on "authenticated", (socket) ->
# add the socket to the error domain
d.add(socket)
# Socket is now autheticated, continue to bind other handlers
Logger.module("IO").log "DECODED TOKEN ID: #{socket.decoded_token.d.id.blue}"
savePlayerCount(++playerCount)
# Send message to user that connection is succesful
socket.emit "connected",
message: "Successfully connected to server"
# Bind socket event handlers
socket.on EVENTS.join_game, onGamePlayerJoin
socket.on EVENTS.spectate_game, onGameSpectatorJoin
socket.on EVENTS.leave_game, onGameLeave
socket.on EVENTS.network_game_event, onGameEvent
socket.on "disconnect", onGameDisconnect
getConnectedSpectatorsDataForGamePlayer = (gameId,playerId)->
spectators = []
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
socket = io.sockets.connected[socketId]
if socket.playerId == playerId
spectators.push({
id:socket.spectatorId,
playerId:socket.playerId,
username:socket.spectateToken?.u
})
return spectators
###
# socket handler for players joining game
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGamePlayerJoin = (requestData) ->
# request parameters
gameId = requestData.gameId
playerId = requestData.playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> player:#{requestData.playerId} is joining game:#{requestData.gameId}".cyan
# you must have a playerId
if not playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red
@emit "join_game_response",
error:"Your player id seems to be blank (has your login expired?), so we can't join you to the game."
return
# must have a gameId
if not gameId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red
@emit "join_game_response",
error:"Invalid Game ID."
return
# if someone is trying to join a game they don't belong to as a player they are not authenticated as
if @.decoded_token.d.id != playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red
@emit "join_game_response",
error:"Your player id does not match the one you requested to join a game with. Are you sure you're joining the right game?"
return
# if a client is already in another game, leave it
playerLeaveGameIfNeeded(this)
# if this client already exists in this game, disconnect duplicate client
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> detected duplicate connection to #{gameId} GameSession for #{playerId.blue}. Disconnecting duplicate...".cyan
playerLeaveGameIfNeeded(socket, silent=true)
# initialize a server-side game session and join it
initGameSession(gameId)
.bind @
.spread (gameSession) ->
#Logger.module("IO").debug "[G:#{gameId}]", "join_game -> players in data: ", gameSession.players
# player
player = _.find(gameSession.players, (p) -> return p.playerId == playerId)
# get the opponent based on the game session data
opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId)
Logger.module("IO").log "[G:#{gameId}]", "join_game -> Got #{gameId} GameSession data #{playerId.blue}.".cyan
if not player # oops looks like this player does not exist in the requested game
# let the socket know we had an error
@emit "join_game_response",
error:"could not join game because your player id could not be found"
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else if not opponent? # oops, looks like we can'f find an opponent in the game session?
Logger.module("IO").log "[G:#{gameId}]", "join_game -> game #{gameId} ERROR: could not find opponent for #{playerId.blue}.".red
# let the socket know we had an error
@emit "join_game_response",
error:"could not join game because the opponent could not be found"
# issue a warning to our exceptionReporter error tracker
exceptionReporter.notify(new Error("Error joining game: could not find opponent"), {
severity: "warning"
user:
id: playerId
game:
id: gameId
player1Id: gameSession?.players[0].playerId
player2Id: gameSession?.players[1].playerId
})
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else
# rollback if it is this player's followup
# this can happen if a player reconnects without properly disconnecting
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() == playerId
gameSession.executeAction(gameSession.actionRollbackSnapshot())
# set some parameters for the socket
@gameId = gameId
@playerId = playerId
# join game room
@join(gameId)
# update user count for game room
games[gameId].connectedPlayers.push(playerId)
Logger.module("IO").log "[G:#{gameId}]", "join_game -> Game #{gameId} connected players so far: #{games[gameId].connectedPlayers.length}."
# if only one player is in so far, start the disconnection timer
if games[gameId].connectedPlayers.length == 1
# start disconnected player timeout for game
startDisconnectedPlayerTimeout(gameId,opponent.playerId)
else if games[gameId].connectedPlayers.length == 2
# clear timeout when we get two players
clearDisconnectedPlayerTimeout(gameId)
# prepare and scrub game session data for this player
# if a followup is active and it isn't this player's followup, send them the rollback snapshot
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId
gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData())
else
gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession))
UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId)
# respond to client with success and a scrubbed copy of the game session
@emit "join_game_response",
message: "successfully joined game"
gameSessionData: gameSessionData
connectedPlayers:games[gameId].connectedPlayers
connectedSpectators: getConnectedSpectatorsDataForGamePlayer(gameId,playerId)
# broadcast join to any other connected players
@broadcast.to(gameId).emit("player_joined",playerId)
# attempt to update ai turn on active game
if gameSession.isActive()
ai_updateTurn(gameId)
.catch (e) ->
Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game. ERROR: #{e.message}".red
# if we didn't join a game, broadcast a failure
@emit "join_game_response",
error:"Could not join game: " + e?.message
###
# socket handler for spectators joining game
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGameSpectatorJoin = (requestData) ->
# request parameters
# TODO : Sanitize these parameters to prevent crash if gameId = null
gameId = requestData.gameId
spectatorId = requestData.spectatorId
playerId = requestData.playerId
spectateToken = null
# verify - synchronous
try
spectateToken = jwt.verify(requestData.spectateToken, firebaseToken)
catch error
Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> ERROR decoding spectate token: #{error?.message}".red
if not spectateToken or spectateToken.b?.length == 0
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A specate token #{spectateToken} is not valid".red
@emit "spectate_game_response",
error:"Your spectate token is invalid, so we can't join you to the game."
return
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> token contents: ", spectateToken.b
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> playerId: ", playerId
if not _.contains(spectateToken.b,playerId)
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: You do not have permission to specate this game".red
@emit "spectate_game_response",
error:"You do not have permission to specate this game."
return
# must have a spectatorId
if not spectatorId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A spectator #{spectatorId.blue} is not valid".red
@emit "spectate_game_response",
error:"Your login ID is blank (expired?), so we can't join you to the game."
return
# must have a playerId
if not playerId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red
@emit "spectate_game_response",
error:"Invalid player ID."
return
# must have a gameId
if not gameId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red
@emit "spectate_game_response",
error:"Invalid Game ID."
return
# if someone is trying to join a game they don't belong to as a player they are not authenticated as
if @.decoded_token.d.id != spectatorId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red
@emit "spectate_game_response",
error:"Your login ID does not match the one you requested to spectate the game with."
return
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> spectator:#{spectatorId} is joining game:#{gameId}".cyan
# if a client is already in another game, leave it
spectatorLeaveGameIfNeeded(@)
if games[gameId]?.connectedSpectators.length >= 10
# max out at 10 spectators
@emit "spectate_game_response",
error:"Maximum number of spectators already watching."
return
# initialize a server-side game session and join it
initSpectatorGameSession(gameId)
.bind @
.then (spectatorGameSession) ->
# for spectators, use the delayed in-memory game session
gameSession = spectatorGameSession
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> Got #{gameId} GameSession data.".cyan
player = _.find(gameSession.players, (p) -> return p.playerId == playerId)
opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId)
if not player
# let the socket know we had an error
@emit "spectate_game_response",
error:"could not join game because the player id you requested could not be found"
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameSpectatorJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else
# set some parameters for the socket
@gameId = gameId
@spectatorId = spectatorId
@spectateToken = spectateToken
@playerId = playerId
# join game room
@join("spectate-#{gameId}")
# update user count for game room
games[gameId].connectedSpectators.push(spectatorId)
# prepare and scrub game session data for this player
# if a followup is active and it isn't this player's followup, send them the rollback snapshot
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId
gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData())
else
gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession))
UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId, true)
###
# if the spectator does not have the opponent in their buddy list
if not _.contains(spectateToken.b,opponent.playerId)
# scrub deck data and opponent hand data by passing in opponent ID
scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId)
else
# otherwise just scrub deck data in a way you can see both decks
# scrubGameSessionDataForSpectators(gameSession, gameSessionData)
# NOTE: above line is disabled for now since it does some UI jankiness since when a cardId is present the tile layer updates when the spectated opponent starts to select cards
# NOTE: besides, actions will be scrubbed so this idea of watching both players only sort of works right now
scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId, true)
###
# respond to client with success and a scrubbed copy of the game session
@emit "spectate_game_response",
message: "successfully joined game"
gameSessionData: gameSessionData
# broadcast to the game room that a spectator has joined
@broadcast.to(gameId).emit("spectator_joined",{
id: spectatorId,
playerId: playerId,
username: spectateToken.u
})
.catch (e) ->
# if we didn't join a game, broadcast a failure
@emit "spectate_game_response",
error:"could not join game: #{e.message}"
###
# socket handler for leaving a game.
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGameLeave = (requestData) ->
if @.spectatorId
Logger.module("IO").log "[G:#{@.gameId}]", "leave_game -> spectator #{@.spectatorId} leaving #{@.gameId}"
spectatorLeaveGameIfNeeded(@)
else
Logger.module("IO").log "[G:#{@.gameId}]", "leave_game -> player #{@.playerId} leaving #{@.gameId}"
playerLeaveGameIfNeeded(@)
###*
# This method is called every time a socket handler recieves a game event and is executed within the context of the socket (this == sending socket).
# @public
# @param {Object} eventData Plain JS object with event data that contains one "event".
###
onGameEvent = (eventData) ->
# if for some reason spectator sockets start broadcasting game events
if @.spectatorId
Logger.module("IO").log "[G:#{@.gameId}]", "onGameEvent :: ERROR: spectator sockets can't submit game events. (type: #{eventData.type})".red
return
# Logger.module("IO").log "onGameEvent -> #{JSON.stringify(eventData)}".blue
if not @gameId or not games[@gameId]
@emit EVENTS.network_game_error,
code:500
message:"could not broadcast game event because you are not currently in a game"
return
#
gameSession = games[@gameId].session
if eventData.type == EVENTS.step
#Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{JSON.stringify(eventData.step)}".green
#Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{eventData.step?.playerId} #{eventData.step?.action?.type}".green
player = _.find(gameSession.players,(p)-> p.playerId == eventData.step?.playerId)
player?.setLastActionTakenAt(Date.now())
try
step = gameSession.deserializeStepFromFirebase(eventData.step)
action = step.action
if action?
# clear out any implicit actions sent over the network and re-execute this as a fresh explicit action on the server
# the reason is that we want to re-generate and re-validate all the game logic that happens as a result of this FIRST explicit action in the step
action.resetForAuthoritativeExecution()
# execute the action
gameSession.executeAction(action)
catch error
Logger.module("IO").log "[G:#{@.gameId}]", "onGameStep:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{@.gameId}]", "onGameStep:: error stack: #{error.stack}".red
# Report error to exceptionReporter with gameId + eventData
exceptionReporter.notify(error, {
errorName: "onGameStep Error",
game: {
gameId: @gameId
eventData: eventData
}
})
# delete but don't destroy game
destroyGameSessionIfNoConnectionsLeft(@gameId,true)
# send error to client, forcing reconnect on client side
io.to(@gameId).emit EVENTS.network_game_error, JSON.stringify(error.message)
return
else
# transmit the non-step game events to players
# step events are emitted automatically after executed on game session
emitGameEvent(@, @gameId, eventData)
###
# Socket Disconnect Event Handler. Handles rollback if in the middle of followup etc.
# @public
###
onGameDisconnect = () ->
if @.spectatorId
# make spectator leave game room
spectatorLeaveGameIfNeeded(@)
# remove the socket from the error domain, this = socket
d.remove(@)
else
try
clients_in_the_room = io.sockets.adapter.rooms[@.gameId]
for clientId,socket of clients_in_the_room
if socket.playerId == @.playerId
Logger.module("IO").log "onGameDisconnect:: looks like the player #{@.playerId} we are trying to disconnect is still in the game #{@.gameId} room. ABORTING".red
return
for clientId,socket of io.sockets.connected
if socket.playerId == @.playerId and not socket.spectatorId
Logger.module("IO").log "onGameDisconnect:: looks like the player #{@.playerId} that allegedly disconnected is still alive and well.".red
return
catch error
Logger.module("IO").log "onGameDisconnect:: Error #{error?.message}.".red
# if we are in a buffering state
# and the disconnecting player is in the middle of a followup
gs = games[@gameId]?.session
if gs? and gs.getIsBufferingEvents() and gs.getCurrentPlayerId() == @playerId
# execute a rollback to reset server state
# but do not send this action to the still connected player
# because they do not care about rollbacks for the other player
rollBackAction = gs.actionRollbackSnapshot()
gs.executeAction(rollBackAction)
# remove the socket from the error domain, this = socket
d.remove(@)
savePlayerCount(--playerCount)
Logger.module("IO").log "[G:#{@.gameId}]", "disconnect -> #{@.playerId}".red
# if a client is already in another game, leave it
playerLeaveGameIfNeeded(@)
###*
* Leaves a game for a player socket if the socket is connected to a game
* @public
* @param {Socket} socket The socket which wants to leave a game.
* @param {Boolean} [silent=false] whether to disconnect silently, as in the case of duplicate connections for same player
###
playerLeaveGameIfNeeded = (socket, silent=false) ->
if socket?
gameId = socket.gameId
playerId = socket.playerId
# if a player is in a game
if gameId? and playerId?
Logger.module("...").log "[G:#{gameId}]", "playerLeaveGame -> #{playerId} has left game #{gameId}".red
if !silent
# broadcast that player left
socket.broadcast.to(gameId).emit("player_left",playerId)
# leave that game room
socket.leave(gameId)
# update user count for game room
game = games[gameId]
if game?
index = game.connectedPlayers.indexOf(playerId)
game.connectedPlayers.splice(index,1)
if !silent
# start disconnected player timeout for game
startDisconnectedPlayerTimeout(gameId,playerId)
# destroy game if no one is connected anymore
destroyGameSessionIfNoConnectionsLeft(gameId,true)
# finally clear the existing gameId
socket.gameId = null
###
# This function leaves a game for a spectator socket if the socket is connected to a game
# @public
# @param {Socket} socket The socket which wants to leave a game.
###
spectatorLeaveGameIfNeeded = (socket) ->
# if a client is already in another game
if socket.gameId
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} leaving game #{socket.gameId}."
# broadcast that you left
socket.broadcast.to(socket.gameId).emit("spectator_left",{
id:socket.spectatorId,
playerId:socket.playerId,
username:socket.spectateToken?.u
})
# leave specator game room
socket.leave("spectate-#{socket.gameId}")
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} left room for game #{socket.gameId}."
# update spectator count for game room
if games[socket.gameId]
games[socket.gameId].connectedSpectators = _.without(games[socket.gameId].connectedSpectators,socket.spectatorId)
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} removed from list of spectators #{socket.gameId}."
# if no spectators left, stop the delayed game interval and destroy spectator delayed game session
tearDownSpectateSystemsIfNoSpectatorsLeft(socket.gameId)
# destroy game if no one is connected anymore
destroyGameSessionIfNoConnectionsLeft(socket.gameId,true)
remainingSpectators = games[socket.gameId]?.connectedSpectators?.length || 0
Logger.module("...").log "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} has left game #{socket.gameId}. remaining spectators #{remainingSpectators}"
# finally clear the existing gameId
socket.gameId = null
###
# This function destroys in-memory game session of there is no one left connected
# @public
# @param {String} gameId The ID of the game to destroy.
# @param {Boolean} persist Do we need to save/archive this game?
###
destroyGameSessionIfNoConnectionsLeft = (gameId,persist=false)->
if games[gameId].connectedPlayers.length == 1 and games[gameId].connectedSpectators.length == 0
clearDisconnectedPlayerTimeout(gameId)
stopTurnTimer(gameId)
tearDownSpectateSystemsIfNoSpectatorsLeft(gameId)
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> no players left DESTROYING local game cache".red
unsubscribeFromGameSessionEvents(gameId)
ai_terminate(gameId)
# TEMP: a way to upload unfinished game data to AWS S3 Archive. For example: errored out games.
if persist and games?[gameId]?.session?.status != SDK.GameStatus.over
data = games[gameId].session.serializeToJSON(games[gameId].session)
mouseAndUIEventsData = JSON.stringify(games[gameId].mouseAndUIEvents)
Promise.all([
GameManager.saveGameSession(gameId,data),
GameManager.saveGameMouseUIData(gameId,mouseAndUIEventsData),
])
.then (results) ->
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> unfinished Game Archived to S3: #{results[1]}".green
.catch (error)->
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> ERROR: failed to archive unfinished game to S3 due to error #{error.message}".red
delete games[gameId]
saveGameCount(--gameCount)
else
Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> players left: #{games[gameId].connectedPlayers.length} spectators left: #{games[gameId].connectedSpectators.length}"
###
# This function stops all spectate systems if 0 spectators left.
# @public
# @param {String} gameId The ID of the game to tear down spectate systems.
###
tearDownSpectateSystemsIfNoSpectatorsLeft = (gameId)->
# if no spectators left, stop the delayed game interval and destroy spectator delayed game session
if games[gameId]?.connectedSpectators.length == 0
Logger.module("IO").debug "[G:#{gameId}]", "tearDownSpectateSystemsIfNoSpectatorsLeft() -> no spectators left, stopping spectate systems"
stopSpectatorDelayedGameInterval(gameId)
games[gameId].spectatorDelayedGameSession = null
games[gameId].spectateIsRunning = false
games[gameId].spectatorOpponentEventDataBuffer.length = 0
games[gameId].spectatorGameEventBuffer.length = 0
###
# Clears timeout for disconnected players
# @public
# @param {String} gameId The ID of the game to clear disconnected timeout for.
###
clearDisconnectedPlayerTimeout = (gameId) ->
Logger.module("IO").log "[G:#{gameId}]", "clearDisconnectedPlayerTimeout:: for game: #{gameId}".yellow
clearTimeout(games[gameId]?.disconnectedPlayerTimeout)
games[gameId]?.disconnectedPlayerTimeout = null
###
# Starts timeout for disconnected players
# @public
# @param {String} gameId The ID of the game.
# @param {String} playerId The player ID for who to start the timeout.
###
startDisconnectedPlayerTimeout = (gameId,playerId) ->
if games[gameId]?.disconnectedPlayerTimeout?
clearDisconnectedPlayerTimeout(gameId)
Logger.module("IO").log "[G:#{gameId}]", "startDisconnectedPlayerTimeout:: for #{playerId} in game: #{gameId}".yellow
games[gameId]?.disconnectedPlayerTimeout = setTimeout(()->
onDisconnectedPlayerTimeout(gameId,playerId)
,60000)
###
# Resigns game for disconnected player.
# @public
# @param {String} gameId The ID of the game.
# @param {String} playerId The player ID who is resigning.
###
onDisconnectedPlayerTimeout = (gameId,playerId) ->
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} for game: #{gameId}"
clients_in_the_room = io.sockets.adapter.rooms[gameId]
for clientId,socket of clients_in_the_room
if socket.playerId == playerId
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to dis-connect is still in the game #{gameId} room. ABORTING".red
return
for clientId,socket of io.sockets.connected
if socket.playerId == playerId and not socket.spectatorId
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to disconnect is still connected but not in the game #{gameId} room.".red
return
# grab the relevant game session
gs = games[gameId]?.session
# looks like we timed out for a game that's since ended
if !gs or gs?.status == SDK.GameStatus.over
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} timed out for FINISHED or NULL game: #{gameId}".yellow
return
else
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} auto-resigning game: #{gameId}".yellow
# resign the player
player = gs.getPlayerById(playerId)
resignAction = player.actionResign()
gs.executeAction(resignAction)
###*
# Start/Restart server side game timer for a game
# @public
# @param {Object} gameId The game ID.
###
restartTurnTimer = (gameId) ->
stopTurnTimer(gameId)
game = games[gameId]
if game.session?
game.turnTimerStartedAt = game.turnTimeTickAt = Date.now()
if game.session.isBossBattle()
# boss battles turns have infinite time
# so we'll just tick once and wait
onGameTimeTick(gameId)
else
# set turn timer on a 1 second interval
game.turnTimer = setInterval((()-> onGameTimeTick(gameId)),1000)
###*
# Stop server side game timer for a game
# @public
# @param {Object} gameId The game ID.
###
stopTurnTimer = (gameId) ->
game = games[gameId]
if game? and game.turnTimer?
clearInterval(game.turnTimer)
game.turnTimer = null
###*
# Server side game timer. After 90 seconds it will end the turn for the current player.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
onGameTimeTick = (gameId) ->
game = games[gameId]
gameSession = game?.session
if gameSession?
# allowed turn time is 90 seconds + 3 second buffer that clients don't see
allowed_turn_time = MAX_TURN_TIME
# grab the current player
player = gameSession.getCurrentPlayer()
# if we're past the 2nd turn, we can start checking backwards to see how long the PREVIOUS turn for this player took
if player and gameSession.getTurns().length > 2
# find the current player's previous turn
allTurns = gameSession.getTurns()
playersPreviousTurn = null
for i in [allTurns.length-1..0] by -1
if allTurns[i].playerId == player.playerId
playersPreviousTurn = allTurns[i] # gameSession.getTurns()[gameSession.getTurns().length - 3]
break
#Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: last action at #{player.getLastActionTakenAt()} / last turn delta #{playersPreviousTurn?.createdAt - player.getLastActionTakenAt()}".red
# if this player's previous action was on a turn older than the last one
if playersPreviousTurn && (playersPreviousTurn.createdAt - player.getLastActionTakenAt() > 0)
# you're only allowed 15 seconds + 3 second buffer that clients don't see
allowed_turn_time = MAX_TURN_TIME_INACTIVE
lastTurnTimeTickAt = game.turnTimeTickAt
game.turnTimeTickAt = Date.now()
delta_turn_time_tick = game.turnTimeTickAt - lastTurnTimeTickAt
delta_since_timer_began = game.turnTimeTickAt - game.turnTimerStartedAt
game.turnTimeRemaining = Math.max(0.0, allowed_turn_time - delta_since_timer_began + game.turnTimeBonus)
game.turnTimeBonus = Math.max(0.0, game.turnTimeBonus - delta_turn_time_tick)
#Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: delta #{delta_turn_time_tick/1000}, #{game.turnTimeRemaining/1000} time remaining, #{game.turnTimeBonus/1000} bonus remaining"
turnTimeRemainingInSeconds = Math.ceil(game.turnTimeRemaining/1000)
gameSession.setTurnTimeRemaining(turnTimeRemainingInSeconds)
if game.turnTimeRemaining <= 0
# turn time has expired
stopTurnTimer(gameId)
if gameSession.status == SDK.GameStatus.new
# force draw starting hand with current cards
for player in gameSession.players
if not player.getHasStartingHand()
Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: mulligan timer up, submitting player #{player.playerId.blue} mulligan".red
drawStartingHandAction = player.actionDrawStartingHand([])
gameSession.executeAction(drawStartingHandAction)
else if gameSession.status == SDK.GameStatus.active
# force end turn
Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: turn timer up, submitting player #{gameSession.getCurrentPlayerId().blue} turn".red
endTurnAction = gameSession.actionEndTurn()
gameSession.executeAction(endTurnAction)
else
# if the turn timer has not expired, just send the time tick over to all clients
totalStepCount = gameSession.getStepCount() - games[gameId].opponentEventDataBuffer.length
emitGameEvent(null,gameId,{type:EVENTS.turn_time, time: turnTimeRemainingInSeconds, timestamp: Date.now(), stepCount: totalStepCount})
###*
# ...
# @public
# @param {Object} gameId The game ID.
###
restartSpectatorDelayedGameInterval = (gameId) ->
stopSpectatorDelayedGameInterval(gameId)
Logger.module("IO").debug "[G:#{gameId}]", "restartSpectatorDelayedGameInterval"
if games[gameId].spectateIsDelayed
games[gameId].spectatorDelayTimer = setInterval((()-> onSpectatorDelayedGameTick(gameId)), 500)
###*
# ...
# @public
# @param {Object} gameId The game ID.
###
stopSpectatorDelayedGameInterval = (gameId) ->
Logger.module("IO").debug "[G:#{gameId}]", "stopSpectatorDelayedGameInterval"
clearInterval(games[gameId].spectatorDelayTimer)
###*
# Ticks the spectator delayed game and usually flushes the buffer by calling `flushSpectatorNetworkEventBuffer`.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
onSpectatorDelayedGameTick = (gameId) ->
if not games[gameId]
Logger.module("Game").debug "onSpectatorDelayedGameTick() -> game [G:#{gameId}] seems to be destroyed. Stopping ticks."
stopSpectatorDelayedGameInterval(gameId)
return
_logSpectatorTickInfo(gameId)
# flush anything in the spectator buffer
flushSpectatorNetworkEventBuffer(gameId)
###*
# Runs actions delayed in the spectator buffer.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
flushSpectatorNetworkEventBuffer = (gameId) ->
# if there is anything in the buffer
if games[gameId].spectatorGameEventBuffer.length > 0
# Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer()"
# remove all the NULLED out actions
games[gameId].spectatorGameEventBuffer = _.compact(games[gameId].spectatorGameEventBuffer)
# loop through the actions in order
for eventData,i in games[gameId].spectatorGameEventBuffer
timestamp = eventData.timestamp || eventData.step?.timestamp
# if we are not delaying events or if the event time exceeds the delay show it to spectators
if not games[gameId].spectateIsDelayed || timestamp and moment().utc().valueOf() - timestamp > games[gameId].spectateDelay
# null out the event that is about to be broadcast so it can be compacted later
games[gameId].spectatorGameEventBuffer[i] = null
if (eventData.step)
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> broadcasting spectator step #{eventData.type} - #{eventData.step?.action?.type}"
if games[gameId].spectateIsDelayed
step = games[gameId].spectatorDelayedGameSession.deserializeStepFromFirebase(eventData.step)
games[gameId].spectatorDelayedGameSession.executeAuthoritativeStep(step)
# send events over to spectators of current player
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to player's spectators"
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.step.playerId
# scrub the action data. this should not be skipped since some actions include entire deck that needs to be scrubbed because we don't want spectators deck sniping
eventDataCopy = JSON.parse(JSON.stringify(eventData))
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true)
socket.emit EVENTS.network_game_event, eventDataCopy
# skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one
if eventData.step.action.type == SDK.RollbackToSnapshotAction.type
return
# start buffering events until a followup is complete for the opponent since players can cancel out of a followup
games[gameId].spectatorOpponentEventDataBuffer.push(eventData)
# if we are delayed then check the delayed game session for if we are buffering, otherwise use the primary
isSpectatorGameSessionBufferingFollowups = (games[gameId].spectateIsDelayed and games[gameId].spectatorDelayedGameSession?.getIsBufferingEvents()) || games[gameId].session.getIsBufferingEvents()
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> opponentEventDataBuffer at #{games[gameId].spectatorOpponentEventDataBuffer.length} ... buffering: #{isSpectatorGameSessionBufferingFollowups}"
# if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent's spectators
if games[gameId].spectatorOpponentEventDataBuffer.length > 0 and !isSpectatorGameSessionBufferingFollowups
# copy buffer and reset
opponentEventDataBuffer = games[gameId].spectatorOpponentEventDataBuffer.slice(0)
games[gameId].spectatorOpponentEventDataBuffer.length = 0
# broadcast whatever's in the buffer to the opponent
_.each(opponentEventDataBuffer, (eventData) ->
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to opponent's spectators"
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId != eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from opponent's spectator perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true)
socket.emit EVENTS.network_game_event, eventDataCopy
)
else
io.to("spectate-#{gameId}").emit EVENTS.network_game_event, eventData
_logSpectatorTickInfo = _.debounce((gameId)->
Logger.module("Game").debug "onSpectatorDelayedGameTick() ... #{games[gameId]?.spectatorGameEventBuffer?.length} buffered"
if games[gameId]?.spectatorGameEventBuffer
for eventData,i in games[gameId]?.spectatorGameEventBuffer
Logger.module("Game").debug "onSpectatorDelayedGameTick() eventData: ",eventData
, 1000)
###*
# Emit/Broadcast game event to appropriate destination.
# @public
# @param {Socket} event Originating socket.
# @param {String} gameId The game id for which to broadcast.
# @param {Object} eventData Data to broadcast.
###
emitGameEvent = (fromSocket,gameId,eventData)->
if games[gameId]?
if eventData.type == EVENTS.step
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> step #{eventData.step?.index?.toString().yellow} with timestamp #{eventData.step?.timestamp} and action #{eventData.step?.action?.type}"
# only broadcast valid steps
if eventData.step? and eventData.step.timestamp? and eventData.step.action?
# send the step to the owner
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from player perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId)
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to origin"
socket.emit EVENTS.network_game_event, eventDataCopy
# NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected:
# 2 for this current reconnecting player and 1 for the opponent
# breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event
# break
# buffer actions for the opponent other than a rollback action since that should clear the buffer during followups and there's no need to be sent to the opponent
# essentially: skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one
if eventData.step.action.type != SDK.RollbackToSnapshotAction.type
# start buffering events until a followup is complete for the opponent since players can cancel out of a followup
games[gameId].opponentEventDataBuffer.push(eventData)
# if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent
if games[gameId].opponentEventDataBuffer.length > 0 and !games[gameId].session.getIsBufferingEvents()
# copy buffer and reset
opponentEventDataBuffer = games[gameId].opponentEventDataBuffer.slice(0)
games[gameId].opponentEventDataBuffer.length = 0
# broadcast whatever's in the buffer to the opponent
_.each(opponentEventDataBuffer, (eventData) ->
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId != eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from player perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId)
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to opponent"
socket.emit EVENTS.network_game_event, eventDataCopy
)
else if eventData.type == EVENTS.invalid_action
# send the invalid action notification to the owner
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
socket.emit EVENTS.network_game_event, eventDataCopy
# NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected:
# 2 for this current reconnecting player and 1 for the opponent
# breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event
else
if eventData.type == EVENTS.network_game_hover or eventData.type == EVENTS.network_game_select or eventData.type == EVENTS.network_game_mouse_clear or eventData.type == EVENTS.show_emote
# save the player id of this event
eventData.playerId ?= fromSocket?.playerId
eventData.timestamp = moment().utc().valueOf()
# mouse events, emotes, etc should be saved and persisted to S3 for replays
games[gameId].mouseAndUIEvents ?= []
games[gameId].mouseAndUIEvents.push(eventData)
if fromSocket?
# send it along to other connected sockets in the game room
fromSocket.broadcast.to(gameId).emit EVENTS.network_game_event, eventData
else
# send to all sockets connected to the game room
io.to(gameId).emit EVENTS.network_game_event, eventData
# push a deep clone of the event data to the spectator buffer
if games[gameId]?.spectateIsRunning
spectatorEventDataCopy = JSON.parse(JSON.stringify(eventData))
games[gameId].spectatorGameEventBuffer.push(spectatorEventDataCopy)
# if we're not running a timed delay, just flush everything now
if not games[gameId]?.spectateIsDelayed
flushSpectatorNetworkEventBuffer(gameId)
###
# start a game session if one doesn't exist and call a completion handler when done
# @public
# @param {Object} gameId The game ID to load.
# @param {Function} onComplete Callback when done.
###
initGameSession = (gameId,onComplete) ->
if games[gameId]?.loadingPromise
return games[gameId].loadingPromise
# setup local cache reference if none already there
if not games[gameId]
games[gameId] =
opponentEventDataBuffer:[]
connectedPlayers:[]
session:null
connectedSpectators:[]
spectateIsRunning:false
spectateIsDelayed:false
spectateDelay:30000
spectatorGameEventBuffer:[]
spectatorOpponentEventDataBuffer:[]
spectatorDelayedGameSession:null
turnTimerStartedAt: 0
turnTimeTickAt: 0
turnTimeRemaining: 0
turnTimeBonus: 0
# return game session from redis
games[gameId].loadingPromise = Promise.all([
GameManager.loadGameSession(gameId)
GameManager.loadGameMouseUIData(gameId)
])
.spread (gameData,mouseData)->
return [
JSON.parse(gameData)
JSON.parse(mouseData)
]
.spread (gameDataIn,mouseData) ->
Logger.module("IO").log "[G:#{gameId}]", "initGameSession -> loaded game data for game:#{gameId}"
# deserialize game session
gameSession = SDK.GameSession.create()
gameSession.setIsRunningAsAuthoritative(true)
gameSession.deserializeSessionFromFirebase(gameDataIn)
if gameSession.isOver()
throw new Error("Game is already over!")
# store session
games[gameId].session = gameSession
# store mouse and ui event data
games[gameId].mouseAndUIEvents = mouseData
saveGameCount(++gameCount)
# setup AI
ai_setup(gameId)
# in case the server restarted or loading data for first time, set the last action at timestamp for both players to now
# this timestamp is used to shorten turn timer if player has not made any moves for a long time
_.each(gameSession.players,(player)->
player.setLastActionTakenAt(Date.now())
)
# this is ugly but a simple way to subscribe to turn change events to save the game session
subscribeToGameSessionEvents(gameId)
# start the turn timer
restartTurnTimer(gameId)
return Promise.resolve([
games[gameId].session
])
.catch (error) ->
Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error stack: #{error.stack}".red
# Report error to exceptionReporter with gameId
exceptionReporter.notify(error, {
errorName: "initGameSession Error",
severity: "error",
game: {
id: gameId
}
})
throw error
###
# start a spectator game session if one doesn't exist and call a completion handler when done
# @public
# @param {Object} gameId The game ID to load.
# @param {Function} onComplete Callback when done.
###
initSpectatorGameSession = (gameId)->
if not games[gameId]
return Promise.reject(new Error("This game is no longer in progress"))
return Promise.resolve()
.then ()->
# if we're not already running spectate systems
if not games[gameId].spectateIsRunning
# mark that we are running spectate systems
games[gameId].spectateIsRunning = true
# if we're in the middle of a followup and we have some buffered events, we need to copy them over to the spectate buffer
if games[gameId].session.getIsBufferingEvents() and games[gameId].opponentEventDataBuffer.length > 0
games[gameId].spectatorOpponentEventDataBuffer.length = 0
for eventData in games[gameId].opponentEventDataBuffer
eventDataCopy = JSON.parse(JSON.stringify(eventData))
games[gameId].spectatorOpponentEventDataBuffer.push(eventDataCopy)
if games[gameId].spectateIsDelayed and not games[gameId].spectatorDelayedGameSession
Logger.module("...").log "[G:#{gameId}]", "initSpectatorDelayedGameSession() -> creating delayed game session"
# create
delayedGameDataIn = games[gameId].session.serializeToJSON(games[gameId].session)
delayedGameSession = SDK.GameSession.create()
delayedGameSession.setIsRunningAsAuthoritative(false)
delayedGameSession.deserializeSessionFromFirebase(JSON.parse(delayedGameDataIn))
delayedGameSession.gameId = "SPECTATE:#{delayedGameSession.gameId}"
games[gameId].spectatorDelayedGameSession = delayedGameSession
# start timer to execute delayed / buffered spectator game events
restartSpectatorDelayedGameInterval(gameId)
return Promise.resolve(games[gameId].spectatorDelayedGameSession)
else
return Promise.resolve(games[gameId].session)
###*
* Handler for before a game session rolls back to a snapshot.
###
onBeforeRollbackToSnapshot = (event) ->
# clear the buffer just before rolling back
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
game.opponentEventDataBuffer.length = 0
game.spectatorOpponentEventDataBuffer.length = 0
###*
* Handler for a game session step.
###
onStep = (event) ->
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
step = event.step
if step? and step.timestamp? and step.action?
# send out step events
stepEventData = {type: EVENTS.step, step: JSON.parse(game.session.serializeToJSON(step))}
emitGameEvent(null, gameId, stepEventData)
# special action cases
action = step.action
if action instanceof SDK.EndTurnAction
# save game on end turn
# delay so that we don't block sending the step back to the players
_.delay((()->
if games[gameId]? and games[gameId].session?
GameManager.saveGameSession(gameId, games[gameId].session.serializeToJSON(games[gameId].session))
), 500)
else if action instanceof SDK.StartTurnAction
# restart the turn timer whenever a turn starts
restartTurnTimer(gameId)
else if action instanceof SDK.DrawStartingHandAction
# restart turn timer if both players have a starting hand and this step is for a DrawStartingHandAction
bothPlayersHaveStartingHand = _.reduce(game.session.players,((memo,player)-> memo && player.getHasStartingHand()),true)
if bothPlayersHaveStartingHand
restartTurnTimer(gameId)
if action.getIsAutomatic() and !game.session.getIsFollowupActive()
# add bonus to turn time for every automatic step
# unless followup is active, to prevent rollbacks for infinite turn time
# bonus as a separate parameter accounts for cases such as:
# - battle pet automatic actions eating up your own time
# - queuing up many actions and ending turn quickly to eat into opponent's time
game.turnTimeBonus += 2000
# when game is over and we have the final step
# we cannot archive game until final step event
# because otherwise step won't be finished/signed correctly
# so we must do this on step event and not on game_over event
if game.session.status == SDK.GameStatus.over
# stop any turn timers
stopTurnTimer(gameId)
if !game.isArchived?
game.isArchived = true
afterGameOver(gameId, game.session, game.mouseAndUIEvents)
###*
* Handler for an invalid action.
###
onInvalidAction = (event) ->
# safety fallback: if player attempts to make an invalid explicit action, notify that player only
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
action = event.action
if !action.getIsImplicit()
#Logger.module("...").log "[G:#{gameId}]", "onInvalidAction -> INVALID ACTION: #{action.getLogName()} / VALIDATED BY: #{action.getValidatorType()} / MESSAGE: #{action.getValidationMessage()}"
invalidActionEventData = {
type: EVENTS.invalid_action,
playerId: action.getOwnerId(),
action: JSON.parse(game.session.serializeToJSON(action)),
validatorType: event.validatorType,
validationMessage: event.validationMessage,
validationMessagePosition: event.validationMessagePosition,
desync: gameSession.isActive() and
gameSession.getCurrentPlayerId() == action.getOwnerId() and
gameSession.getTurnTimeRemaining() > CONFIG.TURN_DURATION_LATENCY_BUFFER
}
emitGameEvent(null, gameId, invalidActionEventData)
###
# Subscribes to the gamesession's event bus.
# Can be called multiple times in order to re-subscribe.
# @public
# @param {Object} gameId The game ID to subscribe for.
###
subscribeToGameSessionEvents = (gameId)->
Logger.module("...").log "[G:#{gameId}]", "subscribeToGameSessionEvents -> subscribing to GameSession events"
game = games[gameId]
if game?
# unsubscribe from previous
unsubscribeFromGameSessionEvents(gameId)
# listen for game events
game.session.getEventBus().on(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot)
game.session.getEventBus().on(EVENTS.step, onStep)
game.session.getEventBus().on(EVENTS.invalid_action, onInvalidAction)
# subscribe AI to events
ai_subscribeToGameSessionEvents(gameId)
###
# Unsubscribe from event listeners on the game session for this game ID.
# @public
# @param {String} gameId The game ID that needs to be unsubscribed.
###
unsubscribeFromGameSessionEvents = (gameId)->
Logger.module("...").log "[G:#{gameId}]", "unsubscribeFromGameSessionEvents -> un-subscribing from GameSession events"
game = games[gameId]
if game?
game.session.getEventBus().off(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot)
game.session.getEventBus().off(EVENTS.step, onStep)
game.session.getEventBus().off(EVENTS.invalid_action, onInvalidAction)
ai_unsubscribeFromGameSessionEvents(gameId)
###
# must be called after game is over
# processes a game, saves to redis, and kicks-off post-game processing jobs
# @public
# @param {String} gameId The game ID that is over.
# @param {Object} gameSession The game session data.
# @param {Array} mouseAndUIEvents The mouse and UI events for this game.
###
afterGameOver = (gameId, gameSession, mouseAndUIEvents) ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "---------- ======= GAME #{gameId} OVER ======= ---------".green
# Update User Ranking, Progression, Quests, Stats
updateUser = (userId, opponentId, gameId, factionId, generalId, isWinner, isDraw, ticketId) ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "UPDATING user #{userId}. (winner:#{isWinner})"
# check for isFriendly
# check for isUnscored
isFriendly = gameSession.gameType == SDK.GameType.Friendly
isUnscored = false
# Ranking and Progression only process in NON-FRIENDLY matches
if not isFriendly
# calculate based on number of resign status and number of actions
lastStep = gameSession.getLastStep()
# if the game didn't have a single turn, mark the game as unscored
if gameSession.getPlayerById(userId).hasResigned and gameSession.getTurns().length == 0
Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} CONCEDED a game with 0 turns. Marking as UNSCORED".yellow
isUnscored = true
else if not isWinner and not isDraw
# otherwise check how many actions the player took
playerActionCount = 0
meaningfulActionCount = 0
moveActionCount = 0
for a in gameSession.getActions()
# explicit actions
if a.getOwnerId() == userId && a.getIsImplicit() == false
playerActionCount++
# meaningful actions
if a instanceof SDK.AttackAction
if a.getTarget().getIsGeneral()
meaningfulActionCount += 2
else
meaningfulActionCount += 1
if a instanceof SDK.PlayCardFromHandAction or a instanceof SDK.PlaySignatureCardAction
meaningfulActionCount += 1
if a instanceof SDK.BonusManaAction
meaningfulActionCount += 2
# move actions
if a instanceof SDK.MoveAction
moveActionCount += 1
# more than 9 explicit actions
# more than 1 move action
# more than 5 meaningful actions
if playerActionCount > 9 and moveActionCount > 1 and meaningfulActionCount > 4
break
###
what we're looking for:
* more than 9 explicit actions
* more than 1 move action
* more than 5 meaningful actions
... otherwise mark the game as unscored
###
# Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} #{playerActionCount}, #{moveActionCount}, #{meaningfulActionCount}".cyan
if playerActionCount <= 9 or moveActionCount <= 1 or meaningfulActionCount <= 4
Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} CONCEDED a game with too few meaningful actions. Marking as UNSCORED".yellow
isUnscored = true
# start the job to process the game for a user
Jobs.create("update-user-post-game",
name: "Update User Ranking"
title: util.format("User %s :: Game %s", userId, gameId)
userId: userId
opponentId: opponentId
gameId: gameId
gameType: gameSession.gameType
factionId: factionId
generalId: generalId
isWinner: isWinner
isDraw: isDraw
isUnscored: isUnscored
isBotGame: true
ticketId: ticketId
).removeOnComplete(true).save()
# Save then archive game session
archiveGame = (gameId, gameSession, mouseAndUIEvents) ->
Promise.all([
GameManager.saveGameMouseUIData(gameId, JSON.stringify(mouseAndUIEvents)),
GameManager.saveGameSession(gameId, gameSession.serializeToJSON(gameSession))
]).then () ->
# Job: Archive Game
Jobs.create("archive-game",
name: "Archive Game"
title: util.format("Archiving Game %s", gameId)
gameId: gameId
gameType: gameSession.gameType
).removeOnComplete(true).save()
# update promises
promises = [
archiveGame(gameId, gameSession, mouseAndUIEvents)
]
for player in gameSession.players
playerId = player.getPlayerId()
# don't update normal AI (non-bot user)
if playerId != CONFIG.AI_PLAYER_ID
# find player data
winnerId = gameSession.getWinnerId()
isWinner = (playerId == winnerId)
isDraw = if !winnerId? then true else false
playerSetupData = gameSession.getPlayerSetupDataForPlayerId(playerId)
playerFactionId = playerSetupData.factionId
generalId = playerSetupData.generalId
ticketId = playerSetupData.ticketId
promises.push(updateUser(playerId,CONFIG.AI_PLAYER_ID,gameId,playerFactionId,generalId,isWinner,isDraw,ticketId))
# execute promises
Promise.all(promises)
.then () ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "afterGameOver done, game has been archived".green
.catch (error) ->
Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver failed #{error}".red
# issue a warning to our exceptionReporter error tracker
exceptionReporter.notify(error, {
errorName: "afterGameOver failed",
severity: "error"
game:
id: gameId
gameType: gameSession.gameType
player1Id: player1Id
player2Id: player2Id
winnerId: winnerId
loserId: loserId
})
### Shutdown Handler ###
shutdown = () ->
Logger.module("SERVER").log "Shutting down game server."
Logger.module("SERVER").log "Active Players: #{playerCount}."
Logger.module("SERVER").log "Active Games: #{gameCount}."
if !config.get('consul.enabled')
process.exit(0)
return Consul.getReassignmentStatus()
.then (reassign) ->
if reassign == false
Logger.module("SERVER").log "Reassignment disabled - exiting."
process.exit(0)
# Build an array of game IDs
ids = []
_.each games, (game, id) ->
ids.push(id)
# Map to save each game to Redis before shutdown
return Promise.map ids, (id) ->
serializedData = games[id].session.serializeToJSON(games[id].session)
return GameManager.saveGameSession(id, serializedData)
.then () ->
return Consul.getHealthyServers()
.then (servers) ->
# Filter 'yourself' from list of nodes
filtered = _.reject servers, (server)->
return server["Node"]?["Node"] == os.hostname()
if filtered.length == 0
Logger.module("SERVER").log "No servers available - exiting without re-assignment."
process.exit(1)
random_node = _.sample(filtered)
node_name = random_node["Node"]?["Node"]
return Consul.kv.get("nodes/#{node_name}/public_ip")
.then (newServerIp) ->
# Development override for testing, bounces between port 9000 & 9001
if config.isDevelopment()
port = 9001 if config.get('port') is 9000
port = 9000 if config.get('port') is 9001
newServerIp = "127.0.0.1:#{port}"
msg = "Server is shutting down. You will be reconnected automatically."
io.emit "game_server_shutdown", {msg:msg,ip:newServerIp}
Logger.module("SERVER").log "Players reconnecting to: #{newServerIp}"
Logger.module("SERVER").log "Re-assignment complete. Exiting."
process.exit(0)
.catch (err) ->
Logger.module("SERVER").log "Re-assignment failed: #{err.message}. Exiting."
process.exit(1)
process.on "SIGTERM", shutdown
process.on "SIGINT", shutdown
process.on "SIGHUP", shutdown
process.on "SIGQUIT", shutdown
# region AI
###*
* Returns whether a session is valid for AI usage.
* @param {String} gameId
###
ai_isValidSession = (gameId) ->
return games[gameId]?.session? and !games[gameId].session.isOver() and games[gameId].ai?
###*
* Returns whether a session and turn is valid for AI usage.
* @param {String} gameId
###
ai_isValidTurn = (gameId) ->
return ai_isValidSession(gameId) and games[gameId].session.isActive() and games[gameId].session.getCurrentPlayerId() == games[gameId].ai.getMyPlayerId()
###*
* Returns whether AI can start turn.
* @param {String} gameId
###
ai_canStartTurn = (gameId) ->
return ai_isValidTurn(gameId) and !ai_isExecutingTurn(gameId) and !games[gameId].session.hasStepsInQueue()
###*
* Returns whether ai is currently executing turn.
* @param {String} gameId
###
ai_isExecutingTurn = (gameId) ->
return games[gameId].executingAITurn
###*
* Returns whether ai can progress turn.
* @param {String} gameId
###
ai_canProgressTurn = (gameId) ->
return ai_isValidTurn(gameId) and ai_isExecutingTurn(gameId) and !games[gameId].aiStartTurnTimeoutId?
###*
* Returns whether ai can taunt.
* @param {String} gameId
###
ai_canEmote = (gameId) ->
return ai_isValidSession(gameId) and !ai_isBot(gameId) and !games[gameId].session.getIsBufferingEvents() and Math.random() < 0.05
###*
* Returns whether ai is normal ai or bot.
* @param {String} gameId
###
ai_isBot = (gameId) ->
return games[gameId]?.session? and games[gameId].session.getAiPlayerId() != CONFIG.AI_PLAYER_ID
###*
* Initializes AI for a game session.
* @param {String} gameId
###
ai_setup = (gameId) ->
if games[gameId]?.session? and !games[gameId].ai?
aiPlayerId = games[gameId].session.getAiPlayerId()
aiDifficulty = games[gameId].session.getAiDifficulty()
Logger.module("AI").debug "[G:#{gameId}]", "Setup AI -> aiPlayerId #{aiPlayerId} - aiDifficulty #{aiDifficulty}"
games[gameId].ai = new StarterAI(games[gameId].session, aiPlayerId, aiDifficulty)
# add AI as a connected player
games[gameId].connectedPlayers.push(games[gameId].session.getAiPlayerId())
# attempt to mulligan immediately on new game
if games[gameId].session.isNew()
nextAction = games[gameId].ai.nextAction()
if nextAction?
games[gameId].session.executeAction(nextAction)
###*
* Terminates AI for a game session.
* @param {String} gameId
###
ai_terminate = (gameId) ->
ai_unsubscribeFromGameSessionEvents(gameId)
ai_stopTurn(gameId)
ai_stopTimeouts(gameId)
ai_onStep = (event) ->
gameSession = event.gameSession
gameId = gameSession.gameId
# emote after step
ai_emoteForLastStep(gameId)
# progress turn
ai_updateTurn(gameId)
ai_onInvalidAction = (event) ->
# safety fallback: if AI attempts to make an invalid explicit action, end AI turn immediately
if event?
gameSession = event.gameSession
gameId = gameSession.gameId
action = event.action
if action? and !action.getIsImplicit() and ai_isExecutingTurn(gameId) and action.getOwnerId() == games[gameId].ai.getMyPlayerId()
ai_endTurn(gameId)
ai_subscribeToGameSessionEvents = (gameId) ->
game = games[gameId]
if game?
# if we're already subscribed, unsubscribe
ai_unsubscribeFromGameSessionEvents(gameId)
# listen for game events
game.session.getEventBus().on(EVENTS.step, ai_onStep)
game.session.getEventBus().on(EVENTS.invalid_action, ai_onInvalidAction)
ai_unsubscribeFromGameSessionEvents = (gameId) ->
game = games[gameId]
if game?
game.session.getEventBus().off(EVENTS.step, ai_onStep)
game.session.getEventBus().off(EVENTS.invalid_action, ai_onInvalidAction)
###*
* Updates AI turn for a game session.
* @param {String} gameId
###
ai_updateTurn = (gameId) ->
Logger.module("AI").debug "[G:#{gameId}]", "ai_updateTurn"
if ai_canStartTurn(gameId)
ai_startTurn(gameId)
else if ai_canProgressTurn(gameId)
ai_progressTurn(gameId)
else if ai_isExecutingTurn(gameId)
ai_endTurn(gameId)
###*
* Progresses AI turn for a game session.
* @param {String} gameId
###
ai_progressTurn = (gameId) ->
if ai_canProgressTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_progressTurn".cyan
# request next action from AI
try
nextAction = games[gameId].ai.nextAction()
catch error
Logger.module("IO").log "[G:#{gameId}]", "ai.nextAction:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{gameId}]", "ai.nextAction:: error stack: #{error.stack}".red
# retain player id
playerId = games[gameId].ai.getOpponentPlayerId()
# Report error to exceptionReporter with gameId + eventData
exceptionReporter.notify(error, {
errorName: "ai_progressTurn Error",
game: {
gameId: gameId
turnIndex: games[gameId].session.getTurns().length
stepIndex: games[gameId].session.getCurrentTurn().getSteps().length
}
})
# delete but don't destroy game
destroyGameSessionIfNoConnectionsLeft(gameId,true)
# send error to client, forcing reconnect on client side
io.to(gameId).emit EVENTS.network_game_error, JSON.stringify(error.message)
return
# if we didn't have an error and somehow destroy the game data in the try/catch above
if games[gameId]?
if nextAction?
# always delay AI actions slightly
if !games[gameId].aiExecuteActionTimeoutId?
if ai_isBot(gameId)
if games[gameId].session.getIsFollowupActive()
actionDelayTime = 1.0 + Math.random() * 3.0
else if nextAction instanceof SDK.EndTurnAction
actionDelayTime = 1.0 + Math.random() * 2.0
else
actionDelayTime = 1.0 + Math.random() * 8.0
else
if games[gameId].session.getIsFollowupActive()
actionDelayTime = 0.0
else
actionDelayTime = 5.0
# action delay time can never be more than a quarter of remaining turn time
if games[gameId].turnTimeRemaining?
actionDelayTime = Math.min((games[gameId].turnTimeRemaining * 0.25) / 1000.0, actionDelayTime)
# show UI as needed
ai_showUIForAction(gameId, nextAction, actionDelayTime)
# delay and then execute action
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiExecuteActionTimeoutId = setTimeout((() ->
games[gameId].aiExecuteActionTimeoutId = null
ai_showClearUI(gameId)
ai_executeAction(gameId, nextAction)
), Math.max(1.0, actionDelayTime * 1000.0))
else if ai_isExecutingTurn(gameId)
# end turn as needed
ai_endTurn(gameId)
###*
* Starts AI turn for a game session.
* @param {String} gameId
###
ai_startTurn = (gameId) ->
if ai_canStartTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_startTurn".cyan
# set as executing AI turn
games[gameId].executingAITurn = true
if !games[gameId].aiStartTurnTimeoutId?
# delay initial turn progress
if ai_isBot(gameId)
delayTime = 2.0 + Math.random() * 2.0
else
delayTime = 2.0
# choose random starting point for pointer
games[gameId].aiPointer = {
x: Math.floor(Math.random() * CONFIG.BOARDCOL),
y: Math.floor(Math.random() * CONFIG.BOARDROW)
}
Logger.module("AI").debug "[G:#{gameId}]", "ai_startTurn init aiPointer at #{games[gameId].aiPointer.x}, #{games[gameId].aiPointer.y}".cyan
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiStartTurnTimeoutId = setTimeout((()->
games[gameId].aiStartTurnTimeoutId = null
ai_progressTurn(gameId)
), Math.max(1.0, delayTime * 1000.0))
###*
* Stops AI turn for a game session, and ends it if necessary.
* @param {String} gameId
###
ai_endTurn = (gameId) ->
# stop turn
ai_stopTurn(gameId)
# force end turn if still AI's turn
if ai_isValidTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_endTurn".cyan
ai_executeAction(gameId, games[gameId].session.actionEndTurn())
###*
* Stops AI turn for a game session. Does not end AI turn.
* @param {String} gameId
###
ai_stopTurn = (gameId) ->
if games[gameId].executingAITurn
Logger.module("AI").debug "[G:#{gameId}]", "ai_stopTurn".cyan
games[gameId].executingAITurn = false
ai_stopTurnTimeouts(gameId)
###*
* Stops AI timeouts for a game session.
* @param {String} gameId
###
ai_stopTimeouts = (gameId) ->
ai_stopTurnTimeouts(gameId)
ai_stopEmoteTimeouts(gameId)
ai_stopUITimeouts(gameId)
###*
* Stops AI timeouts for turn actions.
* @param {String} gameId
###
ai_stopTurnTimeouts = (gameId) ->
if games[gameId].aiStartTurnTimeoutId?
clearTimeout(games[gameId].aiStartTurnTimeoutId)
games[gameId].aiStartTurnTimeoutId = null
if games[gameId].aiExecuteActionTimeoutId?
clearTimeout(games[gameId].aiExecuteActionTimeoutId)
games[gameId].aiExecuteActionTimeoutId = null
###*
* Executes an AI action for a game session.
* @param {String} gameId
* @param {Action} action
###
ai_executeAction = (gameId, action) ->
if ai_canProgressTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_executeAction -> #{action.getLogName()}".cyan
# simulate AI sending step to server
step = new SDK.Step(games[gameId].session, action.getOwnerId())
step.setAction(action)
opponentPlayerId = games[gameId].ai.getOpponentPlayerId()
for clientId,socket of io.sockets.connected
if socket.playerId == opponentPlayerId and !socket.spectatorId
onGameEvent.call(socket, {
type: EVENTS.step
step: JSON.parse(games[gameId].session.serializeToJSON(step))
})
###*
* Returns whether an action is valid for showing UI.
* @param {String} gameId
* @param {Action} action
* @return {Boolean}
###
ai_isValidActionForUI = (gameId, action) ->
return (games[gameId].session.getIsFollowupActive() and !(action instanceof SDK.EndFollowupAction)) or
action instanceof SDK.ReplaceCardFromHandAction or
action instanceof SDK.PlayCardFromHandAction or
action instanceof SDK.PlaySignatureCardAction or
action instanceof SDK.MoveAction or
action instanceof SDK.AttackAction
###*
* Shows UI for an action that will be taken by AI.
* @param {String} gameId
* @param {Action} action
* @param {Number} actionDelayTime must be at least 0.25s or greater
###
ai_showUIForAction = (gameId, action, actionDelayTime) ->
if ai_isValidTurn(gameId) and ai_isValidActionForUI(gameId, action) and _.isNumber(actionDelayTime) and actionDelayTime > 0.25
aiPlayerId = games[gameId].ai.getMyPlayerId()
# stop any previous UI animations
ai_stopUITimeouts(gameId)
# get ui animation times
if ai_isBot(gameId)
if games[gameId].session.getIsFollowupActive()
uiDelayTime = actionDelayTime * (0.7 + Math.random() * 0.1)
uiAnimationDuration = actionDelayTime - uiDelayTime
moveToSelectDuration = 0.0
pauseAtSelectDuration = 0.0
pauseAtTargetDuration = (0.1 + Math.random() * 0.25) * uiAnimationDuration
moveToTargetDuration = uiAnimationDuration - pauseAtTargetDuration
else
uiDelayTime = actionDelayTime * (0.4 + Math.random() * 0.4)
uiAnimationDuration = actionDelayTime - uiDelayTime
pauseAtTargetDuration = Math.min(1.0, (0.1 + Math.random() * 0.25) * uiAnimationDuration)
moveToSelectDuration = (0.2 + Math.random() * 0.4) * (uiAnimationDuration - pauseAtTargetDuration)
moveToTargetDuration = (0.4 + Math.random() * 0.5) * (uiAnimationDuration - pauseAtTargetDuration - moveToSelectDuration)
pauseAtSelectDuration = uiAnimationDuration - pauseAtTargetDuration - moveToSelectDuration - moveToTargetDuration
else
uiDelayTime = actionDelayTime * 0.7
uiAnimationDuration = actionDelayTime - uiDelayTime
moveToSelectDuration = 0.0
pauseAtSelectDuration = 0.0
moveToTargetDuration = 0.0
pauseAtTargetDuration = uiAnimationDuration
# get action properties
selectEventData = {
type: EVENTS.network_game_select
playerId: aiPlayerId
}
if action instanceof SDK.ReplaceCardFromHandAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
handIndex = selectEventData.handIndex = action.getIndexOfCardInHand()
selectPosition = { x: Math.round((handIndex + 0.5) * (CONFIG.BOARDCOL / CONFIG.MAX_HAND_SIZE)), y: -1 }
else if action instanceof SDK.ApplyCardToBoardAction
if action instanceof SDK.PlayCardFromHandAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
handIndex = selectEventData.handIndex = action.getIndexOfCardInHand()
selectPosition = { x: Math.round((handIndex + 0.5) * (CONFIG.BOARDCOL / CONFIG.MAX_HAND_SIZE)), y: -1 }
targetPosition = action.getTargetPosition()
else if action instanceof SDK.PlaySignatureCardAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
isSignatureCard = true
if action.getCard().isOwnedByPlayer2()
selectEventData.player2SignatureCard = true
else
selectEventData.player1SignatureCard = true
if aiPlayerId == games[gameId].session.getPlayer2Id()
selectPosition = { x: CONFIG.BOARDCOL, y: Math.floor(CONFIG.BOARDROW * 0.5 + Math.random() * CONFIG.BOARDROW * 0.5) }
else
selectPosition = { x: -1, y: Math.floor(CONFIG.BOARDROW * 0.5 + Math.random() * CONFIG.BOARDROW * 0.5) }
targetPosition = action.getTargetPosition()
else
# followup has no selection
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
selectEventData = null
selectPosition = action.getSourcePosition()
targetPosition = action.getTargetPosition()
else if action instanceof SDK.MoveAction
intent = selectEventData.intentType = SDK.IntentType.MoveIntent
cardIndex = selectEventData.cardIndex = action.getSourceIndex()
card = games[gameId].session.getCardByIndex(cardIndex)
selectPosition = card.getPosition()
targetPosition = action.getTargetPosition()
else if action instanceof SDK.AttackAction
intent = selectEventData.intentType = SDK.IntentType.DamageIntent
cardIndex = selectEventData.cardIndex = action.getSourceIndex()
card = games[gameId].session.getCardByIndex(cardIndex)
selectPosition = card.getPosition()
targetPosition = action.getTargetPosition()
# failsafe in case action doesn't have a select position
# (actions should always have a select position)
if !selectPosition?
if action instanceof SDK.ApplyCardToBoardAction
Logger.module("AI").log "[G:#{gameId}]", "ai_showUIForAction -> no sel pos #{action.getLogName()} w/ card #{action.getCard()?.getName()} w/ root #{action.getCard()?.getRootCard()?.getName()}".cyan
else
Logger.module("AI").log "[G:#{gameId}]", "ai_showUIForAction -> no sel pos #{action.getLogName()}".cyan
return
# setup sequence
actionPointerSequence = () ->
# move to select
ai_animatePointer(gameId, moveToSelectDuration, selectPosition, SDK.IntentType.NeutralIntent, false, isSignatureCard, () ->
if selectEventData?
if action instanceof SDK.MoveAction or action instanceof SDK.AttackAction
# clear pointer before select
emitGameEvent(null, gameId, {
type: EVENTS.network_game_mouse_clear
playerId: aiPlayerId,
intentType: SDK.IntentType.NeutralIntent
})
# show selection event
emitGameEvent(null, gameId, selectEventData)
if targetPosition?
# pause at select
ai_animatePointer(gameId, pauseAtSelectDuration, selectPosition, intent, isSignatureCard, false, () ->
# move to target
ai_animatePointer(gameId, moveToTargetDuration, targetPosition, intent)
)
)
# random chance to hover enemy unit on the board
if ai_isBot(gameId) and uiDelayTime >= 5.0 && Math.random() < 0.05
opponentGeneral = games[gameId].session.getGeneralForOpponentOfPlayerId(games[gameId].session.getAiPlayerId())
units = games[gameId].session.getBoard().getFriendlyEntitiesForEntity(opponentGeneral)
if units.length > 0
unitToHover = units[Math.floor(Math.random() * units.length)]
if unitToHover?
# hover unit before showing action UI
unitPosition = unitToHover.getPosition()
moveToUnitDuration = Math.random() * 1.0
pauseAtUnitDuration = 2.0 + Math.random() * 2.0
uiDelayTime = uiDelayTime - moveToUnitDuration - pauseAtUnitDuration
# delay for remaining time
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
# move to random unit
ai_animatePointer(gameId, moveToUnitDuration, unitPosition, SDK.IntentType.NeutralIntent, false, false, () ->
# pause at random unit and then show action pointer sequence
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
actionPointerSequence()
, pauseAtUnitDuration * 1000.0)
)
, uiDelayTime * 1000.0)
else
# delay and then show action pointer sequence
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
actionPointerSequence()
, uiDelayTime * 1000.0)
ai_showClearUI = (gameId) ->
if ai_isValidTurn(gameId)
ai_stopUITimeouts(gameId)
emitGameEvent(null, gameId, {
type: EVENTS.network_game_mouse_clear
playerId: games[gameId].ai.getMyPlayerId(),
intentType: SDK.IntentType.NeutralIntent
})
###*
* Clears out any timeouts for AI UI.
* @param {String} gameId
###
ai_stopUITimeouts = (gameId) ->
if games[gameId]?
if games[gameId].aiShowUITimeoutId?
clearTimeout(games[gameId].aiShowUITimeoutId)
games[gameId].aiShowUITimeoutId = null
ai_stopAnimatingPointer(gameId)
###*
* Shows AI pointer hover at a board position if it is different from the current position.
* @param {String} gameId
* @param {Number} boardX
* @param {Number} boardY
* @param {Number} [intent]
* @param {Number} [isSignatureCard=false]
###
ai_showHover = (gameId, boardX, boardY, intent=SDK.IntentType.NeutralIntent, isSignatureCard=false) ->
if ai_isValidTurn(gameId)
pointer = games[gameId].aiPointer
if pointer.x != boardX or pointer.y != boardY
# set pointer to position
pointer.x = boardX
pointer.y = boardY
# setup hover event data
hoverEventData = {
type: EVENTS.network_game_hover
boardPosition: {x: boardX, y: boardY},
playerId: games[gameId].ai.getMyPlayerId(),
intentType: intent
}
# check for hover target
if isSignatureCard
if games[gameId].ai.getMyPlayerId() == games[gameId].session.getPlayer2Id()
hoverEventData.player2SignatureCard = true
else
hoverEventData.player1SignatureCard = true
else
target = games[gameId].session.getBoard().getUnitAtPosition(pointer)
if target?
hoverEventData.cardIndex = target.getIndex()
# show hover
emitGameEvent(null, gameId, hoverEventData)
###*
* Animates AI pointer movement.
* @param {String} gameId
* @param {Number} duration in seconds
* @param {Vec2} [targetBoardPosition]
* @param {Number} [intent]
* @param {Number} [isSignatureCardAtSource]
* @param {Number} [isSignatureCardAtTarget]
* @param {Function} [callback]
###
ai_animatePointer = (gameId, duration, targetBoardPosition, intent, isSignatureCardAtSource, isSignatureCardAtTarget, callback) ->
if ai_isValidTurn(gameId)
# stop current animation
ai_stopAnimatingPointer(gameId)
pointer = games[gameId].aiPointer
sx = pointer.x
sy = pointer.y
tx = targetBoardPosition.x
ty = targetBoardPosition.y
dx = tx - sx
dy = ty - sy
if duration > 0.0
# show pointer at source
ai_showHover(gameId, sx, sy, intent, isSignatureCardAtSource)
# animate to target
dms = duration * 1000.0
startTime = Date.now()
games[gameId].aiPointerIntervalId = setInterval(() ->
# cubic ease out
currentTime = Date.now()
dt = currentTime - startTime
val = Math.min(1.0, dt / dms)
e = val - 1
ee = e * e * e + 1
cx = dx * ee + sx
cy = dy * ee + sy
ai_showHover(gameId, Math.round(cx), Math.round(cy), intent, isSignatureCardAtTarget)
if val == 1.0
ai_stopAnimatingPointer(gameId)
if callback then callback()
, dms / 10)
else
# show pointer at target
ai_showHover(gameId, tx, ty, intent, isSignatureCardAtTarget)
# no animation needed
if callback then callback()
###*
* Stops showing AI pointer movement.
###
ai_stopAnimatingPointer = (gameId) ->
if games[gameId]? and games[gameId].aiPointerIntervalId != null
clearInterval(games[gameId].aiPointerIntervalId)
games[gameId].aiPointerIntervalId = null
###*
* Prompts AI to emote to opponent based on last step.
* @param {String} gameId
###
ai_emoteForLastStep = (gameId) ->
if ai_canEmote(gameId)
step = games[gameId].session.getLastStep()
action = step?.action
if action? and !(action instanceof SDK.EndTurnAction)
aiPlayerId = games[gameId].ai.getMyPlayerId()
isMyAction = action.getOwnerId() == aiPlayerId
# search action + sub actions for any played or removed units
actionsToSearch = [action]
numHappyActions = 0
numTauntingActions = 0
numAngryActions = 0
while actionsToSearch.length > 0
searchAction = actionsToSearch.shift()
if searchAction instanceof SDK.RemoveAction
if !isMyAction and searchAction.getTarget()?.getOwnerId() == aiPlayerId
numAngryActions += 2
else if isMyAction and searchAction.getTarget()?.getOwnerId() != aiPlayerId
numTauntingActions += 1
else if searchAction instanceof SDK.HealAction
if isMyAction and searchAction.getTarget()?.getOwnerId() == aiPlayerId
numTauntingActions += 1
else if !isMyAction and searchAction.getTarget()?.getOwnerId() != aiPlayerId
numAngryActions += 1
else if searchAction instanceof SDK.PlayCardFromHandAction or searchAction instanceof SDK.PlaySignatureCardAction
if isMyAction and searchAction.getCard() instanceof SDK.Unit
numHappyActions += 1
# add sub actions
actionsToSearch = actionsToSearch.concat(searchAction.getSubActions())
maxEmotion = Math.max(numHappyActions, numTauntingActions, numAngryActions)
if maxEmotion > 0
emoteIds = []
myGeneral = games[gameId].ai.getMyGeneral()
myGeneralId = myGeneral.getId()
factionEmotesData = SDK.CosmeticsFactory.cosmeticsForTypeAndFaction(SDK.CosmeticsTypeLookup.Emote, myGeneral.getFactionId())
# use ai faction emote that were most present in last step
if maxEmotion == numAngryActions
for emoteData in factionEmotesData
if emoteData.enabled and (emoteData.title == "Angry" or emoteData.title == "Sad" or emoteData.title == "Frustrated") and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
else if maxEmotion == numHappyActions
for emoteData in factionEmotesData
if emoteData.enabled and emoteData.title == "Happy" and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
else if maxEmotion == numTauntingActions
for emoteData in factionEmotesData
if emoteData.enabled and (emoteData.title == "Taunt" or emoteData.title == "Sunglasses" or emoteData.title == "Kiss") and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
# pick a random emote
emoteId = emoteIds[Math.floor(Math.random() * emoteIds.length)]
#Logger.module("AI").debug "[G:#{gameId}]", "ai_emoteForLastStep -> #{emoteId} for #{games[gameId].session.getLastStep()?.action?.getLogName()}".cyan
if emoteId?
# clear any waiting emote timeout
ai_stopEmoteTimeouts(gameId)
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiEmoteTimeoutId = setTimeout((()->
games[gameId].aiEmoteTimeoutId = null
#Logger.module("AI").debug "[G:#{gameId}]", "ai_showEmote -> #{emoteId}".cyan
emitGameEvent(null, gameId, {
type: EVENTS.show_emote
id: emoteId,
playerId: games[gameId].ai.getMyPlayerId()
})
), 4000.0)
###*
* Stops AI timeouts for emotes.
* @param {String} gameId
###
ai_stopEmoteTimeouts = (gameId) ->
if games[gameId].aiEmoteTimeoutId?
clearTimeout(games[gameId].aiEmoteTimeoutId)
games[gameId].aiEmoteTimeoutId = null
# endregion AI
| 21663 | ###
Game Server Pieces
###
fs = require 'fs'
os = require 'os'
util = require 'util'
_ = require 'underscore'
colors = require 'colors' # used for console message coloring
jwt = require 'jsonwebtoken'
io = require 'socket.io'
ioJwt = require 'socketio-jwt'
Promise = require 'bluebird'
kue = require 'kue'
moment = require 'moment'
request = require 'superagent'
# Our modules
shutdown = require './shutdown'
StarterAI = require './ai/starter_ai'
SDK = require '../app/sdk.coffee'
Logger = require '../app/common/logger.coffee'
EVENTS = require '../app/common/event_types'
UtilsGameSession = require '../app/common/utils/utils_game_session.coffee'
exceptionReporter = require '@counterplay/exception-reporter'
# lib Modules
Consul = require './lib/consul'
# Configuration object
config = require '../config/config.js'
env = config.get('env')
firebaseToken = config.get('firebaseToken')
# Boots up a basic HTTP server on port 8080
# Responds to /health endpoint with status 200
# Otherwise responds with status 404
Logger = require '../app/common/logger.coffee'
CONFIG = require '../app/common/config'
http = require 'http'
url = require 'url'
Promise = require 'bluebird'
# perform DNS health check
dnsHealthCheck = () ->
if config.isDevelopment()
return Promise.resolve({healthy: true})
nodename = "#{config.get('env')}-#{os.hostname().split('.')[0]}"
return Consul.kv.get("nodes/#{nodename}/dns_name")
.then (dnsName) ->
return new Promise (resolve, reject) ->
request.get("https://#{dnsName}/health")
.end (err, res) ->
if err
return resolve({dnsName: dnsName, healthy: false})
if res? && res.status == 200
return resolve({dnsName: dnsName, healthy: true})
return ({dnsName: dnsName, healthy: false})
.catch (e) ->
return {healthy: false}
# create http server and respond to /health requests
server = http.createServer (req, res) ->
pathname = url.parse(req.url).pathname
if pathname == '/health'
Logger.module("GAME SERVER").debug "HTTP Health Ping"
res.statusCode = 200
res.write JSON.stringify({players: playerCount, games: gameCount})
res.end()
else
res.statusCode = 404
res.end()
# io server setup, binds to http server
io = require('socket.io')().listen(server, {
cors: {
origin: "*"
}
})
io.use(
ioJwt.authorize(
secret:firebaseToken
timeout: 15000
)
)
module.exports = io
server.listen config.get('game_port'), () ->
Logger.module("AI SERVER").log "AI Server <b>#{os.hostname()}</b> started."
# redis
{Redis, Jobs, GameManager} = require './redis/'
# server id for this game server
serverId = os.hostname()
# the 'games' hash maps game IDs to References for those games
games = {}
# save some basic stats about this server into redis
playerCount = 0
gameCount = 0
# turn times
MAX_TURN_TIME = (CONFIG.TURN_DURATION + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0
MAX_TURN_TIME_INACTIVE = (CONFIG.TURN_DURATION_INACTIVE + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0
savePlayerCount = (playerCount) ->
Redis.hsetAsync("servers:#{serverId}", "players", playerCount)
saveGameCount = (gameCount) ->
Redis.hsetAsync("servers:#{serverId}", "games", gameCount)
# error 'domain' to deal with io.sockets uncaught errors
d = require('domain').create()
d.on 'error', shutdown.errorShutdown
d.add(io.sockets)
# health ping on socket namespace /health
healthPing = io
.of '/health'
.on 'connection', (socket) ->
socket.on 'ping', () ->
Logger.module("GAME SERVER").debug "socket.io Health Ping"
socket.emit 'pong'
# run main io.sockets inside of the domain
d.run () ->
io.sockets.on "authenticated", (socket) ->
# add the socket to the error domain
d.add(socket)
# Socket is now autheticated, continue to bind other handlers
Logger.module("IO").log "DECODED TOKEN ID: #{<KEY>.decoded_token.<KEY>
savePlayerCount(++playerCount)
# Send message to user that connection is succesful
socket.emit "connected",
message: "Successfully connected to server"
# Bind socket event handlers
socket.on EVENTS.join_game, onGamePlayerJoin
socket.on EVENTS.spectate_game, onGameSpectatorJoin
socket.on EVENTS.leave_game, onGameLeave
socket.on EVENTS.network_game_event, onGameEvent
socket.on "disconnect", onGameDisconnect
getConnectedSpectatorsDataForGamePlayer = (gameId,playerId)->
spectators = []
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
socket = io.sockets.connected[socketId]
if socket.playerId == playerId
spectators.push({
id:socket.spectatorId,
playerId:socket.playerId,
username:socket.spectateToken?.u
})
return spectators
###
# socket handler for players joining game
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGamePlayerJoin = (requestData) ->
# request parameters
gameId = requestData.gameId
playerId = requestData.playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> player:#{requestData.playerId} is joining game:#{requestData.gameId}".cyan
# you must have a playerId
if not playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red
@emit "join_game_response",
error:"Your player id seems to be blank (has your login expired?), so we can't join you to the game."
return
# must have a gameId
if not gameId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red
@emit "join_game_response",
error:"Invalid Game ID."
return
# if someone is trying to join a game they don't belong to as a player they are not authenticated as
if @.decoded_token.d.id != playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red
@emit "join_game_response",
error:"Your player id does not match the one you requested to join a game with. Are you sure you're joining the right game?"
return
# if a client is already in another game, leave it
playerLeaveGameIfNeeded(this)
# if this client already exists in this game, disconnect duplicate client
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> detected duplicate connection to #{gameId} GameSession for #{playerId.blue}. Disconnecting duplicate...".cyan
playerLeaveGameIfNeeded(socket, silent=true)
# initialize a server-side game session and join it
initGameSession(gameId)
.bind @
.spread (gameSession) ->
#Logger.module("IO").debug "[G:#{gameId}]", "join_game -> players in data: ", gameSession.players
# player
player = _.find(gameSession.players, (p) -> return p.playerId == playerId)
# get the opponent based on the game session data
opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId)
Logger.module("IO").log "[G:#{gameId}]", "join_game -> Got #{gameId} GameSession data #{playerId.blue}.".cyan
if not player # oops looks like this player does not exist in the requested game
# let the socket know we had an error
@emit "join_game_response",
error:"could not join game because your player id could not be found"
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else if not opponent? # oops, looks like we can'f find an opponent in the game session?
Logger.module("IO").log "[G:#{gameId}]", "join_game -> game #{gameId} ERROR: could not find opponent for #{playerId.blue}.".red
# let the socket know we had an error
@emit "join_game_response",
error:"could not join game because the opponent could not be found"
# issue a warning to our exceptionReporter error tracker
exceptionReporter.notify(new Error("Error joining game: could not find opponent"), {
severity: "warning"
user:
id: playerId
game:
id: gameId
player1Id: gameSession?.players[0].playerId
player2Id: gameSession?.players[1].playerId
})
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else
# rollback if it is this player's followup
# this can happen if a player reconnects without properly disconnecting
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() == playerId
gameSession.executeAction(gameSession.actionRollbackSnapshot())
# set some parameters for the socket
@gameId = gameId
@playerId = playerId
# join game room
@join(gameId)
# update user count for game room
games[gameId].connectedPlayers.push(playerId)
Logger.module("IO").log "[G:#{gameId}]", "join_game -> Game #{gameId} connected players so far: #{games[gameId].connectedPlayers.length}."
# if only one player is in so far, start the disconnection timer
if games[gameId].connectedPlayers.length == 1
# start disconnected player timeout for game
startDisconnectedPlayerTimeout(gameId,opponent.playerId)
else if games[gameId].connectedPlayers.length == 2
# clear timeout when we get two players
clearDisconnectedPlayerTimeout(gameId)
# prepare and scrub game session data for this player
# if a followup is active and it isn't this player's followup, send them the rollback snapshot
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId
gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData())
else
gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession))
UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId)
# respond to client with success and a scrubbed copy of the game session
@emit "join_game_response",
message: "successfully joined game"
gameSessionData: gameSessionData
connectedPlayers:games[gameId].connectedPlayers
connectedSpectators: getConnectedSpectatorsDataForGamePlayer(gameId,playerId)
# broadcast join to any other connected players
@broadcast.to(gameId).emit("player_joined",playerId)
# attempt to update ai turn on active game
if gameSession.isActive()
ai_updateTurn(gameId)
.catch (e) ->
Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game. ERROR: #{e.message}".red
# if we didn't join a game, broadcast a failure
@emit "join_game_response",
error:"Could not join game: " + e?.message
###
# socket handler for spectators joining game
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGameSpectatorJoin = (requestData) ->
# request parameters
# TODO : Sanitize these parameters to prevent crash if gameId = null
gameId = requestData.gameId
spectatorId = requestData.spectatorId
playerId = requestData.playerId
spectateToken = null
# verify - synchronous
try
spectateToken = jwt.verify(requestData.spectateToken, firebaseToken)
catch error
Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> ERROR decoding spectate token: #{error?.message}".red
if not spectateToken or spectateToken.b?.length == 0
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A specate token #{spectateToken} is not valid".red
@emit "spectate_game_response",
error:"Your spectate token is invalid, so we can't join you to the game."
return
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> token contents: ", spectateToken.b
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> playerId: ", playerId
if not _.contains(spectateToken.b,playerId)
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: You do not have permission to specate this game".red
@emit "spectate_game_response",
error:"You do not have permission to specate this game."
return
# must have a spectatorId
if not spectatorId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A spectator #{spectatorId.blue} is not valid".red
@emit "spectate_game_response",
error:"Your login ID is blank (expired?), so we can't join you to the game."
return
# must have a playerId
if not playerId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red
@emit "spectate_game_response",
error:"Invalid player ID."
return
# must have a gameId
if not gameId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red
@emit "spectate_game_response",
error:"Invalid Game ID."
return
# if someone is trying to join a game they don't belong to as a player they are not authenticated as
if @.decoded_token.d.id != spectatorId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red
@emit "spectate_game_response",
error:"Your login ID does not match the one you requested to spectate the game with."
return
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> spectator:#{spectatorId} is joining game:#{gameId}".cyan
# if a client is already in another game, leave it
spectatorLeaveGameIfNeeded(@)
if games[gameId]?.connectedSpectators.length >= 10
# max out at 10 spectators
@emit "spectate_game_response",
error:"Maximum number of spectators already watching."
return
# initialize a server-side game session and join it
initSpectatorGameSession(gameId)
.bind @
.then (spectatorGameSession) ->
# for spectators, use the delayed in-memory game session
gameSession = spectatorGameSession
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> Got #{gameId} GameSession data.".cyan
player = _.find(gameSession.players, (p) -> return p.playerId == playerId)
opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId)
if not player
# let the socket know we had an error
@emit "spectate_game_response",
error:"could not join game because the player id you requested could not be found"
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameSpectatorJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else
# set some parameters for the socket
@gameId = gameId
@spectatorId = spectatorId
@spectateToken = spectateToken
@playerId = playerId
# join game room
@join("spectate-#{gameId}")
# update user count for game room
games[gameId].connectedSpectators.push(spectatorId)
# prepare and scrub game session data for this player
# if a followup is active and it isn't this player's followup, send them the rollback snapshot
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId
gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData())
else
gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession))
UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId, true)
###
# if the spectator does not have the opponent in their buddy list
if not _.contains(spectateToken.b,opponent.playerId)
# scrub deck data and opponent hand data by passing in opponent ID
scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId)
else
# otherwise just scrub deck data in a way you can see both decks
# scrubGameSessionDataForSpectators(gameSession, gameSessionData)
# NOTE: above line is disabled for now since it does some UI jankiness since when a cardId is present the tile layer updates when the spectated opponent starts to select cards
# NOTE: besides, actions will be scrubbed so this idea of watching both players only sort of works right now
scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId, true)
###
# respond to client with success and a scrubbed copy of the game session
@emit "spectate_game_response",
message: "successfully joined game"
gameSessionData: gameSessionData
# broadcast to the game room that a spectator has joined
@broadcast.to(gameId).emit("spectator_joined",{
id: spectatorId,
playerId: playerId,
username: spectateToken.u
})
.catch (e) ->
# if we didn't join a game, broadcast a failure
@emit "spectate_game_response",
error:"could not join game: #{e.message}"
###
# socket handler for leaving a game.
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGameLeave = (requestData) ->
if @.spectatorId
Logger.module("IO").log "[G:#{@.gameId}]", "leave_game -> spectator #{@.spectatorId} leaving #{@.gameId}"
spectatorLeaveGameIfNeeded(@)
else
Logger.module("IO").log "[G:#{@.gameId}]", "leave_game -> player #{@.playerId} leaving #{@.gameId}"
playerLeaveGameIfNeeded(@)
###*
# This method is called every time a socket handler recieves a game event and is executed within the context of the socket (this == sending socket).
# @public
# @param {Object} eventData Plain JS object with event data that contains one "event".
###
onGameEvent = (eventData) ->
# if for some reason spectator sockets start broadcasting game events
if @.spectatorId
Logger.module("IO").log "[G:#{@.gameId}]", "onGameEvent :: ERROR: spectator sockets can't submit game events. (type: #{eventData.type})".red
return
# Logger.module("IO").log "onGameEvent -> #{JSON.stringify(eventData)}".blue
if not @gameId or not games[@gameId]
@emit EVENTS.network_game_error,
code:500
message:"could not broadcast game event because you are not currently in a game"
return
#
gameSession = games[@gameId].session
if eventData.type == EVENTS.step
#Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{JSON.stringify(eventData.step)}".green
#Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{eventData.step?.playerId} #{eventData.step?.action?.type}".green
player = _.find(gameSession.players,(p)-> p.playerId == eventData.step?.playerId)
player?.setLastActionTakenAt(Date.now())
try
step = gameSession.deserializeStepFromFirebase(eventData.step)
action = step.action
if action?
# clear out any implicit actions sent over the network and re-execute this as a fresh explicit action on the server
# the reason is that we want to re-generate and re-validate all the game logic that happens as a result of this FIRST explicit action in the step
action.resetForAuthoritativeExecution()
# execute the action
gameSession.executeAction(action)
catch error
Logger.module("IO").log "[G:#{@.gameId}]", "onGameStep:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{@.gameId}]", "onGameStep:: error stack: #{error.stack}".red
# Report error to exceptionReporter with gameId + eventData
exceptionReporter.notify(error, {
errorName: "onGameStep Error",
game: {
gameId: @gameId
eventData: eventData
}
})
# delete but don't destroy game
destroyGameSessionIfNoConnectionsLeft(@gameId,true)
# send error to client, forcing reconnect on client side
io.to(@gameId).emit EVENTS.network_game_error, JSON.stringify(error.message)
return
else
# transmit the non-step game events to players
# step events are emitted automatically after executed on game session
emitGameEvent(@, @gameId, eventData)
###
# Socket Disconnect Event Handler. Handles rollback if in the middle of followup etc.
# @public
###
onGameDisconnect = () ->
if @.spectatorId
# make spectator leave game room
spectatorLeaveGameIfNeeded(@)
# remove the socket from the error domain, this = socket
d.remove(@)
else
try
clients_in_the_room = io.sockets.adapter.rooms[@.gameId]
for clientId,socket of clients_in_the_room
if socket.playerId == @.playerId
Logger.module("IO").log "onGameDisconnect:: looks like the player #{@.playerId} we are trying to disconnect is still in the game #{@.gameId} room. ABORTING".red
return
for clientId,socket of io.sockets.connected
if socket.playerId == @.playerId and not socket.spectatorId
Logger.module("IO").log "onGameDisconnect:: looks like the player #{@.playerId} that allegedly disconnected is still alive and well.".red
return
catch error
Logger.module("IO").log "onGameDisconnect:: Error #{error?.message}.".red
# if we are in a buffering state
# and the disconnecting player is in the middle of a followup
gs = games[@gameId]?.session
if gs? and gs.getIsBufferingEvents() and gs.getCurrentPlayerId() == @playerId
# execute a rollback to reset server state
# but do not send this action to the still connected player
# because they do not care about rollbacks for the other player
rollBackAction = gs.actionRollbackSnapshot()
gs.executeAction(rollBackAction)
# remove the socket from the error domain, this = socket
d.remove(@)
savePlayerCount(--playerCount)
Logger.module("IO").log "[G:#{@.gameId}]", "disconnect -> #{@.playerId}".red
# if a client is already in another game, leave it
playerLeaveGameIfNeeded(@)
###*
* Leaves a game for a player socket if the socket is connected to a game
* @public
* @param {Socket} socket The socket which wants to leave a game.
* @param {Boolean} [silent=false] whether to disconnect silently, as in the case of duplicate connections for same player
###
playerLeaveGameIfNeeded = (socket, silent=false) ->
if socket?
gameId = socket.gameId
playerId = socket.playerId
# if a player is in a game
if gameId? and playerId?
Logger.module("...").log "[G:#{gameId}]", "playerLeaveGame -> #{playerId} has left game #{gameId}".red
if !silent
# broadcast that player left
socket.broadcast.to(gameId).emit("player_left",playerId)
# leave that game room
socket.leave(gameId)
# update user count for game room
game = games[gameId]
if game?
index = game.connectedPlayers.indexOf(playerId)
game.connectedPlayers.splice(index,1)
if !silent
# start disconnected player timeout for game
startDisconnectedPlayerTimeout(gameId,playerId)
# destroy game if no one is connected anymore
destroyGameSessionIfNoConnectionsLeft(gameId,true)
# finally clear the existing gameId
socket.gameId = null
###
# This function leaves a game for a spectator socket if the socket is connected to a game
# @public
# @param {Socket} socket The socket which wants to leave a game.
###
spectatorLeaveGameIfNeeded = (socket) ->
# if a client is already in another game
if socket.gameId
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} leaving game #{socket.gameId}."
# broadcast that you left
socket.broadcast.to(socket.gameId).emit("spectator_left",{
id:socket.spectatorId,
playerId:socket.playerId,
username:socket.spectateToken?.u
})
# leave specator game room
socket.leave("spectate-#{socket.gameId}")
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} left room for game #{socket.gameId}."
# update spectator count for game room
if games[socket.gameId]
games[socket.gameId].connectedSpectators = _.without(games[socket.gameId].connectedSpectators,socket.spectatorId)
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} removed from list of spectators #{socket.gameId}."
# if no spectators left, stop the delayed game interval and destroy spectator delayed game session
tearDownSpectateSystemsIfNoSpectatorsLeft(socket.gameId)
# destroy game if no one is connected anymore
destroyGameSessionIfNoConnectionsLeft(socket.gameId,true)
remainingSpectators = games[socket.gameId]?.connectedSpectators?.length || 0
Logger.module("...").log "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} has left game #{socket.gameId}. remaining spectators #{remainingSpectators}"
# finally clear the existing gameId
socket.gameId = null
###
# This function destroys in-memory game session of there is no one left connected
# @public
# @param {String} gameId The ID of the game to destroy.
# @param {Boolean} persist Do we need to save/archive this game?
###
destroyGameSessionIfNoConnectionsLeft = (gameId,persist=false)->
if games[gameId].connectedPlayers.length == 1 and games[gameId].connectedSpectators.length == 0
clearDisconnectedPlayerTimeout(gameId)
stopTurnTimer(gameId)
tearDownSpectateSystemsIfNoSpectatorsLeft(gameId)
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> no players left DESTROYING local game cache".red
unsubscribeFromGameSessionEvents(gameId)
ai_terminate(gameId)
# TEMP: a way to upload unfinished game data to AWS S3 Archive. For example: errored out games.
if persist and games?[gameId]?.session?.status != SDK.GameStatus.over
data = games[gameId].session.serializeToJSON(games[gameId].session)
mouseAndUIEventsData = JSON.stringify(games[gameId].mouseAndUIEvents)
Promise.all([
GameManager.saveGameSession(gameId,data),
GameManager.saveGameMouseUIData(gameId,mouseAndUIEventsData),
])
.then (results) ->
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> unfinished Game Archived to S3: #{results[1]}".green
.catch (error)->
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> ERROR: failed to archive unfinished game to S3 due to error #{error.message}".red
delete games[gameId]
saveGameCount(--gameCount)
else
Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> players left: #{games[gameId].connectedPlayers.length} spectators left: #{games[gameId].connectedSpectators.length}"
###
# This function stops all spectate systems if 0 spectators left.
# @public
# @param {String} gameId The ID of the game to tear down spectate systems.
###
tearDownSpectateSystemsIfNoSpectatorsLeft = (gameId)->
# if no spectators left, stop the delayed game interval and destroy spectator delayed game session
if games[gameId]?.connectedSpectators.length == 0
Logger.module("IO").debug "[G:#{gameId}]", "tearDownSpectateSystemsIfNoSpectatorsLeft() -> no spectators left, stopping spectate systems"
stopSpectatorDelayedGameInterval(gameId)
games[gameId].spectatorDelayedGameSession = null
games[gameId].spectateIsRunning = false
games[gameId].spectatorOpponentEventDataBuffer.length = 0
games[gameId].spectatorGameEventBuffer.length = 0
###
# Clears timeout for disconnected players
# @public
# @param {String} gameId The ID of the game to clear disconnected timeout for.
###
clearDisconnectedPlayerTimeout = (gameId) ->
Logger.module("IO").log "[G:#{gameId}]", "clearDisconnectedPlayerTimeout:: for game: #{gameId}".yellow
clearTimeout(games[gameId]?.disconnectedPlayerTimeout)
games[gameId]?.disconnectedPlayerTimeout = null
###
# Starts timeout for disconnected players
# @public
# @param {String} gameId The ID of the game.
# @param {String} playerId The player ID for who to start the timeout.
###
startDisconnectedPlayerTimeout = (gameId,playerId) ->
if games[gameId]?.disconnectedPlayerTimeout?
clearDisconnectedPlayerTimeout(gameId)
Logger.module("IO").log "[G:#{gameId}]", "startDisconnectedPlayerTimeout:: for #{playerId} in game: #{gameId}".yellow
games[gameId]?.disconnectedPlayerTimeout = setTimeout(()->
onDisconnectedPlayerTimeout(gameId,playerId)
,60000)
###
# Resigns game for disconnected player.
# @public
# @param {String} gameId The ID of the game.
# @param {String} playerId The player ID who is resigning.
###
onDisconnectedPlayerTimeout = (gameId,playerId) ->
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} for game: #{gameId}"
clients_in_the_room = io.sockets.adapter.rooms[gameId]
for clientId,socket of clients_in_the_room
if socket.playerId == playerId
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to dis-connect is still in the game #{gameId} room. ABORTING".red
return
for clientId,socket of io.sockets.connected
if socket.playerId == playerId and not socket.spectatorId
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to disconnect is still connected but not in the game #{gameId} room.".red
return
# grab the relevant game session
gs = games[gameId]?.session
# looks like we timed out for a game that's since ended
if !gs or gs?.status == SDK.GameStatus.over
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} timed out for FINISHED or NULL game: #{gameId}".yellow
return
else
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} auto-resigning game: #{gameId}".yellow
# resign the player
player = gs.getPlayerById(playerId)
resignAction = player.actionResign()
gs.executeAction(resignAction)
###*
# Start/Restart server side game timer for a game
# @public
# @param {Object} gameId The game ID.
###
restartTurnTimer = (gameId) ->
stopTurnTimer(gameId)
game = games[gameId]
if game.session?
game.turnTimerStartedAt = game.turnTimeTickAt = Date.now()
if game.session.isBossBattle()
# boss battles turns have infinite time
# so we'll just tick once and wait
onGameTimeTick(gameId)
else
# set turn timer on a 1 second interval
game.turnTimer = setInterval((()-> onGameTimeTick(gameId)),1000)
###*
# Stop server side game timer for a game
# @public
# @param {Object} gameId The game ID.
###
stopTurnTimer = (gameId) ->
game = games[gameId]
if game? and game.turnTimer?
clearInterval(game.turnTimer)
game.turnTimer = null
###*
# Server side game timer. After 90 seconds it will end the turn for the current player.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
onGameTimeTick = (gameId) ->
game = games[gameId]
gameSession = game?.session
if gameSession?
# allowed turn time is 90 seconds + 3 second buffer that clients don't see
allowed_turn_time = MAX_TURN_TIME
# grab the current player
player = gameSession.getCurrentPlayer()
# if we're past the 2nd turn, we can start checking backwards to see how long the PREVIOUS turn for this player took
if player and gameSession.getTurns().length > 2
# find the current player's previous turn
allTurns = gameSession.getTurns()
playersPreviousTurn = null
for i in [allTurns.length-1..0] by -1
if allTurns[i].playerId == player.playerId
playersPreviousTurn = allTurns[i] # gameSession.getTurns()[gameSession.getTurns().length - 3]
break
#Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: last action at #{player.getLastActionTakenAt()} / last turn delta #{playersPreviousTurn?.createdAt - player.getLastActionTakenAt()}".red
# if this player's previous action was on a turn older than the last one
if playersPreviousTurn && (playersPreviousTurn.createdAt - player.getLastActionTakenAt() > 0)
# you're only allowed 15 seconds + 3 second buffer that clients don't see
allowed_turn_time = MAX_TURN_TIME_INACTIVE
lastTurnTimeTickAt = game.turnTimeTickAt
game.turnTimeTickAt = Date.now()
delta_turn_time_tick = game.turnTimeTickAt - lastTurnTimeTickAt
delta_since_timer_began = game.turnTimeTickAt - game.turnTimerStartedAt
game.turnTimeRemaining = Math.max(0.0, allowed_turn_time - delta_since_timer_began + game.turnTimeBonus)
game.turnTimeBonus = Math.max(0.0, game.turnTimeBonus - delta_turn_time_tick)
#Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: delta #{delta_turn_time_tick/1000}, #{game.turnTimeRemaining/1000} time remaining, #{game.turnTimeBonus/1000} bonus remaining"
turnTimeRemainingInSeconds = Math.ceil(game.turnTimeRemaining/1000)
gameSession.setTurnTimeRemaining(turnTimeRemainingInSeconds)
if game.turnTimeRemaining <= 0
# turn time has expired
stopTurnTimer(gameId)
if gameSession.status == SDK.GameStatus.new
# force draw starting hand with current cards
for player in gameSession.players
if not player.getHasStartingHand()
Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: mulligan timer up, submitting player #{player.playerId.blue} mulligan".red
drawStartingHandAction = player.actionDrawStartingHand([])
gameSession.executeAction(drawStartingHandAction)
else if gameSession.status == SDK.GameStatus.active
# force end turn
Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: turn timer up, submitting player #{gameSession.getCurrentPlayerId().blue} turn".red
endTurnAction = gameSession.actionEndTurn()
gameSession.executeAction(endTurnAction)
else
# if the turn timer has not expired, just send the time tick over to all clients
totalStepCount = gameSession.getStepCount() - games[gameId].opponentEventDataBuffer.length
emitGameEvent(null,gameId,{type:EVENTS.turn_time, time: turnTimeRemainingInSeconds, timestamp: Date.now(), stepCount: totalStepCount})
###*
# ...
# @public
# @param {Object} gameId The game ID.
###
restartSpectatorDelayedGameInterval = (gameId) ->
stopSpectatorDelayedGameInterval(gameId)
Logger.module("IO").debug "[G:#{gameId}]", "restartSpectatorDelayedGameInterval"
if games[gameId].spectateIsDelayed
games[gameId].spectatorDelayTimer = setInterval((()-> onSpectatorDelayedGameTick(gameId)), 500)
###*
# ...
# @public
# @param {Object} gameId The game ID.
###
stopSpectatorDelayedGameInterval = (gameId) ->
Logger.module("IO").debug "[G:#{gameId}]", "stopSpectatorDelayedGameInterval"
clearInterval(games[gameId].spectatorDelayTimer)
###*
# Ticks the spectator delayed game and usually flushes the buffer by calling `flushSpectatorNetworkEventBuffer`.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
onSpectatorDelayedGameTick = (gameId) ->
if not games[gameId]
Logger.module("Game").debug "onSpectatorDelayedGameTick() -> game [G:#{gameId}] seems to be destroyed. Stopping ticks."
stopSpectatorDelayedGameInterval(gameId)
return
_logSpectatorTickInfo(gameId)
# flush anything in the spectator buffer
flushSpectatorNetworkEventBuffer(gameId)
###*
# Runs actions delayed in the spectator buffer.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
flushSpectatorNetworkEventBuffer = (gameId) ->
# if there is anything in the buffer
if games[gameId].spectatorGameEventBuffer.length > 0
# Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer()"
# remove all the NULLED out actions
games[gameId].spectatorGameEventBuffer = _.compact(games[gameId].spectatorGameEventBuffer)
# loop through the actions in order
for eventData,i in games[gameId].spectatorGameEventBuffer
timestamp = eventData.timestamp || eventData.step?.timestamp
# if we are not delaying events or if the event time exceeds the delay show it to spectators
if not games[gameId].spectateIsDelayed || timestamp and moment().utc().valueOf() - timestamp > games[gameId].spectateDelay
# null out the event that is about to be broadcast so it can be compacted later
games[gameId].spectatorGameEventBuffer[i] = null
if (eventData.step)
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> broadcasting spectator step #{eventData.type} - #{eventData.step?.action?.type}"
if games[gameId].spectateIsDelayed
step = games[gameId].spectatorDelayedGameSession.deserializeStepFromFirebase(eventData.step)
games[gameId].spectatorDelayedGameSession.executeAuthoritativeStep(step)
# send events over to spectators of current player
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to player's spectators"
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.step.playerId
# scrub the action data. this should not be skipped since some actions include entire deck that needs to be scrubbed because we don't want spectators deck sniping
eventDataCopy = JSON.parse(JSON.stringify(eventData))
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true)
socket.emit EVENTS.network_game_event, eventDataCopy
# skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one
if eventData.step.action.type == SDK.RollbackToSnapshotAction.type
return
# start buffering events until a followup is complete for the opponent since players can cancel out of a followup
games[gameId].spectatorOpponentEventDataBuffer.push(eventData)
# if we are delayed then check the delayed game session for if we are buffering, otherwise use the primary
isSpectatorGameSessionBufferingFollowups = (games[gameId].spectateIsDelayed and games[gameId].spectatorDelayedGameSession?.getIsBufferingEvents()) || games[gameId].session.getIsBufferingEvents()
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> opponentEventDataBuffer at #{games[gameId].spectatorOpponentEventDataBuffer.length} ... buffering: #{isSpectatorGameSessionBufferingFollowups}"
# if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent's spectators
if games[gameId].spectatorOpponentEventDataBuffer.length > 0 and !isSpectatorGameSessionBufferingFollowups
# copy buffer and reset
opponentEventDataBuffer = games[gameId].spectatorOpponentEventDataBuffer.slice(0)
games[gameId].spectatorOpponentEventDataBuffer.length = 0
# broadcast whatever's in the buffer to the opponent
_.each(opponentEventDataBuffer, (eventData) ->
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to opponent's spectators"
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId != eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from opponent's spectator perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true)
socket.emit EVENTS.network_game_event, eventDataCopy
)
else
io.to("spectate-#{gameId}").emit EVENTS.network_game_event, eventData
_logSpectatorTickInfo = _.debounce((gameId)->
Logger.module("Game").debug "onSpectatorDelayedGameTick() ... #{games[gameId]?.spectatorGameEventBuffer?.length} buffered"
if games[gameId]?.spectatorGameEventBuffer
for eventData,i in games[gameId]?.spectatorGameEventBuffer
Logger.module("Game").debug "onSpectatorDelayedGameTick() eventData: ",eventData
, 1000)
###*
# Emit/Broadcast game event to appropriate destination.
# @public
# @param {Socket} event Originating socket.
# @param {String} gameId The game id for which to broadcast.
# @param {Object} eventData Data to broadcast.
###
emitGameEvent = (fromSocket,gameId,eventData)->
if games[gameId]?
if eventData.type == EVENTS.step
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> step #{eventData.step?.index?.toString().yellow} with timestamp #{eventData.step?.timestamp} and action #{eventData.step?.action?.type}"
# only broadcast valid steps
if eventData.step? and eventData.step.timestamp? and eventData.step.action?
# send the step to the owner
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from player perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId)
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to origin"
socket.emit EVENTS.network_game_event, eventDataCopy
# NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected:
# 2 for this current reconnecting player and 1 for the opponent
# breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event
# break
# buffer actions for the opponent other than a rollback action since that should clear the buffer during followups and there's no need to be sent to the opponent
# essentially: skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one
if eventData.step.action.type != SDK.RollbackToSnapshotAction.type
# start buffering events until a followup is complete for the opponent since players can cancel out of a followup
games[gameId].opponentEventDataBuffer.push(eventData)
# if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent
if games[gameId].opponentEventDataBuffer.length > 0 and !games[gameId].session.getIsBufferingEvents()
# copy buffer and reset
opponentEventDataBuffer = games[gameId].opponentEventDataBuffer.slice(0)
games[gameId].opponentEventDataBuffer.length = 0
# broadcast whatever's in the buffer to the opponent
_.each(opponentEventDataBuffer, (eventData) ->
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId != eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from player perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId)
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to opponent"
socket.emit EVENTS.network_game_event, eventDataCopy
)
else if eventData.type == EVENTS.invalid_action
# send the invalid action notification to the owner
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
socket.emit EVENTS.network_game_event, eventDataCopy
# NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected:
# 2 for this current reconnecting player and 1 for the opponent
# breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event
else
if eventData.type == EVENTS.network_game_hover or eventData.type == EVENTS.network_game_select or eventData.type == EVENTS.network_game_mouse_clear or eventData.type == EVENTS.show_emote
# save the player id of this event
eventData.playerId ?= fromSocket?.playerId
eventData.timestamp = moment().utc().valueOf()
# mouse events, emotes, etc should be saved and persisted to S3 for replays
games[gameId].mouseAndUIEvents ?= []
games[gameId].mouseAndUIEvents.push(eventData)
if fromSocket?
# send it along to other connected sockets in the game room
fromSocket.broadcast.to(gameId).emit EVENTS.network_game_event, eventData
else
# send to all sockets connected to the game room
io.to(gameId).emit EVENTS.network_game_event, eventData
# push a deep clone of the event data to the spectator buffer
if games[gameId]?.spectateIsRunning
spectatorEventDataCopy = JSON.parse(JSON.stringify(eventData))
games[gameId].spectatorGameEventBuffer.push(spectatorEventDataCopy)
# if we're not running a timed delay, just flush everything now
if not games[gameId]?.spectateIsDelayed
flushSpectatorNetworkEventBuffer(gameId)
###
# start a game session if one doesn't exist and call a completion handler when done
# @public
# @param {Object} gameId The game ID to load.
# @param {Function} onComplete Callback when done.
###
initGameSession = (gameId,onComplete) ->
if games[gameId]?.loadingPromise
return games[gameId].loadingPromise
# setup local cache reference if none already there
if not games[gameId]
games[gameId] =
opponentEventDataBuffer:[]
connectedPlayers:[]
session:null
connectedSpectators:[]
spectateIsRunning:false
spectateIsDelayed:false
spectateDelay:30000
spectatorGameEventBuffer:[]
spectatorOpponentEventDataBuffer:[]
spectatorDelayedGameSession:null
turnTimerStartedAt: 0
turnTimeTickAt: 0
turnTimeRemaining: 0
turnTimeBonus: 0
# return game session from redis
games[gameId].loadingPromise = Promise.all([
GameManager.loadGameSession(gameId)
GameManager.loadGameMouseUIData(gameId)
])
.spread (gameData,mouseData)->
return [
JSON.parse(gameData)
JSON.parse(mouseData)
]
.spread (gameDataIn,mouseData) ->
Logger.module("IO").log "[G:#{gameId}]", "initGameSession -> loaded game data for game:#{gameId}"
# deserialize game session
gameSession = SDK.GameSession.create()
gameSession.setIsRunningAsAuthoritative(true)
gameSession.deserializeSessionFromFirebase(gameDataIn)
if gameSession.isOver()
throw new Error("Game is already over!")
# store session
games[gameId].session = gameSession
# store mouse and ui event data
games[gameId].mouseAndUIEvents = mouseData
saveGameCount(++gameCount)
# setup AI
ai_setup(gameId)
# in case the server restarted or loading data for first time, set the last action at timestamp for both players to now
# this timestamp is used to shorten turn timer if player has not made any moves for a long time
_.each(gameSession.players,(player)->
player.setLastActionTakenAt(Date.now())
)
# this is ugly but a simple way to subscribe to turn change events to save the game session
subscribeToGameSessionEvents(gameId)
# start the turn timer
restartTurnTimer(gameId)
return Promise.resolve([
games[gameId].session
])
.catch (error) ->
Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error stack: #{error.stack}".red
# Report error to exceptionReporter with gameId
exceptionReporter.notify(error, {
errorName: "initGameSession Error",
severity: "error",
game: {
id: gameId
}
})
throw error
###
# start a spectator game session if one doesn't exist and call a completion handler when done
# @public
# @param {Object} gameId The game ID to load.
# @param {Function} onComplete Callback when done.
###
initSpectatorGameSession = (gameId)->
if not games[gameId]
return Promise.reject(new Error("This game is no longer in progress"))
return Promise.resolve()
.then ()->
# if we're not already running spectate systems
if not games[gameId].spectateIsRunning
# mark that we are running spectate systems
games[gameId].spectateIsRunning = true
# if we're in the middle of a followup and we have some buffered events, we need to copy them over to the spectate buffer
if games[gameId].session.getIsBufferingEvents() and games[gameId].opponentEventDataBuffer.length > 0
games[gameId].spectatorOpponentEventDataBuffer.length = 0
for eventData in games[gameId].opponentEventDataBuffer
eventDataCopy = JSON.parse(JSON.stringify(eventData))
games[gameId].spectatorOpponentEventDataBuffer.push(eventDataCopy)
if games[gameId].spectateIsDelayed and not games[gameId].spectatorDelayedGameSession
Logger.module("...").log "[G:#{gameId}]", "initSpectatorDelayedGameSession() -> creating delayed game session"
# create
delayedGameDataIn = games[gameId].session.serializeToJSON(games[gameId].session)
delayedGameSession = SDK.GameSession.create()
delayedGameSession.setIsRunningAsAuthoritative(false)
delayedGameSession.deserializeSessionFromFirebase(JSON.parse(delayedGameDataIn))
delayedGameSession.gameId = "SPECTATE:#{delayedGameSession.gameId}"
games[gameId].spectatorDelayedGameSession = delayedGameSession
# start timer to execute delayed / buffered spectator game events
restartSpectatorDelayedGameInterval(gameId)
return Promise.resolve(games[gameId].spectatorDelayedGameSession)
else
return Promise.resolve(games[gameId].session)
###*
* Handler for before a game session rolls back to a snapshot.
###
onBeforeRollbackToSnapshot = (event) ->
# clear the buffer just before rolling back
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
game.opponentEventDataBuffer.length = 0
game.spectatorOpponentEventDataBuffer.length = 0
###*
* Handler for a game session step.
###
onStep = (event) ->
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
step = event.step
if step? and step.timestamp? and step.action?
# send out step events
stepEventData = {type: EVENTS.step, step: JSON.parse(game.session.serializeToJSON(step))}
emitGameEvent(null, gameId, stepEventData)
# special action cases
action = step.action
if action instanceof SDK.EndTurnAction
# save game on end turn
# delay so that we don't block sending the step back to the players
_.delay((()->
if games[gameId]? and games[gameId].session?
GameManager.saveGameSession(gameId, games[gameId].session.serializeToJSON(games[gameId].session))
), 500)
else if action instanceof SDK.StartTurnAction
# restart the turn timer whenever a turn starts
restartTurnTimer(gameId)
else if action instanceof SDK.DrawStartingHandAction
# restart turn timer if both players have a starting hand and this step is for a DrawStartingHandAction
bothPlayersHaveStartingHand = _.reduce(game.session.players,((memo,player)-> memo && player.getHasStartingHand()),true)
if bothPlayersHaveStartingHand
restartTurnTimer(gameId)
if action.getIsAutomatic() and !game.session.getIsFollowupActive()
# add bonus to turn time for every automatic step
# unless followup is active, to prevent rollbacks for infinite turn time
# bonus as a separate parameter accounts for cases such as:
# - battle pet automatic actions eating up your own time
# - queuing up many actions and ending turn quickly to eat into opponent's time
game.turnTimeBonus += 2000
# when game is over and we have the final step
# we cannot archive game until final step event
# because otherwise step won't be finished/signed correctly
# so we must do this on step event and not on game_over event
if game.session.status == SDK.GameStatus.over
# stop any turn timers
stopTurnTimer(gameId)
if !game.isArchived?
game.isArchived = true
afterGameOver(gameId, game.session, game.mouseAndUIEvents)
###*
* Handler for an invalid action.
###
onInvalidAction = (event) ->
# safety fallback: if player attempts to make an invalid explicit action, notify that player only
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
action = event.action
if !action.getIsImplicit()
#Logger.module("...").log "[G:#{gameId}]", "onInvalidAction -> INVALID ACTION: #{action.getLogName()} / VALIDATED BY: #{action.getValidatorType()} / MESSAGE: #{action.getValidationMessage()}"
invalidActionEventData = {
type: EVENTS.invalid_action,
playerId: action.getOwnerId(),
action: JSON.parse(game.session.serializeToJSON(action)),
validatorType: event.validatorType,
validationMessage: event.validationMessage,
validationMessagePosition: event.validationMessagePosition,
desync: gameSession.isActive() and
gameSession.getCurrentPlayerId() == action.getOwnerId() and
gameSession.getTurnTimeRemaining() > CONFIG.TURN_DURATION_LATENCY_BUFFER
}
emitGameEvent(null, gameId, invalidActionEventData)
###
# Subscribes to the gamesession's event bus.
# Can be called multiple times in order to re-subscribe.
# @public
# @param {Object} gameId The game ID to subscribe for.
###
subscribeToGameSessionEvents = (gameId)->
Logger.module("...").log "[G:#{gameId}]", "subscribeToGameSessionEvents -> subscribing to GameSession events"
game = games[gameId]
if game?
# unsubscribe from previous
unsubscribeFromGameSessionEvents(gameId)
# listen for game events
game.session.getEventBus().on(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot)
game.session.getEventBus().on(EVENTS.step, onStep)
game.session.getEventBus().on(EVENTS.invalid_action, onInvalidAction)
# subscribe AI to events
ai_subscribeToGameSessionEvents(gameId)
###
# Unsubscribe from event listeners on the game session for this game ID.
# @public
# @param {String} gameId The game ID that needs to be unsubscribed.
###
unsubscribeFromGameSessionEvents = (gameId)->
Logger.module("...").log "[G:#{gameId}]", "unsubscribeFromGameSessionEvents -> un-subscribing from GameSession events"
game = games[gameId]
if game?
game.session.getEventBus().off(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot)
game.session.getEventBus().off(EVENTS.step, onStep)
game.session.getEventBus().off(EVENTS.invalid_action, onInvalidAction)
ai_unsubscribeFromGameSessionEvents(gameId)
###
# must be called after game is over
# processes a game, saves to redis, and kicks-off post-game processing jobs
# @public
# @param {String} gameId The game ID that is over.
# @param {Object} gameSession The game session data.
# @param {Array} mouseAndUIEvents The mouse and UI events for this game.
###
afterGameOver = (gameId, gameSession, mouseAndUIEvents) ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "---------- ======= GAME #{gameId} OVER ======= ---------".green
# Update User Ranking, Progression, Quests, Stats
updateUser = (userId, opponentId, gameId, factionId, generalId, isWinner, isDraw, ticketId) ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "UPDATING user #{userId}. (winner:#{isWinner})"
# check for isFriendly
# check for isUnscored
isFriendly = gameSession.gameType == SDK.GameType.Friendly
isUnscored = false
# Ranking and Progression only process in NON-FRIENDLY matches
if not isFriendly
# calculate based on number of resign status and number of actions
lastStep = gameSession.getLastStep()
# if the game didn't have a single turn, mark the game as unscored
if gameSession.getPlayerById(userId).hasResigned and gameSession.getTurns().length == 0
Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} CONCEDED a game with 0 turns. Marking as UNSCORED".yellow
isUnscored = true
else if not isWinner and not isDraw
# otherwise check how many actions the player took
playerActionCount = 0
meaningfulActionCount = 0
moveActionCount = 0
for a in gameSession.getActions()
# explicit actions
if a.getOwnerId() == userId && a.getIsImplicit() == false
playerActionCount++
# meaningful actions
if a instanceof SDK.AttackAction
if a.getTarget().getIsGeneral()
meaningfulActionCount += 2
else
meaningfulActionCount += 1
if a instanceof SDK.PlayCardFromHandAction or a instanceof SDK.PlaySignatureCardAction
meaningfulActionCount += 1
if a instanceof SDK.BonusManaAction
meaningfulActionCount += 2
# move actions
if a instanceof SDK.MoveAction
moveActionCount += 1
# more than 9 explicit actions
# more than 1 move action
# more than 5 meaningful actions
if playerActionCount > 9 and moveActionCount > 1 and meaningfulActionCount > 4
break
###
what we're looking for:
* more than 9 explicit actions
* more than 1 move action
* more than 5 meaningful actions
... otherwise mark the game as unscored
###
# Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} #{playerActionCount}, #{moveActionCount}, #{meaningfulActionCount}".cyan
if playerActionCount <= 9 or moveActionCount <= 1 or meaningfulActionCount <= 4
Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} CONCEDED a game with too few meaningful actions. Marking as UNSCORED".yellow
isUnscored = true
# start the job to process the game for a user
Jobs.create("update-user-post-game",
name: "Update User Ranking"
title: util.format("User %s :: Game %s", userId, gameId)
userId: userId
opponentId: opponentId
gameId: gameId
gameType: gameSession.gameType
factionId: factionId
generalId: generalId
isWinner: isWinner
isDraw: isDraw
isUnscored: isUnscored
isBotGame: true
ticketId: ticketId
).removeOnComplete(true).save()
# Save then archive game session
archiveGame = (gameId, gameSession, mouseAndUIEvents) ->
Promise.all([
GameManager.saveGameMouseUIData(gameId, JSON.stringify(mouseAndUIEvents)),
GameManager.saveGameSession(gameId, gameSession.serializeToJSON(gameSession))
]).then () ->
# Job: Archive Game
Jobs.create("archive-game",
name: "Archive Game"
title: util.format("Archiving Game %s", gameId)
gameId: gameId
gameType: gameSession.gameType
).removeOnComplete(true).save()
# update promises
promises = [
archiveGame(gameId, gameSession, mouseAndUIEvents)
]
for player in gameSession.players
playerId = player.getPlayerId()
# don't update normal AI (non-bot user)
if playerId != CONFIG.AI_PLAYER_ID
# find player data
winnerId = gameSession.getWinnerId()
isWinner = (playerId == winnerId)
isDraw = if !winnerId? then true else false
playerSetupData = gameSession.getPlayerSetupDataForPlayerId(playerId)
playerFactionId = playerSetupData.factionId
generalId = playerSetupData.generalId
ticketId = playerSetupData.ticketId
promises.push(updateUser(playerId,CONFIG.AI_PLAYER_ID,gameId,playerFactionId,generalId,isWinner,isDraw,ticketId))
# execute promises
Promise.all(promises)
.then () ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "afterGameOver done, game has been archived".green
.catch (error) ->
Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver failed #{error}".red
# issue a warning to our exceptionReporter error tracker
exceptionReporter.notify(error, {
errorName: "afterGameOver failed",
severity: "error"
game:
id: gameId
gameType: gameSession.gameType
player1Id: player1Id
player2Id: player2Id
winnerId: winnerId
loserId: loserId
})
### Shutdown Handler ###
shutdown = () ->
Logger.module("SERVER").log "Shutting down game server."
Logger.module("SERVER").log "Active Players: #{playerCount}."
Logger.module("SERVER").log "Active Games: #{gameCount}."
if !config.get('consul.enabled')
process.exit(0)
return Consul.getReassignmentStatus()
.then (reassign) ->
if reassign == false
Logger.module("SERVER").log "Reassignment disabled - exiting."
process.exit(0)
# Build an array of game IDs
ids = []
_.each games, (game, id) ->
ids.push(id)
# Map to save each game to Redis before shutdown
return Promise.map ids, (id) ->
serializedData = games[id].session.serializeToJSON(games[id].session)
return GameManager.saveGameSession(id, serializedData)
.then () ->
return Consul.getHealthyServers()
.then (servers) ->
# Filter 'yourself' from list of nodes
filtered = _.reject servers, (server)->
return server["Node"]?["Node"] == os.hostname()
if filtered.length == 0
Logger.module("SERVER").log "No servers available - exiting without re-assignment."
process.exit(1)
random_node = _.sample(filtered)
node_name = random_node["Node"]?["Node"]
return Consul.kv.get("nodes/#{node_name}/public_ip")
.then (newServerIp) ->
# Development override for testing, bounces between port 9000 & 9001
if config.isDevelopment()
port = 9001 if config.get('port') is 9000
port = 9000 if config.get('port') is 9001
newServerIp = "127.0.0.1:#{port}"
msg = "Server is shutting down. You will be reconnected automatically."
io.emit "game_server_shutdown", {msg:msg,ip:newServerIp}
Logger.module("SERVER").log "Players reconnecting to: #{newServerIp}"
Logger.module("SERVER").log "Re-assignment complete. Exiting."
process.exit(0)
.catch (err) ->
Logger.module("SERVER").log "Re-assignment failed: #{err.message}. Exiting."
process.exit(1)
process.on "SIGTERM", shutdown
process.on "SIGINT", shutdown
process.on "SIGHUP", shutdown
process.on "SIGQUIT", shutdown
# region AI
###*
* Returns whether a session is valid for AI usage.
* @param {String} gameId
###
ai_isValidSession = (gameId) ->
return games[gameId]?.session? and !games[gameId].session.isOver() and games[gameId].ai?
###*
* Returns whether a session and turn is valid for AI usage.
* @param {String} gameId
###
ai_isValidTurn = (gameId) ->
return ai_isValidSession(gameId) and games[gameId].session.isActive() and games[gameId].session.getCurrentPlayerId() == games[gameId].ai.getMyPlayerId()
###*
* Returns whether AI can start turn.
* @param {String} gameId
###
ai_canStartTurn = (gameId) ->
return ai_isValidTurn(gameId) and !ai_isExecutingTurn(gameId) and !games[gameId].session.hasStepsInQueue()
###*
* Returns whether ai is currently executing turn.
* @param {String} gameId
###
ai_isExecutingTurn = (gameId) ->
return games[gameId].executingAITurn
###*
* Returns whether ai can progress turn.
* @param {String} gameId
###
ai_canProgressTurn = (gameId) ->
return ai_isValidTurn(gameId) and ai_isExecutingTurn(gameId) and !games[gameId].aiStartTurnTimeoutId?
###*
* Returns whether ai can taunt.
* @param {String} gameId
###
ai_canEmote = (gameId) ->
return ai_isValidSession(gameId) and !ai_isBot(gameId) and !games[gameId].session.getIsBufferingEvents() and Math.random() < 0.05
###*
* Returns whether ai is normal ai or bot.
* @param {String} gameId
###
ai_isBot = (gameId) ->
return games[gameId]?.session? and games[gameId].session.getAiPlayerId() != CONFIG.AI_PLAYER_ID
###*
* Initializes AI for a game session.
* @param {String} gameId
###
ai_setup = (gameId) ->
if games[gameId]?.session? and !games[gameId].ai?
aiPlayerId = games[gameId].session.getAiPlayerId()
aiDifficulty = games[gameId].session.getAiDifficulty()
Logger.module("AI").debug "[G:#{gameId}]", "Setup AI -> aiPlayerId #{aiPlayerId} - aiDifficulty #{aiDifficulty}"
games[gameId].ai = new StarterAI(games[gameId].session, aiPlayerId, aiDifficulty)
# add AI as a connected player
games[gameId].connectedPlayers.push(games[gameId].session.getAiPlayerId())
# attempt to mulligan immediately on new game
if games[gameId].session.isNew()
nextAction = games[gameId].ai.nextAction()
if nextAction?
games[gameId].session.executeAction(nextAction)
###*
* Terminates AI for a game session.
* @param {String} gameId
###
ai_terminate = (gameId) ->
ai_unsubscribeFromGameSessionEvents(gameId)
ai_stopTurn(gameId)
ai_stopTimeouts(gameId)
ai_onStep = (event) ->
gameSession = event.gameSession
gameId = gameSession.gameId
# emote after step
ai_emoteForLastStep(gameId)
# progress turn
ai_updateTurn(gameId)
ai_onInvalidAction = (event) ->
# safety fallback: if AI attempts to make an invalid explicit action, end AI turn immediately
if event?
gameSession = event.gameSession
gameId = gameSession.gameId
action = event.action
if action? and !action.getIsImplicit() and ai_isExecutingTurn(gameId) and action.getOwnerId() == games[gameId].ai.getMyPlayerId()
ai_endTurn(gameId)
ai_subscribeToGameSessionEvents = (gameId) ->
game = games[gameId]
if game?
# if we're already subscribed, unsubscribe
ai_unsubscribeFromGameSessionEvents(gameId)
# listen for game events
game.session.getEventBus().on(EVENTS.step, ai_onStep)
game.session.getEventBus().on(EVENTS.invalid_action, ai_onInvalidAction)
ai_unsubscribeFromGameSessionEvents = (gameId) ->
game = games[gameId]
if game?
game.session.getEventBus().off(EVENTS.step, ai_onStep)
game.session.getEventBus().off(EVENTS.invalid_action, ai_onInvalidAction)
###*
* Updates AI turn for a game session.
* @param {String} gameId
###
ai_updateTurn = (gameId) ->
Logger.module("AI").debug "[G:#{gameId}]", "ai_updateTurn"
if ai_canStartTurn(gameId)
ai_startTurn(gameId)
else if ai_canProgressTurn(gameId)
ai_progressTurn(gameId)
else if ai_isExecutingTurn(gameId)
ai_endTurn(gameId)
###*
* Progresses AI turn for a game session.
* @param {String} gameId
###
ai_progressTurn = (gameId) ->
if ai_canProgressTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_progressTurn".cyan
# request next action from AI
try
nextAction = games[gameId].ai.nextAction()
catch error
Logger.module("IO").log "[G:#{gameId}]", "ai.nextAction:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{gameId}]", "ai.nextAction:: error stack: #{error.stack}".red
# retain player id
playerId = games[gameId].ai.getOpponentPlayerId()
# Report error to exceptionReporter with gameId + eventData
exceptionReporter.notify(error, {
errorName: "ai_progressTurn Error",
game: {
gameId: gameId
turnIndex: games[gameId].session.getTurns().length
stepIndex: games[gameId].session.getCurrentTurn().getSteps().length
}
})
# delete but don't destroy game
destroyGameSessionIfNoConnectionsLeft(gameId,true)
# send error to client, forcing reconnect on client side
io.to(gameId).emit EVENTS.network_game_error, JSON.stringify(error.message)
return
# if we didn't have an error and somehow destroy the game data in the try/catch above
if games[gameId]?
if nextAction?
# always delay AI actions slightly
if !games[gameId].aiExecuteActionTimeoutId?
if ai_isBot(gameId)
if games[gameId].session.getIsFollowupActive()
actionDelayTime = 1.0 + Math.random() * 3.0
else if nextAction instanceof SDK.EndTurnAction
actionDelayTime = 1.0 + Math.random() * 2.0
else
actionDelayTime = 1.0 + Math.random() * 8.0
else
if games[gameId].session.getIsFollowupActive()
actionDelayTime = 0.0
else
actionDelayTime = 5.0
# action delay time can never be more than a quarter of remaining turn time
if games[gameId].turnTimeRemaining?
actionDelayTime = Math.min((games[gameId].turnTimeRemaining * 0.25) / 1000.0, actionDelayTime)
# show UI as needed
ai_showUIForAction(gameId, nextAction, actionDelayTime)
# delay and then execute action
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiExecuteActionTimeoutId = setTimeout((() ->
games[gameId].aiExecuteActionTimeoutId = null
ai_showClearUI(gameId)
ai_executeAction(gameId, nextAction)
), Math.max(1.0, actionDelayTime * 1000.0))
else if ai_isExecutingTurn(gameId)
# end turn as needed
ai_endTurn(gameId)
###*
* Starts AI turn for a game session.
* @param {String} gameId
###
ai_startTurn = (gameId) ->
if ai_canStartTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_startTurn".cyan
# set as executing AI turn
games[gameId].executingAITurn = true
if !games[gameId].aiStartTurnTimeoutId?
# delay initial turn progress
if ai_isBot(gameId)
delayTime = 2.0 + Math.random() * 2.0
else
delayTime = 2.0
# choose random starting point for pointer
games[gameId].aiPointer = {
x: Math.floor(Math.random() * CONFIG.BOARDCOL),
y: Math.floor(Math.random() * CONFIG.BOARDROW)
}
Logger.module("AI").debug "[G:#{gameId}]", "ai_startTurn init aiPointer at #{games[gameId].aiPointer.x}, #{games[gameId].aiPointer.y}".cyan
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiStartTurnTimeoutId = setTimeout((()->
games[gameId].aiStartTurnTimeoutId = null
ai_progressTurn(gameId)
), Math.max(1.0, delayTime * 1000.0))
###*
* Stops AI turn for a game session, and ends it if necessary.
* @param {String} gameId
###
ai_endTurn = (gameId) ->
# stop turn
ai_stopTurn(gameId)
# force end turn if still AI's turn
if ai_isValidTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_endTurn".cyan
ai_executeAction(gameId, games[gameId].session.actionEndTurn())
###*
* Stops AI turn for a game session. Does not end AI turn.
* @param {String} gameId
###
ai_stopTurn = (gameId) ->
if games[gameId].executingAITurn
Logger.module("AI").debug "[G:#{gameId}]", "ai_stopTurn".cyan
games[gameId].executingAITurn = false
ai_stopTurnTimeouts(gameId)
###*
* Stops AI timeouts for a game session.
* @param {String} gameId
###
ai_stopTimeouts = (gameId) ->
ai_stopTurnTimeouts(gameId)
ai_stopEmoteTimeouts(gameId)
ai_stopUITimeouts(gameId)
###*
* Stops AI timeouts for turn actions.
* @param {String} gameId
###
ai_stopTurnTimeouts = (gameId) ->
if games[gameId].aiStartTurnTimeoutId?
clearTimeout(games[gameId].aiStartTurnTimeoutId)
games[gameId].aiStartTurnTimeoutId = null
if games[gameId].aiExecuteActionTimeoutId?
clearTimeout(games[gameId].aiExecuteActionTimeoutId)
games[gameId].aiExecuteActionTimeoutId = null
###*
* Executes an AI action for a game session.
* @param {String} gameId
* @param {Action} action
###
ai_executeAction = (gameId, action) ->
if ai_canProgressTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_executeAction -> #{action.getLogName()}".cyan
# simulate AI sending step to server
step = new SDK.Step(games[gameId].session, action.getOwnerId())
step.setAction(action)
opponentPlayerId = games[gameId].ai.getOpponentPlayerId()
for clientId,socket of io.sockets.connected
if socket.playerId == opponentPlayerId and !socket.spectatorId
onGameEvent.call(socket, {
type: EVENTS.step
step: JSON.parse(games[gameId].session.serializeToJSON(step))
})
###*
* Returns whether an action is valid for showing UI.
* @param {String} gameId
* @param {Action} action
* @return {Boolean}
###
ai_isValidActionForUI = (gameId, action) ->
return (games[gameId].session.getIsFollowupActive() and !(action instanceof SDK.EndFollowupAction)) or
action instanceof SDK.ReplaceCardFromHandAction or
action instanceof SDK.PlayCardFromHandAction or
action instanceof SDK.PlaySignatureCardAction or
action instanceof SDK.MoveAction or
action instanceof SDK.AttackAction
###*
* Shows UI for an action that will be taken by AI.
* @param {String} gameId
* @param {Action} action
* @param {Number} actionDelayTime must be at least 0.25s or greater
###
ai_showUIForAction = (gameId, action, actionDelayTime) ->
if ai_isValidTurn(gameId) and ai_isValidActionForUI(gameId, action) and _.isNumber(actionDelayTime) and actionDelayTime > 0.25
aiPlayerId = games[gameId].ai.getMyPlayerId()
# stop any previous UI animations
ai_stopUITimeouts(gameId)
# get ui animation times
if ai_isBot(gameId)
if games[gameId].session.getIsFollowupActive()
uiDelayTime = actionDelayTime * (0.7 + Math.random() * 0.1)
uiAnimationDuration = actionDelayTime - uiDelayTime
moveToSelectDuration = 0.0
pauseAtSelectDuration = 0.0
pauseAtTargetDuration = (0.1 + Math.random() * 0.25) * uiAnimationDuration
moveToTargetDuration = uiAnimationDuration - pauseAtTargetDuration
else
uiDelayTime = actionDelayTime * (0.4 + Math.random() * 0.4)
uiAnimationDuration = actionDelayTime - uiDelayTime
pauseAtTargetDuration = Math.min(1.0, (0.1 + Math.random() * 0.25) * uiAnimationDuration)
moveToSelectDuration = (0.2 + Math.random() * 0.4) * (uiAnimationDuration - pauseAtTargetDuration)
moveToTargetDuration = (0.4 + Math.random() * 0.5) * (uiAnimationDuration - pauseAtTargetDuration - moveToSelectDuration)
pauseAtSelectDuration = uiAnimationDuration - pauseAtTargetDuration - moveToSelectDuration - moveToTargetDuration
else
uiDelayTime = actionDelayTime * 0.7
uiAnimationDuration = actionDelayTime - uiDelayTime
moveToSelectDuration = 0.0
pauseAtSelectDuration = 0.0
moveToTargetDuration = 0.0
pauseAtTargetDuration = uiAnimationDuration
# get action properties
selectEventData = {
type: EVENTS.network_game_select
playerId: aiPlayerId
}
if action instanceof SDK.ReplaceCardFromHandAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
handIndex = selectEventData.handIndex = action.getIndexOfCardInHand()
selectPosition = { x: Math.round((handIndex + 0.5) * (CONFIG.BOARDCOL / CONFIG.MAX_HAND_SIZE)), y: -1 }
else if action instanceof SDK.ApplyCardToBoardAction
if action instanceof SDK.PlayCardFromHandAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
handIndex = selectEventData.handIndex = action.getIndexOfCardInHand()
selectPosition = { x: Math.round((handIndex + 0.5) * (CONFIG.BOARDCOL / CONFIG.MAX_HAND_SIZE)), y: -1 }
targetPosition = action.getTargetPosition()
else if action instanceof SDK.PlaySignatureCardAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
isSignatureCard = true
if action.getCard().isOwnedByPlayer2()
selectEventData.player2SignatureCard = true
else
selectEventData.player1SignatureCard = true
if aiPlayerId == games[gameId].session.getPlayer2Id()
selectPosition = { x: CONFIG.BOARDCOL, y: Math.floor(CONFIG.BOARDROW * 0.5 + Math.random() * CONFIG.BOARDROW * 0.5) }
else
selectPosition = { x: -1, y: Math.floor(CONFIG.BOARDROW * 0.5 + Math.random() * CONFIG.BOARDROW * 0.5) }
targetPosition = action.getTargetPosition()
else
# followup has no selection
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
selectEventData = null
selectPosition = action.getSourcePosition()
targetPosition = action.getTargetPosition()
else if action instanceof SDK.MoveAction
intent = selectEventData.intentType = SDK.IntentType.MoveIntent
cardIndex = selectEventData.cardIndex = action.getSourceIndex()
card = games[gameId].session.getCardByIndex(cardIndex)
selectPosition = card.getPosition()
targetPosition = action.getTargetPosition()
else if action instanceof SDK.AttackAction
intent = selectEventData.intentType = SDK.IntentType.DamageIntent
cardIndex = selectEventData.cardIndex = action.getSourceIndex()
card = games[gameId].session.getCardByIndex(cardIndex)
selectPosition = card.getPosition()
targetPosition = action.getTargetPosition()
# failsafe in case action doesn't have a select position
# (actions should always have a select position)
if !selectPosition?
if action instanceof SDK.ApplyCardToBoardAction
Logger.module("AI").log "[G:#{gameId}]", "ai_showUIForAction -> no sel pos #{action.getLogName()} w/ card #{action.getCard()?.getName()} w/ root #{action.getCard()?.getRootCard()?.getName()}".cyan
else
Logger.module("AI").log "[G:#{gameId}]", "ai_showUIForAction -> no sel pos #{action.getLogName()}".cyan
return
# setup sequence
actionPointerSequence = () ->
# move to select
ai_animatePointer(gameId, moveToSelectDuration, selectPosition, SDK.IntentType.NeutralIntent, false, isSignatureCard, () ->
if selectEventData?
if action instanceof SDK.MoveAction or action instanceof SDK.AttackAction
# clear pointer before select
emitGameEvent(null, gameId, {
type: EVENTS.network_game_mouse_clear
playerId: aiPlayerId,
intentType: SDK.IntentType.NeutralIntent
})
# show selection event
emitGameEvent(null, gameId, selectEventData)
if targetPosition?
# pause at select
ai_animatePointer(gameId, pauseAtSelectDuration, selectPosition, intent, isSignatureCard, false, () ->
# move to target
ai_animatePointer(gameId, moveToTargetDuration, targetPosition, intent)
)
)
# random chance to hover enemy unit on the board
if ai_isBot(gameId) and uiDelayTime >= 5.0 && Math.random() < 0.05
opponentGeneral = games[gameId].session.getGeneralForOpponentOfPlayerId(games[gameId].session.getAiPlayerId())
units = games[gameId].session.getBoard().getFriendlyEntitiesForEntity(opponentGeneral)
if units.length > 0
unitToHover = units[Math.floor(Math.random() * units.length)]
if unitToHover?
# hover unit before showing action UI
unitPosition = unitToHover.getPosition()
moveToUnitDuration = Math.random() * 1.0
pauseAtUnitDuration = 2.0 + Math.random() * 2.0
uiDelayTime = uiDelayTime - moveToUnitDuration - pauseAtUnitDuration
# delay for remaining time
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
# move to random unit
ai_animatePointer(gameId, moveToUnitDuration, unitPosition, SDK.IntentType.NeutralIntent, false, false, () ->
# pause at random unit and then show action pointer sequence
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
actionPointerSequence()
, pauseAtUnitDuration * 1000.0)
)
, uiDelayTime * 1000.0)
else
# delay and then show action pointer sequence
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
actionPointerSequence()
, uiDelayTime * 1000.0)
ai_showClearUI = (gameId) ->
if ai_isValidTurn(gameId)
ai_stopUITimeouts(gameId)
emitGameEvent(null, gameId, {
type: EVENTS.network_game_mouse_clear
playerId: games[gameId].ai.getMyPlayerId(),
intentType: SDK.IntentType.NeutralIntent
})
###*
* Clears out any timeouts for AI UI.
* @param {String} gameId
###
ai_stopUITimeouts = (gameId) ->
if games[gameId]?
if games[gameId].aiShowUITimeoutId?
clearTimeout(games[gameId].aiShowUITimeoutId)
games[gameId].aiShowUITimeoutId = null
ai_stopAnimatingPointer(gameId)
###*
* Shows AI pointer hover at a board position if it is different from the current position.
* @param {String} gameId
* @param {Number} boardX
* @param {Number} boardY
* @param {Number} [intent]
* @param {Number} [isSignatureCard=false]
###
ai_showHover = (gameId, boardX, boardY, intent=SDK.IntentType.NeutralIntent, isSignatureCard=false) ->
if ai_isValidTurn(gameId)
pointer = games[gameId].aiPointer
if pointer.x != boardX or pointer.y != boardY
# set pointer to position
pointer.x = boardX
pointer.y = boardY
# setup hover event data
hoverEventData = {
type: EVENTS.network_game_hover
boardPosition: {x: boardX, y: boardY},
playerId: games[gameId].ai.getMyPlayerId(),
intentType: intent
}
# check for hover target
if isSignatureCard
if games[gameId].ai.getMyPlayerId() == games[gameId].session.getPlayer2Id()
hoverEventData.player2SignatureCard = true
else
hoverEventData.player1SignatureCard = true
else
target = games[gameId].session.getBoard().getUnitAtPosition(pointer)
if target?
hoverEventData.cardIndex = target.getIndex()
# show hover
emitGameEvent(null, gameId, hoverEventData)
###*
* Animates AI pointer movement.
* @param {String} gameId
* @param {Number} duration in seconds
* @param {Vec2} [targetBoardPosition]
* @param {Number} [intent]
* @param {Number} [isSignatureCardAtSource]
* @param {Number} [isSignatureCardAtTarget]
* @param {Function} [callback]
###
ai_animatePointer = (gameId, duration, targetBoardPosition, intent, isSignatureCardAtSource, isSignatureCardAtTarget, callback) ->
if ai_isValidTurn(gameId)
# stop current animation
ai_stopAnimatingPointer(gameId)
pointer = games[gameId].aiPointer
sx = pointer.x
sy = pointer.y
tx = targetBoardPosition.x
ty = targetBoardPosition.y
dx = tx - sx
dy = ty - sy
if duration > 0.0
# show pointer at source
ai_showHover(gameId, sx, sy, intent, isSignatureCardAtSource)
# animate to target
dms = duration * 1000.0
startTime = Date.now()
games[gameId].aiPointerIntervalId = setInterval(() ->
# cubic ease out
currentTime = Date.now()
dt = currentTime - startTime
val = Math.min(1.0, dt / dms)
e = val - 1
ee = e * e * e + 1
cx = dx * ee + sx
cy = dy * ee + sy
ai_showHover(gameId, Math.round(cx), Math.round(cy), intent, isSignatureCardAtTarget)
if val == 1.0
ai_stopAnimatingPointer(gameId)
if callback then callback()
, dms / 10)
else
# show pointer at target
ai_showHover(gameId, tx, ty, intent, isSignatureCardAtTarget)
# no animation needed
if callback then callback()
###*
* Stops showing AI pointer movement.
###
ai_stopAnimatingPointer = (gameId) ->
if games[gameId]? and games[gameId].aiPointerIntervalId != null
clearInterval(games[gameId].aiPointerIntervalId)
games[gameId].aiPointerIntervalId = null
###*
* Prompts AI to emote to opponent based on last step.
* @param {String} gameId
###
ai_emoteForLastStep = (gameId) ->
if ai_canEmote(gameId)
step = games[gameId].session.getLastStep()
action = step?.action
if action? and !(action instanceof SDK.EndTurnAction)
aiPlayerId = games[gameId].ai.getMyPlayerId()
isMyAction = action.getOwnerId() == aiPlayerId
# search action + sub actions for any played or removed units
actionsToSearch = [action]
numHappyActions = 0
numTauntingActions = 0
numAngryActions = 0
while actionsToSearch.length > 0
searchAction = actionsToSearch.shift()
if searchAction instanceof SDK.RemoveAction
if !isMyAction and searchAction.getTarget()?.getOwnerId() == aiPlayerId
numAngryActions += 2
else if isMyAction and searchAction.getTarget()?.getOwnerId() != aiPlayerId
numTauntingActions += 1
else if searchAction instanceof SDK.HealAction
if isMyAction and searchAction.getTarget()?.getOwnerId() == aiPlayerId
numTauntingActions += 1
else if !isMyAction and searchAction.getTarget()?.getOwnerId() != aiPlayerId
numAngryActions += 1
else if searchAction instanceof SDK.PlayCardFromHandAction or searchAction instanceof SDK.PlaySignatureCardAction
if isMyAction and searchAction.getCard() instanceof SDK.Unit
numHappyActions += 1
# add sub actions
actionsToSearch = actionsToSearch.concat(searchAction.getSubActions())
maxEmotion = Math.max(numHappyActions, numTauntingActions, numAngryActions)
if maxEmotion > 0
emoteIds = []
myGeneral = games[gameId].ai.getMyGeneral()
myGeneralId = myGeneral.getId()
factionEmotesData = SDK.CosmeticsFactory.cosmeticsForTypeAndFaction(SDK.CosmeticsTypeLookup.Emote, myGeneral.getFactionId())
# use ai faction emote that were most present in last step
if maxEmotion == numAngryActions
for emoteData in factionEmotesData
if emoteData.enabled and (emoteData.title == "Angry" or emoteData.title == "Sad" or emoteData.title == "Frustrated") and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
else if maxEmotion == numHappyActions
for emoteData in factionEmotesData
if emoteData.enabled and emoteData.title == "Happy" and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
else if maxEmotion == numTauntingActions
for emoteData in factionEmotesData
if emoteData.enabled and (emoteData.title == "Taunt" or emoteData.title == "Sunglasses" or emoteData.title == "Kiss") and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
# pick a random emote
emoteId = emoteIds[Math.floor(Math.random() * emoteIds.length)]
#Logger.module("AI").debug "[G:#{gameId}]", "ai_emoteForLastStep -> #{emoteId} for #{games[gameId].session.getLastStep()?.action?.getLogName()}".cyan
if emoteId?
# clear any waiting emote timeout
ai_stopEmoteTimeouts(gameId)
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiEmoteTimeoutId = setTimeout((()->
games[gameId].aiEmoteTimeoutId = null
#Logger.module("AI").debug "[G:#{gameId}]", "ai_showEmote -> #{emoteId}".cyan
emitGameEvent(null, gameId, {
type: EVENTS.show_emote
id: emoteId,
playerId: games[gameId].ai.getMyPlayerId()
})
), 4000.0)
###*
* Stops AI timeouts for emotes.
* @param {String} gameId
###
ai_stopEmoteTimeouts = (gameId) ->
if games[gameId].aiEmoteTimeoutId?
clearTimeout(games[gameId].aiEmoteTimeoutId)
games[gameId].aiEmoteTimeoutId = null
# endregion AI
| true | ###
Game Server Pieces
###
fs = require 'fs'
os = require 'os'
util = require 'util'
_ = require 'underscore'
colors = require 'colors' # used for console message coloring
jwt = require 'jsonwebtoken'
io = require 'socket.io'
ioJwt = require 'socketio-jwt'
Promise = require 'bluebird'
kue = require 'kue'
moment = require 'moment'
request = require 'superagent'
# Our modules
shutdown = require './shutdown'
StarterAI = require './ai/starter_ai'
SDK = require '../app/sdk.coffee'
Logger = require '../app/common/logger.coffee'
EVENTS = require '../app/common/event_types'
UtilsGameSession = require '../app/common/utils/utils_game_session.coffee'
exceptionReporter = require '@counterplay/exception-reporter'
# lib Modules
Consul = require './lib/consul'
# Configuration object
config = require '../config/config.js'
env = config.get('env')
firebaseToken = config.get('firebaseToken')
# Boots up a basic HTTP server on port 8080
# Responds to /health endpoint with status 200
# Otherwise responds with status 404
Logger = require '../app/common/logger.coffee'
CONFIG = require '../app/common/config'
http = require 'http'
url = require 'url'
Promise = require 'bluebird'
# perform DNS health check
dnsHealthCheck = () ->
if config.isDevelopment()
return Promise.resolve({healthy: true})
nodename = "#{config.get('env')}-#{os.hostname().split('.')[0]}"
return Consul.kv.get("nodes/#{nodename}/dns_name")
.then (dnsName) ->
return new Promise (resolve, reject) ->
request.get("https://#{dnsName}/health")
.end (err, res) ->
if err
return resolve({dnsName: dnsName, healthy: false})
if res? && res.status == 200
return resolve({dnsName: dnsName, healthy: true})
return ({dnsName: dnsName, healthy: false})
.catch (e) ->
return {healthy: false}
# create http server and respond to /health requests
server = http.createServer (req, res) ->
pathname = url.parse(req.url).pathname
if pathname == '/health'
Logger.module("GAME SERVER").debug "HTTP Health Ping"
res.statusCode = 200
res.write JSON.stringify({players: playerCount, games: gameCount})
res.end()
else
res.statusCode = 404
res.end()
# io server setup, binds to http server
io = require('socket.io')().listen(server, {
cors: {
origin: "*"
}
})
io.use(
ioJwt.authorize(
secret:firebaseToken
timeout: 15000
)
)
module.exports = io
server.listen config.get('game_port'), () ->
Logger.module("AI SERVER").log "AI Server <b>#{os.hostname()}</b> started."
# redis
{Redis, Jobs, GameManager} = require './redis/'
# server id for this game server
serverId = os.hostname()
# the 'games' hash maps game IDs to References for those games
games = {}
# save some basic stats about this server into redis
playerCount = 0
gameCount = 0
# turn times
MAX_TURN_TIME = (CONFIG.TURN_DURATION + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0
MAX_TURN_TIME_INACTIVE = (CONFIG.TURN_DURATION_INACTIVE + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0
savePlayerCount = (playerCount) ->
Redis.hsetAsync("servers:#{serverId}", "players", playerCount)
saveGameCount = (gameCount) ->
Redis.hsetAsync("servers:#{serverId}", "games", gameCount)
# error 'domain' to deal with io.sockets uncaught errors
d = require('domain').create()
d.on 'error', shutdown.errorShutdown
d.add(io.sockets)
# health ping on socket namespace /health
healthPing = io
.of '/health'
.on 'connection', (socket) ->
socket.on 'ping', () ->
Logger.module("GAME SERVER").debug "socket.io Health Ping"
socket.emit 'pong'
# run main io.sockets inside of the domain
d.run () ->
io.sockets.on "authenticated", (socket) ->
# add the socket to the error domain
d.add(socket)
# Socket is now autheticated, continue to bind other handlers
Logger.module("IO").log "DECODED TOKEN ID: #{PI:KEY:<KEY>END_PI.decoded_token.PI:KEY:<KEY>END_PI
savePlayerCount(++playerCount)
# Send message to user that connection is succesful
socket.emit "connected",
message: "Successfully connected to server"
# Bind socket event handlers
socket.on EVENTS.join_game, onGamePlayerJoin
socket.on EVENTS.spectate_game, onGameSpectatorJoin
socket.on EVENTS.leave_game, onGameLeave
socket.on EVENTS.network_game_event, onGameEvent
socket.on "disconnect", onGameDisconnect
getConnectedSpectatorsDataForGamePlayer = (gameId,playerId)->
spectators = []
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
socket = io.sockets.connected[socketId]
if socket.playerId == playerId
spectators.push({
id:socket.spectatorId,
playerId:socket.playerId,
username:socket.spectateToken?.u
})
return spectators
###
# socket handler for players joining game
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGamePlayerJoin = (requestData) ->
# request parameters
gameId = requestData.gameId
playerId = requestData.playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> player:#{requestData.playerId} is joining game:#{requestData.gameId}".cyan
# you must have a playerId
if not playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red
@emit "join_game_response",
error:"Your player id seems to be blank (has your login expired?), so we can't join you to the game."
return
# must have a gameId
if not gameId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red
@emit "join_game_response",
error:"Invalid Game ID."
return
# if someone is trying to join a game they don't belong to as a player they are not authenticated as
if @.decoded_token.d.id != playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red
@emit "join_game_response",
error:"Your player id does not match the one you requested to join a game with. Are you sure you're joining the right game?"
return
# if a client is already in another game, leave it
playerLeaveGameIfNeeded(this)
# if this client already exists in this game, disconnect duplicate client
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == playerId
Logger.module("IO").log "[G:#{gameId}]", "join_game -> detected duplicate connection to #{gameId} GameSession for #{playerId.blue}. Disconnecting duplicate...".cyan
playerLeaveGameIfNeeded(socket, silent=true)
# initialize a server-side game session and join it
initGameSession(gameId)
.bind @
.spread (gameSession) ->
#Logger.module("IO").debug "[G:#{gameId}]", "join_game -> players in data: ", gameSession.players
# player
player = _.find(gameSession.players, (p) -> return p.playerId == playerId)
# get the opponent based on the game session data
opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId)
Logger.module("IO").log "[G:#{gameId}]", "join_game -> Got #{gameId} GameSession data #{playerId.blue}.".cyan
if not player # oops looks like this player does not exist in the requested game
# let the socket know we had an error
@emit "join_game_response",
error:"could not join game because your player id could not be found"
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else if not opponent? # oops, looks like we can'f find an opponent in the game session?
Logger.module("IO").log "[G:#{gameId}]", "join_game -> game #{gameId} ERROR: could not find opponent for #{playerId.blue}.".red
# let the socket know we had an error
@emit "join_game_response",
error:"could not join game because the opponent could not be found"
# issue a warning to our exceptionReporter error tracker
exceptionReporter.notify(new Error("Error joining game: could not find opponent"), {
severity: "warning"
user:
id: playerId
game:
id: gameId
player1Id: gameSession?.players[0].playerId
player2Id: gameSession?.players[1].playerId
})
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else
# rollback if it is this player's followup
# this can happen if a player reconnects without properly disconnecting
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() == playerId
gameSession.executeAction(gameSession.actionRollbackSnapshot())
# set some parameters for the socket
@gameId = gameId
@playerId = playerId
# join game room
@join(gameId)
# update user count for game room
games[gameId].connectedPlayers.push(playerId)
Logger.module("IO").log "[G:#{gameId}]", "join_game -> Game #{gameId} connected players so far: #{games[gameId].connectedPlayers.length}."
# if only one player is in so far, start the disconnection timer
if games[gameId].connectedPlayers.length == 1
# start disconnected player timeout for game
startDisconnectedPlayerTimeout(gameId,opponent.playerId)
else if games[gameId].connectedPlayers.length == 2
# clear timeout when we get two players
clearDisconnectedPlayerTimeout(gameId)
# prepare and scrub game session data for this player
# if a followup is active and it isn't this player's followup, send them the rollback snapshot
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId
gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData())
else
gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession))
UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId)
# respond to client with success and a scrubbed copy of the game session
@emit "join_game_response",
message: "successfully joined game"
gameSessionData: gameSessionData
connectedPlayers:games[gameId].connectedPlayers
connectedSpectators: getConnectedSpectatorsDataForGamePlayer(gameId,playerId)
# broadcast join to any other connected players
@broadcast.to(gameId).emit("player_joined",playerId)
# attempt to update ai turn on active game
if gameSession.isActive()
ai_updateTurn(gameId)
.catch (e) ->
Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game. ERROR: #{e.message}".red
# if we didn't join a game, broadcast a failure
@emit "join_game_response",
error:"Could not join game: " + e?.message
###
# socket handler for spectators joining game
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGameSpectatorJoin = (requestData) ->
# request parameters
# TODO : Sanitize these parameters to prevent crash if gameId = null
gameId = requestData.gameId
spectatorId = requestData.spectatorId
playerId = requestData.playerId
spectateToken = null
# verify - synchronous
try
spectateToken = jwt.verify(requestData.spectateToken, firebaseToken)
catch error
Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> ERROR decoding spectate token: #{error?.message}".red
if not spectateToken or spectateToken.b?.length == 0
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A specate token #{spectateToken} is not valid".red
@emit "spectate_game_response",
error:"Your spectate token is invalid, so we can't join you to the game."
return
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> token contents: ", spectateToken.b
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> playerId: ", playerId
if not _.contains(spectateToken.b,playerId)
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: You do not have permission to specate this game".red
@emit "spectate_game_response",
error:"You do not have permission to specate this game."
return
# must have a spectatorId
if not spectatorId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A spectator #{spectatorId.blue} is not valid".red
@emit "spectate_game_response",
error:"Your login ID is blank (expired?), so we can't join you to the game."
return
# must have a playerId
if not playerId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red
@emit "spectate_game_response",
error:"Invalid player ID."
return
# must have a gameId
if not gameId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red
@emit "spectate_game_response",
error:"Invalid Game ID."
return
# if someone is trying to join a game they don't belong to as a player they are not authenticated as
if @.decoded_token.d.id != spectatorId
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red
@emit "spectate_game_response",
error:"Your login ID does not match the one you requested to spectate the game with."
return
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> spectator:#{spectatorId} is joining game:#{gameId}".cyan
# if a client is already in another game, leave it
spectatorLeaveGameIfNeeded(@)
if games[gameId]?.connectedSpectators.length >= 10
# max out at 10 spectators
@emit "spectate_game_response",
error:"Maximum number of spectators already watching."
return
# initialize a server-side game session and join it
initSpectatorGameSession(gameId)
.bind @
.then (spectatorGameSession) ->
# for spectators, use the delayed in-memory game session
gameSession = spectatorGameSession
Logger.module("IO").log "[G:#{gameId}]", "spectate_game -> Got #{gameId} GameSession data.".cyan
player = _.find(gameSession.players, (p) -> return p.playerId == playerId)
opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId)
if not player
# let the socket know we had an error
@emit "spectate_game_response",
error:"could not join game because the player id you requested could not be found"
# destroy the game data loaded so far if the opponent can't be defined and no one else is connected
Logger.module("IO").log "[G:#{gameId}]", "onGameSpectatorJoin -> DESTROYING local game cache due to join error".red
destroyGameSessionIfNoConnectionsLeft(gameId)
# stop any further processing
return
else
# set some parameters for the socket
@gameId = gameId
@spectatorId = spectatorId
@spectateToken = spectateToken
@playerId = playerId
# join game room
@join("spectate-#{gameId}")
# update user count for game room
games[gameId].connectedSpectators.push(spectatorId)
# prepare and scrub game session data for this player
# if a followup is active and it isn't this player's followup, send them the rollback snapshot
if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId
gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData())
else
gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession))
UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId, true)
###
# if the spectator does not have the opponent in their buddy list
if not _.contains(spectateToken.b,opponent.playerId)
# scrub deck data and opponent hand data by passing in opponent ID
scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId)
else
# otherwise just scrub deck data in a way you can see both decks
# scrubGameSessionDataForSpectators(gameSession, gameSessionData)
# NOTE: above line is disabled for now since it does some UI jankiness since when a cardId is present the tile layer updates when the spectated opponent starts to select cards
# NOTE: besides, actions will be scrubbed so this idea of watching both players only sort of works right now
scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId, true)
###
# respond to client with success and a scrubbed copy of the game session
@emit "spectate_game_response",
message: "successfully joined game"
gameSessionData: gameSessionData
# broadcast to the game room that a spectator has joined
@broadcast.to(gameId).emit("spectator_joined",{
id: spectatorId,
playerId: playerId,
username: spectateToken.u
})
.catch (e) ->
# if we didn't join a game, broadcast a failure
@emit "spectate_game_response",
error:"could not join game: #{e.message}"
###
# socket handler for leaving a game.
# @public
# @param {Object} requestData Plain JS object with socket event data.
###
onGameLeave = (requestData) ->
if @.spectatorId
Logger.module("IO").log "[G:#{@.gameId}]", "leave_game -> spectator #{@.spectatorId} leaving #{@.gameId}"
spectatorLeaveGameIfNeeded(@)
else
Logger.module("IO").log "[G:#{@.gameId}]", "leave_game -> player #{@.playerId} leaving #{@.gameId}"
playerLeaveGameIfNeeded(@)
###*
# This method is called every time a socket handler recieves a game event and is executed within the context of the socket (this == sending socket).
# @public
# @param {Object} eventData Plain JS object with event data that contains one "event".
###
onGameEvent = (eventData) ->
# if for some reason spectator sockets start broadcasting game events
if @.spectatorId
Logger.module("IO").log "[G:#{@.gameId}]", "onGameEvent :: ERROR: spectator sockets can't submit game events. (type: #{eventData.type})".red
return
# Logger.module("IO").log "onGameEvent -> #{JSON.stringify(eventData)}".blue
if not @gameId or not games[@gameId]
@emit EVENTS.network_game_error,
code:500
message:"could not broadcast game event because you are not currently in a game"
return
#
gameSession = games[@gameId].session
if eventData.type == EVENTS.step
#Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{JSON.stringify(eventData.step)}".green
#Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{eventData.step?.playerId} #{eventData.step?.action?.type}".green
player = _.find(gameSession.players,(p)-> p.playerId == eventData.step?.playerId)
player?.setLastActionTakenAt(Date.now())
try
step = gameSession.deserializeStepFromFirebase(eventData.step)
action = step.action
if action?
# clear out any implicit actions sent over the network and re-execute this as a fresh explicit action on the server
# the reason is that we want to re-generate and re-validate all the game logic that happens as a result of this FIRST explicit action in the step
action.resetForAuthoritativeExecution()
# execute the action
gameSession.executeAction(action)
catch error
Logger.module("IO").log "[G:#{@.gameId}]", "onGameStep:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{@.gameId}]", "onGameStep:: error stack: #{error.stack}".red
# Report error to exceptionReporter with gameId + eventData
exceptionReporter.notify(error, {
errorName: "onGameStep Error",
game: {
gameId: @gameId
eventData: eventData
}
})
# delete but don't destroy game
destroyGameSessionIfNoConnectionsLeft(@gameId,true)
# send error to client, forcing reconnect on client side
io.to(@gameId).emit EVENTS.network_game_error, JSON.stringify(error.message)
return
else
# transmit the non-step game events to players
# step events are emitted automatically after executed on game session
emitGameEvent(@, @gameId, eventData)
###
# Socket Disconnect Event Handler. Handles rollback if in the middle of followup etc.
# @public
###
onGameDisconnect = () ->
if @.spectatorId
# make spectator leave game room
spectatorLeaveGameIfNeeded(@)
# remove the socket from the error domain, this = socket
d.remove(@)
else
try
clients_in_the_room = io.sockets.adapter.rooms[@.gameId]
for clientId,socket of clients_in_the_room
if socket.playerId == @.playerId
Logger.module("IO").log "onGameDisconnect:: looks like the player #{@.playerId} we are trying to disconnect is still in the game #{@.gameId} room. ABORTING".red
return
for clientId,socket of io.sockets.connected
if socket.playerId == @.playerId and not socket.spectatorId
Logger.module("IO").log "onGameDisconnect:: looks like the player #{@.playerId} that allegedly disconnected is still alive and well.".red
return
catch error
Logger.module("IO").log "onGameDisconnect:: Error #{error?.message}.".red
# if we are in a buffering state
# and the disconnecting player is in the middle of a followup
gs = games[@gameId]?.session
if gs? and gs.getIsBufferingEvents() and gs.getCurrentPlayerId() == @playerId
# execute a rollback to reset server state
# but do not send this action to the still connected player
# because they do not care about rollbacks for the other player
rollBackAction = gs.actionRollbackSnapshot()
gs.executeAction(rollBackAction)
# remove the socket from the error domain, this = socket
d.remove(@)
savePlayerCount(--playerCount)
Logger.module("IO").log "[G:#{@.gameId}]", "disconnect -> #{@.playerId}".red
# if a client is already in another game, leave it
playerLeaveGameIfNeeded(@)
###*
* Leaves a game for a player socket if the socket is connected to a game
* @public
* @param {Socket} socket The socket which wants to leave a game.
* @param {Boolean} [silent=false] whether to disconnect silently, as in the case of duplicate connections for same player
###
playerLeaveGameIfNeeded = (socket, silent=false) ->
if socket?
gameId = socket.gameId
playerId = socket.playerId
# if a player is in a game
if gameId? and playerId?
Logger.module("...").log "[G:#{gameId}]", "playerLeaveGame -> #{playerId} has left game #{gameId}".red
if !silent
# broadcast that player left
socket.broadcast.to(gameId).emit("player_left",playerId)
# leave that game room
socket.leave(gameId)
# update user count for game room
game = games[gameId]
if game?
index = game.connectedPlayers.indexOf(playerId)
game.connectedPlayers.splice(index,1)
if !silent
# start disconnected player timeout for game
startDisconnectedPlayerTimeout(gameId,playerId)
# destroy game if no one is connected anymore
destroyGameSessionIfNoConnectionsLeft(gameId,true)
# finally clear the existing gameId
socket.gameId = null
###
# This function leaves a game for a spectator socket if the socket is connected to a game
# @public
# @param {Socket} socket The socket which wants to leave a game.
###
spectatorLeaveGameIfNeeded = (socket) ->
# if a client is already in another game
if socket.gameId
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} leaving game #{socket.gameId}."
# broadcast that you left
socket.broadcast.to(socket.gameId).emit("spectator_left",{
id:socket.spectatorId,
playerId:socket.playerId,
username:socket.spectateToken?.u
})
# leave specator game room
socket.leave("spectate-#{socket.gameId}")
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} left room for game #{socket.gameId}."
# update spectator count for game room
if games[socket.gameId]
games[socket.gameId].connectedSpectators = _.without(games[socket.gameId].connectedSpectators,socket.spectatorId)
Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} removed from list of spectators #{socket.gameId}."
# if no spectators left, stop the delayed game interval and destroy spectator delayed game session
tearDownSpectateSystemsIfNoSpectatorsLeft(socket.gameId)
# destroy game if no one is connected anymore
destroyGameSessionIfNoConnectionsLeft(socket.gameId,true)
remainingSpectators = games[socket.gameId]?.connectedSpectators?.length || 0
Logger.module("...").log "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} has left game #{socket.gameId}. remaining spectators #{remainingSpectators}"
# finally clear the existing gameId
socket.gameId = null
###
# This function destroys in-memory game session of there is no one left connected
# @public
# @param {String} gameId The ID of the game to destroy.
# @param {Boolean} persist Do we need to save/archive this game?
###
destroyGameSessionIfNoConnectionsLeft = (gameId,persist=false)->
if games[gameId].connectedPlayers.length == 1 and games[gameId].connectedSpectators.length == 0
clearDisconnectedPlayerTimeout(gameId)
stopTurnTimer(gameId)
tearDownSpectateSystemsIfNoSpectatorsLeft(gameId)
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> no players left DESTROYING local game cache".red
unsubscribeFromGameSessionEvents(gameId)
ai_terminate(gameId)
# TEMP: a way to upload unfinished game data to AWS S3 Archive. For example: errored out games.
if persist and games?[gameId]?.session?.status != SDK.GameStatus.over
data = games[gameId].session.serializeToJSON(games[gameId].session)
mouseAndUIEventsData = JSON.stringify(games[gameId].mouseAndUIEvents)
Promise.all([
GameManager.saveGameSession(gameId,data),
GameManager.saveGameMouseUIData(gameId,mouseAndUIEventsData),
])
.then (results) ->
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> unfinished Game Archived to S3: #{results[1]}".green
.catch (error)->
Logger.module("...").log "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> ERROR: failed to archive unfinished game to S3 due to error #{error.message}".red
delete games[gameId]
saveGameCount(--gameCount)
else
Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> players left: #{games[gameId].connectedPlayers.length} spectators left: #{games[gameId].connectedSpectators.length}"
###
# This function stops all spectate systems if 0 spectators left.
# @public
# @param {String} gameId The ID of the game to tear down spectate systems.
###
tearDownSpectateSystemsIfNoSpectatorsLeft = (gameId)->
# if no spectators left, stop the delayed game interval and destroy spectator delayed game session
if games[gameId]?.connectedSpectators.length == 0
Logger.module("IO").debug "[G:#{gameId}]", "tearDownSpectateSystemsIfNoSpectatorsLeft() -> no spectators left, stopping spectate systems"
stopSpectatorDelayedGameInterval(gameId)
games[gameId].spectatorDelayedGameSession = null
games[gameId].spectateIsRunning = false
games[gameId].spectatorOpponentEventDataBuffer.length = 0
games[gameId].spectatorGameEventBuffer.length = 0
###
# Clears timeout for disconnected players
# @public
# @param {String} gameId The ID of the game to clear disconnected timeout for.
###
clearDisconnectedPlayerTimeout = (gameId) ->
Logger.module("IO").log "[G:#{gameId}]", "clearDisconnectedPlayerTimeout:: for game: #{gameId}".yellow
clearTimeout(games[gameId]?.disconnectedPlayerTimeout)
games[gameId]?.disconnectedPlayerTimeout = null
###
# Starts timeout for disconnected players
# @public
# @param {String} gameId The ID of the game.
# @param {String} playerId The player ID for who to start the timeout.
###
startDisconnectedPlayerTimeout = (gameId,playerId) ->
if games[gameId]?.disconnectedPlayerTimeout?
clearDisconnectedPlayerTimeout(gameId)
Logger.module("IO").log "[G:#{gameId}]", "startDisconnectedPlayerTimeout:: for #{playerId} in game: #{gameId}".yellow
games[gameId]?.disconnectedPlayerTimeout = setTimeout(()->
onDisconnectedPlayerTimeout(gameId,playerId)
,60000)
###
# Resigns game for disconnected player.
# @public
# @param {String} gameId The ID of the game.
# @param {String} playerId The player ID who is resigning.
###
onDisconnectedPlayerTimeout = (gameId,playerId) ->
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} for game: #{gameId}"
clients_in_the_room = io.sockets.adapter.rooms[gameId]
for clientId,socket of clients_in_the_room
if socket.playerId == playerId
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to dis-connect is still in the game #{gameId} room. ABORTING".red
return
for clientId,socket of io.sockets.connected
if socket.playerId == playerId and not socket.spectatorId
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to disconnect is still connected but not in the game #{gameId} room.".red
return
# grab the relevant game session
gs = games[gameId]?.session
# looks like we timed out for a game that's since ended
if !gs or gs?.status == SDK.GameStatus.over
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} timed out for FINISHED or NULL game: #{gameId}".yellow
return
else
Logger.module("IO").log "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} auto-resigning game: #{gameId}".yellow
# resign the player
player = gs.getPlayerById(playerId)
resignAction = player.actionResign()
gs.executeAction(resignAction)
###*
# Start/Restart server side game timer for a game
# @public
# @param {Object} gameId The game ID.
###
restartTurnTimer = (gameId) ->
stopTurnTimer(gameId)
game = games[gameId]
if game.session?
game.turnTimerStartedAt = game.turnTimeTickAt = Date.now()
if game.session.isBossBattle()
# boss battles turns have infinite time
# so we'll just tick once and wait
onGameTimeTick(gameId)
else
# set turn timer on a 1 second interval
game.turnTimer = setInterval((()-> onGameTimeTick(gameId)),1000)
###*
# Stop server side game timer for a game
# @public
# @param {Object} gameId The game ID.
###
stopTurnTimer = (gameId) ->
game = games[gameId]
if game? and game.turnTimer?
clearInterval(game.turnTimer)
game.turnTimer = null
###*
# Server side game timer. After 90 seconds it will end the turn for the current player.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
onGameTimeTick = (gameId) ->
game = games[gameId]
gameSession = game?.session
if gameSession?
# allowed turn time is 90 seconds + 3 second buffer that clients don't see
allowed_turn_time = MAX_TURN_TIME
# grab the current player
player = gameSession.getCurrentPlayer()
# if we're past the 2nd turn, we can start checking backwards to see how long the PREVIOUS turn for this player took
if player and gameSession.getTurns().length > 2
# find the current player's previous turn
allTurns = gameSession.getTurns()
playersPreviousTurn = null
for i in [allTurns.length-1..0] by -1
if allTurns[i].playerId == player.playerId
playersPreviousTurn = allTurns[i] # gameSession.getTurns()[gameSession.getTurns().length - 3]
break
#Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: last action at #{player.getLastActionTakenAt()} / last turn delta #{playersPreviousTurn?.createdAt - player.getLastActionTakenAt()}".red
# if this player's previous action was on a turn older than the last one
if playersPreviousTurn && (playersPreviousTurn.createdAt - player.getLastActionTakenAt() > 0)
# you're only allowed 15 seconds + 3 second buffer that clients don't see
allowed_turn_time = MAX_TURN_TIME_INACTIVE
lastTurnTimeTickAt = game.turnTimeTickAt
game.turnTimeTickAt = Date.now()
delta_turn_time_tick = game.turnTimeTickAt - lastTurnTimeTickAt
delta_since_timer_began = game.turnTimeTickAt - game.turnTimerStartedAt
game.turnTimeRemaining = Math.max(0.0, allowed_turn_time - delta_since_timer_began + game.turnTimeBonus)
game.turnTimeBonus = Math.max(0.0, game.turnTimeBonus - delta_turn_time_tick)
#Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: delta #{delta_turn_time_tick/1000}, #{game.turnTimeRemaining/1000} time remaining, #{game.turnTimeBonus/1000} bonus remaining"
turnTimeRemainingInSeconds = Math.ceil(game.turnTimeRemaining/1000)
gameSession.setTurnTimeRemaining(turnTimeRemainingInSeconds)
if game.turnTimeRemaining <= 0
# turn time has expired
stopTurnTimer(gameId)
if gameSession.status == SDK.GameStatus.new
# force draw starting hand with current cards
for player in gameSession.players
if not player.getHasStartingHand()
Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: mulligan timer up, submitting player #{player.playerId.blue} mulligan".red
drawStartingHandAction = player.actionDrawStartingHand([])
gameSession.executeAction(drawStartingHandAction)
else if gameSession.status == SDK.GameStatus.active
# force end turn
Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: turn timer up, submitting player #{gameSession.getCurrentPlayerId().blue} turn".red
endTurnAction = gameSession.actionEndTurn()
gameSession.executeAction(endTurnAction)
else
# if the turn timer has not expired, just send the time tick over to all clients
totalStepCount = gameSession.getStepCount() - games[gameId].opponentEventDataBuffer.length
emitGameEvent(null,gameId,{type:EVENTS.turn_time, time: turnTimeRemainingInSeconds, timestamp: Date.now(), stepCount: totalStepCount})
###*
# ...
# @public
# @param {Object} gameId The game ID.
###
restartSpectatorDelayedGameInterval = (gameId) ->
stopSpectatorDelayedGameInterval(gameId)
Logger.module("IO").debug "[G:#{gameId}]", "restartSpectatorDelayedGameInterval"
if games[gameId].spectateIsDelayed
games[gameId].spectatorDelayTimer = setInterval((()-> onSpectatorDelayedGameTick(gameId)), 500)
###*
# ...
# @public
# @param {Object} gameId The game ID.
###
stopSpectatorDelayedGameInterval = (gameId) ->
Logger.module("IO").debug "[G:#{gameId}]", "stopSpectatorDelayedGameInterval"
clearInterval(games[gameId].spectatorDelayTimer)
###*
# Ticks the spectator delayed game and usually flushes the buffer by calling `flushSpectatorNetworkEventBuffer`.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
onSpectatorDelayedGameTick = (gameId) ->
if not games[gameId]
Logger.module("Game").debug "onSpectatorDelayedGameTick() -> game [G:#{gameId}] seems to be destroyed. Stopping ticks."
stopSpectatorDelayedGameInterval(gameId)
return
_logSpectatorTickInfo(gameId)
# flush anything in the spectator buffer
flushSpectatorNetworkEventBuffer(gameId)
###*
# Runs actions delayed in the spectator buffer.
# @public
# @param {Object} gameId The game for which to iterate the time.
###
flushSpectatorNetworkEventBuffer = (gameId) ->
# if there is anything in the buffer
if games[gameId].spectatorGameEventBuffer.length > 0
# Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer()"
# remove all the NULLED out actions
games[gameId].spectatorGameEventBuffer = _.compact(games[gameId].spectatorGameEventBuffer)
# loop through the actions in order
for eventData,i in games[gameId].spectatorGameEventBuffer
timestamp = eventData.timestamp || eventData.step?.timestamp
# if we are not delaying events or if the event time exceeds the delay show it to spectators
if not games[gameId].spectateIsDelayed || timestamp and moment().utc().valueOf() - timestamp > games[gameId].spectateDelay
# null out the event that is about to be broadcast so it can be compacted later
games[gameId].spectatorGameEventBuffer[i] = null
if (eventData.step)
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> broadcasting spectator step #{eventData.type} - #{eventData.step?.action?.type}"
if games[gameId].spectateIsDelayed
step = games[gameId].spectatorDelayedGameSession.deserializeStepFromFirebase(eventData.step)
games[gameId].spectatorDelayedGameSession.executeAuthoritativeStep(step)
# send events over to spectators of current player
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to player's spectators"
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.step.playerId
# scrub the action data. this should not be skipped since some actions include entire deck that needs to be scrubbed because we don't want spectators deck sniping
eventDataCopy = JSON.parse(JSON.stringify(eventData))
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true)
socket.emit EVENTS.network_game_event, eventDataCopy
# skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one
if eventData.step.action.type == SDK.RollbackToSnapshotAction.type
return
# start buffering events until a followup is complete for the opponent since players can cancel out of a followup
games[gameId].spectatorOpponentEventDataBuffer.push(eventData)
# if we are delayed then check the delayed game session for if we are buffering, otherwise use the primary
isSpectatorGameSessionBufferingFollowups = (games[gameId].spectateIsDelayed and games[gameId].spectatorDelayedGameSession?.getIsBufferingEvents()) || games[gameId].session.getIsBufferingEvents()
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> opponentEventDataBuffer at #{games[gameId].spectatorOpponentEventDataBuffer.length} ... buffering: #{isSpectatorGameSessionBufferingFollowups}"
# if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent's spectators
if games[gameId].spectatorOpponentEventDataBuffer.length > 0 and !isSpectatorGameSessionBufferingFollowups
# copy buffer and reset
opponentEventDataBuffer = games[gameId].spectatorOpponentEventDataBuffer.slice(0)
games[gameId].spectatorOpponentEventDataBuffer.length = 0
# broadcast whatever's in the buffer to the opponent
_.each(opponentEventDataBuffer, (eventData) ->
Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to opponent's spectators"
for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId != eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from opponent's spectator perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true)
socket.emit EVENTS.network_game_event, eventDataCopy
)
else
io.to("spectate-#{gameId}").emit EVENTS.network_game_event, eventData
_logSpectatorTickInfo = _.debounce((gameId)->
Logger.module("Game").debug "onSpectatorDelayedGameTick() ... #{games[gameId]?.spectatorGameEventBuffer?.length} buffered"
if games[gameId]?.spectatorGameEventBuffer
for eventData,i in games[gameId]?.spectatorGameEventBuffer
Logger.module("Game").debug "onSpectatorDelayedGameTick() eventData: ",eventData
, 1000)
###*
# Emit/Broadcast game event to appropriate destination.
# @public
# @param {Socket} event Originating socket.
# @param {String} gameId The game id for which to broadcast.
# @param {Object} eventData Data to broadcast.
###
emitGameEvent = (fromSocket,gameId,eventData)->
if games[gameId]?
if eventData.type == EVENTS.step
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> step #{eventData.step?.index?.toString().yellow} with timestamp #{eventData.step?.timestamp} and action #{eventData.step?.action?.type}"
# only broadcast valid steps
if eventData.step? and eventData.step.timestamp? and eventData.step.action?
# send the step to the owner
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from player perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId)
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to origin"
socket.emit EVENTS.network_game_event, eventDataCopy
# NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected:
# 2 for this current reconnecting player and 1 for the opponent
# breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event
# break
# buffer actions for the opponent other than a rollback action since that should clear the buffer during followups and there's no need to be sent to the opponent
# essentially: skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one
if eventData.step.action.type != SDK.RollbackToSnapshotAction.type
# start buffering events until a followup is complete for the opponent since players can cancel out of a followup
games[gameId].opponentEventDataBuffer.push(eventData)
# if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent
if games[gameId].opponentEventDataBuffer.length > 0 and !games[gameId].session.getIsBufferingEvents()
# copy buffer and reset
opponentEventDataBuffer = games[gameId].opponentEventDataBuffer.slice(0)
games[gameId].opponentEventDataBuffer.length = 0
# broadcast whatever's in the buffer to the opponent
_.each(opponentEventDataBuffer, (eventData) ->
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId != eventData.step.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
# always scrub steps for sensitive data from player perspective
UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId)
Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to opponent"
socket.emit EVENTS.network_game_event, eventDataCopy
)
else if eventData.type == EVENTS.invalid_action
# send the invalid action notification to the owner
for socketId,connected of io.sockets.adapter.rooms[gameId]
socket = io.sockets.connected[socketId]
if socket? and socket.playerId == eventData.playerId
eventDataCopy = JSON.parse(JSON.stringify(eventData))
socket.emit EVENTS.network_game_event, eventDataCopy
# NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected:
# 2 for this current reconnecting player and 1 for the opponent
# breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event
else
if eventData.type == EVENTS.network_game_hover or eventData.type == EVENTS.network_game_select or eventData.type == EVENTS.network_game_mouse_clear or eventData.type == EVENTS.show_emote
# save the player id of this event
eventData.playerId ?= fromSocket?.playerId
eventData.timestamp = moment().utc().valueOf()
# mouse events, emotes, etc should be saved and persisted to S3 for replays
games[gameId].mouseAndUIEvents ?= []
games[gameId].mouseAndUIEvents.push(eventData)
if fromSocket?
# send it along to other connected sockets in the game room
fromSocket.broadcast.to(gameId).emit EVENTS.network_game_event, eventData
else
# send to all sockets connected to the game room
io.to(gameId).emit EVENTS.network_game_event, eventData
# push a deep clone of the event data to the spectator buffer
if games[gameId]?.spectateIsRunning
spectatorEventDataCopy = JSON.parse(JSON.stringify(eventData))
games[gameId].spectatorGameEventBuffer.push(spectatorEventDataCopy)
# if we're not running a timed delay, just flush everything now
if not games[gameId]?.spectateIsDelayed
flushSpectatorNetworkEventBuffer(gameId)
###
# start a game session if one doesn't exist and call a completion handler when done
# @public
# @param {Object} gameId The game ID to load.
# @param {Function} onComplete Callback when done.
###
initGameSession = (gameId,onComplete) ->
if games[gameId]?.loadingPromise
return games[gameId].loadingPromise
# setup local cache reference if none already there
if not games[gameId]
games[gameId] =
opponentEventDataBuffer:[]
connectedPlayers:[]
session:null
connectedSpectators:[]
spectateIsRunning:false
spectateIsDelayed:false
spectateDelay:30000
spectatorGameEventBuffer:[]
spectatorOpponentEventDataBuffer:[]
spectatorDelayedGameSession:null
turnTimerStartedAt: 0
turnTimeTickAt: 0
turnTimeRemaining: 0
turnTimeBonus: 0
# return game session from redis
games[gameId].loadingPromise = Promise.all([
GameManager.loadGameSession(gameId)
GameManager.loadGameMouseUIData(gameId)
])
.spread (gameData,mouseData)->
return [
JSON.parse(gameData)
JSON.parse(mouseData)
]
.spread (gameDataIn,mouseData) ->
Logger.module("IO").log "[G:#{gameId}]", "initGameSession -> loaded game data for game:#{gameId}"
# deserialize game session
gameSession = SDK.GameSession.create()
gameSession.setIsRunningAsAuthoritative(true)
gameSession.deserializeSessionFromFirebase(gameDataIn)
if gameSession.isOver()
throw new Error("Game is already over!")
# store session
games[gameId].session = gameSession
# store mouse and ui event data
games[gameId].mouseAndUIEvents = mouseData
saveGameCount(++gameCount)
# setup AI
ai_setup(gameId)
# in case the server restarted or loading data for first time, set the last action at timestamp for both players to now
# this timestamp is used to shorten turn timer if player has not made any moves for a long time
_.each(gameSession.players,(player)->
player.setLastActionTakenAt(Date.now())
)
# this is ugly but a simple way to subscribe to turn change events to save the game session
subscribeToGameSessionEvents(gameId)
# start the turn timer
restartTurnTimer(gameId)
return Promise.resolve([
games[gameId].session
])
.catch (error) ->
Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error stack: #{error.stack}".red
# Report error to exceptionReporter with gameId
exceptionReporter.notify(error, {
errorName: "initGameSession Error",
severity: "error",
game: {
id: gameId
}
})
throw error
###
# start a spectator game session if one doesn't exist and call a completion handler when done
# @public
# @param {Object} gameId The game ID to load.
# @param {Function} onComplete Callback when done.
###
initSpectatorGameSession = (gameId)->
if not games[gameId]
return Promise.reject(new Error("This game is no longer in progress"))
return Promise.resolve()
.then ()->
# if we're not already running spectate systems
if not games[gameId].spectateIsRunning
# mark that we are running spectate systems
games[gameId].spectateIsRunning = true
# if we're in the middle of a followup and we have some buffered events, we need to copy them over to the spectate buffer
if games[gameId].session.getIsBufferingEvents() and games[gameId].opponentEventDataBuffer.length > 0
games[gameId].spectatorOpponentEventDataBuffer.length = 0
for eventData in games[gameId].opponentEventDataBuffer
eventDataCopy = JSON.parse(JSON.stringify(eventData))
games[gameId].spectatorOpponentEventDataBuffer.push(eventDataCopy)
if games[gameId].spectateIsDelayed and not games[gameId].spectatorDelayedGameSession
Logger.module("...").log "[G:#{gameId}]", "initSpectatorDelayedGameSession() -> creating delayed game session"
# create
delayedGameDataIn = games[gameId].session.serializeToJSON(games[gameId].session)
delayedGameSession = SDK.GameSession.create()
delayedGameSession.setIsRunningAsAuthoritative(false)
delayedGameSession.deserializeSessionFromFirebase(JSON.parse(delayedGameDataIn))
delayedGameSession.gameId = "SPECTATE:#{delayedGameSession.gameId}"
games[gameId].spectatorDelayedGameSession = delayedGameSession
# start timer to execute delayed / buffered spectator game events
restartSpectatorDelayedGameInterval(gameId)
return Promise.resolve(games[gameId].spectatorDelayedGameSession)
else
return Promise.resolve(games[gameId].session)
###*
* Handler for before a game session rolls back to a snapshot.
###
onBeforeRollbackToSnapshot = (event) ->
# clear the buffer just before rolling back
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
game.opponentEventDataBuffer.length = 0
game.spectatorOpponentEventDataBuffer.length = 0
###*
* Handler for a game session step.
###
onStep = (event) ->
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
step = event.step
if step? and step.timestamp? and step.action?
# send out step events
stepEventData = {type: EVENTS.step, step: JSON.parse(game.session.serializeToJSON(step))}
emitGameEvent(null, gameId, stepEventData)
# special action cases
action = step.action
if action instanceof SDK.EndTurnAction
# save game on end turn
# delay so that we don't block sending the step back to the players
_.delay((()->
if games[gameId]? and games[gameId].session?
GameManager.saveGameSession(gameId, games[gameId].session.serializeToJSON(games[gameId].session))
), 500)
else if action instanceof SDK.StartTurnAction
# restart the turn timer whenever a turn starts
restartTurnTimer(gameId)
else if action instanceof SDK.DrawStartingHandAction
# restart turn timer if both players have a starting hand and this step is for a DrawStartingHandAction
bothPlayersHaveStartingHand = _.reduce(game.session.players,((memo,player)-> memo && player.getHasStartingHand()),true)
if bothPlayersHaveStartingHand
restartTurnTimer(gameId)
if action.getIsAutomatic() and !game.session.getIsFollowupActive()
# add bonus to turn time for every automatic step
# unless followup is active, to prevent rollbacks for infinite turn time
# bonus as a separate parameter accounts for cases such as:
# - battle pet automatic actions eating up your own time
# - queuing up many actions and ending turn quickly to eat into opponent's time
game.turnTimeBonus += 2000
# when game is over and we have the final step
# we cannot archive game until final step event
# because otherwise step won't be finished/signed correctly
# so we must do this on step event and not on game_over event
if game.session.status == SDK.GameStatus.over
# stop any turn timers
stopTurnTimer(gameId)
if !game.isArchived?
game.isArchived = true
afterGameOver(gameId, game.session, game.mouseAndUIEvents)
###*
* Handler for an invalid action.
###
onInvalidAction = (event) ->
# safety fallback: if player attempts to make an invalid explicit action, notify that player only
gameSession = event.gameSession
gameId = gameSession.gameId
game = games[gameId]
if game?
action = event.action
if !action.getIsImplicit()
#Logger.module("...").log "[G:#{gameId}]", "onInvalidAction -> INVALID ACTION: #{action.getLogName()} / VALIDATED BY: #{action.getValidatorType()} / MESSAGE: #{action.getValidationMessage()}"
invalidActionEventData = {
type: EVENTS.invalid_action,
playerId: action.getOwnerId(),
action: JSON.parse(game.session.serializeToJSON(action)),
validatorType: event.validatorType,
validationMessage: event.validationMessage,
validationMessagePosition: event.validationMessagePosition,
desync: gameSession.isActive() and
gameSession.getCurrentPlayerId() == action.getOwnerId() and
gameSession.getTurnTimeRemaining() > CONFIG.TURN_DURATION_LATENCY_BUFFER
}
emitGameEvent(null, gameId, invalidActionEventData)
###
# Subscribes to the gamesession's event bus.
# Can be called multiple times in order to re-subscribe.
# @public
# @param {Object} gameId The game ID to subscribe for.
###
subscribeToGameSessionEvents = (gameId)->
Logger.module("...").log "[G:#{gameId}]", "subscribeToGameSessionEvents -> subscribing to GameSession events"
game = games[gameId]
if game?
# unsubscribe from previous
unsubscribeFromGameSessionEvents(gameId)
# listen for game events
game.session.getEventBus().on(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot)
game.session.getEventBus().on(EVENTS.step, onStep)
game.session.getEventBus().on(EVENTS.invalid_action, onInvalidAction)
# subscribe AI to events
ai_subscribeToGameSessionEvents(gameId)
###
# Unsubscribe from event listeners on the game session for this game ID.
# @public
# @param {String} gameId The game ID that needs to be unsubscribed.
###
unsubscribeFromGameSessionEvents = (gameId)->
Logger.module("...").log "[G:#{gameId}]", "unsubscribeFromGameSessionEvents -> un-subscribing from GameSession events"
game = games[gameId]
if game?
game.session.getEventBus().off(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot)
game.session.getEventBus().off(EVENTS.step, onStep)
game.session.getEventBus().off(EVENTS.invalid_action, onInvalidAction)
ai_unsubscribeFromGameSessionEvents(gameId)
###
# must be called after game is over
# processes a game, saves to redis, and kicks-off post-game processing jobs
# @public
# @param {String} gameId The game ID that is over.
# @param {Object} gameSession The game session data.
# @param {Array} mouseAndUIEvents The mouse and UI events for this game.
###
afterGameOver = (gameId, gameSession, mouseAndUIEvents) ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "---------- ======= GAME #{gameId} OVER ======= ---------".green
# Update User Ranking, Progression, Quests, Stats
updateUser = (userId, opponentId, gameId, factionId, generalId, isWinner, isDraw, ticketId) ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "UPDATING user #{userId}. (winner:#{isWinner})"
# check for isFriendly
# check for isUnscored
isFriendly = gameSession.gameType == SDK.GameType.Friendly
isUnscored = false
# Ranking and Progression only process in NON-FRIENDLY matches
if not isFriendly
# calculate based on number of resign status and number of actions
lastStep = gameSession.getLastStep()
# if the game didn't have a single turn, mark the game as unscored
if gameSession.getPlayerById(userId).hasResigned and gameSession.getTurns().length == 0
Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} CONCEDED a game with 0 turns. Marking as UNSCORED".yellow
isUnscored = true
else if not isWinner and not isDraw
# otherwise check how many actions the player took
playerActionCount = 0
meaningfulActionCount = 0
moveActionCount = 0
for a in gameSession.getActions()
# explicit actions
if a.getOwnerId() == userId && a.getIsImplicit() == false
playerActionCount++
# meaningful actions
if a instanceof SDK.AttackAction
if a.getTarget().getIsGeneral()
meaningfulActionCount += 2
else
meaningfulActionCount += 1
if a instanceof SDK.PlayCardFromHandAction or a instanceof SDK.PlaySignatureCardAction
meaningfulActionCount += 1
if a instanceof SDK.BonusManaAction
meaningfulActionCount += 2
# move actions
if a instanceof SDK.MoveAction
moveActionCount += 1
# more than 9 explicit actions
# more than 1 move action
# more than 5 meaningful actions
if playerActionCount > 9 and moveActionCount > 1 and meaningfulActionCount > 4
break
###
what we're looking for:
* more than 9 explicit actions
* more than 1 move action
* more than 5 meaningful actions
... otherwise mark the game as unscored
###
# Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} #{playerActionCount}, #{moveActionCount}, #{meaningfulActionCount}".cyan
if playerActionCount <= 9 or moveActionCount <= 1 or meaningfulActionCount <= 4
Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} CONCEDED a game with too few meaningful actions. Marking as UNSCORED".yellow
isUnscored = true
# start the job to process the game for a user
Jobs.create("update-user-post-game",
name: "Update User Ranking"
title: util.format("User %s :: Game %s", userId, gameId)
userId: userId
opponentId: opponentId
gameId: gameId
gameType: gameSession.gameType
factionId: factionId
generalId: generalId
isWinner: isWinner
isDraw: isDraw
isUnscored: isUnscored
isBotGame: true
ticketId: ticketId
).removeOnComplete(true).save()
# Save then archive game session
archiveGame = (gameId, gameSession, mouseAndUIEvents) ->
Promise.all([
GameManager.saveGameMouseUIData(gameId, JSON.stringify(mouseAndUIEvents)),
GameManager.saveGameSession(gameId, gameSession.serializeToJSON(gameSession))
]).then () ->
# Job: Archive Game
Jobs.create("archive-game",
name: "Archive Game"
title: util.format("Archiving Game %s", gameId)
gameId: gameId
gameType: gameSession.gameType
).removeOnComplete(true).save()
# update promises
promises = [
archiveGame(gameId, gameSession, mouseAndUIEvents)
]
for player in gameSession.players
playerId = player.getPlayerId()
# don't update normal AI (non-bot user)
if playerId != CONFIG.AI_PLAYER_ID
# find player data
winnerId = gameSession.getWinnerId()
isWinner = (playerId == winnerId)
isDraw = if !winnerId? then true else false
playerSetupData = gameSession.getPlayerSetupDataForPlayerId(playerId)
playerFactionId = playerSetupData.factionId
generalId = playerSetupData.generalId
ticketId = playerSetupData.ticketId
promises.push(updateUser(playerId,CONFIG.AI_PLAYER_ID,gameId,playerFactionId,generalId,isWinner,isDraw,ticketId))
# execute promises
Promise.all(promises)
.then () ->
Logger.module("GAME-OVER").log "[G:#{gameId}]", "afterGameOver done, game has been archived".green
.catch (error) ->
Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver failed #{error}".red
# issue a warning to our exceptionReporter error tracker
exceptionReporter.notify(error, {
errorName: "afterGameOver failed",
severity: "error"
game:
id: gameId
gameType: gameSession.gameType
player1Id: player1Id
player2Id: player2Id
winnerId: winnerId
loserId: loserId
})
### Shutdown Handler ###
shutdown = () ->
Logger.module("SERVER").log "Shutting down game server."
Logger.module("SERVER").log "Active Players: #{playerCount}."
Logger.module("SERVER").log "Active Games: #{gameCount}."
if !config.get('consul.enabled')
process.exit(0)
return Consul.getReassignmentStatus()
.then (reassign) ->
if reassign == false
Logger.module("SERVER").log "Reassignment disabled - exiting."
process.exit(0)
# Build an array of game IDs
ids = []
_.each games, (game, id) ->
ids.push(id)
# Map to save each game to Redis before shutdown
return Promise.map ids, (id) ->
serializedData = games[id].session.serializeToJSON(games[id].session)
return GameManager.saveGameSession(id, serializedData)
.then () ->
return Consul.getHealthyServers()
.then (servers) ->
# Filter 'yourself' from list of nodes
filtered = _.reject servers, (server)->
return server["Node"]?["Node"] == os.hostname()
if filtered.length == 0
Logger.module("SERVER").log "No servers available - exiting without re-assignment."
process.exit(1)
random_node = _.sample(filtered)
node_name = random_node["Node"]?["Node"]
return Consul.kv.get("nodes/#{node_name}/public_ip")
.then (newServerIp) ->
# Development override for testing, bounces between port 9000 & 9001
if config.isDevelopment()
port = 9001 if config.get('port') is 9000
port = 9000 if config.get('port') is 9001
newServerIp = "127.0.0.1:#{port}"
msg = "Server is shutting down. You will be reconnected automatically."
io.emit "game_server_shutdown", {msg:msg,ip:newServerIp}
Logger.module("SERVER").log "Players reconnecting to: #{newServerIp}"
Logger.module("SERVER").log "Re-assignment complete. Exiting."
process.exit(0)
.catch (err) ->
Logger.module("SERVER").log "Re-assignment failed: #{err.message}. Exiting."
process.exit(1)
process.on "SIGTERM", shutdown
process.on "SIGINT", shutdown
process.on "SIGHUP", shutdown
process.on "SIGQUIT", shutdown
# region AI
###*
* Returns whether a session is valid for AI usage.
* @param {String} gameId
###
ai_isValidSession = (gameId) ->
return games[gameId]?.session? and !games[gameId].session.isOver() and games[gameId].ai?
###*
* Returns whether a session and turn is valid for AI usage.
* @param {String} gameId
###
ai_isValidTurn = (gameId) ->
return ai_isValidSession(gameId) and games[gameId].session.isActive() and games[gameId].session.getCurrentPlayerId() == games[gameId].ai.getMyPlayerId()
###*
* Returns whether AI can start turn.
* @param {String} gameId
###
ai_canStartTurn = (gameId) ->
return ai_isValidTurn(gameId) and !ai_isExecutingTurn(gameId) and !games[gameId].session.hasStepsInQueue()
###*
* Returns whether ai is currently executing turn.
* @param {String} gameId
###
ai_isExecutingTurn = (gameId) ->
return games[gameId].executingAITurn
###*
* Returns whether ai can progress turn.
* @param {String} gameId
###
ai_canProgressTurn = (gameId) ->
return ai_isValidTurn(gameId) and ai_isExecutingTurn(gameId) and !games[gameId].aiStartTurnTimeoutId?
###*
* Returns whether ai can taunt.
* @param {String} gameId
###
ai_canEmote = (gameId) ->
return ai_isValidSession(gameId) and !ai_isBot(gameId) and !games[gameId].session.getIsBufferingEvents() and Math.random() < 0.05
###*
* Returns whether ai is normal ai or bot.
* @param {String} gameId
###
ai_isBot = (gameId) ->
return games[gameId]?.session? and games[gameId].session.getAiPlayerId() != CONFIG.AI_PLAYER_ID
###*
* Initializes AI for a game session.
* @param {String} gameId
###
ai_setup = (gameId) ->
if games[gameId]?.session? and !games[gameId].ai?
aiPlayerId = games[gameId].session.getAiPlayerId()
aiDifficulty = games[gameId].session.getAiDifficulty()
Logger.module("AI").debug "[G:#{gameId}]", "Setup AI -> aiPlayerId #{aiPlayerId} - aiDifficulty #{aiDifficulty}"
games[gameId].ai = new StarterAI(games[gameId].session, aiPlayerId, aiDifficulty)
# add AI as a connected player
games[gameId].connectedPlayers.push(games[gameId].session.getAiPlayerId())
# attempt to mulligan immediately on new game
if games[gameId].session.isNew()
nextAction = games[gameId].ai.nextAction()
if nextAction?
games[gameId].session.executeAction(nextAction)
###*
* Terminates AI for a game session.
* @param {String} gameId
###
ai_terminate = (gameId) ->
ai_unsubscribeFromGameSessionEvents(gameId)
ai_stopTurn(gameId)
ai_stopTimeouts(gameId)
ai_onStep = (event) ->
gameSession = event.gameSession
gameId = gameSession.gameId
# emote after step
ai_emoteForLastStep(gameId)
# progress turn
ai_updateTurn(gameId)
ai_onInvalidAction = (event) ->
# safety fallback: if AI attempts to make an invalid explicit action, end AI turn immediately
if event?
gameSession = event.gameSession
gameId = gameSession.gameId
action = event.action
if action? and !action.getIsImplicit() and ai_isExecutingTurn(gameId) and action.getOwnerId() == games[gameId].ai.getMyPlayerId()
ai_endTurn(gameId)
ai_subscribeToGameSessionEvents = (gameId) ->
game = games[gameId]
if game?
# if we're already subscribed, unsubscribe
ai_unsubscribeFromGameSessionEvents(gameId)
# listen for game events
game.session.getEventBus().on(EVENTS.step, ai_onStep)
game.session.getEventBus().on(EVENTS.invalid_action, ai_onInvalidAction)
ai_unsubscribeFromGameSessionEvents = (gameId) ->
game = games[gameId]
if game?
game.session.getEventBus().off(EVENTS.step, ai_onStep)
game.session.getEventBus().off(EVENTS.invalid_action, ai_onInvalidAction)
###*
* Updates AI turn for a game session.
* @param {String} gameId
###
ai_updateTurn = (gameId) ->
Logger.module("AI").debug "[G:#{gameId}]", "ai_updateTurn"
if ai_canStartTurn(gameId)
ai_startTurn(gameId)
else if ai_canProgressTurn(gameId)
ai_progressTurn(gameId)
else if ai_isExecutingTurn(gameId)
ai_endTurn(gameId)
###*
* Progresses AI turn for a game session.
* @param {String} gameId
###
ai_progressTurn = (gameId) ->
if ai_canProgressTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_progressTurn".cyan
# request next action from AI
try
nextAction = games[gameId].ai.nextAction()
catch error
Logger.module("IO").log "[G:#{gameId}]", "ai.nextAction:: error: #{JSON.stringify(error.message)}".red
Logger.module("IO").log "[G:#{gameId}]", "ai.nextAction:: error stack: #{error.stack}".red
# retain player id
playerId = games[gameId].ai.getOpponentPlayerId()
# Report error to exceptionReporter with gameId + eventData
exceptionReporter.notify(error, {
errorName: "ai_progressTurn Error",
game: {
gameId: gameId
turnIndex: games[gameId].session.getTurns().length
stepIndex: games[gameId].session.getCurrentTurn().getSteps().length
}
})
# delete but don't destroy game
destroyGameSessionIfNoConnectionsLeft(gameId,true)
# send error to client, forcing reconnect on client side
io.to(gameId).emit EVENTS.network_game_error, JSON.stringify(error.message)
return
# if we didn't have an error and somehow destroy the game data in the try/catch above
if games[gameId]?
if nextAction?
# always delay AI actions slightly
if !games[gameId].aiExecuteActionTimeoutId?
if ai_isBot(gameId)
if games[gameId].session.getIsFollowupActive()
actionDelayTime = 1.0 + Math.random() * 3.0
else if nextAction instanceof SDK.EndTurnAction
actionDelayTime = 1.0 + Math.random() * 2.0
else
actionDelayTime = 1.0 + Math.random() * 8.0
else
if games[gameId].session.getIsFollowupActive()
actionDelayTime = 0.0
else
actionDelayTime = 5.0
# action delay time can never be more than a quarter of remaining turn time
if games[gameId].turnTimeRemaining?
actionDelayTime = Math.min((games[gameId].turnTimeRemaining * 0.25) / 1000.0, actionDelayTime)
# show UI as needed
ai_showUIForAction(gameId, nextAction, actionDelayTime)
# delay and then execute action
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiExecuteActionTimeoutId = setTimeout((() ->
games[gameId].aiExecuteActionTimeoutId = null
ai_showClearUI(gameId)
ai_executeAction(gameId, nextAction)
), Math.max(1.0, actionDelayTime * 1000.0))
else if ai_isExecutingTurn(gameId)
# end turn as needed
ai_endTurn(gameId)
###*
* Starts AI turn for a game session.
* @param {String} gameId
###
ai_startTurn = (gameId) ->
if ai_canStartTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_startTurn".cyan
# set as executing AI turn
games[gameId].executingAITurn = true
if !games[gameId].aiStartTurnTimeoutId?
# delay initial turn progress
if ai_isBot(gameId)
delayTime = 2.0 + Math.random() * 2.0
else
delayTime = 2.0
# choose random starting point for pointer
games[gameId].aiPointer = {
x: Math.floor(Math.random() * CONFIG.BOARDCOL),
y: Math.floor(Math.random() * CONFIG.BOARDROW)
}
Logger.module("AI").debug "[G:#{gameId}]", "ai_startTurn init aiPointer at #{games[gameId].aiPointer.x}, #{games[gameId].aiPointer.y}".cyan
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiStartTurnTimeoutId = setTimeout((()->
games[gameId].aiStartTurnTimeoutId = null
ai_progressTurn(gameId)
), Math.max(1.0, delayTime * 1000.0))
###*
* Stops AI turn for a game session, and ends it if necessary.
* @param {String} gameId
###
ai_endTurn = (gameId) ->
# stop turn
ai_stopTurn(gameId)
# force end turn if still AI's turn
if ai_isValidTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_endTurn".cyan
ai_executeAction(gameId, games[gameId].session.actionEndTurn())
###*
* Stops AI turn for a game session. Does not end AI turn.
* @param {String} gameId
###
ai_stopTurn = (gameId) ->
if games[gameId].executingAITurn
Logger.module("AI").debug "[G:#{gameId}]", "ai_stopTurn".cyan
games[gameId].executingAITurn = false
ai_stopTurnTimeouts(gameId)
###*
* Stops AI timeouts for a game session.
* @param {String} gameId
###
ai_stopTimeouts = (gameId) ->
ai_stopTurnTimeouts(gameId)
ai_stopEmoteTimeouts(gameId)
ai_stopUITimeouts(gameId)
###*
* Stops AI timeouts for turn actions.
* @param {String} gameId
###
ai_stopTurnTimeouts = (gameId) ->
if games[gameId].aiStartTurnTimeoutId?
clearTimeout(games[gameId].aiStartTurnTimeoutId)
games[gameId].aiStartTurnTimeoutId = null
if games[gameId].aiExecuteActionTimeoutId?
clearTimeout(games[gameId].aiExecuteActionTimeoutId)
games[gameId].aiExecuteActionTimeoutId = null
###*
* Executes an AI action for a game session.
* @param {String} gameId
* @param {Action} action
###
ai_executeAction = (gameId, action) ->
if ai_canProgressTurn(gameId)
Logger.module("AI").debug "[G:#{gameId}]", "ai_executeAction -> #{action.getLogName()}".cyan
# simulate AI sending step to server
step = new SDK.Step(games[gameId].session, action.getOwnerId())
step.setAction(action)
opponentPlayerId = games[gameId].ai.getOpponentPlayerId()
for clientId,socket of io.sockets.connected
if socket.playerId == opponentPlayerId and !socket.spectatorId
onGameEvent.call(socket, {
type: EVENTS.step
step: JSON.parse(games[gameId].session.serializeToJSON(step))
})
###*
* Returns whether an action is valid for showing UI.
* @param {String} gameId
* @param {Action} action
* @return {Boolean}
###
ai_isValidActionForUI = (gameId, action) ->
return (games[gameId].session.getIsFollowupActive() and !(action instanceof SDK.EndFollowupAction)) or
action instanceof SDK.ReplaceCardFromHandAction or
action instanceof SDK.PlayCardFromHandAction or
action instanceof SDK.PlaySignatureCardAction or
action instanceof SDK.MoveAction or
action instanceof SDK.AttackAction
###*
* Shows UI for an action that will be taken by AI.
* @param {String} gameId
* @param {Action} action
* @param {Number} actionDelayTime must be at least 0.25s or greater
###
ai_showUIForAction = (gameId, action, actionDelayTime) ->
if ai_isValidTurn(gameId) and ai_isValidActionForUI(gameId, action) and _.isNumber(actionDelayTime) and actionDelayTime > 0.25
aiPlayerId = games[gameId].ai.getMyPlayerId()
# stop any previous UI animations
ai_stopUITimeouts(gameId)
# get ui animation times
if ai_isBot(gameId)
if games[gameId].session.getIsFollowupActive()
uiDelayTime = actionDelayTime * (0.7 + Math.random() * 0.1)
uiAnimationDuration = actionDelayTime - uiDelayTime
moveToSelectDuration = 0.0
pauseAtSelectDuration = 0.0
pauseAtTargetDuration = (0.1 + Math.random() * 0.25) * uiAnimationDuration
moveToTargetDuration = uiAnimationDuration - pauseAtTargetDuration
else
uiDelayTime = actionDelayTime * (0.4 + Math.random() * 0.4)
uiAnimationDuration = actionDelayTime - uiDelayTime
pauseAtTargetDuration = Math.min(1.0, (0.1 + Math.random() * 0.25) * uiAnimationDuration)
moveToSelectDuration = (0.2 + Math.random() * 0.4) * (uiAnimationDuration - pauseAtTargetDuration)
moveToTargetDuration = (0.4 + Math.random() * 0.5) * (uiAnimationDuration - pauseAtTargetDuration - moveToSelectDuration)
pauseAtSelectDuration = uiAnimationDuration - pauseAtTargetDuration - moveToSelectDuration - moveToTargetDuration
else
uiDelayTime = actionDelayTime * 0.7
uiAnimationDuration = actionDelayTime - uiDelayTime
moveToSelectDuration = 0.0
pauseAtSelectDuration = 0.0
moveToTargetDuration = 0.0
pauseAtTargetDuration = uiAnimationDuration
# get action properties
selectEventData = {
type: EVENTS.network_game_select
playerId: aiPlayerId
}
if action instanceof SDK.ReplaceCardFromHandAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
handIndex = selectEventData.handIndex = action.getIndexOfCardInHand()
selectPosition = { x: Math.round((handIndex + 0.5) * (CONFIG.BOARDCOL / CONFIG.MAX_HAND_SIZE)), y: -1 }
else if action instanceof SDK.ApplyCardToBoardAction
if action instanceof SDK.PlayCardFromHandAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
handIndex = selectEventData.handIndex = action.getIndexOfCardInHand()
selectPosition = { x: Math.round((handIndex + 0.5) * (CONFIG.BOARDCOL / CONFIG.MAX_HAND_SIZE)), y: -1 }
targetPosition = action.getTargetPosition()
else if action instanceof SDK.PlaySignatureCardAction
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
isSignatureCard = true
if action.getCard().isOwnedByPlayer2()
selectEventData.player2SignatureCard = true
else
selectEventData.player1SignatureCard = true
if aiPlayerId == games[gameId].session.getPlayer2Id()
selectPosition = { x: CONFIG.BOARDCOL, y: Math.floor(CONFIG.BOARDROW * 0.5 + Math.random() * CONFIG.BOARDROW * 0.5) }
else
selectPosition = { x: -1, y: Math.floor(CONFIG.BOARDROW * 0.5 + Math.random() * CONFIG.BOARDROW * 0.5) }
targetPosition = action.getTargetPosition()
else
# followup has no selection
intent = selectEventData.intentType = SDK.IntentType.DeckIntent
selectEventData = null
selectPosition = action.getSourcePosition()
targetPosition = action.getTargetPosition()
else if action instanceof SDK.MoveAction
intent = selectEventData.intentType = SDK.IntentType.MoveIntent
cardIndex = selectEventData.cardIndex = action.getSourceIndex()
card = games[gameId].session.getCardByIndex(cardIndex)
selectPosition = card.getPosition()
targetPosition = action.getTargetPosition()
else if action instanceof SDK.AttackAction
intent = selectEventData.intentType = SDK.IntentType.DamageIntent
cardIndex = selectEventData.cardIndex = action.getSourceIndex()
card = games[gameId].session.getCardByIndex(cardIndex)
selectPosition = card.getPosition()
targetPosition = action.getTargetPosition()
# failsafe in case action doesn't have a select position
# (actions should always have a select position)
if !selectPosition?
if action instanceof SDK.ApplyCardToBoardAction
Logger.module("AI").log "[G:#{gameId}]", "ai_showUIForAction -> no sel pos #{action.getLogName()} w/ card #{action.getCard()?.getName()} w/ root #{action.getCard()?.getRootCard()?.getName()}".cyan
else
Logger.module("AI").log "[G:#{gameId}]", "ai_showUIForAction -> no sel pos #{action.getLogName()}".cyan
return
# setup sequence
actionPointerSequence = () ->
# move to select
ai_animatePointer(gameId, moveToSelectDuration, selectPosition, SDK.IntentType.NeutralIntent, false, isSignatureCard, () ->
if selectEventData?
if action instanceof SDK.MoveAction or action instanceof SDK.AttackAction
# clear pointer before select
emitGameEvent(null, gameId, {
type: EVENTS.network_game_mouse_clear
playerId: aiPlayerId,
intentType: SDK.IntentType.NeutralIntent
})
# show selection event
emitGameEvent(null, gameId, selectEventData)
if targetPosition?
# pause at select
ai_animatePointer(gameId, pauseAtSelectDuration, selectPosition, intent, isSignatureCard, false, () ->
# move to target
ai_animatePointer(gameId, moveToTargetDuration, targetPosition, intent)
)
)
# random chance to hover enemy unit on the board
if ai_isBot(gameId) and uiDelayTime >= 5.0 && Math.random() < 0.05
opponentGeneral = games[gameId].session.getGeneralForOpponentOfPlayerId(games[gameId].session.getAiPlayerId())
units = games[gameId].session.getBoard().getFriendlyEntitiesForEntity(opponentGeneral)
if units.length > 0
unitToHover = units[Math.floor(Math.random() * units.length)]
if unitToHover?
# hover unit before showing action UI
unitPosition = unitToHover.getPosition()
moveToUnitDuration = Math.random() * 1.0
pauseAtUnitDuration = 2.0 + Math.random() * 2.0
uiDelayTime = uiDelayTime - moveToUnitDuration - pauseAtUnitDuration
# delay for remaining time
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
# move to random unit
ai_animatePointer(gameId, moveToUnitDuration, unitPosition, SDK.IntentType.NeutralIntent, false, false, () ->
# pause at random unit and then show action pointer sequence
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
actionPointerSequence()
, pauseAtUnitDuration * 1000.0)
)
, uiDelayTime * 1000.0)
else
# delay and then show action pointer sequence
games[gameId].aiShowUITimeoutId = setTimeout(() ->
games[gameId].aiShowUITimeoutId = null
actionPointerSequence()
, uiDelayTime * 1000.0)
ai_showClearUI = (gameId) ->
if ai_isValidTurn(gameId)
ai_stopUITimeouts(gameId)
emitGameEvent(null, gameId, {
type: EVENTS.network_game_mouse_clear
playerId: games[gameId].ai.getMyPlayerId(),
intentType: SDK.IntentType.NeutralIntent
})
###*
* Clears out any timeouts for AI UI.
* @param {String} gameId
###
ai_stopUITimeouts = (gameId) ->
if games[gameId]?
if games[gameId].aiShowUITimeoutId?
clearTimeout(games[gameId].aiShowUITimeoutId)
games[gameId].aiShowUITimeoutId = null
ai_stopAnimatingPointer(gameId)
###*
* Shows AI pointer hover at a board position if it is different from the current position.
* @param {String} gameId
* @param {Number} boardX
* @param {Number} boardY
* @param {Number} [intent]
* @param {Number} [isSignatureCard=false]
###
ai_showHover = (gameId, boardX, boardY, intent=SDK.IntentType.NeutralIntent, isSignatureCard=false) ->
if ai_isValidTurn(gameId)
pointer = games[gameId].aiPointer
if pointer.x != boardX or pointer.y != boardY
# set pointer to position
pointer.x = boardX
pointer.y = boardY
# setup hover event data
hoverEventData = {
type: EVENTS.network_game_hover
boardPosition: {x: boardX, y: boardY},
playerId: games[gameId].ai.getMyPlayerId(),
intentType: intent
}
# check for hover target
if isSignatureCard
if games[gameId].ai.getMyPlayerId() == games[gameId].session.getPlayer2Id()
hoverEventData.player2SignatureCard = true
else
hoverEventData.player1SignatureCard = true
else
target = games[gameId].session.getBoard().getUnitAtPosition(pointer)
if target?
hoverEventData.cardIndex = target.getIndex()
# show hover
emitGameEvent(null, gameId, hoverEventData)
###*
* Animates AI pointer movement.
* @param {String} gameId
* @param {Number} duration in seconds
* @param {Vec2} [targetBoardPosition]
* @param {Number} [intent]
* @param {Number} [isSignatureCardAtSource]
* @param {Number} [isSignatureCardAtTarget]
* @param {Function} [callback]
###
ai_animatePointer = (gameId, duration, targetBoardPosition, intent, isSignatureCardAtSource, isSignatureCardAtTarget, callback) ->
if ai_isValidTurn(gameId)
# stop current animation
ai_stopAnimatingPointer(gameId)
pointer = games[gameId].aiPointer
sx = pointer.x
sy = pointer.y
tx = targetBoardPosition.x
ty = targetBoardPosition.y
dx = tx - sx
dy = ty - sy
if duration > 0.0
# show pointer at source
ai_showHover(gameId, sx, sy, intent, isSignatureCardAtSource)
# animate to target
dms = duration * 1000.0
startTime = Date.now()
games[gameId].aiPointerIntervalId = setInterval(() ->
# cubic ease out
currentTime = Date.now()
dt = currentTime - startTime
val = Math.min(1.0, dt / dms)
e = val - 1
ee = e * e * e + 1
cx = dx * ee + sx
cy = dy * ee + sy
ai_showHover(gameId, Math.round(cx), Math.round(cy), intent, isSignatureCardAtTarget)
if val == 1.0
ai_stopAnimatingPointer(gameId)
if callback then callback()
, dms / 10)
else
# show pointer at target
ai_showHover(gameId, tx, ty, intent, isSignatureCardAtTarget)
# no animation needed
if callback then callback()
###*
* Stops showing AI pointer movement.
###
ai_stopAnimatingPointer = (gameId) ->
if games[gameId]? and games[gameId].aiPointerIntervalId != null
clearInterval(games[gameId].aiPointerIntervalId)
games[gameId].aiPointerIntervalId = null
###*
* Prompts AI to emote to opponent based on last step.
* @param {String} gameId
###
ai_emoteForLastStep = (gameId) ->
if ai_canEmote(gameId)
step = games[gameId].session.getLastStep()
action = step?.action
if action? and !(action instanceof SDK.EndTurnAction)
aiPlayerId = games[gameId].ai.getMyPlayerId()
isMyAction = action.getOwnerId() == aiPlayerId
# search action + sub actions for any played or removed units
actionsToSearch = [action]
numHappyActions = 0
numTauntingActions = 0
numAngryActions = 0
while actionsToSearch.length > 0
searchAction = actionsToSearch.shift()
if searchAction instanceof SDK.RemoveAction
if !isMyAction and searchAction.getTarget()?.getOwnerId() == aiPlayerId
numAngryActions += 2
else if isMyAction and searchAction.getTarget()?.getOwnerId() != aiPlayerId
numTauntingActions += 1
else if searchAction instanceof SDK.HealAction
if isMyAction and searchAction.getTarget()?.getOwnerId() == aiPlayerId
numTauntingActions += 1
else if !isMyAction and searchAction.getTarget()?.getOwnerId() != aiPlayerId
numAngryActions += 1
else if searchAction instanceof SDK.PlayCardFromHandAction or searchAction instanceof SDK.PlaySignatureCardAction
if isMyAction and searchAction.getCard() instanceof SDK.Unit
numHappyActions += 1
# add sub actions
actionsToSearch = actionsToSearch.concat(searchAction.getSubActions())
maxEmotion = Math.max(numHappyActions, numTauntingActions, numAngryActions)
if maxEmotion > 0
emoteIds = []
myGeneral = games[gameId].ai.getMyGeneral()
myGeneralId = myGeneral.getId()
factionEmotesData = SDK.CosmeticsFactory.cosmeticsForTypeAndFaction(SDK.CosmeticsTypeLookup.Emote, myGeneral.getFactionId())
# use ai faction emote that were most present in last step
if maxEmotion == numAngryActions
for emoteData in factionEmotesData
if emoteData.enabled and (emoteData.title == "Angry" or emoteData.title == "Sad" or emoteData.title == "Frustrated") and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
else if maxEmotion == numHappyActions
for emoteData in factionEmotesData
if emoteData.enabled and emoteData.title == "Happy" and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
else if maxEmotion == numTauntingActions
for emoteData in factionEmotesData
if emoteData.enabled and (emoteData.title == "Taunt" or emoteData.title == "Sunglasses" or emoteData.title == "Kiss") and (emoteData.generalId == myGeneralId)
emoteIds.push(emoteData.id)
# pick a random emote
emoteId = emoteIds[Math.floor(Math.random() * emoteIds.length)]
#Logger.module("AI").debug "[G:#{gameId}]", "ai_emoteForLastStep -> #{emoteId} for #{games[gameId].session.getLastStep()?.action?.getLogName()}".cyan
if emoteId?
# clear any waiting emote timeout
ai_stopEmoteTimeouts(gameId)
# delay must be at least 1 ms to ensure current call stack completes
games[gameId].aiEmoteTimeoutId = setTimeout((()->
games[gameId].aiEmoteTimeoutId = null
#Logger.module("AI").debug "[G:#{gameId}]", "ai_showEmote -> #{emoteId}".cyan
emitGameEvent(null, gameId, {
type: EVENTS.show_emote
id: emoteId,
playerId: games[gameId].ai.getMyPlayerId()
})
), 4000.0)
###*
* Stops AI timeouts for emotes.
* @param {String} gameId
###
ai_stopEmoteTimeouts = (gameId) ->
if games[gameId].aiEmoteTimeoutId?
clearTimeout(games[gameId].aiEmoteTimeoutId)
games[gameId].aiEmoteTimeoutId = null
# endregion AI
|
[
{
"context": "Meteor.settings.myFrenchContactForm = emailTo: 'acoucou@test.com'\nemailData =\n name: 'Coucou Test'\n email: '",
"end": 64,
"score": 0.9999276995658875,
"start": 48,
"tag": "EMAIL",
"value": "acoucou@test.com"
},
{
"context": "mailTo: 'acoucou@test.com'\nemailDat... | contact-form-tests.coffee | JustinRvt/Meteor-French-Contact-Form | 0 | Meteor.settings.myFrenchContactForm = emailTo: 'acoucou@test.com'
emailData =
name: 'Coucou Test'
email: 'decoucou@test.com'
subject: 'Coucou sujet test'
message: 'Coucou message test'
dataSent = null
# Email sending stub
Email = send: (data) ->
dataSent = data
return
Tinytest.add 'Schema', (test) ->
test.instanceOf Schema, Object
return
Tinytest.add 'Schema - myFrenchContactForm', (test) ->
test.instanceOf Schema.myFrenchContactForm, SimpleSchema
return
Tinytest.add 'Schema - myFrenchContactForm - name', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.name, Object
return
Tinytest.add 'Schema - myFrenchContactForm - email', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.email, Object
return
Tinytest.add 'Schema - myFrenchContactForm - subject', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.subject, Object
return
Tinytest.add 'Schema - myFrenchContactForm - message', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.message, Object
return
if Meteor.isServer
Tinytest.add 'Meteor - methods - sendEmail - exists', (test) ->
test.include Meteor.server.method_handlers, 'sendEmail'
return
Tinytest.add 'Meteor - methods - sendEmail - fails on malformed data', (test) ->
test.throws ->
Meteor.call 'sendEmail', something: 'wrong'
return
return
Tinytest.add 'Meteor - methods - sendEmail - sends email successfully', (test) ->
dataSent = null
Meteor.call 'sendEmail', emailData
test.equal dataSent.from, emailData.email
test.equal dataSent.to, Meteor.settings.myFrenchContactForm.emailTo
test.include dataSent.text, emailData.subject
test.include dataSent.text, emailData.message
return
if Meteor.isClient
Tinytest.add 'Meteor - templates - myFrenchContactForm - has a schema helper', (test) ->
test.equal typeof Template.myFrenchContactForm.__helpers.get('myFrenchContactFormSchema'), 'function'
test.equal Template.myFrenchContactForm.__helpers.get('myFrenchContactFormSchema')(), Schema.myFrenchContactForm
return
| 58423 | Meteor.settings.myFrenchContactForm = emailTo: '<EMAIL>'
emailData =
name: '<NAME>'
email: '<EMAIL>'
subject: 'Coucou sujet test'
message: 'Coucou message test'
dataSent = null
# Email sending stub
Email = send: (data) ->
dataSent = data
return
Tinytest.add 'Schema', (test) ->
test.instanceOf Schema, Object
return
Tinytest.add 'Schema - myFrenchContactForm', (test) ->
test.instanceOf Schema.myFrenchContactForm, SimpleSchema
return
Tinytest.add 'Schema - myFrenchContactForm - name', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.name, Object
return
Tinytest.add 'Schema - myFrenchContactForm - email', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.email, Object
return
Tinytest.add 'Schema - myFrenchContactForm - subject', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.subject, Object
return
Tinytest.add 'Schema - myFrenchContactForm - message', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.message, Object
return
if Meteor.isServer
Tinytest.add 'Meteor - methods - sendEmail - exists', (test) ->
test.include Meteor.server.method_handlers, 'sendEmail'
return
Tinytest.add 'Meteor - methods - sendEmail - fails on malformed data', (test) ->
test.throws ->
Meteor.call 'sendEmail', something: 'wrong'
return
return
Tinytest.add 'Meteor - methods - sendEmail - sends email successfully', (test) ->
dataSent = null
Meteor.call 'sendEmail', emailData
test.equal dataSent.from, emailData.email
test.equal dataSent.to, Meteor.settings.myFrenchContactForm.emailTo
test.include dataSent.text, emailData.subject
test.include dataSent.text, emailData.message
return
if Meteor.isClient
Tinytest.add 'Meteor - templates - myFrenchContactForm - has a schema helper', (test) ->
test.equal typeof Template.myFrenchContactForm.__helpers.get('myFrenchContactFormSchema'), 'function'
test.equal Template.myFrenchContactForm.__helpers.get('myFrenchContactFormSchema')(), Schema.myFrenchContactForm
return
| true | Meteor.settings.myFrenchContactForm = emailTo: 'PI:EMAIL:<EMAIL>END_PI'
emailData =
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
subject: 'Coucou sujet test'
message: 'Coucou message test'
dataSent = null
# Email sending stub
Email = send: (data) ->
dataSent = data
return
Tinytest.add 'Schema', (test) ->
test.instanceOf Schema, Object
return
Tinytest.add 'Schema - myFrenchContactForm', (test) ->
test.instanceOf Schema.myFrenchContactForm, SimpleSchema
return
Tinytest.add 'Schema - myFrenchContactForm - name', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.name, Object
return
Tinytest.add 'Schema - myFrenchContactForm - email', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.email, Object
return
Tinytest.add 'Schema - myFrenchContactForm - subject', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.subject, Object
return
Tinytest.add 'Schema - myFrenchContactForm - message', (test) ->
test.instanceOf Schema.myFrenchContactForm._schema.message, Object
return
if Meteor.isServer
Tinytest.add 'Meteor - methods - sendEmail - exists', (test) ->
test.include Meteor.server.method_handlers, 'sendEmail'
return
Tinytest.add 'Meteor - methods - sendEmail - fails on malformed data', (test) ->
test.throws ->
Meteor.call 'sendEmail', something: 'wrong'
return
return
Tinytest.add 'Meteor - methods - sendEmail - sends email successfully', (test) ->
dataSent = null
Meteor.call 'sendEmail', emailData
test.equal dataSent.from, emailData.email
test.equal dataSent.to, Meteor.settings.myFrenchContactForm.emailTo
test.include dataSent.text, emailData.subject
test.include dataSent.text, emailData.message
return
if Meteor.isClient
Tinytest.add 'Meteor - templates - myFrenchContactForm - has a schema helper', (test) ->
test.equal typeof Template.myFrenchContactForm.__helpers.get('myFrenchContactFormSchema'), 'function'
test.equal Template.myFrenchContactForm.__helpers.get('myFrenchContactFormSchema')(), Schema.myFrenchContactForm
return
|
[
{
"context": "app-id-key',\n secret: 'secret-token', name: 'Example App',\n origin: 'https://example.app.com')\n\n des",
"end": 196,
"score": 0.6803656220436096,
"start": 185,
"tag": "NAME",
"value": "Example App"
},
{
"context": "ers, and - _', ->\n expect(App.isVali... | test/app_test.coffee | jjzhang166/w3gram-server | 0 | App = W3gramServer.AppList.App
describe 'App', ->
beforeEach ->
@app = new App(
id: 42, key: 'news-app-key', idKey: 'news-app-id-key',
secret: 'secret-token', name: 'Example App',
origin: 'https://example.app.com')
describe '.isValidDeviceId', ->
it 'rejects long device IDs', ->
deviceId = (new Array(66)).join 'a'
expect(deviceId.length).to.equal 65
expect(App.isValidDeviceId(deviceId)).to.equal false
it 'rejects empty device IDs', ->
expect(App.isValidDeviceId('')).to.equal false
it 'rejects device IDs with invalid characters', ->
expect(App.isValidDeviceId('invalid deviceid')).to.equal false
expect(App.isValidDeviceId('invalid@deviceid')).to.equal false
expect(App.isValidDeviceId('invalid.deviceid')).to.equal false
expect(App.isValidDeviceId('invalid+deviceid')).to.equal false
it 'accepts 64-byte IDs', ->
deviceId = (new Array(65)).join 'a'
expect(deviceId.length).to.equal 64
expect(App.isValidDeviceId(deviceId)).to.equal true
it 'accepts IDs with digits, letters, and - _', ->
expect(App.isValidDeviceId('0129abczABCZ-_')).to.equal true
describe '.isValidAppKey', ->
it 'rejects long app keys', ->
appKey = (new Array(26)).join 'a'
expect(appKey.length).to.equal 25
expect(App.isValidAppKey(appKey)).to.equal false
it 'rejects empty app keys', ->
expect(App.isValidAppKey('')).to.equal false
it 'rejects app keys with invalid characters', ->
expect(App.isValidAppKey('invalid appkey')).to.equal false
expect(App.isValidAppKey('invalid@appkey')).to.equal false
expect(App.isValidAppKey('invalid.appkey')).to.equal false
expect(App.isValidAppKey('invalid+appkey')).to.equal false
it 'accepts 24-byte keys', ->
appKey = (new Array(25)).join 'a'
expect(appKey.length).to.equal 24
expect(App.isValidAppKey(appKey)).to.equal true
it 'accepts keys with digits, letters, and - _', ->
expect(App.isValidAppKey('0129abczABCZ-_')).to.equal true
describe '.isValidAppSecret', ->
it 'rejects long app secrets', ->
appSecret = (new Array(50)).join 'a'
expect(appSecret.length).to.equal 49
expect(App.isValidAppSecret(appSecret)).to.equal false
it 'rejects empty app secrets', ->
expect(App.isValidAppSecret('')).to.equal false
it 'rejects app secrets with invalid characters', ->
expect(App.isValidAppSecret('invalid appsecret')).to.equal false
expect(App.isValidAppSecret('invalid@appsecret')).to.equal false
expect(App.isValidAppSecret('invalid.appsecret')).to.equal false
expect(App.isValidAppSecret('invalid+appsecret')).to.equal false
it 'accepts 48-byte secrets', ->
appSecret = (new Array(49)).join 'a'
expect(appSecret.length).to.equal 48
expect(App.isValidAppSecret(appSecret)).to.equal true
it 'accepts secrets with digits, letters, and - _', ->
expect(App.isValidAppSecret('0129abczABCZ-_')).to.equal true
describe '._hmac', ->
it 'works on the RFC 4231 test case 2', ->
expect(App._hmac('Jefe', 'what do ya want for nothing?')).to.equal(
'W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM')
describe '#acceptsOrigin', ->
describe 'when set', ->
it 'returns true for null origin', ->
expect(@app.acceptsOrigin(null)).to.equal true
it 'returns true when the origin matches', ->
expect(@app.acceptsOrigin('https://example.app.com')).to.equal true
it 'returns false for a port mismatch', ->
expect(@app.acceptsOrigin('https://example.app.com:8443')).to.equal false
it 'returns false for a protocol mismatch', ->
expect(@app.acceptsOrigin('http://example.app.com')).to.equal false
it 'returns false for a host mismatch', ->
expect(@app.acceptsOrigin('http://another.app.com')).to.equal false
describe 'when set to *', ->
beforeEach ->
@app.origin = '*'
it 'returns true for null origin', ->
expect(@app.acceptsOrigin(null)).to.equal true
it 'returns true for an https origin', ->
expect(@app.acceptsOrigin('https://some.app.com')).to.equal true
it 'returns true for an https+port origin', ->
expect(@app.acceptsOrigin('https://some.app.com:8443')).to.equal true
it 'returns true for an http origin', ->
expect(@app.acceptsOrigin('http://some.app.com')).to.equal true
it 'returns true for a file origin', ->
expect(@app.acceptsOrigin('file:null')).to.equal true
describe '#token', ->
it 'returns null for invalid device IDs', ->
expect(@app.token('invalid device')).to.equal null
it 'works on the documentation example', ->
expect(@app.token('tablet-device-id')).to.equal(
'DtzV3N04Ao7eJb-H09CAk0GxgREOlOvAEAbBc4H4HAQ')
describe '#receiverIdHmac', ->
it 'returns null for invalid device IDs', ->
expect(@app.receiverIdHmac('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|receiver|42|tablet-device-id'
expect(@app.receiverIdHmac('tablet-device-id')).to.equal hmac
describe '#receiverId', ->
it 'returns null for invalid device IDs', ->
expect(@app.receiverId('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|receiver|42|tablet-device-id'
expect(@app.receiverId('tablet-device-id')).to.equal(
"42.tablet-device-id.#{hmac}")
describe '#listenerIdHmac', ->
it 'returns null for invalid device IDs', ->
expect(@app.listenerIdHmac('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|listener|42|tablet-device-id'
expect(@app.listenerIdHmac('tablet-device-id')).to.equal hmac
describe '#listenerId', ->
it 'returns null for invalid device IDs', ->
expect(@app.listenerId('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|listener|42|tablet-device-id'
expect(@app.listenerId('tablet-device-id')).to.equal(
"42.tablet-device-id.#{hmac}")
describe '#hashKey', ->
it 'returns null for invalid device IDs', ->
expect(@app.hashKey('invalid device')).to.equal null
it 'works on the documentation example', ->
expect(@app.hashKey('tablet-device-id')).to.equal '42_tablet-device-id'
describe '#json', ->
it 'includes the public fields', ->
json = @app.json()
expect(json).to.be.an 'object'
expect(json.key).to.equal @app.key
expect(json.secret).to.equal @app.secret
expect(json.origin).to.equal @app.origin
expect(json.name).to.equal @app.name
it 'does not include the ID key', ->
json = @app.json()
expect(json).to.be.an 'object'
expect(json).not.to.have.property 'idKey'
for property of json
expect(json[property]).not.to.equal @app.idKey
| 178310 | App = W3gramServer.AppList.App
describe 'App', ->
beforeEach ->
@app = new App(
id: 42, key: 'news-app-key', idKey: 'news-app-id-key',
secret: 'secret-token', name: '<NAME>',
origin: 'https://example.app.com')
describe '.isValidDeviceId', ->
it 'rejects long device IDs', ->
deviceId = (new Array(66)).join 'a'
expect(deviceId.length).to.equal 65
expect(App.isValidDeviceId(deviceId)).to.equal false
it 'rejects empty device IDs', ->
expect(App.isValidDeviceId('')).to.equal false
it 'rejects device IDs with invalid characters', ->
expect(App.isValidDeviceId('invalid deviceid')).to.equal false
expect(App.isValidDeviceId('invalid@deviceid')).to.equal false
expect(App.isValidDeviceId('invalid.deviceid')).to.equal false
expect(App.isValidDeviceId('invalid+deviceid')).to.equal false
it 'accepts 64-byte IDs', ->
deviceId = (new Array(65)).join 'a'
expect(deviceId.length).to.equal 64
expect(App.isValidDeviceId(deviceId)).to.equal true
it 'accepts IDs with digits, letters, and - _', ->
expect(App.isValidDeviceId('0129abczABCZ-_')).to.equal true
describe '.isValidAppKey', ->
it 'rejects long app keys', ->
appKey = (new Array(26)).join 'a'
expect(appKey.length).to.equal 25
expect(App.isValidAppKey(appKey)).to.equal false
it 'rejects empty app keys', ->
expect(App.isValidAppKey('')).to.equal false
it 'rejects app keys with invalid characters', ->
expect(App.isValidAppKey('invalid appkey')).to.equal false
expect(App.isValidAppKey('invalid@appkey')).to.equal false
expect(App.isValidAppKey('invalid.appkey')).to.equal false
expect(App.isValidAppKey('invalid+appkey')).to.equal false
it 'accepts 24-byte keys', ->
appKey = (new Array(25)).join 'a'
expect(appKey.length).to.equal 24
expect(App.isValidAppKey(appKey)).to.equal true
it 'accepts keys with digits, letters, and - _', ->
expect(App.isValidAppKey('<KEY>')).to.equal true
describe '.isValidAppSecret', ->
it 'rejects long app secrets', ->
appSecret = (new Array(50)).join 'a'
expect(appSecret.length).to.equal 49
expect(App.isValidAppSecret(appSecret)).to.equal false
it 'rejects empty app secrets', ->
expect(App.isValidAppSecret('')).to.equal false
it 'rejects app secrets with invalid characters', ->
expect(App.isValidAppSecret('invalid appsecret')).to.equal false
expect(App.isValidAppSecret('invalid@appsecret')).to.equal false
expect(App.isValidAppSecret('invalid.appsecret')).to.equal false
expect(App.isValidAppSecret('invalid+appsecret')).to.equal false
it 'accepts 48-byte secrets', ->
appSecret = (new Array(49)).join 'a'
expect(appSecret.length).to.equal 48
expect(App.isValidAppSecret(appSecret)).to.equal true
it 'accepts secrets with digits, letters, and - _', ->
expect(App.isValidAppSecret('0129abczABCZ-_')).to.equal true
describe '._hmac', ->
it 'works on the RFC 4231 test case 2', ->
expect(App._hmac('Jefe', 'what do ya want for nothing?')).to.equal(
'W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM')
describe '#acceptsOrigin', ->
describe 'when set', ->
it 'returns true for null origin', ->
expect(@app.acceptsOrigin(null)).to.equal true
it 'returns true when the origin matches', ->
expect(@app.acceptsOrigin('https://example.app.com')).to.equal true
it 'returns false for a port mismatch', ->
expect(@app.acceptsOrigin('https://example.app.com:8443')).to.equal false
it 'returns false for a protocol mismatch', ->
expect(@app.acceptsOrigin('http://example.app.com')).to.equal false
it 'returns false for a host mismatch', ->
expect(@app.acceptsOrigin('http://another.app.com')).to.equal false
describe 'when set to *', ->
beforeEach ->
@app.origin = '*'
it 'returns true for null origin', ->
expect(@app.acceptsOrigin(null)).to.equal true
it 'returns true for an https origin', ->
expect(@app.acceptsOrigin('https://some.app.com')).to.equal true
it 'returns true for an https+port origin', ->
expect(@app.acceptsOrigin('https://some.app.com:8443')).to.equal true
it 'returns true for an http origin', ->
expect(@app.acceptsOrigin('http://some.app.com')).to.equal true
it 'returns true for a file origin', ->
expect(@app.acceptsOrigin('file:null')).to.equal true
describe '#token', ->
it 'returns null for invalid device IDs', ->
expect(@app.token('invalid device')).to.equal null
it 'works on the documentation example', ->
expect(@app.token('tablet-device-id')).to.equal(
'D<KEY>')
describe '#receiverIdHmac', ->
it 'returns null for invalid device IDs', ->
expect(@app.receiverIdHmac('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|receiver|42|tablet-device-id'
expect(@app.receiverIdHmac('tablet-device-id')).to.equal hmac
describe '#receiverId', ->
it 'returns null for invalid device IDs', ->
expect(@app.receiverId('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|receiver|42|tablet-device-id'
expect(@app.receiverId('tablet-device-id')).to.equal(
"42.tablet-device-id.#{hmac}")
describe '#listenerIdHmac', ->
it 'returns null for invalid device IDs', ->
expect(@app.listenerIdHmac('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|listener|42|tablet-device-id'
expect(@app.listenerIdHmac('tablet-device-id')).to.equal hmac
describe '#listenerId', ->
it 'returns null for invalid device IDs', ->
expect(@app.listenerId('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|listener|42|tablet-device-id'
expect(@app.listenerId('tablet-device-id')).to.equal(
"42.tablet-device-id.#{hmac}")
describe '#hashKey', ->
it 'returns null for invalid device IDs', ->
expect(@app.hashKey('invalid device')).to.equal null
it 'works on the documentation example', ->
expect(@app.hashKey('tablet-device-id')).to.equal '42_tablet-device-id'
describe '#json', ->
it 'includes the public fields', ->
json = @app.json()
expect(json).to.be.an 'object'
expect(json.key).to.equal @app.key
expect(json.secret).to.equal @app.secret
expect(json.origin).to.equal @app.origin
expect(json.name).to.equal @app.name
it 'does not include the ID key', ->
json = @app.json()
expect(json).to.be.an 'object'
expect(json).not.to.have.property 'idKey'
for property of json
expect(json[property]).not.to.equal @app.idKey
| true | App = W3gramServer.AppList.App
describe 'App', ->
beforeEach ->
@app = new App(
id: 42, key: 'news-app-key', idKey: 'news-app-id-key',
secret: 'secret-token', name: 'PI:NAME:<NAME>END_PI',
origin: 'https://example.app.com')
describe '.isValidDeviceId', ->
it 'rejects long device IDs', ->
deviceId = (new Array(66)).join 'a'
expect(deviceId.length).to.equal 65
expect(App.isValidDeviceId(deviceId)).to.equal false
it 'rejects empty device IDs', ->
expect(App.isValidDeviceId('')).to.equal false
it 'rejects device IDs with invalid characters', ->
expect(App.isValidDeviceId('invalid deviceid')).to.equal false
expect(App.isValidDeviceId('invalid@deviceid')).to.equal false
expect(App.isValidDeviceId('invalid.deviceid')).to.equal false
expect(App.isValidDeviceId('invalid+deviceid')).to.equal false
it 'accepts 64-byte IDs', ->
deviceId = (new Array(65)).join 'a'
expect(deviceId.length).to.equal 64
expect(App.isValidDeviceId(deviceId)).to.equal true
it 'accepts IDs with digits, letters, and - _', ->
expect(App.isValidDeviceId('0129abczABCZ-_')).to.equal true
describe '.isValidAppKey', ->
it 'rejects long app keys', ->
appKey = (new Array(26)).join 'a'
expect(appKey.length).to.equal 25
expect(App.isValidAppKey(appKey)).to.equal false
it 'rejects empty app keys', ->
expect(App.isValidAppKey('')).to.equal false
it 'rejects app keys with invalid characters', ->
expect(App.isValidAppKey('invalid appkey')).to.equal false
expect(App.isValidAppKey('invalid@appkey')).to.equal false
expect(App.isValidAppKey('invalid.appkey')).to.equal false
expect(App.isValidAppKey('invalid+appkey')).to.equal false
it 'accepts 24-byte keys', ->
appKey = (new Array(25)).join 'a'
expect(appKey.length).to.equal 24
expect(App.isValidAppKey(appKey)).to.equal true
it 'accepts keys with digits, letters, and - _', ->
expect(App.isValidAppKey('PI:KEY:<KEY>END_PI')).to.equal true
describe '.isValidAppSecret', ->
it 'rejects long app secrets', ->
appSecret = (new Array(50)).join 'a'
expect(appSecret.length).to.equal 49
expect(App.isValidAppSecret(appSecret)).to.equal false
it 'rejects empty app secrets', ->
expect(App.isValidAppSecret('')).to.equal false
it 'rejects app secrets with invalid characters', ->
expect(App.isValidAppSecret('invalid appsecret')).to.equal false
expect(App.isValidAppSecret('invalid@appsecret')).to.equal false
expect(App.isValidAppSecret('invalid.appsecret')).to.equal false
expect(App.isValidAppSecret('invalid+appsecret')).to.equal false
it 'accepts 48-byte secrets', ->
appSecret = (new Array(49)).join 'a'
expect(appSecret.length).to.equal 48
expect(App.isValidAppSecret(appSecret)).to.equal true
it 'accepts secrets with digits, letters, and - _', ->
expect(App.isValidAppSecret('0129abczABCZ-_')).to.equal true
describe '._hmac', ->
it 'works on the RFC 4231 test case 2', ->
expect(App._hmac('Jefe', 'what do ya want for nothing?')).to.equal(
'W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM')
describe '#acceptsOrigin', ->
describe 'when set', ->
it 'returns true for null origin', ->
expect(@app.acceptsOrigin(null)).to.equal true
it 'returns true when the origin matches', ->
expect(@app.acceptsOrigin('https://example.app.com')).to.equal true
it 'returns false for a port mismatch', ->
expect(@app.acceptsOrigin('https://example.app.com:8443')).to.equal false
it 'returns false for a protocol mismatch', ->
expect(@app.acceptsOrigin('http://example.app.com')).to.equal false
it 'returns false for a host mismatch', ->
expect(@app.acceptsOrigin('http://another.app.com')).to.equal false
describe 'when set to *', ->
beforeEach ->
@app.origin = '*'
it 'returns true for null origin', ->
expect(@app.acceptsOrigin(null)).to.equal true
it 'returns true for an https origin', ->
expect(@app.acceptsOrigin('https://some.app.com')).to.equal true
it 'returns true for an https+port origin', ->
expect(@app.acceptsOrigin('https://some.app.com:8443')).to.equal true
it 'returns true for an http origin', ->
expect(@app.acceptsOrigin('http://some.app.com')).to.equal true
it 'returns true for a file origin', ->
expect(@app.acceptsOrigin('file:null')).to.equal true
describe '#token', ->
it 'returns null for invalid device IDs', ->
expect(@app.token('invalid device')).to.equal null
it 'works on the documentation example', ->
expect(@app.token('tablet-device-id')).to.equal(
'DPI:KEY:<KEY>END_PI')
describe '#receiverIdHmac', ->
it 'returns null for invalid device IDs', ->
expect(@app.receiverIdHmac('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|receiver|42|tablet-device-id'
expect(@app.receiverIdHmac('tablet-device-id')).to.equal hmac
describe '#receiverId', ->
it 'returns null for invalid device IDs', ->
expect(@app.receiverId('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|receiver|42|tablet-device-id'
expect(@app.receiverId('tablet-device-id')).to.equal(
"42.tablet-device-id.#{hmac}")
describe '#listenerIdHmac', ->
it 'returns null for invalid device IDs', ->
expect(@app.listenerIdHmac('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|listener|42|tablet-device-id'
expect(@app.listenerIdHmac('tablet-device-id')).to.equal hmac
describe '#listenerId', ->
it 'returns null for invalid device IDs', ->
expect(@app.listenerId('invalid device')).to.equal null
it 'works on the documentation example', ->
hmac = App._hmac 'news-app-id-key',
'signed-id|listener|42|tablet-device-id'
expect(@app.listenerId('tablet-device-id')).to.equal(
"42.tablet-device-id.#{hmac}")
describe '#hashKey', ->
it 'returns null for invalid device IDs', ->
expect(@app.hashKey('invalid device')).to.equal null
it 'works on the documentation example', ->
expect(@app.hashKey('tablet-device-id')).to.equal '42_tablet-device-id'
describe '#json', ->
it 'includes the public fields', ->
json = @app.json()
expect(json).to.be.an 'object'
expect(json.key).to.equal @app.key
expect(json.secret).to.equal @app.secret
expect(json.origin).to.equal @app.origin
expect(json.name).to.equal @app.name
it 'does not include the ID key', ->
json = @app.json()
expect(json).to.be.an 'object'
expect(json).not.to.have.property 'idKey'
for property of json
expect(json[property]).not.to.equal @app.idKey
|
[
{
"context": "# grammars/tal.cson\n# Autor: JCMiguel\n# Date: 05-2019\n# References:\n# http",
"end": 34,
"score": 0.8248594403266907,
"start": 31,
"tag": "USERNAME",
"value": "JCM"
},
{
"context": "# grammars/tal.cson\n# Autor: JCMiguel\n# Date: 05-2019\n# References... | grammars/tal.cson | JCMiguel/atom-language-tal | 0 | # grammars/tal.cson
# Autor: JCMiguel
# Date: 05-2019
# References:
# https://github.com/atom/language-c/blob/master/grammars/c.cson
# https://macromates.com/manual/en/language_grammars
scopeName: 'source.tal'
name: 'TAL'
fileTypes: [ 'tal' ]
limitLineLength: false
patterns: [
{
## COMENTARIO CON !
begin: '!'
end: '(!|$)'
name: 'comment.block'
}
{
## COMENTARIO CON --
name: 'comment.line'
match: '--.*$'
}
{
## STRING LITERAL ENTRE COMILLAS "hOLI"
match: '(\\")(.*?)(\\")'
captures:
1:
name: 'string.quoted.double'
2:
name: 'string.quoted.double'
3:
name: 'string.quoted.double'
}
{
## OPERADORES VARIOS
name: 'entity.name.type' #Uso esto sólo por el color
match: "(?i:(:=|=:|':='|'=:'|<<|>>|'<<'|'>>'|\\+|-|\\/|\\*|<|>|=|<=|>=|<>|'<'|'>'|'='|'<='|'>='|'<>'|\\slor\\s|\\sland\\s|\\snot\\s|\\sxor\\s|\\sor\\s|\\sand\\s))"
}
{
## TIPOS DE VARIABLES
name: 'support.type'
match: '(?i:\\b(string|int|unsigned|struct|fixed|real|literal|label|block|name)\\b)'
}
{
## ESTA REGLA ESTÁ PARA EVITAR LA COLORACIÓN DE TEXTO^TIPOVARIABLE
name: 'support.other'
match: '(?i:\\^(string|int|unsigned|struct|fixed|real|literal|label|block|name)\\b)'
}
{
## DIRECCIONAMIENTO E INDIRECCIONAMIENTO @PTR
name: 'entity.name.tag'
match: '(\\@((\\w*\\^\\w*\\^\\w*)|(\\w*\\^\\w*)|(\\w*)))'
}
{
## KEYWORDS PROC, BEGIN Y END
name: 'support.function'
match: '(?i:\\b(proc|subproc|begin|end)\\b)'
}
{
## ATRIBUTOS DE PROC
name: 'entity.name.tag'
match: '(?i:\\b(main|variable|extensible|forward|external)\\b)'
}
{
## USO DE REGISTROS DE OPTIMIZACIÓN
name: 'entity.name.tag'
match: '(?i:\\b(use|drop)\\b)'
}
{
## SENTENCIAS DE CONTROL
name: 'keyword.control'
match: '(?i:\\b(if|then|while|for|else|case|otherwise|to|do|call|assert|bytes|words)\\b)'
}
{
## DIRECTIVAS DE COMPILACION PARTE I
begin: '(?i:(\\?(source|section|list|nolist|nocode|block)(,|\\s|,\\s)))'
end: '(\\s|$)'
name: 'entity.name.section'
}
{
## DIRECTIVAS DE COMPILACION PARTE II
begin: '(?i:(\\?(page|map|assertion)))'
end: '$'
name: 'entity.name.section'
}
{
## DECLARACIÓN EXTENDIDA
name: 'keyword.control'
match: '(?i:\\s(\\.ext))'
}
{
## NUMEROS REAL (FLOTANTES)
name: 'constant.numeric'
match: '(?i:((\\d+\\.\\d+)|(\\d+))e(\\d+|.\\d+))'
}
{
## NUMEROS INT(32) #BINARIO
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%b)[0-1]+d)'
}
{
## NUMEROS INT(16) #BINARIO
name: 'constant.numeric'
match: '(?i:(\\%b)[0-1]+)'
}
{
## NUMEROS INT(32) #HEXADECIMAL
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%h)[0-9a-fA-F]+\\%d)'
}
{
## NUMEROS INT(16) #HEXADECIMAL
name: 'constant.numeric'
match: '(?i:(\\%h)[0-9a-fA-F]+)'
}
{
## NUMEROS INT(32) #OCTAL
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%)[0-7]+d)'
}
{
## NUMEROS INT(16) #OCTAL
name: 'constant.numeric'
match: '(?i:(\\%)[0-7]+)'
}
{
## NUMEROS FIXED
name: 'constant.numeric'
match: '(?i:(\\d+f)|(\\d+\\.\\d+f))'
}
{
## NUMEROS INT(32) #DECIMAL
name: 'entity.name.tag' #Uso esto sólo por el color
match: '(?i:\\b\\d+d)'
}
{
## NUMEROS INT(16) #DECIMAL
name: 'keyword.control' #Uso esto sólo por el color
match: '(\\b\\d+)'
}
{
## IDENTIFICADORES DE FUNCIONES
match: '((\\w*)|(\\w*\\^\\w*)|(\\w*\\^\\w*\\^\\w*))(\\(|\\s\\()'
captures:
1:
name: 'string.quoted.double' #Uso esto sólo por el color
}
{
## FUNCIONES ESTANDAR
match: '(\\$\\w*)(\\(|\\s)'
captures:
1:
name: 'support.function'
}
]
| 95163 | # grammars/tal.cson
# Autor: JCM<NAME>
# Date: 05-2019
# References:
# https://github.com/atom/language-c/blob/master/grammars/c.cson
# https://macromates.com/manual/en/language_grammars
scopeName: 'source.tal'
name: 'TAL'
fileTypes: [ 'tal' ]
limitLineLength: false
patterns: [
{
## COMENTARIO CON !
begin: '!'
end: '(!|$)'
name: 'comment.block'
}
{
## COMENTARIO CON --
name: 'comment.line'
match: '--.*$'
}
{
## STRING LITERAL ENTRE COMILLAS "hOLI"
match: '(\\")(.*?)(\\")'
captures:
1:
name: 'string.quoted.double'
2:
name: 'string.quoted.double'
3:
name: 'string.quoted.double'
}
{
## OPERADORES VARIOS
name: 'entity.name.type' #Uso esto sólo por el color
match: "(?i:(:=|=:|':='|'=:'|<<|>>|'<<'|'>>'|\\+|-|\\/|\\*|<|>|=|<=|>=|<>|'<'|'>'|'='|'<='|'>='|'<>'|\\slor\\s|\\sland\\s|\\snot\\s|\\sxor\\s|\\sor\\s|\\sand\\s))"
}
{
## TIPOS DE VARIABLES
name: 'support.type'
match: '(?i:\\b(string|int|unsigned|struct|fixed|real|literal|label|block|name)\\b)'
}
{
## ESTA REGLA ESTÁ PARA EVITAR LA COLORACIÓN DE TEXTO^TIPOVARIABLE
name: 'support.other'
match: '(?i:\\^(string|int|unsigned|struct|fixed|real|literal|label|block|name)\\b)'
}
{
## DIRECCIONAMIENTO E INDIRECCIONAMIENTO @PTR
name: 'entity.name.tag'
match: '(\\@((\\w*\\^\\w*\\^\\w*)|(\\w*\\^\\w*)|(\\w*)))'
}
{
## KEYWORDS PROC, BEGIN Y END
name: 'support.function'
match: '(?i:\\b(proc|subproc|begin|end)\\b)'
}
{
## ATRIBUTOS DE PROC
name: 'entity.name.tag'
match: '(?i:\\b(main|variable|extensible|forward|external)\\b)'
}
{
## USO DE REGISTROS DE OPTIMIZACIÓN
name: 'entity.name.tag'
match: '(?i:\\b(use|drop)\\b)'
}
{
## SENTENCIAS DE CONTROL
name: 'keyword.control'
match: '(?i:\\b(if|then|while|for|else|case|otherwise|to|do|call|assert|bytes|words)\\b)'
}
{
## DIRECTIVAS DE COMPILACION PARTE I
begin: '(?i:(\\?(source|section|list|nolist|nocode|block)(,|\\s|,\\s)))'
end: '(\\s|$)'
name: 'entity.name.section'
}
{
## DIRECTIVAS DE COMPILACION PARTE II
begin: '(?i:(\\?(page|map|assertion)))'
end: '$'
name: 'entity.name.section'
}
{
## DECLARACIÓN EXTENDIDA
name: 'keyword.control'
match: '(?i:\\s(\\.ext))'
}
{
## NUMEROS REAL (FLOTANTES)
name: 'constant.numeric'
match: '(?i:((\\d+\\.\\d+)|(\\d+))e(\\d+|.\\d+))'
}
{
## NUMEROS INT(32) #BINARIO
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%b)[0-1]+d)'
}
{
## NUMEROS INT(16) #BINARIO
name: 'constant.numeric'
match: '(?i:(\\%b)[0-1]+)'
}
{
## NUMEROS INT(32) #HEXADECIMAL
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%h)[0-9a-fA-F]+\\%d)'
}
{
## NUMEROS INT(16) #HEXADECIMAL
name: 'constant.numeric'
match: '(?i:(\\%h)[0-9a-fA-F]+)'
}
{
## NUMEROS INT(32) #OCTAL
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%)[0-7]+d)'
}
{
## NUMEROS INT(16) #OCTAL
name: 'constant.numeric'
match: '(?i:(\\%)[0-7]+)'
}
{
## NUMEROS FIXED
name: 'constant.numeric'
match: '(?i:(\\d+f)|(\\d+\\.\\d+f))'
}
{
## NUMEROS INT(32) #DECIMAL
name: 'entity.name.tag' #Uso esto sólo por el color
match: '(?i:\\b\\d+d)'
}
{
## NUMEROS INT(16) #DECIMAL
name: 'keyword.control' #Uso esto sólo por el color
match: '(\\b\\d+)'
}
{
## IDENTIFICADORES DE FUNCIONES
match: '((\\w*)|(\\w*\\^\\w*)|(\\w*\\^\\w*\\^\\w*))(\\(|\\s\\()'
captures:
1:
name: 'string.quoted.double' #Uso esto sólo por el color
}
{
## FUNCIONES ESTANDAR
match: '(\\$\\w*)(\\(|\\s)'
captures:
1:
name: 'support.function'
}
]
| true | # grammars/tal.cson
# Autor: JCMPI:NAME:<NAME>END_PI
# Date: 05-2019
# References:
# https://github.com/atom/language-c/blob/master/grammars/c.cson
# https://macromates.com/manual/en/language_grammars
scopeName: 'source.tal'
name: 'TAL'
fileTypes: [ 'tal' ]
limitLineLength: false
patterns: [
{
## COMENTARIO CON !
begin: '!'
end: '(!|$)'
name: 'comment.block'
}
{
## COMENTARIO CON --
name: 'comment.line'
match: '--.*$'
}
{
## STRING LITERAL ENTRE COMILLAS "hOLI"
match: '(\\")(.*?)(\\")'
captures:
1:
name: 'string.quoted.double'
2:
name: 'string.quoted.double'
3:
name: 'string.quoted.double'
}
{
## OPERADORES VARIOS
name: 'entity.name.type' #Uso esto sólo por el color
match: "(?i:(:=|=:|':='|'=:'|<<|>>|'<<'|'>>'|\\+|-|\\/|\\*|<|>|=|<=|>=|<>|'<'|'>'|'='|'<='|'>='|'<>'|\\slor\\s|\\sland\\s|\\snot\\s|\\sxor\\s|\\sor\\s|\\sand\\s))"
}
{
## TIPOS DE VARIABLES
name: 'support.type'
match: '(?i:\\b(string|int|unsigned|struct|fixed|real|literal|label|block|name)\\b)'
}
{
## ESTA REGLA ESTÁ PARA EVITAR LA COLORACIÓN DE TEXTO^TIPOVARIABLE
name: 'support.other'
match: '(?i:\\^(string|int|unsigned|struct|fixed|real|literal|label|block|name)\\b)'
}
{
## DIRECCIONAMIENTO E INDIRECCIONAMIENTO @PTR
name: 'entity.name.tag'
match: '(\\@((\\w*\\^\\w*\\^\\w*)|(\\w*\\^\\w*)|(\\w*)))'
}
{
## KEYWORDS PROC, BEGIN Y END
name: 'support.function'
match: '(?i:\\b(proc|subproc|begin|end)\\b)'
}
{
## ATRIBUTOS DE PROC
name: 'entity.name.tag'
match: '(?i:\\b(main|variable|extensible|forward|external)\\b)'
}
{
## USO DE REGISTROS DE OPTIMIZACIÓN
name: 'entity.name.tag'
match: '(?i:\\b(use|drop)\\b)'
}
{
## SENTENCIAS DE CONTROL
name: 'keyword.control'
match: '(?i:\\b(if|then|while|for|else|case|otherwise|to|do|call|assert|bytes|words)\\b)'
}
{
## DIRECTIVAS DE COMPILACION PARTE I
begin: '(?i:(\\?(source|section|list|nolist|nocode|block)(,|\\s|,\\s)))'
end: '(\\s|$)'
name: 'entity.name.section'
}
{
## DIRECTIVAS DE COMPILACION PARTE II
begin: '(?i:(\\?(page|map|assertion)))'
end: '$'
name: 'entity.name.section'
}
{
## DECLARACIÓN EXTENDIDA
name: 'keyword.control'
match: '(?i:\\s(\\.ext))'
}
{
## NUMEROS REAL (FLOTANTES)
name: 'constant.numeric'
match: '(?i:((\\d+\\.\\d+)|(\\d+))e(\\d+|.\\d+))'
}
{
## NUMEROS INT(32) #BINARIO
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%b)[0-1]+d)'
}
{
## NUMEROS INT(16) #BINARIO
name: 'constant.numeric'
match: '(?i:(\\%b)[0-1]+)'
}
{
## NUMEROS INT(32) #HEXADECIMAL
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%h)[0-9a-fA-F]+\\%d)'
}
{
## NUMEROS INT(16) #HEXADECIMAL
name: 'constant.numeric'
match: '(?i:(\\%h)[0-9a-fA-F]+)'
}
{
## NUMEROS INT(32) #OCTAL
name: 'entity.name.section' #Uso esto sólo por el color
match: '(?i:(\\%)[0-7]+d)'
}
{
## NUMEROS INT(16) #OCTAL
name: 'constant.numeric'
match: '(?i:(\\%)[0-7]+)'
}
{
## NUMEROS FIXED
name: 'constant.numeric'
match: '(?i:(\\d+f)|(\\d+\\.\\d+f))'
}
{
## NUMEROS INT(32) #DECIMAL
name: 'entity.name.tag' #Uso esto sólo por el color
match: '(?i:\\b\\d+d)'
}
{
## NUMEROS INT(16) #DECIMAL
name: 'keyword.control' #Uso esto sólo por el color
match: '(\\b\\d+)'
}
{
## IDENTIFICADORES DE FUNCIONES
match: '((\\w*)|(\\w*\\^\\w*)|(\\w*\\^\\w*\\^\\w*))(\\(|\\s\\()'
captures:
1:
name: 'string.quoted.double' #Uso esto sólo por el color
}
{
## FUNCIONES ESTANDAR
match: '(\\$\\w*)(\\(|\\s)'
captures:
1:
name: 'support.function'
}
]
|
[
{
"context": "# quantize.coffee, Copyright 2012 Shao-Chung Chen.\n# Licensed under the MIT license (http://www.ope",
"end": 49,
"score": 0.9998567700386047,
"start": 34,
"tag": "NAME",
"value": "Shao-Chung Chen"
},
{
"context": "rt (http://gist.github.com/1104622)\n# developed by Nic... | quantize.coffee | npenin/ColorTunes | 1 | # quantize.coffee, Copyright 2012 Shao-Chung Chen.
# Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
# Basic CoffeeScript port of the (MMCQ) Modified Media Cut Quantization
# algorithm from the Leptonica library (http://www.leptonica.com/).
# Return a color map you can use to map original pixels to the reduced palette.
#
# Rewritten from the JavaScript port (http://gist.github.com/1104622)
# developed by Nick Rabinowitz under the MIT license.
# example (pixels are represented in an array of [R,G,B] arrays)
#
# myPixels = [[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207]]
# maxColors = 4
#
# cmap = MMCQ.quantize myPixels, maxColors
# newPalette = cmap.palette()
# newPixels = myPixels.map (p) -> cmap.map(p)
class PriorityQueue
constructor: (@comparator) ->
@contents = []
@sorted = false
sort: ->
@contents.sort @comparator
@sotred = true
push: (obj) ->
@contents.push obj
@sorted = false
peek: (index = (@contents.length - 1)) ->
@sort() unless @sorted
@contents[index]
pop: ->
@sort() unless @sorted
@contents.pop()
size: ->
@contents.length
map: (func) ->
@contents.map func
class MMCQ
@sigbits = 5
@rshift = (8 - MMCQ.sigbits)
constructor: ->
@maxIterations = 1000
@fractByPopulations = 0.75
# private method
getColorIndex = (r, g, b) ->
(r << (2 * MMCQ.sigbits)) + (g << MMCQ.sigbits) + b
class ColorBox
constructor: (@r1, @r2, @g1, @g2, @b1, @b2, @histo) ->
volume: (forced) ->
@_volume = ((@r2 - @r1 + 1) * (@g2 - @g1 + 1) * (@b2 - @b1 + 1)) if !@_volume or forced
@_volume
count: (forced) ->
if !@_count_set or forced
numpix = 0
for r in [@r1..@r2] by 1
for g in [@g1..@g2] by 1
for b in [@b1..@b2] by 1
index = getColorIndex r, g, b
numpix += (@histo[index] || 0)
@_count_set = true
@_count = numpix
@_count
copy: ->
new ColorBox @r1, @r2, @g1, @g2, @b1, @b2, @histo
average: (forced) ->
if !@_average or forced
mult = (1 << (8 - MMCQ.sigbits))
total = 0; rsum = 0; gsum = 0; bsum = 0;
for r in [@r1..@r2] by 1
for g in [@g1..@g2] by 1
for b in [@b1..@b2] by 1
index = getColorIndex r, g, b
hval = (@histo[index] || 0)
total += hval
rsum += (hval * (r + 0.5) * mult)
gsum += (hval * (g + 0.5) * mult)
bsum += (hval * (b + 0.5) * mult)
if total
@_average = [~~(rsum / total), ~~(gsum / total), ~~(bsum / total)]
else
@_average = [
~~(mult * (@r1 + @r2 + 1) / 2),
~~(mult * (@g1 + @g2 + 1) / 2),
~~(mult * (@b1 + @b2 + 1) / 2),
]
@_average
contains: (pixel) ->
r = (pixel[0] >> MMCQ.rshift); g = (pixel[1] >> MMCQ.rshift); b = (pixel[2] >> MMCQ.rshift)
((@r1 <= r <= @r2) and (@g1 <= g <= @g2) and (@b1 <= b <= @b2))
class ColorMap
constructor: ->
@cboxes = new PriorityQueue (a, b) ->
va = (a.count() * a.volume()); vb = (b.count() * b.volume())
if va > vb then 1 else if va < vb then (-1) else 0
push: (cbox) ->
@cboxes.push { cbox: cbox, color: cbox.average() }
palette: ->
@cboxes.map (cbox) -> cbox.color
size: ->
@cboxes.size()
map: (color) ->
for i in [0...(@cboxes.size())] by 1
if @cboxes.peek(i).cbox.contains color
return @cboxes.peek(i).color
return @.nearest color
cboxes: ->
@cboxes
nearest: (color) ->
square = (n) -> n * n
minDist = 1e9
for i in [0...(@cboxes.size())] by 1
dist = Math.sqrt(
square(color[0] - @cboxes.peek(i).color[0]) +
square(color[1] - @cboxes.peek(i).color[1]) +
square(color[2] - @cboxes.peek(i).color[2]))
if dist < minDist
minDist = dist
retColor = @cboxes.peek(i).color
retColor
# private method
getHisto = (pixels) =>
histosize = 1 << (3 * @sigbits)
histo = new Array(histosize)
for pixel in pixels
r = (pixel[0] >> @rshift); g = (pixel[1] >> @rshift); b = (pixel[2] >> @rshift)
index = getColorIndex r, g, b
histo[index] = (histo[index] || 0) + 1
histo
# private method
cboxFromPixels = (pixels, histo) =>
rmin = 1e6; rmax = 0
gmin = 1e6; gmax = 0
bmin = 1e6; bmax = 0
for pixel in pixels
r = (pixel[0] >> @rshift); g = (pixel[1] >> @rshift); b = (pixel[2] >> @rshift)
if r < rmin then rmin = r else if r > rmax then rmax = r
if g < gmin then gmin = g else if g > gmax then gmax = g
if b < bmin then bmin = b else if b > bmax then bmax = b
new ColorBox rmin, rmax, gmin, gmax, bmin, bmax, histo
# private method
medianCutApply = (histo, cbox) ->
return unless cbox.count()
return [cbox.copy()] if cbox.count() is 1
rw = (cbox.r2 - cbox.r1 + 1)
gw = (cbox.g2 - cbox.g1 + 1)
bw = (cbox.b2 - cbox.b1 + 1)
maxw = Math.max rw, gw, bw
total = 0; partialsum = []; lookaheadsum = []
if maxw is rw
for r in [(cbox.r1)..(cbox.r2)] by 1
sum = 0
for g in [(cbox.g1)..(cbox.g2)] by 1
for b in [(cbox.b1)..(cbox.b2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[r] = total
else if maxw is gw
for g in [(cbox.g1)..(cbox.g2)] by 1
sum = 0
for r in [(cbox.r1)..(cbox.r2)] by 1
for b in [(cbox.b1)..(cbox.b2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[g] = total
else # maxw is bw
for b in [(cbox.b1)..(cbox.b2)] by 1
sum = 0
for r in [(cbox.r1)..(cbox.r2)] by 1
for g in [(cbox.g1)..(cbox.g2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[b] = total
partialsum.forEach (d, i) ->
lookaheadsum[i] = (total - d)
doCut = (color) ->
dim1 = (color + '1'); dim2 = (color + '2')
for i in [(cbox[dim1])..(cbox[dim2])] by 1
if partialsum[i] > (total / 2)
cbox1 = cbox.copy(); cbox2 = cbox.copy()
left = (i - cbox[dim1]); right = (cbox[dim2] - i)
if left <= right
d2 = Math.min (cbox[dim2] - 1), ~~(i + right / 2)
else
d2 = Math.max (cbox[dim1]), ~~(i - 1 - left / 2)
# avoid 0-count boxes
d2++ while !partialsum[d2]
count2 = lookaheadsum[d2]
count2 = lookaheadsum[--d2] while !count2 and partialsum[(d2 - 1)]
# set dimensions
cbox1[dim2] = d2
cbox2[dim1] = (cbox1[dim2] + 1)
console.log "cbox counts: #{cbox.count()}, #{cbox1.count()}, #{cbox2.count()}"
return [cbox1, cbox2]
return doCut "r" if maxw == rw
return doCut "g" if maxw == gw
return doCut "b" if maxw == bw
quantize: (pixels, maxcolors) ->
if (!pixels.length) or (maxcolors < 2) or (maxcolors > 256)
console.log "invalid arguments"
return false
# get the beginning cbox from the colors
histo = getHisto pixels
cbox = cboxFromPixels pixels, histo
pq = new PriorityQueue (a, b) ->
va = a.count(); vb = b.count()
if va > vb then 1 else if va < vb then (-1) else 0
pq.push cbox
# inner function to do the iteration
iter = (lh, target) =>
ncolors = 1
niters = 0
while niters < @maxIterations
cbox = lh.pop()
unless cbox.count()
lh.push cbox
niters++
continue
# do the cut
cboxes = medianCutApply histo, cbox
cbox1 = cboxes[0]; cbox2 = cboxes[1]
unless cbox1
console.log "cbox1 not defined; shouldn't happen"
return;
lh.push cbox1
if cbox2 # cbox2 can be null
lh.push cbox2
ncolors++
return if (ncolors >= target)
if (niters++) > @maxIterations
console.log "infinite loop; perhaps too few pixels"
return
# first set of colors, sorted by population
iter pq, (@fractByPopulations * maxcolors)
# re-sort by the product of pixel occupancy times the size in color space
pq2 = new PriorityQueue (a, b) ->
va = (a.count() * a.volume()); vb = (b.count() * b.volume())
if va > vb then 1 else if va < vb then (-1) else 0
pq2.push pq.pop() while pq.size()
# next set - generate the median cuts using the (npix * vol) sorting
iter pq2, (maxcolors - pq2.size())
# calculate the actual colors
cmap = new ColorMap
cmap.push pq2.pop() while pq2.size()
cmap
| 59095 | # quantize.coffee, Copyright 2012 <NAME>.
# Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
# Basic CoffeeScript port of the (MMCQ) Modified Media Cut Quantization
# algorithm from the Leptonica library (http://www.leptonica.com/).
# Return a color map you can use to map original pixels to the reduced palette.
#
# Rewritten from the JavaScript port (http://gist.github.com/1104622)
# developed by <NAME> under the MIT license.
# example (pixels are represented in an array of [R,G,B] arrays)
#
# myPixels = [[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207]]
# maxColors = 4
#
# cmap = MMCQ.quantize myPixels, maxColors
# newPalette = cmap.palette()
# newPixels = myPixels.map (p) -> cmap.map(p)
class PriorityQueue
constructor: (@comparator) ->
@contents = []
@sorted = false
sort: ->
@contents.sort @comparator
@sotred = true
push: (obj) ->
@contents.push obj
@sorted = false
peek: (index = (@contents.length - 1)) ->
@sort() unless @sorted
@contents[index]
pop: ->
@sort() unless @sorted
@contents.pop()
size: ->
@contents.length
map: (func) ->
@contents.map func
class MMCQ
@sigbits = 5
@rshift = (8 - MMCQ.sigbits)
constructor: ->
@maxIterations = 1000
@fractByPopulations = 0.75
# private method
getColorIndex = (r, g, b) ->
(r << (2 * MMCQ.sigbits)) + (g << MMCQ.sigbits) + b
class ColorBox
constructor: (@r1, @r2, @g1, @g2, @b1, @b2, @histo) ->
volume: (forced) ->
@_volume = ((@r2 - @r1 + 1) * (@g2 - @g1 + 1) * (@b2 - @b1 + 1)) if !@_volume or forced
@_volume
count: (forced) ->
if !@_count_set or forced
numpix = 0
for r in [@r1..@r2] by 1
for g in [@g1..@g2] by 1
for b in [@b1..@b2] by 1
index = getColorIndex r, g, b
numpix += (@histo[index] || 0)
@_count_set = true
@_count = numpix
@_count
copy: ->
new ColorBox @r1, @r2, @g1, @g2, @b1, @b2, @histo
average: (forced) ->
if !@_average or forced
mult = (1 << (8 - MMCQ.sigbits))
total = 0; rsum = 0; gsum = 0; bsum = 0;
for r in [@r1..@r2] by 1
for g in [@g1..@g2] by 1
for b in [@b1..@b2] by 1
index = getColorIndex r, g, b
hval = (@histo[index] || 0)
total += hval
rsum += (hval * (r + 0.5) * mult)
gsum += (hval * (g + 0.5) * mult)
bsum += (hval * (b + 0.5) * mult)
if total
@_average = [~~(rsum / total), ~~(gsum / total), ~~(bsum / total)]
else
@_average = [
~~(mult * (@r1 + @r2 + 1) / 2),
~~(mult * (@g1 + @g2 + 1) / 2),
~~(mult * (@b1 + @b2 + 1) / 2),
]
@_average
contains: (pixel) ->
r = (pixel[0] >> MMCQ.rshift); g = (pixel[1] >> MMCQ.rshift); b = (pixel[2] >> MMCQ.rshift)
((@r1 <= r <= @r2) and (@g1 <= g <= @g2) and (@b1 <= b <= @b2))
class ColorMap
constructor: ->
@cboxes = new PriorityQueue (a, b) ->
va = (a.count() * a.volume()); vb = (b.count() * b.volume())
if va > vb then 1 else if va < vb then (-1) else 0
push: (cbox) ->
@cboxes.push { cbox: cbox, color: cbox.average() }
palette: ->
@cboxes.map (cbox) -> cbox.color
size: ->
@cboxes.size()
map: (color) ->
for i in [0...(@cboxes.size())] by 1
if @cboxes.peek(i).cbox.contains color
return @cboxes.peek(i).color
return @.nearest color
cboxes: ->
@cboxes
nearest: (color) ->
square = (n) -> n * n
minDist = 1e9
for i in [0...(@cboxes.size())] by 1
dist = Math.sqrt(
square(color[0] - @cboxes.peek(i).color[0]) +
square(color[1] - @cboxes.peek(i).color[1]) +
square(color[2] - @cboxes.peek(i).color[2]))
if dist < minDist
minDist = dist
retColor = @cboxes.peek(i).color
retColor
# private method
getHisto = (pixels) =>
histosize = 1 << (3 * @sigbits)
histo = new Array(histosize)
for pixel in pixels
r = (pixel[0] >> @rshift); g = (pixel[1] >> @rshift); b = (pixel[2] >> @rshift)
index = getColorIndex r, g, b
histo[index] = (histo[index] || 0) + 1
histo
# private method
cboxFromPixels = (pixels, histo) =>
rmin = 1e6; rmax = 0
gmin = 1e6; gmax = 0
bmin = 1e6; bmax = 0
for pixel in pixels
r = (pixel[0] >> @rshift); g = (pixel[1] >> @rshift); b = (pixel[2] >> @rshift)
if r < rmin then rmin = r else if r > rmax then rmax = r
if g < gmin then gmin = g else if g > gmax then gmax = g
if b < bmin then bmin = b else if b > bmax then bmax = b
new ColorBox rmin, rmax, gmin, gmax, bmin, bmax, histo
# private method
medianCutApply = (histo, cbox) ->
return unless cbox.count()
return [cbox.copy()] if cbox.count() is 1
rw = (cbox.r2 - cbox.r1 + 1)
gw = (cbox.g2 - cbox.g1 + 1)
bw = (cbox.b2 - cbox.b1 + 1)
maxw = Math.max rw, gw, bw
total = 0; partialsum = []; lookaheadsum = []
if maxw is rw
for r in [(cbox.r1)..(cbox.r2)] by 1
sum = 0
for g in [(cbox.g1)..(cbox.g2)] by 1
for b in [(cbox.b1)..(cbox.b2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[r] = total
else if maxw is gw
for g in [(cbox.g1)..(cbox.g2)] by 1
sum = 0
for r in [(cbox.r1)..(cbox.r2)] by 1
for b in [(cbox.b1)..(cbox.b2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[g] = total
else # maxw is bw
for b in [(cbox.b1)..(cbox.b2)] by 1
sum = 0
for r in [(cbox.r1)..(cbox.r2)] by 1
for g in [(cbox.g1)..(cbox.g2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[b] = total
partialsum.forEach (d, i) ->
lookaheadsum[i] = (total - d)
doCut = (color) ->
dim1 = (color + '1'); dim2 = (color + '2')
for i in [(cbox[dim1])..(cbox[dim2])] by 1
if partialsum[i] > (total / 2)
cbox1 = cbox.copy(); cbox2 = cbox.copy()
left = (i - cbox[dim1]); right = (cbox[dim2] - i)
if left <= right
d2 = Math.min (cbox[dim2] - 1), ~~(i + right / 2)
else
d2 = Math.max (cbox[dim1]), ~~(i - 1 - left / 2)
# avoid 0-count boxes
d2++ while !partialsum[d2]
count2 = lookaheadsum[d2]
count2 = lookaheadsum[--d2] while !count2 and partialsum[(d2 - 1)]
# set dimensions
cbox1[dim2] = d2
cbox2[dim1] = (cbox1[dim2] + 1)
console.log "cbox counts: #{cbox.count()}, #{cbox1.count()}, #{cbox2.count()}"
return [cbox1, cbox2]
return doCut "r" if maxw == rw
return doCut "g" if maxw == gw
return doCut "b" if maxw == bw
quantize: (pixels, maxcolors) ->
if (!pixels.length) or (maxcolors < 2) or (maxcolors > 256)
console.log "invalid arguments"
return false
# get the beginning cbox from the colors
histo = getHisto pixels
cbox = cboxFromPixels pixels, histo
pq = new PriorityQueue (a, b) ->
va = a.count(); vb = b.count()
if va > vb then 1 else if va < vb then (-1) else 0
pq.push cbox
# inner function to do the iteration
iter = (lh, target) =>
ncolors = 1
niters = 0
while niters < @maxIterations
cbox = lh.pop()
unless cbox.count()
lh.push cbox
niters++
continue
# do the cut
cboxes = medianCutApply histo, cbox
cbox1 = cboxes[0]; cbox2 = cboxes[1]
unless cbox1
console.log "cbox1 not defined; shouldn't happen"
return;
lh.push cbox1
if cbox2 # cbox2 can be null
lh.push cbox2
ncolors++
return if (ncolors >= target)
if (niters++) > @maxIterations
console.log "infinite loop; perhaps too few pixels"
return
# first set of colors, sorted by population
iter pq, (@fractByPopulations * maxcolors)
# re-sort by the product of pixel occupancy times the size in color space
pq2 = new PriorityQueue (a, b) ->
va = (a.count() * a.volume()); vb = (b.count() * b.volume())
if va > vb then 1 else if va < vb then (-1) else 0
pq2.push pq.pop() while pq.size()
# next set - generate the median cuts using the (npix * vol) sorting
iter pq2, (maxcolors - pq2.size())
# calculate the actual colors
cmap = new ColorMap
cmap.push pq2.pop() while pq2.size()
cmap
| true | # quantize.coffee, Copyright 2012 PI:NAME:<NAME>END_PI.
# Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
# Basic CoffeeScript port of the (MMCQ) Modified Media Cut Quantization
# algorithm from the Leptonica library (http://www.leptonica.com/).
# Return a color map you can use to map original pixels to the reduced palette.
#
# Rewritten from the JavaScript port (http://gist.github.com/1104622)
# developed by PI:NAME:<NAME>END_PI under the MIT license.
# example (pixels are represented in an array of [R,G,B] arrays)
#
# myPixels = [[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207]]
# maxColors = 4
#
# cmap = MMCQ.quantize myPixels, maxColors
# newPalette = cmap.palette()
# newPixels = myPixels.map (p) -> cmap.map(p)
class PriorityQueue
constructor: (@comparator) ->
@contents = []
@sorted = false
sort: ->
@contents.sort @comparator
@sotred = true
push: (obj) ->
@contents.push obj
@sorted = false
peek: (index = (@contents.length - 1)) ->
@sort() unless @sorted
@contents[index]
pop: ->
@sort() unless @sorted
@contents.pop()
size: ->
@contents.length
map: (func) ->
@contents.map func
class MMCQ
@sigbits = 5
@rshift = (8 - MMCQ.sigbits)
constructor: ->
@maxIterations = 1000
@fractByPopulations = 0.75
# private method
getColorIndex = (r, g, b) ->
(r << (2 * MMCQ.sigbits)) + (g << MMCQ.sigbits) + b
class ColorBox
constructor: (@r1, @r2, @g1, @g2, @b1, @b2, @histo) ->
volume: (forced) ->
@_volume = ((@r2 - @r1 + 1) * (@g2 - @g1 + 1) * (@b2 - @b1 + 1)) if !@_volume or forced
@_volume
count: (forced) ->
if !@_count_set or forced
numpix = 0
for r in [@r1..@r2] by 1
for g in [@g1..@g2] by 1
for b in [@b1..@b2] by 1
index = getColorIndex r, g, b
numpix += (@histo[index] || 0)
@_count_set = true
@_count = numpix
@_count
copy: ->
new ColorBox @r1, @r2, @g1, @g2, @b1, @b2, @histo
average: (forced) ->
if !@_average or forced
mult = (1 << (8 - MMCQ.sigbits))
total = 0; rsum = 0; gsum = 0; bsum = 0;
for r in [@r1..@r2] by 1
for g in [@g1..@g2] by 1
for b in [@b1..@b2] by 1
index = getColorIndex r, g, b
hval = (@histo[index] || 0)
total += hval
rsum += (hval * (r + 0.5) * mult)
gsum += (hval * (g + 0.5) * mult)
bsum += (hval * (b + 0.5) * mult)
if total
@_average = [~~(rsum / total), ~~(gsum / total), ~~(bsum / total)]
else
@_average = [
~~(mult * (@r1 + @r2 + 1) / 2),
~~(mult * (@g1 + @g2 + 1) / 2),
~~(mult * (@b1 + @b2 + 1) / 2),
]
@_average
contains: (pixel) ->
r = (pixel[0] >> MMCQ.rshift); g = (pixel[1] >> MMCQ.rshift); b = (pixel[2] >> MMCQ.rshift)
((@r1 <= r <= @r2) and (@g1 <= g <= @g2) and (@b1 <= b <= @b2))
class ColorMap
constructor: ->
@cboxes = new PriorityQueue (a, b) ->
va = (a.count() * a.volume()); vb = (b.count() * b.volume())
if va > vb then 1 else if va < vb then (-1) else 0
push: (cbox) ->
@cboxes.push { cbox: cbox, color: cbox.average() }
palette: ->
@cboxes.map (cbox) -> cbox.color
size: ->
@cboxes.size()
map: (color) ->
for i in [0...(@cboxes.size())] by 1
if @cboxes.peek(i).cbox.contains color
return @cboxes.peek(i).color
return @.nearest color
cboxes: ->
@cboxes
nearest: (color) ->
square = (n) -> n * n
minDist = 1e9
for i in [0...(@cboxes.size())] by 1
dist = Math.sqrt(
square(color[0] - @cboxes.peek(i).color[0]) +
square(color[1] - @cboxes.peek(i).color[1]) +
square(color[2] - @cboxes.peek(i).color[2]))
if dist < minDist
minDist = dist
retColor = @cboxes.peek(i).color
retColor
# private method
getHisto = (pixels) =>
histosize = 1 << (3 * @sigbits)
histo = new Array(histosize)
for pixel in pixels
r = (pixel[0] >> @rshift); g = (pixel[1] >> @rshift); b = (pixel[2] >> @rshift)
index = getColorIndex r, g, b
histo[index] = (histo[index] || 0) + 1
histo
# private method
cboxFromPixels = (pixels, histo) =>
rmin = 1e6; rmax = 0
gmin = 1e6; gmax = 0
bmin = 1e6; bmax = 0
for pixel in pixels
r = (pixel[0] >> @rshift); g = (pixel[1] >> @rshift); b = (pixel[2] >> @rshift)
if r < rmin then rmin = r else if r > rmax then rmax = r
if g < gmin then gmin = g else if g > gmax then gmax = g
if b < bmin then bmin = b else if b > bmax then bmax = b
new ColorBox rmin, rmax, gmin, gmax, bmin, bmax, histo
# private method
medianCutApply = (histo, cbox) ->
return unless cbox.count()
return [cbox.copy()] if cbox.count() is 1
rw = (cbox.r2 - cbox.r1 + 1)
gw = (cbox.g2 - cbox.g1 + 1)
bw = (cbox.b2 - cbox.b1 + 1)
maxw = Math.max rw, gw, bw
total = 0; partialsum = []; lookaheadsum = []
if maxw is rw
for r in [(cbox.r1)..(cbox.r2)] by 1
sum = 0
for g in [(cbox.g1)..(cbox.g2)] by 1
for b in [(cbox.b1)..(cbox.b2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[r] = total
else if maxw is gw
for g in [(cbox.g1)..(cbox.g2)] by 1
sum = 0
for r in [(cbox.r1)..(cbox.r2)] by 1
for b in [(cbox.b1)..(cbox.b2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[g] = total
else # maxw is bw
for b in [(cbox.b1)..(cbox.b2)] by 1
sum = 0
for r in [(cbox.r1)..(cbox.r2)] by 1
for g in [(cbox.g1)..(cbox.g2)] by 1
index = getColorIndex r, g, b
sum += (histo[index] or 0)
total += sum
partialsum[b] = total
partialsum.forEach (d, i) ->
lookaheadsum[i] = (total - d)
doCut = (color) ->
dim1 = (color + '1'); dim2 = (color + '2')
for i in [(cbox[dim1])..(cbox[dim2])] by 1
if partialsum[i] > (total / 2)
cbox1 = cbox.copy(); cbox2 = cbox.copy()
left = (i - cbox[dim1]); right = (cbox[dim2] - i)
if left <= right
d2 = Math.min (cbox[dim2] - 1), ~~(i + right / 2)
else
d2 = Math.max (cbox[dim1]), ~~(i - 1 - left / 2)
# avoid 0-count boxes
d2++ while !partialsum[d2]
count2 = lookaheadsum[d2]
count2 = lookaheadsum[--d2] while !count2 and partialsum[(d2 - 1)]
# set dimensions
cbox1[dim2] = d2
cbox2[dim1] = (cbox1[dim2] + 1)
console.log "cbox counts: #{cbox.count()}, #{cbox1.count()}, #{cbox2.count()}"
return [cbox1, cbox2]
return doCut "r" if maxw == rw
return doCut "g" if maxw == gw
return doCut "b" if maxw == bw
quantize: (pixels, maxcolors) ->
if (!pixels.length) or (maxcolors < 2) or (maxcolors > 256)
console.log "invalid arguments"
return false
# get the beginning cbox from the colors
histo = getHisto pixels
cbox = cboxFromPixels pixels, histo
pq = new PriorityQueue (a, b) ->
va = a.count(); vb = b.count()
if va > vb then 1 else if va < vb then (-1) else 0
pq.push cbox
# inner function to do the iteration
iter = (lh, target) =>
ncolors = 1
niters = 0
while niters < @maxIterations
cbox = lh.pop()
unless cbox.count()
lh.push cbox
niters++
continue
# do the cut
cboxes = medianCutApply histo, cbox
cbox1 = cboxes[0]; cbox2 = cboxes[1]
unless cbox1
console.log "cbox1 not defined; shouldn't happen"
return;
lh.push cbox1
if cbox2 # cbox2 can be null
lh.push cbox2
ncolors++
return if (ncolors >= target)
if (niters++) > @maxIterations
console.log "infinite loop; perhaps too few pixels"
return
# first set of colors, sorted by population
iter pq, (@fractByPopulations * maxcolors)
# re-sort by the product of pixel occupancy times the size in color space
pq2 = new PriorityQueue (a, b) ->
va = (a.count() * a.volume()); vb = (b.count() * b.volume())
if va > vb then 1 else if va < vb then (-1) else 0
pq2.push pq.pop() while pq.size()
# next set - generate the median cuts using the (npix * vol) sorting
iter pq2, (maxcolors - pq2.size())
# calculate the actual colors
cmap = new ColorMap
cmap.push pq2.pop() while pq2.size()
cmap
|
[
{
"context": "###\ngrunt-init-node-bin\nhttps://github.com/weareinteractive/grunt-init-node-bin\n\nCopyright (c) 2013 We Are In",
"end": 59,
"score": 0.9994699358940125,
"start": 43,
"tag": "USERNAME",
"value": "weareinteractive"
},
{
"context": "nteractive/grunt-init-node-bin\n\nCop... | template.coffee | gruntjs-updater/grunt-init-node-bin | 0 | ###
grunt-init-node-bin
https://github.com/weareinteractive/grunt-init-node-bin
Copyright (c) 2013 We Are Interactive, "Cowboy" Ben Alman, contributors
Licensed under the MIT license.
###
"use strict"
path = require("path")
_s = require('underscore.string')
# Basic template description.
exports.description =
"""
Create a Node.js module with Executable, CoffeeScript, Mocha, Chai & Bumber.
"""
# Template-specific notes to be displayed before question prompts.
exports.notes =
"""
For more information about Grunt plugin best practices,
please see the docs at http://gruntjs.com/creating-plugins
"""
# Template-specific notes to be displayed after question prompts.
exports.after =
"""
You should now install project dependencies with _npm install_.
After that, you may execute project tasks with _grunt_.
For more information about installing and configuring Grunt,
please see the Getting Started guide:
http://gruntjs.com/getting-started
"""
# Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = "*"
# The actual init template.
exports.template = (grunt, init, done) ->
init.process({type: "grunt"}, [
# Prompt for these values.
init.prompt('name', (value, props, done) ->
done(null, value.replace(/^node-/, ""))
)
init.prompt("description", "The best Node.js module ever.")
init.prompt("version", "0.1.0")
init.prompt("repository")
init.prompt("homepage")
init.prompt("bugs")
init.prompt("licenses")
init.prompt("author_name")
init.prompt("author_email")
init.prompt("author_url")
init.prompt('main')
init.prompt('bin')
init.prompt("node_version", grunt.package.engines.node)
], (err, props) ->
props.keywords = []
props.npm_test = "grunt test"
props.class_name = _s.classify(props.name)
props.devDependencies = {
"chai": "~1.8.0"
"grunt-coffeelint": "0.0.7"
"grunt-contrib-coffee": "~0.7.0"
"grunt-mocha-cov": "0.0.7"
"coffee-script": "~1.6.3"
"grunt-bumper": "~1.0.1"
}
# Files to copy (and process).
files = init.filesToCopy(props)
# Add properly-named license files.
init.addLicenseFiles(files, props.licenses)
# Actually copy (and process) files.
init.copyAndProcess(files, props)
# Generate package.json file.
init.writePackageJSON("package.json", props)
# empty directories will not be copied, so we need to create them manual
grunt.file.mkdir(path.join(init.destpath(), "lib"))
# All done!
done()
) | 150272 | ###
grunt-init-node-bin
https://github.com/weareinteractive/grunt-init-node-bin
Copyright (c) 2013 <NAME>, "Cowboy" <NAME>, contributors
Licensed under the MIT license.
###
"use strict"
path = require("path")
_s = require('underscore.string')
# Basic template description.
exports.description =
"""
Create a Node.js module with Executable, CoffeeScript, Mocha, Chai & Bumber.
"""
# Template-specific notes to be displayed before question prompts.
exports.notes =
"""
For more information about Grunt plugin best practices,
please see the docs at http://gruntjs.com/creating-plugins
"""
# Template-specific notes to be displayed after question prompts.
exports.after =
"""
You should now install project dependencies with _npm install_.
After that, you may execute project tasks with _grunt_.
For more information about installing and configuring Grunt,
please see the Getting Started guide:
http://gruntjs.com/getting-started
"""
# Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = "*"
# The actual init template.
exports.template = (grunt, init, done) ->
init.process({type: "grunt"}, [
# Prompt for these values.
init.prompt('name', (value, props, done) ->
done(null, value.replace(/^node-/, ""))
)
init.prompt("description", "The best Node.js module ever.")
init.prompt("version", "0.1.0")
init.prompt("repository")
init.prompt("homepage")
init.prompt("bugs")
init.prompt("licenses")
init.prompt("author_name")
init.prompt("author_email")
init.prompt("author_url")
init.prompt('main')
init.prompt('bin')
init.prompt("node_version", grunt.package.engines.node)
], (err, props) ->
props.keywords = []
props.npm_test = "grunt test"
props.class_name = _s.classify(props.name)
props.devDependencies = {
"chai": "~1.8.0"
"grunt-coffeelint": "0.0.7"
"grunt-contrib-coffee": "~0.7.0"
"grunt-mocha-cov": "0.0.7"
"coffee-script": "~1.6.3"
"grunt-bumper": "~1.0.1"
}
# Files to copy (and process).
files = init.filesToCopy(props)
# Add properly-named license files.
init.addLicenseFiles(files, props.licenses)
# Actually copy (and process) files.
init.copyAndProcess(files, props)
# Generate package.json file.
init.writePackageJSON("package.json", props)
# empty directories will not be copied, so we need to create them manual
grunt.file.mkdir(path.join(init.destpath(), "lib"))
# All done!
done()
) | true | ###
grunt-init-node-bin
https://github.com/weareinteractive/grunt-init-node-bin
Copyright (c) 2013 PI:NAME:<NAME>END_PI, "Cowboy" PI:NAME:<NAME>END_PI, contributors
Licensed under the MIT license.
###
"use strict"
path = require("path")
_s = require('underscore.string')
# Basic template description.
exports.description =
"""
Create a Node.js module with Executable, CoffeeScript, Mocha, Chai & Bumber.
"""
# Template-specific notes to be displayed before question prompts.
exports.notes =
"""
For more information about Grunt plugin best practices,
please see the docs at http://gruntjs.com/creating-plugins
"""
# Template-specific notes to be displayed after question prompts.
exports.after =
"""
You should now install project dependencies with _npm install_.
After that, you may execute project tasks with _grunt_.
For more information about installing and configuring Grunt,
please see the Getting Started guide:
http://gruntjs.com/getting-started
"""
# Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = "*"
# The actual init template.
exports.template = (grunt, init, done) ->
init.process({type: "grunt"}, [
# Prompt for these values.
init.prompt('name', (value, props, done) ->
done(null, value.replace(/^node-/, ""))
)
init.prompt("description", "The best Node.js module ever.")
init.prompt("version", "0.1.0")
init.prompt("repository")
init.prompt("homepage")
init.prompt("bugs")
init.prompt("licenses")
init.prompt("author_name")
init.prompt("author_email")
init.prompt("author_url")
init.prompt('main')
init.prompt('bin')
init.prompt("node_version", grunt.package.engines.node)
], (err, props) ->
props.keywords = []
props.npm_test = "grunt test"
props.class_name = _s.classify(props.name)
props.devDependencies = {
"chai": "~1.8.0"
"grunt-coffeelint": "0.0.7"
"grunt-contrib-coffee": "~0.7.0"
"grunt-mocha-cov": "0.0.7"
"coffee-script": "~1.6.3"
"grunt-bumper": "~1.0.1"
}
# Files to copy (and process).
files = init.filesToCopy(props)
# Add properly-named license files.
init.addLicenseFiles(files, props.licenses)
# Actually copy (and process) files.
init.copyAndProcess(files, props)
# Generate package.json file.
init.writePackageJSON("package.json", props)
# empty directories will not be copied, so we need to create them manual
grunt.file.mkdir(path.join(init.destpath(), "lib"))
# All done!
done()
) |
[
{
"context": "^(1/3), mag(z) = 1/3 pi, mag(-z) = -2/3 pi\n\n\t4. jean-francois.debroux reports that when z=(a+i*b)/(c+i",
"end": 531,
"score": 0.5509610176086426,
"start": 529,
"tag": "NAME",
"value": "an"
},
{
"context": "/3), mag(z) = 1/3 pi, mag(-z) = -2/3 pi\n\n\t4. jean-francois... | libs/algebrite/sources/arg.coffee | bengolds/playbook | 4 | ###
Argument (angle) of complex z
z arg(z)
- ------
a 0
-a -pi See note 3 below
(-1)^a a pi
exp(a + i b) b
a b arg(a) + arg(b)
a + i b arctan(b/a)
Result by quadrant
z arg(z)
- ------
1 + i 1/4 pi
1 - i -1/4 pi
-1 + i 3/4 pi
-1 - i -3/4 pi
Notes
1. Handles mixed polar and rectangular forms, e.g. 1 + exp(i pi/3)
2. Symbols in z are assumed to be positive and real.
3. Negative direction adds -pi to angle.
Example: z = (-1)^(1/3), mag(z) = 1/3 pi, mag(-z) = -2/3 pi
4. jean-francois.debroux reports that when z=(a+i*b)/(c+i*d) then
arg(numerator(z)) - arg(denominator(z))
must be used to get the correct answer. Now the operation is
automatic.
###
Eval_arg = ->
push(cadr(p1))
Eval()
arg()
arg = ->
save()
p1 = pop()
push(p1)
numerator()
yyarg()
push(p1)
denominator()
yyarg()
subtract()
restore()
#define RE p2
#define IM p3
yyarg = ->
save()
p1 = pop()
if (isnegativenumber(p1))
if isdouble(p1) or evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
negate()
else if (car(p1) == symbol(POWER) && equaln(cadr(p1), -1))
# -1 to a power
if evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
push(caddr(p1))
multiply()
else if (car(p1) == symbol(POWER) && cadr(p1) == symbol(E))
# exponential
push(caddr(p1))
imag()
else if (car(p1) == symbol(MULTIPLY))
# product of factors
push_integer(0)
p1 = cdr(p1)
while (iscons(p1))
push(car(p1))
arg()
add()
p1 = cdr(p1)
else if (car(p1) == symbol(ADD))
# sum of terms
push(p1)
rect()
p1 = pop()
push(p1)
real()
p2 = pop()
push(p1)
imag()
p3 = pop()
if (iszero(p2))
if evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
if (isnegative(p3))
negate()
else
push(p3)
push(p2)
divide()
arctan()
if (isnegative(p2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
if (isnegative(p3))
subtract(); # quadrant 1 -> 3
else
add(); # quadrant 4 -> 2
else
# pure real
push_integer(0)
restore()
| 187882 | ###
Argument (angle) of complex z
z arg(z)
- ------
a 0
-a -pi See note 3 below
(-1)^a a pi
exp(a + i b) b
a b arg(a) + arg(b)
a + i b arctan(b/a)
Result by quadrant
z arg(z)
- ------
1 + i 1/4 pi
1 - i -1/4 pi
-1 + i 3/4 pi
-1 - i -3/4 pi
Notes
1. Handles mixed polar and rectangular forms, e.g. 1 + exp(i pi/3)
2. Symbols in z are assumed to be positive and real.
3. Negative direction adds -pi to angle.
Example: z = (-1)^(1/3), mag(z) = 1/3 pi, mag(-z) = -2/3 pi
4. je<NAME>-<NAME> reports that when z=(a+i*b)/(c+i*d) then
arg(numerator(z)) - arg(denominator(z))
must be used to get the correct answer. Now the operation is
automatic.
###
Eval_arg = ->
push(cadr(p1))
Eval()
arg()
arg = ->
save()
p1 = pop()
push(p1)
numerator()
yyarg()
push(p1)
denominator()
yyarg()
subtract()
restore()
#define RE p2
#define IM p3
yyarg = ->
save()
p1 = pop()
if (isnegativenumber(p1))
if isdouble(p1) or evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
negate()
else if (car(p1) == symbol(POWER) && equaln(cadr(p1), -1))
# -1 to a power
if evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
push(caddr(p1))
multiply()
else if (car(p1) == symbol(POWER) && cadr(p1) == symbol(E))
# exponential
push(caddr(p1))
imag()
else if (car(p1) == symbol(MULTIPLY))
# product of factors
push_integer(0)
p1 = cdr(p1)
while (iscons(p1))
push(car(p1))
arg()
add()
p1 = cdr(p1)
else if (car(p1) == symbol(ADD))
# sum of terms
push(p1)
rect()
p1 = pop()
push(p1)
real()
p2 = pop()
push(p1)
imag()
p3 = pop()
if (iszero(p2))
if evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
if (isnegative(p3))
negate()
else
push(p3)
push(p2)
divide()
arctan()
if (isnegative(p2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
if (isnegative(p3))
subtract(); # quadrant 1 -> 3
else
add(); # quadrant 4 -> 2
else
# pure real
push_integer(0)
restore()
| true | ###
Argument (angle) of complex z
z arg(z)
- ------
a 0
-a -pi See note 3 below
(-1)^a a pi
exp(a + i b) b
a b arg(a) + arg(b)
a + i b arctan(b/a)
Result by quadrant
z arg(z)
- ------
1 + i 1/4 pi
1 - i -1/4 pi
-1 + i 3/4 pi
-1 - i -3/4 pi
Notes
1. Handles mixed polar and rectangular forms, e.g. 1 + exp(i pi/3)
2. Symbols in z are assumed to be positive and real.
3. Negative direction adds -pi to angle.
Example: z = (-1)^(1/3), mag(z) = 1/3 pi, mag(-z) = -2/3 pi
4. jePI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI reports that when z=(a+i*b)/(c+i*d) then
arg(numerator(z)) - arg(denominator(z))
must be used to get the correct answer. Now the operation is
automatic.
###
Eval_arg = ->
push(cadr(p1))
Eval()
arg()
arg = ->
save()
p1 = pop()
push(p1)
numerator()
yyarg()
push(p1)
denominator()
yyarg()
subtract()
restore()
#define RE p2
#define IM p3
yyarg = ->
save()
p1 = pop()
if (isnegativenumber(p1))
if isdouble(p1) or evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
negate()
else if (car(p1) == symbol(POWER) && equaln(cadr(p1), -1))
# -1 to a power
if evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
push(caddr(p1))
multiply()
else if (car(p1) == symbol(POWER) && cadr(p1) == symbol(E))
# exponential
push(caddr(p1))
imag()
else if (car(p1) == symbol(MULTIPLY))
# product of factors
push_integer(0)
p1 = cdr(p1)
while (iscons(p1))
push(car(p1))
arg()
add()
p1 = cdr(p1)
else if (car(p1) == symbol(ADD))
# sum of terms
push(p1)
rect()
p1 = pop()
push(p1)
real()
p2 = pop()
push(p1)
imag()
p3 = pop()
if (iszero(p2))
if evaluatingAsFloats
push_double(Math.PI)
else
push(symbol(PI))
if (isnegative(p3))
negate()
else
push(p3)
push(p2)
divide()
arctan()
if (isnegative(p2))
if evaluatingAsFloats
push_double(Math.PI)
else
push_symbol(PI)
if (isnegative(p3))
subtract(); # quadrant 1 -> 3
else
add(); # quadrant 4 -> 2
else
# pure real
push_integer(0)
restore()
|
[
{
"context": "###\nsessionCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 50,
"score": 0.9996289610862732,
"start": 42,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "#\nsessionCtrl.coffee\nCopyright (C) 2014 ender xu <xuende... | src/web/cs/sessionCtrl.coffee | xuender/mindfulness | 0 | ###
sessionCtrl.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
SessionCtrl = ($scope, $http, $log, ngTableParams, $filter)->
### 会话 ###
$log.debug '会话'
$scope.remove = (d)->
# 删除
$scope.confirm('是否删除这条会话记录?', ->
$http.delete("/cs/session/#{d.id}").success((data)->
$log.debug data
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
)
$scope.$parent.name = 'session'
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ua: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/cs/session',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
if data.ok
params.total(data.count)
$defer.resolve(data.data)
else
alert(data.err)
)
)
UsersCtrl.$inject = [
'$scope'
'$http'
'$log'
'ngTableParams'
'$filter'
]
| 130863 | ###
sessionCtrl.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
SessionCtrl = ($scope, $http, $log, ngTableParams, $filter)->
### 会话 ###
$log.debug '会话'
$scope.remove = (d)->
# 删除
$scope.confirm('是否删除这条会话记录?', ->
$http.delete("/cs/session/#{d.id}").success((data)->
$log.debug data
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
)
$scope.$parent.name = 'session'
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ua: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/cs/session',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
if data.ok
params.total(data.count)
$defer.resolve(data.data)
else
alert(data.err)
)
)
UsersCtrl.$inject = [
'$scope'
'$http'
'$log'
'ngTableParams'
'$filter'
]
| true | ###
sessionCtrl.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
SessionCtrl = ($scope, $http, $log, ngTableParams, $filter)->
### 会话 ###
$log.debug '会话'
$scope.remove = (d)->
# 删除
$scope.confirm('是否删除这条会话记录?', ->
$http.delete("/cs/session/#{d.id}").success((data)->
$log.debug data
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
)
$scope.$parent.name = 'session'
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ua: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/cs/session',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
if data.ok
params.total(data.count)
$defer.resolve(data.data)
else
alert(data.err)
)
)
UsersCtrl.$inject = [
'$scope'
'$http'
'$log'
'ngTableParams'
'$filter'
]
|
[
{
"context": "### (C) 2014 Narazaka : Licensed under The MIT License - http://narazak",
"end": 21,
"score": 0.9998818039894104,
"start": 13,
"tag": "NAME",
"value": "Narazaka"
}
] | src/NanikaPlugin-prefix.coffee | Ikagaka/NanikaDefaultPlugin | 0 | ### (C) 2014 Narazaka : Licensed under The MIT License - http://narazaka.net/license/MIT?2014 ###
NanikaPlugin = @NanikaPlugin
NanikaPlugin ?= {}
| 207475 | ### (C) 2014 <NAME> : Licensed under The MIT License - http://narazaka.net/license/MIT?2014 ###
NanikaPlugin = @NanikaPlugin
NanikaPlugin ?= {}
| true | ### (C) 2014 PI:NAME:<NAME>END_PI : Licensed under The MIT License - http://narazaka.net/license/MIT?2014 ###
NanikaPlugin = @NanikaPlugin
NanikaPlugin ?= {}
|
[
{
"context": "PI for NodeJS - RestifyJS\n\nCopyright (c) 2015-2021 Steven Agyekum <agyekum@posteo.de>\n\nPermission is hereby granted",
"end": 158,
"score": 0.9998800754547119,
"start": 144,
"tag": "NAME",
"value": "Steven Agyekum"
},
{
"context": "estifyJS\n\nCopyright (c) 2015-2021... | src/addons/Os/index.coffee | Burnett01/sys-api | 6 | ###
The MIT License (MIT)
Product: System API (SysAPI)
Description: A modular System-API for NodeJS - RestifyJS
Copyright (c) 2015-2021 Steven Agyekum <agyekum@posteo.de>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###
os = require 'os'
pwdg = require 'passwd-groups'
Fs = require '../Fs'
module.exports = {
os:
os: os
system:
hostname: () ->
os.hostname()
type: () ->
os.type()
platform: () ->
os.platform()
arch: () ->
os.arch()
release: () ->
os.release()
eol: os.EOL
uptime: () ->
os.uptime()
loadavg: () ->
os.loadavg()
memory:
total: () ->
os.totalmem()
free: () ->
os.freemem()
cpus: () ->
os.cpus()
networkInterfaces: () ->
os.networkInterfaces()
users:
all: (cb) ->
pwdg.getAllUsers((err, users) ->
cb(err, users)
)
get: (username, cb) ->
pwdg.getUser(username, (err, user) ->
cb(err, user)
)
add: (username, pass, opts, cb) ->
pwdg.addUser(username, pass, opts, (err, status) ->
cb(err, status)
)
lock: (username, opts, cb) ->
pwdg.lockUser(username, opts, (err, status) ->
cb(err, status)
)
unlock: (username, opts, cb) ->
pwdg.unlockUser(username, opts, (err, status) ->
cb(err, status)
)
del: (username, opts, cb) ->
pwdg.delUser(username, opts, (err, status) ->
cb(err, status)
)
groups:
all: (cb) ->
pwdg.getAllGroups((err, groups) ->
cb(err, groups)
)
get: (name, cb) ->
pwdg.getGroup(name, (err, group) ->
cb(err, group)
)
add: (name, opts, cb) ->
pwdg.addGroup(name, opts, (err, status) ->
cb(err, status)
)
del: (name, opts, cb) ->
pwdg.delGroup(name, opts, (err, status) ->
cb(err, status)
)
} | 157173 | ###
The MIT License (MIT)
Product: System API (SysAPI)
Description: A modular System-API for NodeJS - RestifyJS
Copyright (c) 2015-2021 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###
os = require 'os'
pwdg = require 'passwd-groups'
Fs = require '../Fs'
module.exports = {
os:
os: os
system:
hostname: () ->
os.hostname()
type: () ->
os.type()
platform: () ->
os.platform()
arch: () ->
os.arch()
release: () ->
os.release()
eol: os.EOL
uptime: () ->
os.uptime()
loadavg: () ->
os.loadavg()
memory:
total: () ->
os.totalmem()
free: () ->
os.freemem()
cpus: () ->
os.cpus()
networkInterfaces: () ->
os.networkInterfaces()
users:
all: (cb) ->
pwdg.getAllUsers((err, users) ->
cb(err, users)
)
get: (username, cb) ->
pwdg.getUser(username, (err, user) ->
cb(err, user)
)
add: (username, pass, opts, cb) ->
pwdg.addUser(username, pass, opts, (err, status) ->
cb(err, status)
)
lock: (username, opts, cb) ->
pwdg.lockUser(username, opts, (err, status) ->
cb(err, status)
)
unlock: (username, opts, cb) ->
pwdg.unlockUser(username, opts, (err, status) ->
cb(err, status)
)
del: (username, opts, cb) ->
pwdg.delUser(username, opts, (err, status) ->
cb(err, status)
)
groups:
all: (cb) ->
pwdg.getAllGroups((err, groups) ->
cb(err, groups)
)
get: (name, cb) ->
pwdg.getGroup(name, (err, group) ->
cb(err, group)
)
add: (name, opts, cb) ->
pwdg.addGroup(name, opts, (err, status) ->
cb(err, status)
)
del: (name, opts, cb) ->
pwdg.delGroup(name, opts, (err, status) ->
cb(err, status)
)
} | true | ###
The MIT License (MIT)
Product: System API (SysAPI)
Description: A modular System-API for NodeJS - RestifyJS
Copyright (c) 2015-2021 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###
os = require 'os'
pwdg = require 'passwd-groups'
Fs = require '../Fs'
module.exports = {
os:
os: os
system:
hostname: () ->
os.hostname()
type: () ->
os.type()
platform: () ->
os.platform()
arch: () ->
os.arch()
release: () ->
os.release()
eol: os.EOL
uptime: () ->
os.uptime()
loadavg: () ->
os.loadavg()
memory:
total: () ->
os.totalmem()
free: () ->
os.freemem()
cpus: () ->
os.cpus()
networkInterfaces: () ->
os.networkInterfaces()
users:
all: (cb) ->
pwdg.getAllUsers((err, users) ->
cb(err, users)
)
get: (username, cb) ->
pwdg.getUser(username, (err, user) ->
cb(err, user)
)
add: (username, pass, opts, cb) ->
pwdg.addUser(username, pass, opts, (err, status) ->
cb(err, status)
)
lock: (username, opts, cb) ->
pwdg.lockUser(username, opts, (err, status) ->
cb(err, status)
)
unlock: (username, opts, cb) ->
pwdg.unlockUser(username, opts, (err, status) ->
cb(err, status)
)
del: (username, opts, cb) ->
pwdg.delUser(username, opts, (err, status) ->
cb(err, status)
)
groups:
all: (cb) ->
pwdg.getAllGroups((err, groups) ->
cb(err, groups)
)
get: (name, cb) ->
pwdg.getGroup(name, (err, group) ->
cb(err, group)
)
add: (name, opts, cb) ->
pwdg.addGroup(name, opts, (err, status) ->
cb(err, status)
)
del: (name, opts, cb) ->
pwdg.delGroup(name, opts, (err, status) ->
cb(err, status)
)
} |
[
{
"context": "ptions.on '--help', ->\n console.log ' Created by Doug Martin, http://dougmart.in/pagepipe'\noptions.parse proce",
"end": 1540,
"score": 0.9993929862976074,
"start": 1529,
"tag": "NAME",
"value": "Doug Martin"
}
] | src/pagepipe.coffee | dougmartin/pagepipe | 9 | options = require 'commander'
express = require 'express'
basicAuth = require 'basic-auth'
http = require 'http'
split = require 'split'
dateformat = require 'dateformat'
favicon = require 'serve-favicon'
# use express for the server - this is probably overkill but
# if makes the code a lot shorter!
app = express()
# add favicon.ico
app.use favicon "#{__dirname}/favicon.ico"
# get the options
options
.version '1.0.0'
.option '-p, --port <n>', 'server port [10371]', '10371'
.option '-c, --color <#rgb>', 'text color for page [#000]', '#000'
.option '-b, --bgcolor <#rgb>', 'background color for page [#fff]', '#fff'
.option '-f, --font <name>', 'font family for page [monospace]', 'monospace'
.option '-m, --margin <n>', 'margin around output in page [1em]', '1em'
.option '-t, --title <text>', 'title tag and text for page [pagepipe]', 'pagepipe'
.option '-i, --interface <ip>', 'server interface [localhost]', 'localhost'
.option '-a, --auth <username>/<password>', 'require basic auth to view page'
.option '-r, --realm <name>', 'realm name for basic auth [pagepipe]', 'pagepipe'
.option '-z, --zombie', 'stays alive after stdin is exhausted'
.option '-o, --output', 'pipes to stdout'
.option '-n, --numlines <n>', 'size of line buffer, 0 is unlimited [0]', '0'
.option '-d, --datestamp', 'prefixes datestamps to all lines'
.option '-l, --lines', 'prefixes 1-based line numbers'
.option '-j, --json', 'sends event-source data as json'
options.on '--help', ->
console.log ' Created by Doug Martin, http://dougmart.in/pagepipe'
options.parse process.argv
# convert the numlines string to an int
options.numlines = parseInt options.numlines, 10
# if authentication is needed parse the username/password
[useAuth, auth] = if not options.auth then [false, null] else
[name, pass] = options.auth.split '/'
if not pass?.length > 0
console.error "auth option must be in the form of <username>/<password>"
process.exit 1
[true, {name: name, pass: pass}]
# add authentication middleware if needed
if useAuth
app.use (req, res, next) ->
user = basicAuth req
if not user or user.name isnt auth.name or user.pass isnt auth.pass
res.set 'WWW-Authenticate', ['Basic realm="', options.realm, '"'].join ''
return res.sendStatus 401
next()
# create the line formatter
formatLine = (line, lineNumber) ->
date = if options.datestamp then dateformat(line.date, 'isoDateTime') else null
if options.json
json = {}
json.line = lineNumber if options.lines
json.date = date if options.datestamp
json.text = line.text
JSON.stringify json
else
prefixes = []
prefixes.push lineNumber if options.lines
prefixes.push "[#{date}]" if options.datestamp
prefix = if prefixes.length > 0 then "#{prefixes.join ' '} " else ''
"#{prefix}#{line.text}"
# homepage html - this could be done in an external template too but I think it is clearer to do it inline
homepage = """
<!DOCTYPE html>
<html>
<head>
<title>#{options.title}</title>
<style>
html, body {
margin: 0;
padding: 0;
}
body {
color: #{options.color};
background-color: #{options.bgcolor};
font-family: #{options.font};
font-size: 1em;
}
div#header {
top: 0;
left: 0;
right: 0;
}
div#title {
padding: 0.25em 0.5em;
}
div#status {
float: right;
padding: 0.25em 0.5em;
}
div#output {
position: absolute;
top: 1.5em;
left: 0;
bottom: 0;
right: 0;
overflow: auto;
}
pre#innerOutput {
margin: #{options.margin};
padding: 0;
font-family: #{options.font};
font-size: 1em;
}
</style>
</head>
<body>
<div id='header'><div id='status'>Loading...</div><div id='title'>#{options.title}</div></div>
<div id='output'><pre id='innerOutput'></pre></div>
<script>
var outputDiv = document.getElementById('innerOutput'),
statusDiv = document.getElementById('status'),
eventSource = window.EventSource ? new EventSource('event-source') : null,
bytesReceived = 0,
setStatus;
setStatus = function (newStatus) {
var html = [newStatus];
if (bytesReceived > 0) {
html.push(' (', bytesReceived, ' bytes)');
}
statusDiv.innerHTML = html.join('');
};
if (!eventSource) {
outputDiv.innerHTML = 'Sorry, your browser does not support EventSource which is needed to get the pagepipe output.';
setStatus('Error!');
}
else {
eventSource.addEventListener('line', function(e) {
outputDiv.appendChild(document.createTextNode(e.data));
outputDiv.appendChild(document.createElement('br'));
bytesReceived += e.data.length;
setStatus('Streaming');
}, false);
eventSource.addEventListener('done', function() {
setStatus('Done');
eventSource.close();
}, false);
eventSource.addEventListener('open', function() {
setStatus('Opened');
}, false);
eventSource.addEventListener('error', function() {
setStatus('Disconnected!');
}, false);
}
</script>
</body>
</html>
"""
# variables used in both processing stdin and sending it out to the page
startLineIndex = 0 # increases to match start of buffer when numlines is used
lines = [] # line buffer
pipeClosed = false # flag to mark when stdin in closed
# split stdin coming in and push each line on the line queue
process.stdin
.pipe split '\n'
.on 'data', (data) ->
lines.push
date: new Date()
text: data
# trim the buffer if needed
linesToRemove = if options.numlines > 0 then Math.max 0, lines.length - options.numlines else 0
if linesToRemove > 0
lines.splice 0, linesToRemove
startLineIndex += linesToRemove
.on 'end', ->
pipeClosed = true
.on 'error', ->
pipeClosed = true
# pipe the data if requested
if options.output
process.stdin.pipe process.stdout
# homepage route
app.get '/', (req, res) ->
res.send homepage
# event source route loaded by homepage javascript
clientCount = 0
app.get '/event-source', (req, res) ->
# track the number of clients so we know when to exit the program
clientCount++
# tell the client that this is an event stream
req.socket.setTimeout Infinity
res.writeHead 200,
'Content-Type': 'text/event-stream'
'Cache-Control': 'no-cache'
'Connection': 'keep-alive'
res.write '\n'
# called when done event received or client closes the connection
endOfResponse = ->
clearInterval sendInterval
clientCount--
# close the program if stdin is exhaused, this is the last connected client and
# we are not in zombie mode
if pipeClosed and clientCount <= 0 and not options.zombie
process.exit 0
# if the client closes unexpectantly then we are done
res.on 'close', endOfResponse
# keep sending lines until stdin is exhausted and the pipeClosed flag is set
lineNumber = startLineIndex
sendLines = ->
lineIndex = Math.max 0, lineNumber - startLineIndex
if lines.length > lineIndex
for index in [lineIndex..(lines.length - 1)]
res.write "event: line\nid: #{lineNumber++}\ndata: #{formatLine lines[index], lineNumber}\n\n"
else if pipeClosed
res.write "event: done\ndata: all done!\n\n"
res.end()
endOfResponse()
sendInterval = setInterval sendLines, 100
# try to create the server manually so we can listen for the error event
server = http.createServer app
server.on 'error', (err) ->
console.error switch err.code
when 'EADDRINUSE' then "Sorry port #{options.port} is already in use"
else "Error: #{err.code}"
process.exit 1
# start 'er up
server.listen options.port, options.interface | 39677 | options = require 'commander'
express = require 'express'
basicAuth = require 'basic-auth'
http = require 'http'
split = require 'split'
dateformat = require 'dateformat'
favicon = require 'serve-favicon'
# use express for the server - this is probably overkill but
# if makes the code a lot shorter!
app = express()
# add favicon.ico
app.use favicon "#{__dirname}/favicon.ico"
# get the options
options
.version '1.0.0'
.option '-p, --port <n>', 'server port [10371]', '10371'
.option '-c, --color <#rgb>', 'text color for page [#000]', '#000'
.option '-b, --bgcolor <#rgb>', 'background color for page [#fff]', '#fff'
.option '-f, --font <name>', 'font family for page [monospace]', 'monospace'
.option '-m, --margin <n>', 'margin around output in page [1em]', '1em'
.option '-t, --title <text>', 'title tag and text for page [pagepipe]', 'pagepipe'
.option '-i, --interface <ip>', 'server interface [localhost]', 'localhost'
.option '-a, --auth <username>/<password>', 'require basic auth to view page'
.option '-r, --realm <name>', 'realm name for basic auth [pagepipe]', 'pagepipe'
.option '-z, --zombie', 'stays alive after stdin is exhausted'
.option '-o, --output', 'pipes to stdout'
.option '-n, --numlines <n>', 'size of line buffer, 0 is unlimited [0]', '0'
.option '-d, --datestamp', 'prefixes datestamps to all lines'
.option '-l, --lines', 'prefixes 1-based line numbers'
.option '-j, --json', 'sends event-source data as json'
options.on '--help', ->
console.log ' Created by <NAME>, http://dougmart.in/pagepipe'
options.parse process.argv
# convert the numlines string to an int
options.numlines = parseInt options.numlines, 10
# if authentication is needed parse the username/password
[useAuth, auth] = if not options.auth then [false, null] else
[name, pass] = options.auth.split '/'
if not pass?.length > 0
console.error "auth option must be in the form of <username>/<password>"
process.exit 1
[true, {name: name, pass: pass}]
# add authentication middleware if needed
if useAuth
app.use (req, res, next) ->
user = basicAuth req
if not user or user.name isnt auth.name or user.pass isnt auth.pass
res.set 'WWW-Authenticate', ['Basic realm="', options.realm, '"'].join ''
return res.sendStatus 401
next()
# create the line formatter
formatLine = (line, lineNumber) ->
date = if options.datestamp then dateformat(line.date, 'isoDateTime') else null
if options.json
json = {}
json.line = lineNumber if options.lines
json.date = date if options.datestamp
json.text = line.text
JSON.stringify json
else
prefixes = []
prefixes.push lineNumber if options.lines
prefixes.push "[#{date}]" if options.datestamp
prefix = if prefixes.length > 0 then "#{prefixes.join ' '} " else ''
"#{prefix}#{line.text}"
# homepage html - this could be done in an external template too but I think it is clearer to do it inline
homepage = """
<!DOCTYPE html>
<html>
<head>
<title>#{options.title}</title>
<style>
html, body {
margin: 0;
padding: 0;
}
body {
color: #{options.color};
background-color: #{options.bgcolor};
font-family: #{options.font};
font-size: 1em;
}
div#header {
top: 0;
left: 0;
right: 0;
}
div#title {
padding: 0.25em 0.5em;
}
div#status {
float: right;
padding: 0.25em 0.5em;
}
div#output {
position: absolute;
top: 1.5em;
left: 0;
bottom: 0;
right: 0;
overflow: auto;
}
pre#innerOutput {
margin: #{options.margin};
padding: 0;
font-family: #{options.font};
font-size: 1em;
}
</style>
</head>
<body>
<div id='header'><div id='status'>Loading...</div><div id='title'>#{options.title}</div></div>
<div id='output'><pre id='innerOutput'></pre></div>
<script>
var outputDiv = document.getElementById('innerOutput'),
statusDiv = document.getElementById('status'),
eventSource = window.EventSource ? new EventSource('event-source') : null,
bytesReceived = 0,
setStatus;
setStatus = function (newStatus) {
var html = [newStatus];
if (bytesReceived > 0) {
html.push(' (', bytesReceived, ' bytes)');
}
statusDiv.innerHTML = html.join('');
};
if (!eventSource) {
outputDiv.innerHTML = 'Sorry, your browser does not support EventSource which is needed to get the pagepipe output.';
setStatus('Error!');
}
else {
eventSource.addEventListener('line', function(e) {
outputDiv.appendChild(document.createTextNode(e.data));
outputDiv.appendChild(document.createElement('br'));
bytesReceived += e.data.length;
setStatus('Streaming');
}, false);
eventSource.addEventListener('done', function() {
setStatus('Done');
eventSource.close();
}, false);
eventSource.addEventListener('open', function() {
setStatus('Opened');
}, false);
eventSource.addEventListener('error', function() {
setStatus('Disconnected!');
}, false);
}
</script>
</body>
</html>
"""
# variables used in both processing stdin and sending it out to the page
startLineIndex = 0 # increases to match start of buffer when numlines is used
lines = [] # line buffer
pipeClosed = false # flag to mark when stdin in closed
# split stdin coming in and push each line on the line queue
process.stdin
.pipe split '\n'
.on 'data', (data) ->
lines.push
date: new Date()
text: data
# trim the buffer if needed
linesToRemove = if options.numlines > 0 then Math.max 0, lines.length - options.numlines else 0
if linesToRemove > 0
lines.splice 0, linesToRemove
startLineIndex += linesToRemove
.on 'end', ->
pipeClosed = true
.on 'error', ->
pipeClosed = true
# pipe the data if requested
if options.output
process.stdin.pipe process.stdout
# homepage route
app.get '/', (req, res) ->
res.send homepage
# event source route loaded by homepage javascript
clientCount = 0
app.get '/event-source', (req, res) ->
# track the number of clients so we know when to exit the program
clientCount++
# tell the client that this is an event stream
req.socket.setTimeout Infinity
res.writeHead 200,
'Content-Type': 'text/event-stream'
'Cache-Control': 'no-cache'
'Connection': 'keep-alive'
res.write '\n'
# called when done event received or client closes the connection
endOfResponse = ->
clearInterval sendInterval
clientCount--
# close the program if stdin is exhaused, this is the last connected client and
# we are not in zombie mode
if pipeClosed and clientCount <= 0 and not options.zombie
process.exit 0
# if the client closes unexpectantly then we are done
res.on 'close', endOfResponse
# keep sending lines until stdin is exhausted and the pipeClosed flag is set
lineNumber = startLineIndex
sendLines = ->
lineIndex = Math.max 0, lineNumber - startLineIndex
if lines.length > lineIndex
for index in [lineIndex..(lines.length - 1)]
res.write "event: line\nid: #{lineNumber++}\ndata: #{formatLine lines[index], lineNumber}\n\n"
else if pipeClosed
res.write "event: done\ndata: all done!\n\n"
res.end()
endOfResponse()
sendInterval = setInterval sendLines, 100
# try to create the server manually so we can listen for the error event
server = http.createServer app
server.on 'error', (err) ->
console.error switch err.code
when 'EADDRINUSE' then "Sorry port #{options.port} is already in use"
else "Error: #{err.code}"
process.exit 1
# start 'er up
server.listen options.port, options.interface | true | options = require 'commander'
express = require 'express'
basicAuth = require 'basic-auth'
http = require 'http'
split = require 'split'
dateformat = require 'dateformat'
favicon = require 'serve-favicon'
# use express for the server - this is probably overkill but
# if makes the code a lot shorter!
app = express()
# add favicon.ico
app.use favicon "#{__dirname}/favicon.ico"
# get the options
options
.version '1.0.0'
.option '-p, --port <n>', 'server port [10371]', '10371'
.option '-c, --color <#rgb>', 'text color for page [#000]', '#000'
.option '-b, --bgcolor <#rgb>', 'background color for page [#fff]', '#fff'
.option '-f, --font <name>', 'font family for page [monospace]', 'monospace'
.option '-m, --margin <n>', 'margin around output in page [1em]', '1em'
.option '-t, --title <text>', 'title tag and text for page [pagepipe]', 'pagepipe'
.option '-i, --interface <ip>', 'server interface [localhost]', 'localhost'
.option '-a, --auth <username>/<password>', 'require basic auth to view page'
.option '-r, --realm <name>', 'realm name for basic auth [pagepipe]', 'pagepipe'
.option '-z, --zombie', 'stays alive after stdin is exhausted'
.option '-o, --output', 'pipes to stdout'
.option '-n, --numlines <n>', 'size of line buffer, 0 is unlimited [0]', '0'
.option '-d, --datestamp', 'prefixes datestamps to all lines'
.option '-l, --lines', 'prefixes 1-based line numbers'
.option '-j, --json', 'sends event-source data as json'
options.on '--help', ->
console.log ' Created by PI:NAME:<NAME>END_PI, http://dougmart.in/pagepipe'
options.parse process.argv
# convert the numlines string to an int
options.numlines = parseInt options.numlines, 10
# if authentication is needed parse the username/password
[useAuth, auth] = if not options.auth then [false, null] else
[name, pass] = options.auth.split '/'
if not pass?.length > 0
console.error "auth option must be in the form of <username>/<password>"
process.exit 1
[true, {name: name, pass: pass}]
# add authentication middleware if needed
if useAuth
app.use (req, res, next) ->
user = basicAuth req
if not user or user.name isnt auth.name or user.pass isnt auth.pass
res.set 'WWW-Authenticate', ['Basic realm="', options.realm, '"'].join ''
return res.sendStatus 401
next()
# create the line formatter
formatLine = (line, lineNumber) ->
date = if options.datestamp then dateformat(line.date, 'isoDateTime') else null
if options.json
json = {}
json.line = lineNumber if options.lines
json.date = date if options.datestamp
json.text = line.text
JSON.stringify json
else
prefixes = []
prefixes.push lineNumber if options.lines
prefixes.push "[#{date}]" if options.datestamp
prefix = if prefixes.length > 0 then "#{prefixes.join ' '} " else ''
"#{prefix}#{line.text}"
# homepage html - this could be done in an external template too but I think it is clearer to do it inline
homepage = """
<!DOCTYPE html>
<html>
<head>
<title>#{options.title}</title>
<style>
html, body {
margin: 0;
padding: 0;
}
body {
color: #{options.color};
background-color: #{options.bgcolor};
font-family: #{options.font};
font-size: 1em;
}
div#header {
top: 0;
left: 0;
right: 0;
}
div#title {
padding: 0.25em 0.5em;
}
div#status {
float: right;
padding: 0.25em 0.5em;
}
div#output {
position: absolute;
top: 1.5em;
left: 0;
bottom: 0;
right: 0;
overflow: auto;
}
pre#innerOutput {
margin: #{options.margin};
padding: 0;
font-family: #{options.font};
font-size: 1em;
}
</style>
</head>
<body>
<div id='header'><div id='status'>Loading...</div><div id='title'>#{options.title}</div></div>
<div id='output'><pre id='innerOutput'></pre></div>
<script>
var outputDiv = document.getElementById('innerOutput'),
statusDiv = document.getElementById('status'),
eventSource = window.EventSource ? new EventSource('event-source') : null,
bytesReceived = 0,
setStatus;
setStatus = function (newStatus) {
var html = [newStatus];
if (bytesReceived > 0) {
html.push(' (', bytesReceived, ' bytes)');
}
statusDiv.innerHTML = html.join('');
};
if (!eventSource) {
outputDiv.innerHTML = 'Sorry, your browser does not support EventSource which is needed to get the pagepipe output.';
setStatus('Error!');
}
else {
eventSource.addEventListener('line', function(e) {
outputDiv.appendChild(document.createTextNode(e.data));
outputDiv.appendChild(document.createElement('br'));
bytesReceived += e.data.length;
setStatus('Streaming');
}, false);
eventSource.addEventListener('done', function() {
setStatus('Done');
eventSource.close();
}, false);
eventSource.addEventListener('open', function() {
setStatus('Opened');
}, false);
eventSource.addEventListener('error', function() {
setStatus('Disconnected!');
}, false);
}
</script>
</body>
</html>
"""
# variables used in both processing stdin and sending it out to the page
startLineIndex = 0 # increases to match start of buffer when numlines is used
lines = [] # line buffer
pipeClosed = false # flag to mark when stdin in closed
# split stdin coming in and push each line on the line queue
process.stdin
.pipe split '\n'
.on 'data', (data) ->
lines.push
date: new Date()
text: data
# trim the buffer if needed
linesToRemove = if options.numlines > 0 then Math.max 0, lines.length - options.numlines else 0
if linesToRemove > 0
lines.splice 0, linesToRemove
startLineIndex += linesToRemove
.on 'end', ->
pipeClosed = true
.on 'error', ->
pipeClosed = true
# pipe the data if requested
if options.output
process.stdin.pipe process.stdout
# homepage route
app.get '/', (req, res) ->
res.send homepage
# event source route loaded by homepage javascript
clientCount = 0
app.get '/event-source', (req, res) ->
# track the number of clients so we know when to exit the program
clientCount++
# tell the client that this is an event stream
req.socket.setTimeout Infinity
res.writeHead 200,
'Content-Type': 'text/event-stream'
'Cache-Control': 'no-cache'
'Connection': 'keep-alive'
res.write '\n'
# called when done event received or client closes the connection
endOfResponse = ->
clearInterval sendInterval
clientCount--
# close the program if stdin is exhaused, this is the last connected client and
# we are not in zombie mode
if pipeClosed and clientCount <= 0 and not options.zombie
process.exit 0
# if the client closes unexpectantly then we are done
res.on 'close', endOfResponse
# keep sending lines until stdin is exhausted and the pipeClosed flag is set
lineNumber = startLineIndex
sendLines = ->
lineIndex = Math.max 0, lineNumber - startLineIndex
if lines.length > lineIndex
for index in [lineIndex..(lines.length - 1)]
res.write "event: line\nid: #{lineNumber++}\ndata: #{formatLine lines[index], lineNumber}\n\n"
else if pipeClosed
res.write "event: done\ndata: all done!\n\n"
res.end()
endOfResponse()
sendInterval = setInterval sendLines, 100
# try to create the server manually so we can listen for the error event
server = http.createServer app
server.on 'error', (err) ->
console.error switch err.code
when 'EADDRINUSE' then "Sorry port #{options.port} is already in use"
else "Error: #{err.code}"
process.exit 1
# start 'er up
server.listen options.port, options.interface |
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999119639396667,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/profile-page/medals-count.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { ValueDisplay } from 'value-display'
el = React.createElement
export MedalsCount = ({userAchievements}) ->
el ValueDisplay,
modifiers: ['medals']
label: osu.trans('users.show.stats.medals')
value: userAchievements.length
| 135934 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { ValueDisplay } from 'value-display'
el = React.createElement
export MedalsCount = ({userAchievements}) ->
el ValueDisplay,
modifiers: ['medals']
label: osu.trans('users.show.stats.medals')
value: userAchievements.length
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { ValueDisplay } from 'value-display'
el = React.createElement
export MedalsCount = ({userAchievements}) ->
el ValueDisplay,
modifiers: ['medals']
label: osu.trans('users.show.stats.medals')
value: userAchievements.length
|
[
{
"context": " \"lastmod\":new Date()\n \"name\":\"Sample Quiz\"\n owner: user._id\n \"questio",
"end": 3087,
"score": 0.9894416928291321,
"start": 3076,
"tag": "NAME",
"value": "Sample Quiz"
}
] | komodo/internals.coffee | KamikazeKumquatsLLC/komodo | 1 | @Quizzes = new Mongo.Collection "quizzes"
@LiveGames = new Mongo.Collection "games"
Router.configure layoutTemplate: 'layout'
Router.route '/', ->
if Meteor.user()
@redirect "/dash"
else
@redirect "/welcome"
if Meteor.isClient
Template.registerHelper "ago", (time) -> moment(time).fromNow()
Template.registerHelper "dump", -> JSON.stringify(Template.currentData())
Template.navbar.helpers
link: (path, text) ->
activeString = if new RegExp(path).test(Router.current().url) then "class='active'" else ""
Spacebars.SafeString "<li #{activeString}><a href='#{path}'>#{text}</a></li>"
activeon: (path) ->
if new RegExp(path).test(Router.current().url)
"active"
Template.loading.rendered = ->
row = (n) -> ->
$.Velocity.animate
elements: document.querySelectorAll(".row#{n}")
properties:
scaleY: "+=2"
translateY: "-=52"
opacity: 1
tri = (n) -> ->
$.Velocity.animate
elements: document.querySelectorAll(".row1 :nth-child(#{n})")
properties:
scale: "+=2"
translateX: "-=15"
translateY: "-=26"
opacity: 1
run = ->
$("*[data-initial-properties]").each ->
$(@).velocity
properties: JSON.parse @dataset.initialProperties
options:
duration: 0
$.Velocity.animate
elements: document.querySelectorAll ".row1 :first-child"
properties:
opacity: 1
.then tri 2
.then tri 3
.then tri 4
.then tri 5
.then row 2
.then row 3
.then row 4
.then -> $.Velocity.animate
elements: document.querySelectorAll("svg")
properties: opacity: 0
options: delay: 500
.then run
run()
if Meteor.isServer
Quizzes.allow
insert: (userId, doc) -> userId and doc.owner is userId
update: (userId, doc, fields, modifier) -> doc.owner is userId
remove: (userId, doc) -> doc.owner is userId
fetch: ["owner"]
Quizzes.deny
update: (userId, doc, fields, modifier) -> _.contains fields, "owner"
fetch: []
LiveGames.allow
update: (userId, doc, fields, modifier) -> (userId is doc.owner)# or _.without(fields, "players").length is 0
remove: (userId, doc) -> userId is doc.owner
fetch: []
LiveGames.deny
update: (userId, doc, fields, modifier) -> _.contains fields, "quiz" or _.contains fields, "owner"
fetch: []
Accounts.onCreateUser (options, user) ->
Quizzes.insert
"description":"A sample quiz of awesomeness."
"lastmod":new Date()
"name":"Sample Quiz"
owner: user._id
"questions": [
{"text":"Do you know that Komodo exists?","answers":["No","Yes"],"correctAnswer":1}
{"text":"Do you know how it works?","answers":["No","Yes"]}
{"text":"There's always more to learn."}
]
return user
Meteor.startup ->
# find everything without a purge date
selector = purgeby: $exists: no
# set its purge date to a week from now
modifier = $set: purgeby: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
LiveGames.update selector, modifier
Meteor.setInterval ->
oldGamesSelector = purgeby: $lte: new Date()
LiveGames.remove oldGamesSelector
, 10000
Meteor.publish "allQuizzes", -> Quizzes.find owner: @userId
Meteor.publish "quiz", (id) -> Quizzes.find id
Meteor.publish "gameIDs", -> LiveGames.find({}, {fields: shortid: 1})
Meteor.publish "quizHost", (shortid) ->
check(shortid, String)
game = LiveGames.findOne({shortid: shortid})
quizId = game.quiz
return [Quizzes.find(quizId), LiveGames.find({shortid: shortid})]
Meteor.publish "quizPlay", (shortid) ->
check(shortid, String)
game = LiveGames.findOne({shortid: shortid})
return [LiveGames.find({shortid: shortid}, {fields: answers: 0, players: 0})]
| 216998 | @Quizzes = new Mongo.Collection "quizzes"
@LiveGames = new Mongo.Collection "games"
Router.configure layoutTemplate: 'layout'
Router.route '/', ->
if Meteor.user()
@redirect "/dash"
else
@redirect "/welcome"
if Meteor.isClient
Template.registerHelper "ago", (time) -> moment(time).fromNow()
Template.registerHelper "dump", -> JSON.stringify(Template.currentData())
Template.navbar.helpers
link: (path, text) ->
activeString = if new RegExp(path).test(Router.current().url) then "class='active'" else ""
Spacebars.SafeString "<li #{activeString}><a href='#{path}'>#{text}</a></li>"
activeon: (path) ->
if new RegExp(path).test(Router.current().url)
"active"
Template.loading.rendered = ->
row = (n) -> ->
$.Velocity.animate
elements: document.querySelectorAll(".row#{n}")
properties:
scaleY: "+=2"
translateY: "-=52"
opacity: 1
tri = (n) -> ->
$.Velocity.animate
elements: document.querySelectorAll(".row1 :nth-child(#{n})")
properties:
scale: "+=2"
translateX: "-=15"
translateY: "-=26"
opacity: 1
run = ->
$("*[data-initial-properties]").each ->
$(@).velocity
properties: JSON.parse @dataset.initialProperties
options:
duration: 0
$.Velocity.animate
elements: document.querySelectorAll ".row1 :first-child"
properties:
opacity: 1
.then tri 2
.then tri 3
.then tri 4
.then tri 5
.then row 2
.then row 3
.then row 4
.then -> $.Velocity.animate
elements: document.querySelectorAll("svg")
properties: opacity: 0
options: delay: 500
.then run
run()
if Meteor.isServer
Quizzes.allow
insert: (userId, doc) -> userId and doc.owner is userId
update: (userId, doc, fields, modifier) -> doc.owner is userId
remove: (userId, doc) -> doc.owner is userId
fetch: ["owner"]
Quizzes.deny
update: (userId, doc, fields, modifier) -> _.contains fields, "owner"
fetch: []
LiveGames.allow
update: (userId, doc, fields, modifier) -> (userId is doc.owner)# or _.without(fields, "players").length is 0
remove: (userId, doc) -> userId is doc.owner
fetch: []
LiveGames.deny
update: (userId, doc, fields, modifier) -> _.contains fields, "quiz" or _.contains fields, "owner"
fetch: []
Accounts.onCreateUser (options, user) ->
Quizzes.insert
"description":"A sample quiz of awesomeness."
"lastmod":new Date()
"name":"<NAME>"
owner: user._id
"questions": [
{"text":"Do you know that Komodo exists?","answers":["No","Yes"],"correctAnswer":1}
{"text":"Do you know how it works?","answers":["No","Yes"]}
{"text":"There's always more to learn."}
]
return user
Meteor.startup ->
# find everything without a purge date
selector = purgeby: $exists: no
# set its purge date to a week from now
modifier = $set: purgeby: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
LiveGames.update selector, modifier
Meteor.setInterval ->
oldGamesSelector = purgeby: $lte: new Date()
LiveGames.remove oldGamesSelector
, 10000
Meteor.publish "allQuizzes", -> Quizzes.find owner: @userId
Meteor.publish "quiz", (id) -> Quizzes.find id
Meteor.publish "gameIDs", -> LiveGames.find({}, {fields: shortid: 1})
Meteor.publish "quizHost", (shortid) ->
check(shortid, String)
game = LiveGames.findOne({shortid: shortid})
quizId = game.quiz
return [Quizzes.find(quizId), LiveGames.find({shortid: shortid})]
Meteor.publish "quizPlay", (shortid) ->
check(shortid, String)
game = LiveGames.findOne({shortid: shortid})
return [LiveGames.find({shortid: shortid}, {fields: answers: 0, players: 0})]
| true | @Quizzes = new Mongo.Collection "quizzes"
@LiveGames = new Mongo.Collection "games"
Router.configure layoutTemplate: 'layout'
Router.route '/', ->
if Meteor.user()
@redirect "/dash"
else
@redirect "/welcome"
if Meteor.isClient
Template.registerHelper "ago", (time) -> moment(time).fromNow()
Template.registerHelper "dump", -> JSON.stringify(Template.currentData())
Template.navbar.helpers
link: (path, text) ->
activeString = if new RegExp(path).test(Router.current().url) then "class='active'" else ""
Spacebars.SafeString "<li #{activeString}><a href='#{path}'>#{text}</a></li>"
activeon: (path) ->
if new RegExp(path).test(Router.current().url)
"active"
Template.loading.rendered = ->
row = (n) -> ->
$.Velocity.animate
elements: document.querySelectorAll(".row#{n}")
properties:
scaleY: "+=2"
translateY: "-=52"
opacity: 1
tri = (n) -> ->
$.Velocity.animate
elements: document.querySelectorAll(".row1 :nth-child(#{n})")
properties:
scale: "+=2"
translateX: "-=15"
translateY: "-=26"
opacity: 1
run = ->
$("*[data-initial-properties]").each ->
$(@).velocity
properties: JSON.parse @dataset.initialProperties
options:
duration: 0
$.Velocity.animate
elements: document.querySelectorAll ".row1 :first-child"
properties:
opacity: 1
.then tri 2
.then tri 3
.then tri 4
.then tri 5
.then row 2
.then row 3
.then row 4
.then -> $.Velocity.animate
elements: document.querySelectorAll("svg")
properties: opacity: 0
options: delay: 500
.then run
run()
if Meteor.isServer
Quizzes.allow
insert: (userId, doc) -> userId and doc.owner is userId
update: (userId, doc, fields, modifier) -> doc.owner is userId
remove: (userId, doc) -> doc.owner is userId
fetch: ["owner"]
Quizzes.deny
update: (userId, doc, fields, modifier) -> _.contains fields, "owner"
fetch: []
LiveGames.allow
update: (userId, doc, fields, modifier) -> (userId is doc.owner)# or _.without(fields, "players").length is 0
remove: (userId, doc) -> userId is doc.owner
fetch: []
LiveGames.deny
update: (userId, doc, fields, modifier) -> _.contains fields, "quiz" or _.contains fields, "owner"
fetch: []
Accounts.onCreateUser (options, user) ->
Quizzes.insert
"description":"A sample quiz of awesomeness."
"lastmod":new Date()
"name":"PI:NAME:<NAME>END_PI"
owner: user._id
"questions": [
{"text":"Do you know that Komodo exists?","answers":["No","Yes"],"correctAnswer":1}
{"text":"Do you know how it works?","answers":["No","Yes"]}
{"text":"There's always more to learn."}
]
return user
Meteor.startup ->
# find everything without a purge date
selector = purgeby: $exists: no
# set its purge date to a week from now
modifier = $set: purgeby: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
LiveGames.update selector, modifier
Meteor.setInterval ->
oldGamesSelector = purgeby: $lte: new Date()
LiveGames.remove oldGamesSelector
, 10000
Meteor.publish "allQuizzes", -> Quizzes.find owner: @userId
Meteor.publish "quiz", (id) -> Quizzes.find id
Meteor.publish "gameIDs", -> LiveGames.find({}, {fields: shortid: 1})
Meteor.publish "quizHost", (shortid) ->
check(shortid, String)
game = LiveGames.findOne({shortid: shortid})
quizId = game.quiz
return [Quizzes.find(quizId), LiveGames.find({shortid: shortid})]
Meteor.publish "quizPlay", (shortid) ->
check(shortid, String)
game = LiveGames.findOne({shortid: shortid})
return [LiveGames.find({shortid: shortid}, {fields: answers: 0, players: 0})]
|
[
{
"context": "newKey = \"<%= #{type} %>\"\n\t\tkey = \"<!--#include #{type}-->\"\n\t\tplaceholders = config.spa.placeholders",
"end": 554,
"score": 0.9039049744606018,
"start": 543,
"tag": "KEY",
"value": "#include #{"
},
{
"context": " #{type} %>\"\n\t\tkey =... | src/tasks/build/build-spa-file.coffee | rapid-build/rapid-build | 5 | module.exports = (config, gulp, Task) ->
q = require 'q'
fs = require 'fs'
path = require 'path'
gulpif = require 'gulp-if'
replace = require 'gulp-replace'
template = require 'gulp-template'
log = require "#{config.req.helpers}/log"
pathHelp = require "#{config.req.helpers}/path"
moduleHelp = require "#{config.req.helpers}/module"
format = require("#{config.req.helpers}/format")()
# helpers
# =======
runReplace = (type) ->
newKey = "<%= #{type} %>"
key = "<!--#include #{type}-->"
placeholders = config.spa.placeholders
replacePH = true # PH = placeholder
if placeholders.indexOf('all') isnt -1
replacePH = false
else if placeholders.indexOf(type) isnt -1
replacePH = false
gulpif replacePH, replace key, newKey
# task
# ====
buildTask = (src, dest, file, data={}) ->
defer = q.defer()
gulp.src src
.on 'error', (e) -> defer.reject e
.pipe runReplace 'clickjacking'
.pipe runReplace 'description'
.pipe runReplace 'moduleName'
.pipe runReplace 'ngCloakStyles'
.pipe runReplace 'scripts'
.pipe runReplace 'styles'
.pipe runReplace 'title'
.pipe template data
.on 'error', (e) -> defer.reject e
.pipe gulp.dest dest
.on 'end', ->
defer.resolve message: 'built spa file'
defer.promise
# helpers
# =======
getFilesJson = (jsonEnvFile) ->
jsonEnvFile = path.join config.generated.pkg.files.path, jsonEnvFile
moduleHelp.cache.delete jsonEnvFile
removePathSection = config.dist.app.client.dir
removePathSection += '/' unless config.dist.client.paths.absolute
files = require(jsonEnvFile).client
files = pathHelp.removeLocPartial files, removePathSection
files.styles = format.paths.to.html files.styles, 'styles', join: true, lineEnding: '\n\t', attrs: config.spa.styles.attrs
files.scripts = format.paths.to.html files.scripts, 'scripts', join: true, lineEnding: '\n\t', attrs: config.spa.scripts.attrs
files
getClickjackingTpl = ->
return '' unless config.security.client.clickjacking
fs.readFileSync(config.templates.clickjacking.src.path).toString()
getNgCloakStylesTpl = ->
fs.readFileSync(config.templates.ngCloakStyles.src.path).toString()
getData = (jsonEnvFile) ->
files = getFilesJson jsonEnvFile
data =
clickjacking: getClickjackingTpl()
description: config.spa.description
moduleName: config.angular.moduleName
ngCloakStyles: getNgCloakStylesTpl()
scripts: files.scripts
styles: files.styles
title: config.spa.title
# API
# ===
api =
runTask: (env) -> # synchronously
json = if env is 'prod' then 'prod-files.json' else 'files.json'
data = getData json
tasks = [
-> buildTask(
config.spa.temp.path
config.dist.app.client.dir
config.spa.dist.file
data
)
]
tasks.reduce(q.when, q()).then ->
log: true
message: "built and copied #{config.spa.dist.file} to: #{config.dist.app.client.dir}"
# return
# ======
api.runTask Task.opts.env
| 101050 | module.exports = (config, gulp, Task) ->
q = require 'q'
fs = require 'fs'
path = require 'path'
gulpif = require 'gulp-if'
replace = require 'gulp-replace'
template = require 'gulp-template'
log = require "#{config.req.helpers}/log"
pathHelp = require "#{config.req.helpers}/path"
moduleHelp = require "#{config.req.helpers}/module"
format = require("#{config.req.helpers}/format")()
# helpers
# =======
runReplace = (type) ->
newKey = "<%= #{type} %>"
key = "<!--<KEY>type<KEY>}-->"
placeholders = config.spa.placeholders
replacePH = true # PH = placeholder
if placeholders.indexOf('all') isnt -1
replacePH = false
else if placeholders.indexOf(type) isnt -1
replacePH = false
gulpif replacePH, replace key, newKey
# task
# ====
buildTask = (src, dest, file, data={}) ->
defer = q.defer()
gulp.src src
.on 'error', (e) -> defer.reject e
.pipe runReplace 'clickjacking'
.pipe runReplace 'description'
.pipe runReplace 'moduleName'
.pipe runReplace 'ngCloakStyles'
.pipe runReplace 'scripts'
.pipe runReplace 'styles'
.pipe runReplace 'title'
.pipe template data
.on 'error', (e) -> defer.reject e
.pipe gulp.dest dest
.on 'end', ->
defer.resolve message: 'built spa file'
defer.promise
# helpers
# =======
getFilesJson = (jsonEnvFile) ->
jsonEnvFile = path.join config.generated.pkg.files.path, jsonEnvFile
moduleHelp.cache.delete jsonEnvFile
removePathSection = config.dist.app.client.dir
removePathSection += '/' unless config.dist.client.paths.absolute
files = require(jsonEnvFile).client
files = pathHelp.removeLocPartial files, removePathSection
files.styles = format.paths.to.html files.styles, 'styles', join: true, lineEnding: '\n\t', attrs: config.spa.styles.attrs
files.scripts = format.paths.to.html files.scripts, 'scripts', join: true, lineEnding: '\n\t', attrs: config.spa.scripts.attrs
files
getClickjackingTpl = ->
return '' unless config.security.client.clickjacking
fs.readFileSync(config.templates.clickjacking.src.path).toString()
getNgCloakStylesTpl = ->
fs.readFileSync(config.templates.ngCloakStyles.src.path).toString()
getData = (jsonEnvFile) ->
files = getFilesJson jsonEnvFile
data =
clickjacking: getClickjackingTpl()
description: config.spa.description
moduleName: config.angular.moduleName
ngCloakStyles: getNgCloakStylesTpl()
scripts: files.scripts
styles: files.styles
title: config.spa.title
# API
# ===
api =
runTask: (env) -> # synchronously
json = if env is 'prod' then 'prod-files.json' else 'files.json'
data = getData json
tasks = [
-> buildTask(
config.spa.temp.path
config.dist.app.client.dir
config.spa.dist.file
data
)
]
tasks.reduce(q.when, q()).then ->
log: true
message: "built and copied #{config.spa.dist.file} to: #{config.dist.app.client.dir}"
# return
# ======
api.runTask Task.opts.env
| true | module.exports = (config, gulp, Task) ->
q = require 'q'
fs = require 'fs'
path = require 'path'
gulpif = require 'gulp-if'
replace = require 'gulp-replace'
template = require 'gulp-template'
log = require "#{config.req.helpers}/log"
pathHelp = require "#{config.req.helpers}/path"
moduleHelp = require "#{config.req.helpers}/module"
format = require("#{config.req.helpers}/format")()
# helpers
# =======
runReplace = (type) ->
newKey = "<%= #{type} %>"
key = "<!--PI:KEY:<KEY>END_PItypePI:KEY:<KEY>END_PI}-->"
placeholders = config.spa.placeholders
replacePH = true # PH = placeholder
if placeholders.indexOf('all') isnt -1
replacePH = false
else if placeholders.indexOf(type) isnt -1
replacePH = false
gulpif replacePH, replace key, newKey
# task
# ====
buildTask = (src, dest, file, data={}) ->
defer = q.defer()
gulp.src src
.on 'error', (e) -> defer.reject e
.pipe runReplace 'clickjacking'
.pipe runReplace 'description'
.pipe runReplace 'moduleName'
.pipe runReplace 'ngCloakStyles'
.pipe runReplace 'scripts'
.pipe runReplace 'styles'
.pipe runReplace 'title'
.pipe template data
.on 'error', (e) -> defer.reject e
.pipe gulp.dest dest
.on 'end', ->
defer.resolve message: 'built spa file'
defer.promise
# helpers
# =======
getFilesJson = (jsonEnvFile) ->
jsonEnvFile = path.join config.generated.pkg.files.path, jsonEnvFile
moduleHelp.cache.delete jsonEnvFile
removePathSection = config.dist.app.client.dir
removePathSection += '/' unless config.dist.client.paths.absolute
files = require(jsonEnvFile).client
files = pathHelp.removeLocPartial files, removePathSection
files.styles = format.paths.to.html files.styles, 'styles', join: true, lineEnding: '\n\t', attrs: config.spa.styles.attrs
files.scripts = format.paths.to.html files.scripts, 'scripts', join: true, lineEnding: '\n\t', attrs: config.spa.scripts.attrs
files
getClickjackingTpl = ->
return '' unless config.security.client.clickjacking
fs.readFileSync(config.templates.clickjacking.src.path).toString()
getNgCloakStylesTpl = ->
fs.readFileSync(config.templates.ngCloakStyles.src.path).toString()
getData = (jsonEnvFile) ->
files = getFilesJson jsonEnvFile
data =
clickjacking: getClickjackingTpl()
description: config.spa.description
moduleName: config.angular.moduleName
ngCloakStyles: getNgCloakStylesTpl()
scripts: files.scripts
styles: files.styles
title: config.spa.title
# API
# ===
api =
runTask: (env) -> # synchronously
json = if env is 'prod' then 'prod-files.json' else 'files.json'
data = getData json
tasks = [
-> buildTask(
config.spa.temp.path
config.dist.app.client.dir
config.spa.dist.file
data
)
]
tasks.reduce(q.when, q()).then ->
log: true
message: "built and copied #{config.spa.dist.file} to: #{config.dist.app.client.dir}"
# return
# ======
api.runTask Task.opts.env
|
[
{
"context": "ter.get '/hello', (req, res) ->\n res.json name: 'Lance'\n return\n\nrouter.get '/data', (req, res) ->\n ra",
"end": 203,
"score": 0.9995335340499878,
"start": 198,
"tag": "NAME",
"value": "Lance"
}
] | server.coffee | fraina/-Ommr-Player | 0 | 'use strict'
Mock = require('mockjs')
router = require('express').Router()
router.get '/user/:id', (req, res) ->
res.json req.params
return
router.get '/hello', (req, res) ->
res.json name: 'Lance'
return
router.get '/data', (req, res) ->
random = Mock.Random
data =
boolean: random.boolean()
integer: random.integer(1, 9527)
float: random.float(1, 200, 0, 99)
string: random.string(7, 10)
range: random.range(1, 78, 5)
res.json data
return
module.exports = router
| 86342 | 'use strict'
Mock = require('mockjs')
router = require('express').Router()
router.get '/user/:id', (req, res) ->
res.json req.params
return
router.get '/hello', (req, res) ->
res.json name: '<NAME>'
return
router.get '/data', (req, res) ->
random = Mock.Random
data =
boolean: random.boolean()
integer: random.integer(1, 9527)
float: random.float(1, 200, 0, 99)
string: random.string(7, 10)
range: random.range(1, 78, 5)
res.json data
return
module.exports = router
| true | 'use strict'
Mock = require('mockjs')
router = require('express').Router()
router.get '/user/:id', (req, res) ->
res.json req.params
return
router.get '/hello', (req, res) ->
res.json name: 'PI:NAME:<NAME>END_PI'
return
router.get '/data', (req, res) ->
random = Mock.Random
data =
boolean: random.boolean()
integer: random.integer(1, 9527)
float: random.float(1, 200, 0, 99)
string: random.string(7, 10)
range: random.range(1, 78, 5)
res.json data
return
module.exports = router
|
[
{
"context": "orial type', ->\n @channel.set\n name: 'Editorial'\n type: 'editorial'\n @channel.hasFeat",
"end": 588,
"score": 0.9842953681945801,
"start": 579,
"tag": "NAME",
"value": "Editorial"
},
{
"context": " team type', ->\n @channel.set\n n... | src/client/test/models/channel.test.coffee | artsyjian/positron | 76 | _ = require 'underscore'
Backbone = require 'backbone'
rewire = require 'rewire'
Channel = rewire '../../models/channel.coffee'
sinon = require 'sinon'
fixtures = require '../../../test/helpers/fixtures'
request = require 'superagent'
{ fabricate } = require '@artsy/antigravity'
describe "Channel", ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe '#hasFeature', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns features for editorial type', ->
@channel.set
name: 'Editorial'
type: 'editorial'
@channel.hasFeature('header').should.be.true()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.true()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.true()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.true()
@channel.hasFeature('callout').should.be.true()
it 'returns features for team type', ->
@channel.set
name: 'Life At Artsy'
type: 'team'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.true()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.true()
@channel.hasFeature('callout').should.be.true()
it 'returns features for support type', ->
@channel.set
name: 'Auctions'
type: 'support'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.false()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.false()
@channel.hasFeature('callout').should.be.true()
it 'returns features for partner type', ->
@channel.set
name: 'Gagosian'
type: 'partner'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.false()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.false()
@channel.hasFeature('callout').should.be.false()
describe '#hasAssociation', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns associations for editorial type', ->
@channel.set
name: 'Editorial'
type: 'editorial'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
it 'returns associations for team type', ->
@channel.set
name: 'Life At Artsy'
type: 'team'
@channel.hasAssociation('artworks').should.be.false()
@channel.hasAssociation('artists').should.be.false()
@channel.hasAssociation('shows').should.be.false()
@channel.hasAssociation('fairs').should.be.false()
@channel.hasAssociation('partners').should.be.false()
@channel.hasAssociation('auctions').should.be.false()
it 'returns associations for support type', ->
@channel.set
name: 'Auctions'
type: 'support'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
it 'returns associations for partner type', ->
@channel.set
name: 'Gagosian'
type: 'partner'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
describe '#isArtsyChannel', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns true for editorial type', ->
@channel.set
name: 'Editorial'
type: 'editorial'
@channel.isArtsyChannel().should.be.true()
it 'returns false for partner type', ->
@channel.set
name: 'Gagosian'
type: 'partner'
@channel.isArtsyChannel().should.be.false()
describe '#fetchChannelOrPartner' , ->
it 'returns an error if it cannot find either' , (done) ->
request.get = sinon.stub().returns
set: sinon.stub().returns
end: (cb) -> cb( null , {} )
Channel.__set__ 'request', request
@channel = new Channel fixtures().channels
@error = false
@channel.fetchChannelOrPartner
error: =>
@error = true
_.defer =>
@error.should.be.true()
done()
it 'returns an error if there is an async error' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields('Async Error', [])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
error: (err) ->
err.should.equal 'Async Error'
done()
it 'fetches a channel' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields(null, [
{
ok: true
body: fixtures().channels
}
{}
])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
success: (channel) ->
channel.get('name').should.equal 'Editorial'
channel.get('type').should.equal 'editorial'
channel.get('id').should.equal '5086df098523e60002000018'
done()
it 'fetches a partner' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields(null, [
{}
{
ok: true
body: fabricate 'partner'
}
])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
success: (channel) ->
channel.get('name').should.equal 'Gagosian Gallery'
channel.get('type').should.equal 'partner'
channel.get('id').should.equal '5086df098523e60002000012'
done()
describe '#denormalized', ->
it 'returns formatted data for a channel', ->
@channel = new Channel fixtures().channels
@channel.denormalized().type.should.equal 'editorial'
@channel.denormalized().name.should.equal 'Editorial'
it 'returns formatted data for a partner channel' , ->
@channel = new Channel fabricate 'partner'
@channel.denormalized().name.should.equal 'Gagosian Gallery'
@channel.denormalized().type.should.equal 'partner'
| 218380 | _ = require 'underscore'
Backbone = require 'backbone'
rewire = require 'rewire'
Channel = rewire '../../models/channel.coffee'
sinon = require 'sinon'
fixtures = require '../../../test/helpers/fixtures'
request = require 'superagent'
{ fabricate } = require '@artsy/antigravity'
describe "Channel", ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe '#hasFeature', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns features for editorial type', ->
@channel.set
name: '<NAME>'
type: 'editorial'
@channel.hasFeature('header').should.be.true()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.true()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.true()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.true()
@channel.hasFeature('callout').should.be.true()
it 'returns features for team type', ->
@channel.set
name: '<NAME>'
type: 'team'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.true()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.true()
@channel.hasFeature('callout').should.be.true()
it 'returns features for support type', ->
@channel.set
name: '<NAME>'
type: 'support'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.false()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.false()
@channel.hasFeature('callout').should.be.true()
it 'returns features for partner type', ->
@channel.set
name: '<NAME>'
type: 'partner'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.false()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.false()
@channel.hasFeature('callout').should.be.false()
describe '#hasAssociation', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns associations for editorial type', ->
@channel.set
name: '<NAME>'
type: 'editorial'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
it 'returns associations for team type', ->
@channel.set
name: '<NAME>'
type: 'team'
@channel.hasAssociation('artworks').should.be.false()
@channel.hasAssociation('artists').should.be.false()
@channel.hasAssociation('shows').should.be.false()
@channel.hasAssociation('fairs').should.be.false()
@channel.hasAssociation('partners').should.be.false()
@channel.hasAssociation('auctions').should.be.false()
it 'returns associations for support type', ->
@channel.set
name: '<NAME>'
type: 'support'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
it 'returns associations for partner type', ->
@channel.set
name: '<NAME>'
type: 'partner'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
describe '#isArtsyChannel', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns true for editorial type', ->
@channel.set
name: '<NAME>'
type: 'editorial'
@channel.isArtsyChannel().should.be.true()
it 'returns false for partner type', ->
@channel.set
name: '<NAME>'
type: 'partner'
@channel.isArtsyChannel().should.be.false()
describe '#fetchChannelOrPartner' , ->
it 'returns an error if it cannot find either' , (done) ->
request.get = sinon.stub().returns
set: sinon.stub().returns
end: (cb) -> cb( null , {} )
Channel.__set__ 'request', request
@channel = new Channel fixtures().channels
@error = false
@channel.fetchChannelOrPartner
error: =>
@error = true
_.defer =>
@error.should.be.true()
done()
it 'returns an error if there is an async error' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields('Async Error', [])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
error: (err) ->
err.should.equal 'Async Error'
done()
it 'fetches a channel' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields(null, [
{
ok: true
body: fixtures().channels
}
{}
])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
success: (channel) ->
channel.get('name').should.equal 'Editor<NAME>'
channel.get('type').should.equal 'editorial'
channel.get('id').should.equal '5086df098523e60002000018'
done()
it 'fetches a partner' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields(null, [
{}
{
ok: true
body: fabricate 'partner'
}
])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
success: (channel) ->
channel.get('name').should.equal '<NAME>'
channel.get('type').should.equal 'partner'
channel.get('id').should.equal '5086df098523e60002000012'
done()
describe '#denormalized', ->
it 'returns formatted data for a channel', ->
@channel = new Channel fixtures().channels
@channel.denormalized().type.should.equal 'editorial'
@channel.denormalized().name.should.equal 'Editorial'
it 'returns formatted data for a partner channel' , ->
@channel = new Channel fabricate 'partner'
@channel.denormalized().name.should.equal '<NAME>'
@channel.denormalized().type.should.equal 'partner'
| true | _ = require 'underscore'
Backbone = require 'backbone'
rewire = require 'rewire'
Channel = rewire '../../models/channel.coffee'
sinon = require 'sinon'
fixtures = require '../../../test/helpers/fixtures'
request = require 'superagent'
{ fabricate } = require '@artsy/antigravity'
describe "Channel", ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe '#hasFeature', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns features for editorial type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'editorial'
@channel.hasFeature('header').should.be.true()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.true()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.true()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.true()
@channel.hasFeature('callout').should.be.true()
it 'returns features for team type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'team'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.true()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.true()
@channel.hasFeature('callout').should.be.true()
it 'returns features for support type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'support'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.false()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.false()
@channel.hasFeature('callout').should.be.true()
it 'returns features for partner type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'partner'
@channel.hasFeature('header').should.be.false()
@channel.hasFeature('text').should.be.true()
@channel.hasFeature('superArticle').should.be.false()
@channel.hasFeature('artworks').should.be.true()
@channel.hasFeature('images').should.be.true()
@channel.hasFeature('image_set').should.be.false()
@channel.hasFeature('video').should.be.true()
@channel.hasFeature('embed').should.be.false()
@channel.hasFeature('callout').should.be.false()
describe '#hasAssociation', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns associations for editorial type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'editorial'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
it 'returns associations for team type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'team'
@channel.hasAssociation('artworks').should.be.false()
@channel.hasAssociation('artists').should.be.false()
@channel.hasAssociation('shows').should.be.false()
@channel.hasAssociation('fairs').should.be.false()
@channel.hasAssociation('partners').should.be.false()
@channel.hasAssociation('auctions').should.be.false()
it 'returns associations for support type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'support'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
it 'returns associations for partner type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'partner'
@channel.hasAssociation('artworks').should.be.true()
@channel.hasAssociation('artists').should.be.true()
@channel.hasAssociation('shows').should.be.true()
@channel.hasAssociation('fairs').should.be.true()
@channel.hasAssociation('partners').should.be.true()
@channel.hasAssociation('auctions').should.be.true()
describe '#isArtsyChannel', ->
beforeEach ->
@channel = new Channel fixtures().channels
it 'returns true for editorial type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'editorial'
@channel.isArtsyChannel().should.be.true()
it 'returns false for partner type', ->
@channel.set
name: 'PI:NAME:<NAME>END_PI'
type: 'partner'
@channel.isArtsyChannel().should.be.false()
describe '#fetchChannelOrPartner' , ->
it 'returns an error if it cannot find either' , (done) ->
request.get = sinon.stub().returns
set: sinon.stub().returns
end: (cb) -> cb( null , {} )
Channel.__set__ 'request', request
@channel = new Channel fixtures().channels
@error = false
@channel.fetchChannelOrPartner
error: =>
@error = true
_.defer =>
@error.should.be.true()
done()
it 'returns an error if there is an async error' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields('Async Error', [])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
error: (err) ->
err.should.equal 'Async Error'
done()
it 'fetches a channel' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields(null, [
{
ok: true
body: fixtures().channels
}
{}
])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
success: (channel) ->
channel.get('name').should.equal 'EditorPI:NAME:<NAME>END_PI'
channel.get('type').should.equal 'editorial'
channel.get('id').should.equal '5086df098523e60002000018'
done()
it 'fetches a partner' , (done) ->
Channel.__set__ 'async',
parallel: sinon.stub().yields(null, [
{}
{
ok: true
body: fabricate 'partner'
}
])
@channel = new Channel fixtures().channels
@channel.fetchChannelOrPartner
success: (channel) ->
channel.get('name').should.equal 'PI:NAME:<NAME>END_PI'
channel.get('type').should.equal 'partner'
channel.get('id').should.equal '5086df098523e60002000012'
done()
describe '#denormalized', ->
it 'returns formatted data for a channel', ->
@channel = new Channel fixtures().channels
@channel.denormalized().type.should.equal 'editorial'
@channel.denormalized().name.should.equal 'Editorial'
it 'returns formatted data for a partner channel' , ->
@channel = new Channel fabricate 'partner'
@channel.denormalized().name.should.equal 'PI:NAME:<NAME>END_PI'
@channel.denormalized().type.should.equal 'partner'
|
[
{
"context": "testMetadata = require('./lib/test-metadata')\n\n# 'mathdown' is a sub-account I created.\nsauceUser = process.",
"end": 504,
"score": 0.9937601685523987,
"start": 496,
"tag": "USERNAME",
"value": "mathdown"
},
{
"context": "eated.\nsauceUser = process.env.SAUCE_USERNAM... | test/browser-on-saucelabs.spec.coffee | cben/mathdown | 444 | # Usage: By default runs local server, tests it via tunnel;
# if SITE_TO_TEST env var is set to a publicly accessible URL, tests that skipping server & tunnel.
SauceLabs = require('saucelabs').default
wd = require('wd') # TODO: compare vs http://webdriver.io/ vs webdriverJS
chalk = require('chalk')
expect = require('expect.js')
lodash = require('lodash')
uuid = require('uuid')
require('coffeescript/register')
server = require('../server')
testMetadata = require('./lib/test-metadata')
# 'mathdown' is a sub-account I created.
sauceUser = process.env.SAUCE_USERNAME || 'mathdown'
# I hope storing this in a public test is OK given that an Open Sauce account
# is free anyway. Can always revoke if needed...
sauceKey = process.env.SAUCE_ACCESS_KEY || '23056294-abe8-4fe9-8140-df9a59c45c7d'
# Try to keep all logging indented deeper than Mocha test tree.
indentation = ' '
log = (fmt, args...) ->
console.log(indentation + fmt, args...)
sec = 1000
min = 60*sec
timeouts = {
tunnel: 60*sec
tunnelClose: 20*sec
# Sauce normally gives a VM in seconds but sometimes it's slow
# and running too many concurrent jobs causes jobs to queue up waiting for a slot.
sauceSession: 5*min
sauceSessionClose: 10*sec
# Waste less Sauce resources than default 90s if this script crashed.
sauceIdle: 30*sec
}
# Desired environments
# =====================
sauceLabs = new SauceLabs({user: sauceUser, key: sauceKey})
getDesiredBrowsers = ->
# https://docs.saucelabs.com/dev/api/platform/index.html
platforms = await sauceLabs.listPlatforms('webdriver')
oldestBrowser = (api_name) ->
matchingPlatforms = lodash.filter(platforms, (p) => p.api_name == api_name)
oldestPlatform = lodash.minBy(matchingPlatforms, (p) => Number(p.short_version))
# Convert to format expected by
{browserName: api_name, version: oldestPlatform.long_version, platform: oldestPlatform.os}
[
# Generated with https://docs.saucelabs.com/reference/platforms-configurator/
# Desktop:
oldestBrowser('internet explorer')
{browserName: 'internet explorer', version: 'latest', platform: 'Windows 10'}
{browserName: 'MicrosoftEdge'}
# arbitrary somewhat old - but not ancient - FF and Chrome versions.
{browserName: 'firefox', version: '30.0', platform: 'Linux'}
{browserName: 'chrome', version: '35.0', platform: 'Linux'}
{browserName: 'Safari', version: '8.0', platform: 'OS X 10.10'}
{browserName: 'Safari', version: 'latest', platform: 'macOS 10.13'}
# Mobile (doesn't mean it's usable though):
# {browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '9.3'}
# {browserName: 'Browser', deviceName: 'Android Emulator', platformName: 'Android', platformVersion: '4.4'}
]
commonDesired = {
build: testMetadata.getBuildInfo()
tags: testMetadata.getTags()
'idle-timeout': timeouts.sauceIdle
}
log("commonDesired =", commonDesired)
merge = (objs...) ->
merged = {}
for obj in objs
for k, v of obj
merged[k] = v
merged
# Tests
# =====
# I've factored parts of the test suite into "desribeFoo" functions.
# When I want to pass them values computed in before[Each] blocks, I have to
# pass "getValue" callables (e.g. `getDesired` here) rather than the values
# themselves (see https://gist.github.com/cben/43fcbbae95019aa73ecd).
describeBrowserTest = (browserName, getDesired, getSite) ->
describe browserName, ->
browser = null
# KLUDGE: to set pass/fail status on Sauce Labs, I want to know whether tests passed.
# Theoretically should use a custom reporter; practically this works, as
# long as test cases set eachPassed to true when done.
eachPassed = false
allPassed = true
beforeEach ->
eachPassed = false
afterEach ->
if not eachPassed
allPassed = false
# TODO: should I reuse one browser instance for many tests?
# From the wd docs reusing one should work but is it isolated enough?
# I suppose `browser.get()` does reset browser state...
# Also, seeing individual tests on SauceLabs would be cool: https://youtu.be/Dzplh1tAwIg?t=370
before (done) ->
this.timeout(timeouts.sauceSession)
browser = wd.remote('ondemand.saucelabs.com', 80, sauceUser, sauceKey)
browser.on 'status', (info) ->
log(chalk.cyan(info))
browser.on 'command', (meth, path) ->
log('> %s: %s', chalk.yellow(meth), path)
#browser.on 'http', (meth, path, data) ->
# log('> %s %s %s', chalk.magenta(meth), path, chalk.grey(data))
log('') # blank line before lots of noise
browser.init getDesired(), (err) ->
expect(err).to.be(null)
done()
# TODO: inspect browser console log
# https://support.saucelabs.com/entries/60070884-Enable-grabbing-server-logs-from-the-wire-protocol
# https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/log
# Sounds like these should work but on SauceLabs they return:
# Selenium error: Command not found: GET /session/XXXXXXXX-XXXX-XXXX-XXXX-XXXXe3fcc97e/log/types
# Selenium error: Command not found: POST /session/XXXXXXXX-XXXX-XXXX-XXXX-XXXX26210a31/log
# respectively...
#
# afterEach (done) ->
# browser.logTypes (err, arrayOfLogTypes) ->
# expect(err).to.be(null)
# log(chalk.yellow('LOG TYPES:'), arrayOfLogTypes)
# browser.log 'browser', (err, arrayOfLogs) ->
# expect(err).to.be(null)
# log(chalk.yellow('LOGS:'), arrayOfLogs)
# done()
after (done) ->
this.timeout(timeouts.sauceSessionClose)
browser.sauceJobStatus allPassed, ->
browser.quit ->
log('') # blank line after lots of noise
done()
it 'should load and render math', (done) ->
this.timeout(60*sec) # 30s would be enough if not for mobile?
browser.get getSite() + '?doc=_mathdown_test_smoke', (err) ->
expect(err).to.be(null)
browser.waitFor wd.asserters.jsCondition('document.title.match(/smoke test/)'), 10*sec, (err, value) ->
expect(err).to.be(null)
browser.waitForElementByCss '.MathJax_Display', 30*sec, (err, el) ->
expect(err).to.be(null)
el.text (err, text) ->
expect(err).to.be(null)
expect(text).to.match(/^\s*(α|𝛼)\s*$/)
eachPassed = true
done()
# Defines test cases and executes them with explicit run(), for mocha --delay mode.
# This lets us do async preparations before defining the cases, see main().
runTests = (desiredBrowsers) ->
describeAllBrowsers = (getDesired, getSite) ->
for b in desiredBrowsers
do (b) ->
name = "#{b.browserName} #{b.deviceName} #{b.version} on #{b.platform}"
describeBrowserTest(name, (-> merge(b, getDesired())), getSite)
siteToTest = process.env.SITE_TO_TEST
if siteToTest # Testing existing instance
describe "#{siteToTest}", ->
describeAllBrowsers(
(-> merge(commonDesired, {name: 'smoke test of ' + siteToTest})),
(-> siteToTest))
else # Run local server, test it via tunnel
describe 'Served site via Sauce Connect', ->
tunnel = null
actualTunnelId = null
httpServer = null
before (done) ->
this.timeout(timeouts.tunnel)
# https://docs.saucelabs.com/reference/sauce-connect/#can-i-access-applications-on-localhost-
# lists ports we can use. TODO: try other ports if in use.
port = 8001
httpServer = server.main port, ->
log(chalk.magenta('Creating tunnel...'))
actualTunnelId = uuid.v4()
tunnel = await sauceLabs.startSauceConnect({
logger: (stdout) => console.log(chalk.magenta(stdout.trimEnd())),
tunnelIdentifier: actualTunnelId,
})
done()
after ->
this.timeout(timeouts.tunnelClose)
# TODO (in mocha?): run this on SIGINT
await tunnel.close()
log(chalk.magenta('Tunnel stopped, cleaned up.'))
# Not waiting for server to close - won't happen if the client kept open
# connections, https://github.com/nodejs/node-v0.x-archive/issues/5052
httpServer.close()
describeAllBrowsers(
(-> merge(commonDesired, {name: 'smoke test', 'tunnel-identifier': actualTunnelId})),
(-> "http://localhost:#{httpServer.address().port}"))
run()
main = ->
desiredBrowsers = await getDesiredBrowsers()
#console.log('desiredBrowsers =', desiredBrowsers)
runTests(desiredBrowsers)
main()
# TODO: parallelize (at least between different browsers).
# I probably want Vows instead of Jasmine, see https://github.com/jlipps/sauce-node-demo example?
# Or Nightwatch.js?
| 89442 | # Usage: By default runs local server, tests it via tunnel;
# if SITE_TO_TEST env var is set to a publicly accessible URL, tests that skipping server & tunnel.
SauceLabs = require('saucelabs').default
wd = require('wd') # TODO: compare vs http://webdriver.io/ vs webdriverJS
chalk = require('chalk')
expect = require('expect.js')
lodash = require('lodash')
uuid = require('uuid')
require('coffeescript/register')
server = require('../server')
testMetadata = require('./lib/test-metadata')
# 'mathdown' is a sub-account I created.
sauceUser = process.env.SAUCE_USERNAME || 'mathdown'
# I hope storing this in a public test is OK given that an Open Sauce account
# is free anyway. Can always revoke if needed...
sauceKey = process.env.SAUCE_ACCESS_KEY || '<KEY>'
# Try to keep all logging indented deeper than Mocha test tree.
indentation = ' '
log = (fmt, args...) ->
console.log(indentation + fmt, args...)
sec = 1000
min = 60*sec
timeouts = {
tunnel: 60*sec
tunnelClose: 20*sec
# Sauce normally gives a VM in seconds but sometimes it's slow
# and running too many concurrent jobs causes jobs to queue up waiting for a slot.
sauceSession: 5*min
sauceSessionClose: 10*sec
# Waste less Sauce resources than default 90s if this script crashed.
sauceIdle: 30*sec
}
# Desired environments
# =====================
sauceLabs = new SauceLabs({user: sauceUser, key: sauceKey})
getDesiredBrowsers = ->
# https://docs.saucelabs.com/dev/api/platform/index.html
platforms = await sauceLabs.listPlatforms('webdriver')
oldestBrowser = (api_name) ->
matchingPlatforms = lodash.filter(platforms, (p) => p.api_name == api_name)
oldestPlatform = lodash.minBy(matchingPlatforms, (p) => Number(p.short_version))
# Convert to format expected by
{browserName: api_name, version: oldestPlatform.long_version, platform: oldestPlatform.os}
[
# Generated with https://docs.saucelabs.com/reference/platforms-configurator/
# Desktop:
oldestBrowser('internet explorer')
{browserName: 'internet explorer', version: 'latest', platform: 'Windows 10'}
{browserName: 'MicrosoftEdge'}
# arbitrary somewhat old - but not ancient - FF and Chrome versions.
{browserName: 'firefox', version: '30.0', platform: 'Linux'}
{browserName: 'chrome', version: '35.0', platform: 'Linux'}
{browserName: 'Safari', version: '8.0', platform: 'OS X 10.10'}
{browserName: 'Safari', version: 'latest', platform: 'macOS 10.13'}
# Mobile (doesn't mean it's usable though):
# {browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '9.3'}
# {browserName: 'Browser', deviceName: 'Android Emulator', platformName: 'Android', platformVersion: '4.4'}
]
commonDesired = {
build: testMetadata.getBuildInfo()
tags: testMetadata.getTags()
'idle-timeout': timeouts.sauceIdle
}
log("commonDesired =", commonDesired)
merge = (objs...) ->
merged = {}
for obj in objs
for k, v of obj
merged[k] = v
merged
# Tests
# =====
# I've factored parts of the test suite into "desribeFoo" functions.
# When I want to pass them values computed in before[Each] blocks, I have to
# pass "getValue" callables (e.g. `getDesired` here) rather than the values
# themselves (see https://gist.github.com/cben/43fcbbae95019aa73ecd).
describeBrowserTest = (browserName, getDesired, getSite) ->
describe browserName, ->
browser = null
# KLUDGE: to set pass/fail status on Sauce Labs, I want to know whether tests passed.
# Theoretically should use a custom reporter; practically this works, as
# long as test cases set eachPassed to true when done.
eachPassed = false
allPassed = true
beforeEach ->
eachPassed = false
afterEach ->
if not eachPassed
allPassed = false
# TODO: should I reuse one browser instance for many tests?
# From the wd docs reusing one should work but is it isolated enough?
# I suppose `browser.get()` does reset browser state...
# Also, seeing individual tests on SauceLabs would be cool: https://youtu.be/Dzplh1tAwIg?t=370
before (done) ->
this.timeout(timeouts.sauceSession)
browser = wd.remote('ondemand.saucelabs.com', 80, sauceUser, sauceKey)
browser.on 'status', (info) ->
log(chalk.cyan(info))
browser.on 'command', (meth, path) ->
log('> %s: %s', chalk.yellow(meth), path)
#browser.on 'http', (meth, path, data) ->
# log('> %s %s %s', chalk.magenta(meth), path, chalk.grey(data))
log('') # blank line before lots of noise
browser.init getDesired(), (err) ->
expect(err).to.be(null)
done()
# TODO: inspect browser console log
# https://support.saucelabs.com/entries/60070884-Enable-grabbing-server-logs-from-the-wire-protocol
# https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/log
# Sounds like these should work but on SauceLabs they return:
# Selenium error: Command not found: GET /session/XXXXXXXX-XXXX-XXXX-XXXX-XXXXe3fcc97e/log/types
# Selenium error: Command not found: POST /session/XXXXXXXX-XXXX-XXXX-XXXX-XXXX26210a31/log
# respectively...
#
# afterEach (done) ->
# browser.logTypes (err, arrayOfLogTypes) ->
# expect(err).to.be(null)
# log(chalk.yellow('LOG TYPES:'), arrayOfLogTypes)
# browser.log 'browser', (err, arrayOfLogs) ->
# expect(err).to.be(null)
# log(chalk.yellow('LOGS:'), arrayOfLogs)
# done()
after (done) ->
this.timeout(timeouts.sauceSessionClose)
browser.sauceJobStatus allPassed, ->
browser.quit ->
log('') # blank line after lots of noise
done()
it 'should load and render math', (done) ->
this.timeout(60*sec) # 30s would be enough if not for mobile?
browser.get getSite() + '?doc=_mathdown_test_smoke', (err) ->
expect(err).to.be(null)
browser.waitFor wd.asserters.jsCondition('document.title.match(/smoke test/)'), 10*sec, (err, value) ->
expect(err).to.be(null)
browser.waitForElementByCss '.MathJax_Display', 30*sec, (err, el) ->
expect(err).to.be(null)
el.text (err, text) ->
expect(err).to.be(null)
expect(text).to.match(/^\s*(α|𝛼)\s*$/)
eachPassed = true
done()
# Defines test cases and executes them with explicit run(), for mocha --delay mode.
# This lets us do async preparations before defining the cases, see main().
runTests = (desiredBrowsers) ->
describeAllBrowsers = (getDesired, getSite) ->
for b in desiredBrowsers
do (b) ->
name = "#{b.browserName} #{b.deviceName} #{b.version} on #{b.platform}"
describeBrowserTest(name, (-> merge(b, getDesired())), getSite)
siteToTest = process.env.SITE_TO_TEST
if siteToTest # Testing existing instance
describe "#{siteToTest}", ->
describeAllBrowsers(
(-> merge(commonDesired, {name: 'smoke test of ' + siteToTest})),
(-> siteToTest))
else # Run local server, test it via tunnel
describe 'Served site via Sauce Connect', ->
tunnel = null
actualTunnelId = null
httpServer = null
before (done) ->
this.timeout(timeouts.tunnel)
# https://docs.saucelabs.com/reference/sauce-connect/#can-i-access-applications-on-localhost-
# lists ports we can use. TODO: try other ports if in use.
port = 8001
httpServer = server.main port, ->
log(chalk.magenta('Creating tunnel...'))
actualTunnelId = uuid.v4()
tunnel = await sauceLabs.startSauceConnect({
logger: (stdout) => console.log(chalk.magenta(stdout.trimEnd())),
tunnelIdentifier: actualTunnelId,
})
done()
after ->
this.timeout(timeouts.tunnelClose)
# TODO (in mocha?): run this on SIGINT
await tunnel.close()
log(chalk.magenta('Tunnel stopped, cleaned up.'))
# Not waiting for server to close - won't happen if the client kept open
# connections, https://github.com/nodejs/node-v0.x-archive/issues/5052
httpServer.close()
describeAllBrowsers(
(-> merge(commonDesired, {name: 'smoke test', 'tunnel-identifier': actualTunnelId})),
(-> "http://localhost:#{httpServer.address().port}"))
run()
main = ->
desiredBrowsers = await getDesiredBrowsers()
#console.log('desiredBrowsers =', desiredBrowsers)
runTests(desiredBrowsers)
main()
# TODO: parallelize (at least between different browsers).
# I probably want Vows instead of Jasmine, see https://github.com/jlipps/sauce-node-demo example?
# Or Nightwatch.js?
| true | # Usage: By default runs local server, tests it via tunnel;
# if SITE_TO_TEST env var is set to a publicly accessible URL, tests that skipping server & tunnel.
SauceLabs = require('saucelabs').default
wd = require('wd') # TODO: compare vs http://webdriver.io/ vs webdriverJS
chalk = require('chalk')
expect = require('expect.js')
lodash = require('lodash')
uuid = require('uuid')
require('coffeescript/register')
server = require('../server')
testMetadata = require('./lib/test-metadata')
# 'mathdown' is a sub-account I created.
sauceUser = process.env.SAUCE_USERNAME || 'mathdown'
# I hope storing this in a public test is OK given that an Open Sauce account
# is free anyway. Can always revoke if needed...
sauceKey = process.env.SAUCE_ACCESS_KEY || 'PI:KEY:<KEY>END_PI'
# Try to keep all logging indented deeper than Mocha test tree.
indentation = ' '
log = (fmt, args...) ->
console.log(indentation + fmt, args...)
sec = 1000
min = 60*sec
timeouts = {
tunnel: 60*sec
tunnelClose: 20*sec
# Sauce normally gives a VM in seconds but sometimes it's slow
# and running too many concurrent jobs causes jobs to queue up waiting for a slot.
sauceSession: 5*min
sauceSessionClose: 10*sec
# Waste less Sauce resources than default 90s if this script crashed.
sauceIdle: 30*sec
}
# Desired environments
# =====================
sauceLabs = new SauceLabs({user: sauceUser, key: sauceKey})
getDesiredBrowsers = ->
# https://docs.saucelabs.com/dev/api/platform/index.html
platforms = await sauceLabs.listPlatforms('webdriver')
oldestBrowser = (api_name) ->
matchingPlatforms = lodash.filter(platforms, (p) => p.api_name == api_name)
oldestPlatform = lodash.minBy(matchingPlatforms, (p) => Number(p.short_version))
# Convert to format expected by
{browserName: api_name, version: oldestPlatform.long_version, platform: oldestPlatform.os}
[
# Generated with https://docs.saucelabs.com/reference/platforms-configurator/
# Desktop:
oldestBrowser('internet explorer')
{browserName: 'internet explorer', version: 'latest', platform: 'Windows 10'}
{browserName: 'MicrosoftEdge'}
# arbitrary somewhat old - but not ancient - FF and Chrome versions.
{browserName: 'firefox', version: '30.0', platform: 'Linux'}
{browserName: 'chrome', version: '35.0', platform: 'Linux'}
{browserName: 'Safari', version: '8.0', platform: 'OS X 10.10'}
{browserName: 'Safari', version: 'latest', platform: 'macOS 10.13'}
# Mobile (doesn't mean it's usable though):
# {browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '9.3'}
# {browserName: 'Browser', deviceName: 'Android Emulator', platformName: 'Android', platformVersion: '4.4'}
]
commonDesired = {
build: testMetadata.getBuildInfo()
tags: testMetadata.getTags()
'idle-timeout': timeouts.sauceIdle
}
log("commonDesired =", commonDesired)
merge = (objs...) ->
merged = {}
for obj in objs
for k, v of obj
merged[k] = v
merged
# Tests
# =====
# I've factored parts of the test suite into "desribeFoo" functions.
# When I want to pass them values computed in before[Each] blocks, I have to
# pass "getValue" callables (e.g. `getDesired` here) rather than the values
# themselves (see https://gist.github.com/cben/43fcbbae95019aa73ecd).
describeBrowserTest = (browserName, getDesired, getSite) ->
describe browserName, ->
browser = null
# KLUDGE: to set pass/fail status on Sauce Labs, I want to know whether tests passed.
# Theoretically should use a custom reporter; practically this works, as
# long as test cases set eachPassed to true when done.
eachPassed = false
allPassed = true
beforeEach ->
eachPassed = false
afterEach ->
if not eachPassed
allPassed = false
# TODO: should I reuse one browser instance for many tests?
# From the wd docs reusing one should work but is it isolated enough?
# I suppose `browser.get()` does reset browser state...
# Also, seeing individual tests on SauceLabs would be cool: https://youtu.be/Dzplh1tAwIg?t=370
before (done) ->
this.timeout(timeouts.sauceSession)
browser = wd.remote('ondemand.saucelabs.com', 80, sauceUser, sauceKey)
browser.on 'status', (info) ->
log(chalk.cyan(info))
browser.on 'command', (meth, path) ->
log('> %s: %s', chalk.yellow(meth), path)
#browser.on 'http', (meth, path, data) ->
# log('> %s %s %s', chalk.magenta(meth), path, chalk.grey(data))
log('') # blank line before lots of noise
browser.init getDesired(), (err) ->
expect(err).to.be(null)
done()
# TODO: inspect browser console log
# https://support.saucelabs.com/entries/60070884-Enable-grabbing-server-logs-from-the-wire-protocol
# https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/log
# Sounds like these should work but on SauceLabs they return:
# Selenium error: Command not found: GET /session/XXXXXXXX-XXXX-XXXX-XXXX-XXXXe3fcc97e/log/types
# Selenium error: Command not found: POST /session/XXXXXXXX-XXXX-XXXX-XXXX-XXXX26210a31/log
# respectively...
#
# afterEach (done) ->
# browser.logTypes (err, arrayOfLogTypes) ->
# expect(err).to.be(null)
# log(chalk.yellow('LOG TYPES:'), arrayOfLogTypes)
# browser.log 'browser', (err, arrayOfLogs) ->
# expect(err).to.be(null)
# log(chalk.yellow('LOGS:'), arrayOfLogs)
# done()
after (done) ->
this.timeout(timeouts.sauceSessionClose)
browser.sauceJobStatus allPassed, ->
browser.quit ->
log('') # blank line after lots of noise
done()
it 'should load and render math', (done) ->
this.timeout(60*sec) # 30s would be enough if not for mobile?
browser.get getSite() + '?doc=_mathdown_test_smoke', (err) ->
expect(err).to.be(null)
browser.waitFor wd.asserters.jsCondition('document.title.match(/smoke test/)'), 10*sec, (err, value) ->
expect(err).to.be(null)
browser.waitForElementByCss '.MathJax_Display', 30*sec, (err, el) ->
expect(err).to.be(null)
el.text (err, text) ->
expect(err).to.be(null)
expect(text).to.match(/^\s*(α|𝛼)\s*$/)
eachPassed = true
done()
# Defines test cases and executes them with explicit run(), for mocha --delay mode.
# This lets us do async preparations before defining the cases, see main().
runTests = (desiredBrowsers) ->
describeAllBrowsers = (getDesired, getSite) ->
for b in desiredBrowsers
do (b) ->
name = "#{b.browserName} #{b.deviceName} #{b.version} on #{b.platform}"
describeBrowserTest(name, (-> merge(b, getDesired())), getSite)
siteToTest = process.env.SITE_TO_TEST
if siteToTest # Testing existing instance
describe "#{siteToTest}", ->
describeAllBrowsers(
(-> merge(commonDesired, {name: 'smoke test of ' + siteToTest})),
(-> siteToTest))
else # Run local server, test it via tunnel
describe 'Served site via Sauce Connect', ->
tunnel = null
actualTunnelId = null
httpServer = null
before (done) ->
this.timeout(timeouts.tunnel)
# https://docs.saucelabs.com/reference/sauce-connect/#can-i-access-applications-on-localhost-
# lists ports we can use. TODO: try other ports if in use.
port = 8001
httpServer = server.main port, ->
log(chalk.magenta('Creating tunnel...'))
actualTunnelId = uuid.v4()
tunnel = await sauceLabs.startSauceConnect({
logger: (stdout) => console.log(chalk.magenta(stdout.trimEnd())),
tunnelIdentifier: actualTunnelId,
})
done()
after ->
this.timeout(timeouts.tunnelClose)
# TODO (in mocha?): run this on SIGINT
await tunnel.close()
log(chalk.magenta('Tunnel stopped, cleaned up.'))
# Not waiting for server to close - won't happen if the client kept open
# connections, https://github.com/nodejs/node-v0.x-archive/issues/5052
httpServer.close()
describeAllBrowsers(
(-> merge(commonDesired, {name: 'smoke test', 'tunnel-identifier': actualTunnelId})),
(-> "http://localhost:#{httpServer.address().port}"))
run()
main = ->
desiredBrowsers = await getDesiredBrowsers()
#console.log('desiredBrowsers =', desiredBrowsers)
runTests(desiredBrowsers)
main()
# TODO: parallelize (at least between different browsers).
# I probably want Vows instead of Jasmine, see https://github.com/jlipps/sauce-node-demo example?
# Or Nightwatch.js?
|
[
{
"context": "ttp://gitlab.mydomain.com/api/v4\"\n token: \"test\"\n\n expect(apibasehttp.options.url).to.equal(",
"end": 547,
"score": 0.6389641761779785,
"start": 543,
"tag": "PASSWORD",
"value": "test"
},
{
"context": "url: \"http://gitlab.mydomain.com\"\n token... | tests/ApiBaseHTTP.test.coffee | JadsonReis/node-gitlab | 0 | chai = require 'chai'
expect = chai.expect
sinon = require 'sinon'
proxyquire = require 'proxyquire'
sinonChai = require 'sinon-chai'
chai.use sinonChai
describe "ApiBaseHTTP", ->
ApiBaseHTTP = null
apibasehttp = null
before ->
ApiBaseHTTP = require('../lib/ApiBaseHTTP').ApiBaseHTTP
beforeEach ->
describe "handleOptions()", ->
it "should strip /api/v4 from `url` parameter if provided", ->
apibasehttp = new ApiBaseHTTP
base_url: "api/v4"
url: "http://gitlab.mydomain.com/api/v4"
token: "test"
expect(apibasehttp.options.url).to.equal("http://gitlab.mydomain.com")
it "should not strip /api/v4 from `url` parameter if not provided", ->
apibasehttp = new ApiBaseHTTP
base_url: "api/v4"
url: "http://gitlab.mydomain.com"
token: "test"
expect(apibasehttp.options.url).to.equal("http://gitlab.mydomain.com")
| 131613 | chai = require 'chai'
expect = chai.expect
sinon = require 'sinon'
proxyquire = require 'proxyquire'
sinonChai = require 'sinon-chai'
chai.use sinonChai
describe "ApiBaseHTTP", ->
ApiBaseHTTP = null
apibasehttp = null
before ->
ApiBaseHTTP = require('../lib/ApiBaseHTTP').ApiBaseHTTP
beforeEach ->
describe "handleOptions()", ->
it "should strip /api/v4 from `url` parameter if provided", ->
apibasehttp = new ApiBaseHTTP
base_url: "api/v4"
url: "http://gitlab.mydomain.com/api/v4"
token: "<PASSWORD>"
expect(apibasehttp.options.url).to.equal("http://gitlab.mydomain.com")
it "should not strip /api/v4 from `url` parameter if not provided", ->
apibasehttp = new ApiBaseHTTP
base_url: "api/v4"
url: "http://gitlab.mydomain.com"
token: "<PASSWORD>"
expect(apibasehttp.options.url).to.equal("http://gitlab.mydomain.com")
| true | chai = require 'chai'
expect = chai.expect
sinon = require 'sinon'
proxyquire = require 'proxyquire'
sinonChai = require 'sinon-chai'
chai.use sinonChai
describe "ApiBaseHTTP", ->
ApiBaseHTTP = null
apibasehttp = null
before ->
ApiBaseHTTP = require('../lib/ApiBaseHTTP').ApiBaseHTTP
beforeEach ->
describe "handleOptions()", ->
it "should strip /api/v4 from `url` parameter if provided", ->
apibasehttp = new ApiBaseHTTP
base_url: "api/v4"
url: "http://gitlab.mydomain.com/api/v4"
token: "PI:PASSWORD:<PASSWORD>END_PI"
expect(apibasehttp.options.url).to.equal("http://gitlab.mydomain.com")
it "should not strip /api/v4 from `url` parameter if not provided", ->
apibasehttp = new ApiBaseHTTP
base_url: "api/v4"
url: "http://gitlab.mydomain.com"
token: "PI:PASSWORD:<PASSWORD>END_PI"
expect(apibasehttp.options.url).to.equal("http://gitlab.mydomain.com")
|
[
{
"context": "# Copyright (c) 2015 Riceball LEE, MIT License\nAbstractIterator = require(\"abs",
"end": 33,
"score": 0.9997236132621765,
"start": 21,
"tag": "NAME",
"value": "Riceball LEE"
}
] | src/encoding-iterator.coffee | snowyu/node-encoding-iterator | 0 | # Copyright (c) 2015 Riceball LEE, MIT License
AbstractIterator = require("abstract-iterator")
inherits = require("inherits-ex")
isArray = require("util-ex/lib/is/type/array")
extend = require("util-ex/lib/_extend")
module.exports = class EncodingIterator
inherits EncodingIterator, AbstractIterator
encodeOptions: (options)->
keyEncoding = options.keyEncoding
if keyEncoding
options.lt = keyEncoding.encode(options.lt, options) if options.lt?
options.lte = keyEncoding.encode(options.lte, options) if options.lte?
options.gt = keyEncoding.encode(options.gt, options) if options.gt?
options.gte = keyEncoding.encode(options.gte, options) if options.gte?
if isArray options.range
options.range = options.range.map (item)->
keyEncoding.encode item, options
options
decodeResult: (result)->
keyEncoding = @options.keyEncoding
valueEncoding = @options.valueEncoding
result[0] = keyEncoding.decode(result[0], @options) if result[0]? and keyEncoding
result[1] = valueEncoding.decode(result[1], @options) if result[1]? and valueEncoding
result
| 75945 | # Copyright (c) 2015 <NAME>, MIT License
AbstractIterator = require("abstract-iterator")
inherits = require("inherits-ex")
isArray = require("util-ex/lib/is/type/array")
extend = require("util-ex/lib/_extend")
module.exports = class EncodingIterator
inherits EncodingIterator, AbstractIterator
encodeOptions: (options)->
keyEncoding = options.keyEncoding
if keyEncoding
options.lt = keyEncoding.encode(options.lt, options) if options.lt?
options.lte = keyEncoding.encode(options.lte, options) if options.lte?
options.gt = keyEncoding.encode(options.gt, options) if options.gt?
options.gte = keyEncoding.encode(options.gte, options) if options.gte?
if isArray options.range
options.range = options.range.map (item)->
keyEncoding.encode item, options
options
decodeResult: (result)->
keyEncoding = @options.keyEncoding
valueEncoding = @options.valueEncoding
result[0] = keyEncoding.decode(result[0], @options) if result[0]? and keyEncoding
result[1] = valueEncoding.decode(result[1], @options) if result[1]? and valueEncoding
result
| true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI, MIT License
AbstractIterator = require("abstract-iterator")
inherits = require("inherits-ex")
isArray = require("util-ex/lib/is/type/array")
extend = require("util-ex/lib/_extend")
module.exports = class EncodingIterator
inherits EncodingIterator, AbstractIterator
encodeOptions: (options)->
keyEncoding = options.keyEncoding
if keyEncoding
options.lt = keyEncoding.encode(options.lt, options) if options.lt?
options.lte = keyEncoding.encode(options.lte, options) if options.lte?
options.gt = keyEncoding.encode(options.gt, options) if options.gt?
options.gte = keyEncoding.encode(options.gte, options) if options.gte?
if isArray options.range
options.range = options.range.map (item)->
keyEncoding.encode item, options
options
decodeResult: (result)->
keyEncoding = @options.keyEncoding
valueEncoding = @options.valueEncoding
result[0] = keyEncoding.decode(result[0], @options) if result[0]? and keyEncoding
result[1] = valueEncoding.decode(result[1], @options) if result[1]? and valueEncoding
result
|
[
{
"context": "*\n# JSWebView - Web site handling class\n# Coded by Hajime Oh-yake 2015.10.05\n#*************************************",
"end": 106,
"score": 0.999890923500061,
"start": 92,
"tag": "NAME",
"value": "Hajime Oh-yake"
}
] | JSKit/04_JSWebView.coffee | digitarhythm/codeJS | 0 | #*****************************************
# JSWebView - Web site handling class
# Coded by Hajime Oh-yake 2015.10.05
#*****************************************
class JSWebView extends JSScrollView
constructor: (frame)->
super(frame)
@scalesPageToFit = false
@loading = false
@_request = undefined
destructor:->
super()
reload:->
@loadRequest(@_request)
loadRequest:(@_request)->
$(@_viewSelector+"_webview").remove()
@viewDidAppear()
setCornerRadius:(cornerradius)->
super(cornerradius)
$(@_viewSelector+"_webview").css("border-radius", cornerradius+"px")
viewDidAppear:->
super()
tag = "<div id='"+@_objectID+"_webview' style='position:absolute; overflow:hidden; width:"+@_frame.size.width+"px; height:"+@_frame.size.height+"px; border-radius:"+@_cornerRadius+"px;'>"
if (@_request?)
tag += "<iframe src='"+@_request+"' style='position:absolute; width:"+@_frame.size.width+"px; height:"+@_frame.size.height+"px; border:0px; margin:0px 0px 0px 0px'></iframe>"
tag += "</div>"
$(@_viewSelector).append(tag)
| 132609 | #*****************************************
# JSWebView - Web site handling class
# Coded by <NAME> 2015.10.05
#*****************************************
class JSWebView extends JSScrollView
constructor: (frame)->
super(frame)
@scalesPageToFit = false
@loading = false
@_request = undefined
destructor:->
super()
reload:->
@loadRequest(@_request)
loadRequest:(@_request)->
$(@_viewSelector+"_webview").remove()
@viewDidAppear()
setCornerRadius:(cornerradius)->
super(cornerradius)
$(@_viewSelector+"_webview").css("border-radius", cornerradius+"px")
viewDidAppear:->
super()
tag = "<div id='"+@_objectID+"_webview' style='position:absolute; overflow:hidden; width:"+@_frame.size.width+"px; height:"+@_frame.size.height+"px; border-radius:"+@_cornerRadius+"px;'>"
if (@_request?)
tag += "<iframe src='"+@_request+"' style='position:absolute; width:"+@_frame.size.width+"px; height:"+@_frame.size.height+"px; border:0px; margin:0px 0px 0px 0px'></iframe>"
tag += "</div>"
$(@_viewSelector).append(tag)
| true | #*****************************************
# JSWebView - Web site handling class
# Coded by PI:NAME:<NAME>END_PI 2015.10.05
#*****************************************
class JSWebView extends JSScrollView
constructor: (frame)->
super(frame)
@scalesPageToFit = false
@loading = false
@_request = undefined
destructor:->
super()
reload:->
@loadRequest(@_request)
loadRequest:(@_request)->
$(@_viewSelector+"_webview").remove()
@viewDidAppear()
setCornerRadius:(cornerradius)->
super(cornerradius)
$(@_viewSelector+"_webview").css("border-radius", cornerradius+"px")
viewDidAppear:->
super()
tag = "<div id='"+@_objectID+"_webview' style='position:absolute; overflow:hidden; width:"+@_frame.size.width+"px; height:"+@_frame.size.height+"px; border-radius:"+@_cornerRadius+"px;'>"
if (@_request?)
tag += "<iframe src='"+@_request+"' style='position:absolute; width:"+@_frame.size.width+"px; height:"+@_frame.size.height+"px; border:0px; margin:0px 0px 0px 0px'></iframe>"
tag += "</div>"
$(@_viewSelector).append(tag)
|
[
{
"context": " _.map [1..p.lastPage], (page) ->\n key = \"page\" + page\n if page == p.currentPage\n ",
"end": 3686,
"score": 0.963005006313324,
"start": 3685,
"tag": "KEY",
"value": "\""
},
{
"context": " _.map [1..p.lastPage], (page) ->\n key = \"page\" ... | src/searchapp.coffee | jaw977/react-isomorphic-webapp-demo | 0 | React = @React or require 'react'
_ = @_ or require 'lodash'
ajax = (method, url, callback) ->
request = new XMLHttpRequest()
request.open method, url, true
if method == 'GET'
request.onreadystatechange = ->
callback JSON.parse @responseText if @readyState == 4
request.send()
components = {}
components.SearchApp = React.createClass
getInitialState: ->
_.assign { sellers: [], listings: [], currentPage: 1, lastPage: 1 }, @props
queryListings: (opts, callback) ->
url = "/api/listings?page=" + (opts.currentPage or 1)
for field in ['seller','watched']
value = opts[field]
url += "&#{field}=#{value}" if value
ajax 'GET', url, callback
componentDidMount: ->
if _.isEmpty @state.sellers
ajax 'GET', '/api/sellers', (sellers) => @setState sellers: sellers
if _.isEmpty @state.listings
@queryListings {}, (results) => @setState results
onChangeSeller: (e) ->
seller = e.target.value
@queryListings { seller: seller, watched: @state.watched }, (results) =>
@setState _.assign { seller: seller, currentPage: 1 }, results
onClickPage: (page) ->
@queryListings { currentPage: page, seller: @state.seller, watched: @state.watched }, (results) =>
@setState _.assign { currentPage: page }, results
onClickWatch: (listing) ->
listing.watched = not listing.watched
@setState listings: @state.listings
ajax 'PUT', "/api/listing/#{listing.id}?watched=#{listing.watched}"
onChangeWatch: (e) ->
watched = e.target.checked
@queryListings { seller: @state.seller, watched: watched }, (results) =>
@setState _.assign { watched: watched, currentPage: 1 }, results
render: ->
s = @state
h = React.DOM
h.div {},
factories.SearchFilters seller: s.seller, sellers: s.sellers, onChangeSeller: @onChangeSeller, onChangeWatch: @onChangeWatch
factories.ListingTable listings: s.listings, onClickWatch: @onClickWatch
factories.PaginateFooter currentPage: s.currentPage, lastPage: s.lastPage, onClickPage: @onClickPage
components.SearchFilters = React.createClass
render: ->
p = @props
h = React.DOM
h.p {},
"Seller: "
h.select value: p.seller, onChange: p.onChangeSeller,
h.option { key: "allSellers" }, ""
for seller in p.sellers
h.option { key: seller, value: seller }, seller
" \u00a0\u00a0\u00a0 Watched listings only: "
h.input type: "checkbox", onChange: p.onChangeWatch
components.ListingTable = React.createClass
render: ->
p = @props
h = React.DOM
return h.p {}, "No results found" if _.isEmpty p.listings
h.table {},
h.thead {},
h.tr {},
for header in ["Watch","ID","Seller","Title"]
h.th { key: header }, header
h.tbody {},
for listing in p.listings
factories.ListingRow key: "listing#{listing.id}", listing: listing, onClickWatch: p.onClickWatch
components.ListingRow = React.createClass
render: ->
p = @props
h = React.DOM
listing = p.listing
h.tr {},
h.td onClick: (-> p.onClickWatch listing), className: (if listing.watched then "watched" else "notwatched"),
if listing.watched then "★" else "☆"
h.td {}, listing.id
h.td {}, listing.seller
h.td {}, listing.title
components.PaginateFooter = React.createClass
render: ->
p = @props
h = React.DOM
return h.p {} if p.lastPage == 0
h.p {},
if p.currentPage == 1
"< Previous"
else
h.a href: '#', onClick: (-> p.onClickPage p.currentPage-1), "< Previous"
" "
_.map [1..p.lastPage], (page) ->
key = "page" + page
if page == p.currentPage
h.span { key: key, style: fontWeight: 'bold' }, " #{page} "
else
h.span { key: key }, " ", h.a(href:'#', onClick: (-> p.onClickPage page), page), " "
" "
if p.currentPage == p.lastPage
"Next >"
else
h.a href: '#', onClick: (-> p.onClickPage p.currentPage+1), "Next >"
factories = _.mapValues components, React.createFactory
if module?
module.exports = factories.SearchApp
else
@SearchApp = factories.SearchApp
| 167152 | React = @React or require 'react'
_ = @_ or require 'lodash'
ajax = (method, url, callback) ->
request = new XMLHttpRequest()
request.open method, url, true
if method == 'GET'
request.onreadystatechange = ->
callback JSON.parse @responseText if @readyState == 4
request.send()
components = {}
components.SearchApp = React.createClass
getInitialState: ->
_.assign { sellers: [], listings: [], currentPage: 1, lastPage: 1 }, @props
queryListings: (opts, callback) ->
url = "/api/listings?page=" + (opts.currentPage or 1)
for field in ['seller','watched']
value = opts[field]
url += "&#{field}=#{value}" if value
ajax 'GET', url, callback
componentDidMount: ->
if _.isEmpty @state.sellers
ajax 'GET', '/api/sellers', (sellers) => @setState sellers: sellers
if _.isEmpty @state.listings
@queryListings {}, (results) => @setState results
onChangeSeller: (e) ->
seller = e.target.value
@queryListings { seller: seller, watched: @state.watched }, (results) =>
@setState _.assign { seller: seller, currentPage: 1 }, results
onClickPage: (page) ->
@queryListings { currentPage: page, seller: @state.seller, watched: @state.watched }, (results) =>
@setState _.assign { currentPage: page }, results
onClickWatch: (listing) ->
listing.watched = not listing.watched
@setState listings: @state.listings
ajax 'PUT', "/api/listing/#{listing.id}?watched=#{listing.watched}"
onChangeWatch: (e) ->
watched = e.target.checked
@queryListings { seller: @state.seller, watched: watched }, (results) =>
@setState _.assign { watched: watched, currentPage: 1 }, results
render: ->
s = @state
h = React.DOM
h.div {},
factories.SearchFilters seller: s.seller, sellers: s.sellers, onChangeSeller: @onChangeSeller, onChangeWatch: @onChangeWatch
factories.ListingTable listings: s.listings, onClickWatch: @onClickWatch
factories.PaginateFooter currentPage: s.currentPage, lastPage: s.lastPage, onClickPage: @onClickPage
components.SearchFilters = React.createClass
render: ->
p = @props
h = React.DOM
h.p {},
"Seller: "
h.select value: p.seller, onChange: p.onChangeSeller,
h.option { key: "allSellers" }, ""
for seller in p.sellers
h.option { key: seller, value: seller }, seller
" \u00a0\u00a0\u00a0 Watched listings only: "
h.input type: "checkbox", onChange: p.onChangeWatch
components.ListingTable = React.createClass
render: ->
p = @props
h = React.DOM
return h.p {}, "No results found" if _.isEmpty p.listings
h.table {},
h.thead {},
h.tr {},
for header in ["Watch","ID","Seller","Title"]
h.th { key: header }, header
h.tbody {},
for listing in p.listings
factories.ListingRow key: "listing#{listing.id}", listing: listing, onClickWatch: p.onClickWatch
components.ListingRow = React.createClass
render: ->
p = @props
h = React.DOM
listing = p.listing
h.tr {},
h.td onClick: (-> p.onClickWatch listing), className: (if listing.watched then "watched" else "notwatched"),
if listing.watched then "★" else "☆"
h.td {}, listing.id
h.td {}, listing.seller
h.td {}, listing.title
components.PaginateFooter = React.createClass
render: ->
p = @props
h = React.DOM
return h.p {} if p.lastPage == 0
h.p {},
if p.currentPage == 1
"< Previous"
else
h.a href: '#', onClick: (-> p.onClickPage p.currentPage-1), "< Previous"
" "
_.map [1..p.lastPage], (page) ->
key = <KEY> <KEY>
if page == p.currentPage
h.span { key: key, style: fontWeight: 'bold' }, " #{page} "
else
h.span { key: key }, " ", h.a(href:'#', onClick: (-> p.onClickPage page), page), " "
" "
if p.currentPage == p.lastPage
"Next >"
else
h.a href: '#', onClick: (-> p.onClickPage p.currentPage+1), "Next >"
factories = _.mapValues components, React.createFactory
if module?
module.exports = factories.SearchApp
else
@SearchApp = factories.SearchApp
| true | React = @React or require 'react'
_ = @_ or require 'lodash'
ajax = (method, url, callback) ->
request = new XMLHttpRequest()
request.open method, url, true
if method == 'GET'
request.onreadystatechange = ->
callback JSON.parse @responseText if @readyState == 4
request.send()
components = {}
components.SearchApp = React.createClass
getInitialState: ->
_.assign { sellers: [], listings: [], currentPage: 1, lastPage: 1 }, @props
queryListings: (opts, callback) ->
url = "/api/listings?page=" + (opts.currentPage or 1)
for field in ['seller','watched']
value = opts[field]
url += "&#{field}=#{value}" if value
ajax 'GET', url, callback
componentDidMount: ->
if _.isEmpty @state.sellers
ajax 'GET', '/api/sellers', (sellers) => @setState sellers: sellers
if _.isEmpty @state.listings
@queryListings {}, (results) => @setState results
onChangeSeller: (e) ->
seller = e.target.value
@queryListings { seller: seller, watched: @state.watched }, (results) =>
@setState _.assign { seller: seller, currentPage: 1 }, results
onClickPage: (page) ->
@queryListings { currentPage: page, seller: @state.seller, watched: @state.watched }, (results) =>
@setState _.assign { currentPage: page }, results
onClickWatch: (listing) ->
listing.watched = not listing.watched
@setState listings: @state.listings
ajax 'PUT', "/api/listing/#{listing.id}?watched=#{listing.watched}"
onChangeWatch: (e) ->
watched = e.target.checked
@queryListings { seller: @state.seller, watched: watched }, (results) =>
@setState _.assign { watched: watched, currentPage: 1 }, results
render: ->
s = @state
h = React.DOM
h.div {},
factories.SearchFilters seller: s.seller, sellers: s.sellers, onChangeSeller: @onChangeSeller, onChangeWatch: @onChangeWatch
factories.ListingTable listings: s.listings, onClickWatch: @onClickWatch
factories.PaginateFooter currentPage: s.currentPage, lastPage: s.lastPage, onClickPage: @onClickPage
components.SearchFilters = React.createClass
render: ->
p = @props
h = React.DOM
h.p {},
"Seller: "
h.select value: p.seller, onChange: p.onChangeSeller,
h.option { key: "allSellers" }, ""
for seller in p.sellers
h.option { key: seller, value: seller }, seller
" \u00a0\u00a0\u00a0 Watched listings only: "
h.input type: "checkbox", onChange: p.onChangeWatch
components.ListingTable = React.createClass
render: ->
p = @props
h = React.DOM
return h.p {}, "No results found" if _.isEmpty p.listings
h.table {},
h.thead {},
h.tr {},
for header in ["Watch","ID","Seller","Title"]
h.th { key: header }, header
h.tbody {},
for listing in p.listings
factories.ListingRow key: "listing#{listing.id}", listing: listing, onClickWatch: p.onClickWatch
components.ListingRow = React.createClass
render: ->
p = @props
h = React.DOM
listing = p.listing
h.tr {},
h.td onClick: (-> p.onClickWatch listing), className: (if listing.watched then "watched" else "notwatched"),
if listing.watched then "★" else "☆"
h.td {}, listing.id
h.td {}, listing.seller
h.td {}, listing.title
components.PaginateFooter = React.createClass
render: ->
p = @props
h = React.DOM
return h.p {} if p.lastPage == 0
h.p {},
if p.currentPage == 1
"< Previous"
else
h.a href: '#', onClick: (-> p.onClickPage p.currentPage-1), "< Previous"
" "
_.map [1..p.lastPage], (page) ->
key = PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI
if page == p.currentPage
h.span { key: key, style: fontWeight: 'bold' }, " #{page} "
else
h.span { key: key }, " ", h.a(href:'#', onClick: (-> p.onClickPage page), page), " "
" "
if p.currentPage == p.lastPage
"Next >"
else
h.a href: '#', onClick: (-> p.onClickPage p.currentPage+1), "Next >"
factories = _.mapValues components, React.createFactory
if module?
module.exports = factories.SearchApp
else
@SearchApp = factories.SearchApp
|
[
{
"context": "# @author Gianluigi Mango\n# Bootstrap App\nexpress = require 'express'\ndb = ",
"end": 25,
"score": 0.999875545501709,
"start": 10,
"tag": "NAME",
"value": "Gianluigi Mango"
},
{
"context": "app.use session\n\tcookieName: 'session',\n\tsecret: 'eg[isfd-8yF9-7w2315df{}+... | dev/app.coffee | knickatheart/mean-api | 0 | # @author Gianluigi Mango
# Bootstrap App
express = require 'express'
db = require './server/db/connection.js'
api = require './server/apiHandler.js'
bodyParser = require 'body-parser'
session = require 'client-sessions'
app = express()
app.listen '3000', console.info '[Listening] 3000'
app.use bodyParser.urlencoded extended: true
app.use bodyParser.json()
app.use session
cookieName: 'session',
secret: 'eg[isfd-8yF9-7w2315df{}+Ijsli;;to8',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
httpOnly: true,
secure: true,
ephemeral: true
db.connect()
app.use '', express.static __dirname
app.use '/api', (req, res) ->
if req and req.url != '/' then api req, res, req.body else res.send error: 'No endpoint specified'
app.use '/*', (req, res) ->
res.sendFile __dirname + '/index.html'
module.exports = app | 70776 | # @author <NAME>
# Bootstrap App
express = require 'express'
db = require './server/db/connection.js'
api = require './server/apiHandler.js'
bodyParser = require 'body-parser'
session = require 'client-sessions'
app = express()
app.listen '3000', console.info '[Listening] 3000'
app.use bodyParser.urlencoded extended: true
app.use bodyParser.json()
app.use session
cookieName: 'session',
secret: '<KEY>',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
httpOnly: true,
secure: true,
ephemeral: true
db.connect()
app.use '', express.static __dirname
app.use '/api', (req, res) ->
if req and req.url != '/' then api req, res, req.body else res.send error: 'No endpoint specified'
app.use '/*', (req, res) ->
res.sendFile __dirname + '/index.html'
module.exports = app | true | # @author PI:NAME:<NAME>END_PI
# Bootstrap App
express = require 'express'
db = require './server/db/connection.js'
api = require './server/apiHandler.js'
bodyParser = require 'body-parser'
session = require 'client-sessions'
app = express()
app.listen '3000', console.info '[Listening] 3000'
app.use bodyParser.urlencoded extended: true
app.use bodyParser.json()
app.use session
cookieName: 'session',
secret: 'PI:KEY:<KEY>END_PI',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
httpOnly: true,
secure: true,
ephemeral: true
db.connect()
app.use '', express.static __dirname
app.use '/api', (req, res) ->
if req and req.url != '/' then api req, res, req.body else res.send error: 'No endpoint specified'
app.use '/*', (req, res) ->
res.sendFile __dirname + '/index.html'
module.exports = app |
[
{
"context": "d to parentWidget\n setting = {}\n setting.key = \"bolt-account\"\n setting.isInitialized = false\n\n # initializat",
"end": 255,
"score": 0.9985730648040771,
"start": 243,
"tag": "KEY",
"value": "bolt-account"
}
] | src/components/widgets-settings/bolt-account/bolt-account.directive.coffee | maestrano/impac-angular | 7 | module = angular.module('impac.components.widgets-settings.bolt-account',[])
module.controller('SettingBoltAccountCtrl', ($scope, $filter) ->
w = $scope.parentWidget
# What will be passed to parentWidget
setting = {}
setting.key = "bolt-account"
setting.isInitialized = false
# initialization of time range parameters from widget.content.hist_parameters
setting.initialize = ->
w.accountList = setOptions() unless w.content.settings.selectors.length == 0
w.selectedAccount = setSelected()
if w.content? && w.accountList? && w.metadata? && w.metadata.account_uid?
w.selectedAccount = setSelected(w.metadata.account_uid)
setting.isInitialized = true
setting.toMetadata = ->
return { account_uid: w.selectedAccount.account_id } if w.selectedAccount?
setOptions = (name = 'account')->
_.find(w.content.settings.selectors, (selector) ->
selector.name == name
).options
setSelected = (selected = 'total_uid')->
_.find(w.accountList, (acc) ->
acc.account_id == selected
)
formatAmount = (anAccount) ->
balance = null
return $filter('mnoCurrency')(balance, anAccount.currency)
$scope.formatLabel = (anAccount) ->
if anAccount.currency?
"#{anAccount.name} (#{anAccount.currency})"
else
"#{anAccount.name}"
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingBoltAccount', ($templateCache, $translate) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
deferred: '='
label: '@'
showLabel: '=?'
onAccountSelected: '&'
},
link: (scope, element) ->
scope.label = $translate.instant('impac.widget.settings.bolt-account.label') if !scope.label
,template: $templateCache.get('widgets-settings/bolt-account.tmpl.html'),
controller: 'SettingBoltAccountCtrl'
}
)
| 143274 | module = angular.module('impac.components.widgets-settings.bolt-account',[])
module.controller('SettingBoltAccountCtrl', ($scope, $filter) ->
w = $scope.parentWidget
# What will be passed to parentWidget
setting = {}
setting.key = "<KEY>"
setting.isInitialized = false
# initialization of time range parameters from widget.content.hist_parameters
setting.initialize = ->
w.accountList = setOptions() unless w.content.settings.selectors.length == 0
w.selectedAccount = setSelected()
if w.content? && w.accountList? && w.metadata? && w.metadata.account_uid?
w.selectedAccount = setSelected(w.metadata.account_uid)
setting.isInitialized = true
setting.toMetadata = ->
return { account_uid: w.selectedAccount.account_id } if w.selectedAccount?
setOptions = (name = 'account')->
_.find(w.content.settings.selectors, (selector) ->
selector.name == name
).options
setSelected = (selected = 'total_uid')->
_.find(w.accountList, (acc) ->
acc.account_id == selected
)
formatAmount = (anAccount) ->
balance = null
return $filter('mnoCurrency')(balance, anAccount.currency)
$scope.formatLabel = (anAccount) ->
if anAccount.currency?
"#{anAccount.name} (#{anAccount.currency})"
else
"#{anAccount.name}"
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingBoltAccount', ($templateCache, $translate) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
deferred: '='
label: '@'
showLabel: '=?'
onAccountSelected: '&'
},
link: (scope, element) ->
scope.label = $translate.instant('impac.widget.settings.bolt-account.label') if !scope.label
,template: $templateCache.get('widgets-settings/bolt-account.tmpl.html'),
controller: 'SettingBoltAccountCtrl'
}
)
| true | module = angular.module('impac.components.widgets-settings.bolt-account',[])
module.controller('SettingBoltAccountCtrl', ($scope, $filter) ->
w = $scope.parentWidget
# What will be passed to parentWidget
setting = {}
setting.key = "PI:KEY:<KEY>END_PI"
setting.isInitialized = false
# initialization of time range parameters from widget.content.hist_parameters
setting.initialize = ->
w.accountList = setOptions() unless w.content.settings.selectors.length == 0
w.selectedAccount = setSelected()
if w.content? && w.accountList? && w.metadata? && w.metadata.account_uid?
w.selectedAccount = setSelected(w.metadata.account_uid)
setting.isInitialized = true
setting.toMetadata = ->
return { account_uid: w.selectedAccount.account_id } if w.selectedAccount?
setOptions = (name = 'account')->
_.find(w.content.settings.selectors, (selector) ->
selector.name == name
).options
setSelected = (selected = 'total_uid')->
_.find(w.accountList, (acc) ->
acc.account_id == selected
)
formatAmount = (anAccount) ->
balance = null
return $filter('mnoCurrency')(balance, anAccount.currency)
$scope.formatLabel = (anAccount) ->
if anAccount.currency?
"#{anAccount.name} (#{anAccount.currency})"
else
"#{anAccount.name}"
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingBoltAccount', ($templateCache, $translate) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
deferred: '='
label: '@'
showLabel: '=?'
onAccountSelected: '&'
},
link: (scope, element) ->
scope.label = $translate.instant('impac.widget.settings.bolt-account.label') if !scope.label
,template: $templateCache.get('widgets-settings/bolt-account.tmpl.html'),
controller: 'SettingBoltAccountCtrl'
}
)
|
[
{
"context": "E: Name of branch, i.e production.\n#\n# Author:\n# Waleed Ashraf\n\n_ = require 'lodash'\n\napi_key = process.env.MAIL",
"end": 354,
"score": 0.9998433589935303,
"start": 341,
"tag": "NAME",
"value": "Waleed Ashraf"
},
{
"context": "e 'lodash'\n\napi_key = process.en... | github.coffee | chaudhryjunaid/github-push-test | 0 | # Description:
# gitHub repo with branch notification
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Config:
# REPO_NAME: Name of repositories, comma (,) separated values.
# GH_CHANNEL_NAME: Id of slack slack channel to post message, comma (,) separated value.
# GB_BRANCH_NAME: Name of branch, i.e production.
#
# Author:
# Waleed Ashraf
_ = require 'lodash'
api_key = process.env.MAILGUN_KEY || '123'
resPusher = process.env.BLOCKED_GH_NOTIF || ''
domain = process.env.MAILGUN_DOMAIN || ''
fromUser = process.env.FROM_USER || ''
toUser = process.env.TO_USER || ''
subject = process.env.SUBJECT || ''
mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
mailSender = (message) ->
data =
from: fromUser
to: toUser
subject: subject
text: message
mailgun.messages().send data, (error, body) ->
console.log body
return
module.exports = (robot) ->
robot.router.post "/caari/gh-repo-event", (req, res) ->
repoName = process.env.REPO_NAME && process.env.REPO_NAME.split(",") || ""
branch = process.env.GH_BRANCH_NAME || "production"
data = req.body
repo = data.repository || ""
pusher = data.pusher || ""
pusher = data.pusher || ""
if (repoName.indexOf(repo.name) != -1 && data.ref == "refs/heads/#{branch}" && pusher.name != resPusher )
commits = data.commits
head_commit = data.head_commit
commit = data.after
channelName = process.env.GH_CHANNEL_NAME && process.env.GH_CHANNEL_NAME.split(",") || ['G1YLK92RE']
headMessage = head_commit.message.replace(/\r?\n|\r/g,"")
mailCheck = headMessage.indexOf("hotfix");
color = "warning"
title = "PR Merge Alert"
if(mailCheck != -1)
color = "danger"
title = "Hotfix Merge Alert"
for channel in channelName
githubMsg = {
"attachments": [
{
"color": color,
"author_name": "caari",
"title": title,
"text": headMessage,
"fields": [
{
"title": "Branch",
"value": branch,
"short": true
},
{
"title": "To",
"value": repo.full_name,
"short": true
},
{
"title": "By",
"value": pusher.name,
"short": true
},
{
"title": "Link",
"value": head_commit.url,
"short": false
}
]
}
]
}
if(mailCheck != -1)
mailMsg = 'New Commit: ' + headMessage + "\n" + 'Branch: ' + branch + "\n" + 'To: ' + repo.full_name + "\n" + 'By: ' + pusher.name + "\n" + 'Link: ' + head_commit.url
mailSender(mailMsg)
robot.messageRoom channel, "@channel \n"
robot.messageRoom channel, githubMsg
console.log "GH message sent #{head_commit.message} in channel #{channel}"
res.sendStatus(200)
robot.router.post "/caari/gh-pr-event", (req, res) ->
repoName = process.env.REPO_NAME && process.env.REPO_NAME.split(",") || ""
data = req.body
pr = data.pull_request || {}
repo = data.repository || ""
console.log 'PR title:', pr.title
console.log 'Action:', data.action, ', Merged:', pr.merged
if data.action != 'closed' || pr.merged != true
console.log 'uninteresting pr action'
res.sendStatus 200
return
releaseBranches = ['production', 'beta', 'staging']
baseIndex = _.findIndex releaseBranches, (br) ->
pr.base && pr.base.ref && pr.base.ref == br
headIndex = _.findIndex releaseBranches, (br) ->
pr.head && pr.head.ref && pr.head.ref == br
if(baseIndex >= 0 and headIndex >= 0)
console.log "Merged interesting branch..."
release = baseIndex < headIndex
releaseChannelName = process.env.PR_RELEASE_CHANNEL && process.env.PR_RELEASE_CHANNEL.split(",")
backmergeChannelName = process.env.PR_BACKMERGE_CHANNEL && process.env.PR_BACKMERGE_CHANNEL.split(",")
if release
actionText = "released"
channelName = releaseChannelName
thumb_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Creative-Tail-rocket.svg/128px-Creative-Tail-rocket.svg.png"
color = "good"
else
actionText = "backmerged"
channelName = backmergeChannelName
thumb_url = ""
color = "#cccccc"
mergedBy = pr.merged_by && pr.merged_by.login
pretext = repo.full_name + ": " + releaseBranches[headIndex] + " " + actionText + " to " + releaseBranches[baseIndex] + " by " + mergedBy
stats = pr.commits + " commits, "+ pr.additions + " additions, " + pr.deletions + " deletions, " + pr.changed_files + " changed files."
for channel in channelName
githubMsg = {
"attachments": [
{
"fallback": pretext,
"color": color,
"pretext": pretext,
"title": "#" + data.number,
"title_link": pr.html_url,
"text": stats,
"thumb_url": thumb_url
}
]
}
robot.messageRoom channel, "@channel \n"
robot.messageRoom channel, githubMsg
console.log 'release/backmerge alert: ' + JSON.stringify(githubMsg)
res.sendStatus(200) | 68574 | # Description:
# gitHub repo with branch notification
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Config:
# REPO_NAME: Name of repositories, comma (,) separated values.
# GH_CHANNEL_NAME: Id of slack slack channel to post message, comma (,) separated value.
# GB_BRANCH_NAME: Name of branch, i.e production.
#
# Author:
# <NAME>
_ = require 'lodash'
api_key = process.env.MAILGUN_KEY || '<KEY>'
resPusher = process.env.BLOCKED_GH_NOTIF || ''
domain = process.env.MAILGUN_DOMAIN || ''
fromUser = process.env.FROM_USER || ''
toUser = process.env.TO_USER || ''
subject = process.env.SUBJECT || ''
mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
mailSender = (message) ->
data =
from: fromUser
to: toUser
subject: subject
text: message
mailgun.messages().send data, (error, body) ->
console.log body
return
module.exports = (robot) ->
robot.router.post "/caari/gh-repo-event", (req, res) ->
repoName = process.env.REPO_NAME && process.env.REPO_NAME.split(",") || ""
branch = process.env.GH_BRANCH_NAME || "production"
data = req.body
repo = data.repository || ""
pusher = data.pusher || ""
pusher = data.pusher || ""
if (repoName.indexOf(repo.name) != -1 && data.ref == "refs/heads/#{branch}" && pusher.name != resPusher )
commits = data.commits
head_commit = data.head_commit
commit = data.after
channelName = process.env.GH_CHANNEL_NAME && process.env.GH_CHANNEL_NAME.split(",") || ['G1YLK92RE']
headMessage = head_commit.message.replace(/\r?\n|\r/g,"")
mailCheck = headMessage.indexOf("hotfix");
color = "warning"
title = "PR Merge Alert"
if(mailCheck != -1)
color = "danger"
title = "Hotfix Merge Alert"
for channel in channelName
githubMsg = {
"attachments": [
{
"color": color,
"author_name": "caari",
"title": title,
"text": headMessage,
"fields": [
{
"title": "Branch",
"value": branch,
"short": true
},
{
"title": "To",
"value": repo.full_name,
"short": true
},
{
"title": "By",
"value": pusher.name,
"short": true
},
{
"title": "Link",
"value": head_commit.url,
"short": false
}
]
}
]
}
if(mailCheck != -1)
mailMsg = 'New Commit: ' + headMessage + "\n" + 'Branch: ' + branch + "\n" + 'To: ' + repo.full_name + "\n" + 'By: ' + pusher.name + "\n" + 'Link: ' + head_commit.url
mailSender(mailMsg)
robot.messageRoom channel, "@channel \n"
robot.messageRoom channel, githubMsg
console.log "GH message sent #{head_commit.message} in channel #{channel}"
res.sendStatus(200)
robot.router.post "/caari/gh-pr-event", (req, res) ->
repoName = process.env.REPO_NAME && process.env.REPO_NAME.split(",") || ""
data = req.body
pr = data.pull_request || {}
repo = data.repository || ""
console.log 'PR title:', pr.title
console.log 'Action:', data.action, ', Merged:', pr.merged
if data.action != 'closed' || pr.merged != true
console.log 'uninteresting pr action'
res.sendStatus 200
return
releaseBranches = ['production', 'beta', 'staging']
baseIndex = _.findIndex releaseBranches, (br) ->
pr.base && pr.base.ref && pr.base.ref == br
headIndex = _.findIndex releaseBranches, (br) ->
pr.head && pr.head.ref && pr.head.ref == br
if(baseIndex >= 0 and headIndex >= 0)
console.log "Merged interesting branch..."
release = baseIndex < headIndex
releaseChannelName = process.env.PR_RELEASE_CHANNEL && process.env.PR_RELEASE_CHANNEL.split(",")
backmergeChannelName = process.env.PR_BACKMERGE_CHANNEL && process.env.PR_BACKMERGE_CHANNEL.split(",")
if release
actionText = "released"
channelName = releaseChannelName
thumb_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Creative-Tail-rocket.svg/128px-Creative-Tail-rocket.svg.png"
color = "good"
else
actionText = "backmerged"
channelName = backmergeChannelName
thumb_url = ""
color = "#cccccc"
mergedBy = pr.merged_by && pr.merged_by.login
pretext = repo.full_name + ": " + releaseBranches[headIndex] + " " + actionText + " to " + releaseBranches[baseIndex] + " by " + mergedBy
stats = pr.commits + " commits, "+ pr.additions + " additions, " + pr.deletions + " deletions, " + pr.changed_files + " changed files."
for channel in channelName
githubMsg = {
"attachments": [
{
"fallback": pretext,
"color": color,
"pretext": pretext,
"title": "#" + data.number,
"title_link": pr.html_url,
"text": stats,
"thumb_url": thumb_url
}
]
}
robot.messageRoom channel, "@channel \n"
robot.messageRoom channel, githubMsg
console.log 'release/backmerge alert: ' + JSON.stringify(githubMsg)
res.sendStatus(200) | true | # Description:
# gitHub repo with branch notification
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Config:
# REPO_NAME: Name of repositories, comma (,) separated values.
# GH_CHANNEL_NAME: Id of slack slack channel to post message, comma (,) separated value.
# GB_BRANCH_NAME: Name of branch, i.e production.
#
# Author:
# PI:NAME:<NAME>END_PI
_ = require 'lodash'
api_key = process.env.MAILGUN_KEY || 'PI:KEY:<KEY>END_PI'
resPusher = process.env.BLOCKED_GH_NOTIF || ''
domain = process.env.MAILGUN_DOMAIN || ''
fromUser = process.env.FROM_USER || ''
toUser = process.env.TO_USER || ''
subject = process.env.SUBJECT || ''
mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
mailSender = (message) ->
data =
from: fromUser
to: toUser
subject: subject
text: message
mailgun.messages().send data, (error, body) ->
console.log body
return
module.exports = (robot) ->
robot.router.post "/caari/gh-repo-event", (req, res) ->
repoName = process.env.REPO_NAME && process.env.REPO_NAME.split(",") || ""
branch = process.env.GH_BRANCH_NAME || "production"
data = req.body
repo = data.repository || ""
pusher = data.pusher || ""
pusher = data.pusher || ""
if (repoName.indexOf(repo.name) != -1 && data.ref == "refs/heads/#{branch}" && pusher.name != resPusher )
commits = data.commits
head_commit = data.head_commit
commit = data.after
channelName = process.env.GH_CHANNEL_NAME && process.env.GH_CHANNEL_NAME.split(",") || ['G1YLK92RE']
headMessage = head_commit.message.replace(/\r?\n|\r/g,"")
mailCheck = headMessage.indexOf("hotfix");
color = "warning"
title = "PR Merge Alert"
if(mailCheck != -1)
color = "danger"
title = "Hotfix Merge Alert"
for channel in channelName
githubMsg = {
"attachments": [
{
"color": color,
"author_name": "caari",
"title": title,
"text": headMessage,
"fields": [
{
"title": "Branch",
"value": branch,
"short": true
},
{
"title": "To",
"value": repo.full_name,
"short": true
},
{
"title": "By",
"value": pusher.name,
"short": true
},
{
"title": "Link",
"value": head_commit.url,
"short": false
}
]
}
]
}
if(mailCheck != -1)
mailMsg = 'New Commit: ' + headMessage + "\n" + 'Branch: ' + branch + "\n" + 'To: ' + repo.full_name + "\n" + 'By: ' + pusher.name + "\n" + 'Link: ' + head_commit.url
mailSender(mailMsg)
robot.messageRoom channel, "@channel \n"
robot.messageRoom channel, githubMsg
console.log "GH message sent #{head_commit.message} in channel #{channel}"
res.sendStatus(200)
robot.router.post "/caari/gh-pr-event", (req, res) ->
repoName = process.env.REPO_NAME && process.env.REPO_NAME.split(",") || ""
data = req.body
pr = data.pull_request || {}
repo = data.repository || ""
console.log 'PR title:', pr.title
console.log 'Action:', data.action, ', Merged:', pr.merged
if data.action != 'closed' || pr.merged != true
console.log 'uninteresting pr action'
res.sendStatus 200
return
releaseBranches = ['production', 'beta', 'staging']
baseIndex = _.findIndex releaseBranches, (br) ->
pr.base && pr.base.ref && pr.base.ref == br
headIndex = _.findIndex releaseBranches, (br) ->
pr.head && pr.head.ref && pr.head.ref == br
if(baseIndex >= 0 and headIndex >= 0)
console.log "Merged interesting branch..."
release = baseIndex < headIndex
releaseChannelName = process.env.PR_RELEASE_CHANNEL && process.env.PR_RELEASE_CHANNEL.split(",")
backmergeChannelName = process.env.PR_BACKMERGE_CHANNEL && process.env.PR_BACKMERGE_CHANNEL.split(",")
if release
actionText = "released"
channelName = releaseChannelName
thumb_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Creative-Tail-rocket.svg/128px-Creative-Tail-rocket.svg.png"
color = "good"
else
actionText = "backmerged"
channelName = backmergeChannelName
thumb_url = ""
color = "#cccccc"
mergedBy = pr.merged_by && pr.merged_by.login
pretext = repo.full_name + ": " + releaseBranches[headIndex] + " " + actionText + " to " + releaseBranches[baseIndex] + " by " + mergedBy
stats = pr.commits + " commits, "+ pr.additions + " additions, " + pr.deletions + " deletions, " + pr.changed_files + " changed files."
for channel in channelName
githubMsg = {
"attachments": [
{
"fallback": pretext,
"color": color,
"pretext": pretext,
"title": "#" + data.number,
"title_link": pr.html_url,
"text": stats,
"thumb_url": thumb_url
}
]
}
robot.messageRoom channel, "@channel \n"
robot.messageRoom channel, githubMsg
console.log 'release/backmerge alert: ' + JSON.stringify(githubMsg)
res.sendStatus(200) |
[
{
"context": "egram only) - Hide custom keyboard\n#\n# Author:\n# nspacestd\n\nplatforms = require('./lib/platforms.json')\nRewa",
"end": 723,
"score": 0.9996323585510254,
"start": 714,
"tag": "USERNAME",
"value": "nspacestd"
},
{
"context": "text = settingsToString settings\n ... | src/settings.coffee | pabletos/Hubot-Discord | 12 | # Description:
# Allows each user to customize their platform and tracked events/rewards
#
# Dependencies:
# None
#
# Configuration:
# MONGODB_URL - MongoDB url
# HUBOT_LINE_END - Configuragble line-return character
# HUBOT_BLOCK_END - Configuragble string for ending blocks
# HUBOT_DOUBLE_RET - Configurable string for double-line returns
#
# Commands:
# hubot settings - Display settings menu
# hubot platform <platform> - Change platform or display menu if no argument
# hubot track <reward or event> - Start tracking reward or event, menu if no argument
# hubot untrack <reward or event> - Stop tracking reward or event
# hubot end (telegram only) - Hide custom keyboard
#
# Author:
# nspacestd
platforms = require('./lib/platforms.json')
Reward = require('./lib/reward.js')
Users = require('./lib/users.js')
mongoURL = process.env.MONGODB_URL
TRACKABLE = (v for k, v of Reward.TYPES).concat ['alerts', 'invasions', 'news', 'all']
module.exports = (robot) ->
userDB = new Users(mongoURL)
robot.respond /settings/i, (res) ->
userDB.getSettings res.message.room, {}, true, (err, settings) ->
if err
robot.logger.error err
else
text = settingsToString settings
keys = ['platform', 'track']
replyWithKeyboard robot, res, text, keys
robot.respond /platform\s*(\w+)?/, (res) ->
platform = res.match[1]
if not platform
text = 'Choose your platform'
keys = ('platform ' + k for k in platforms)
replyWithKeyboard robot, res, text, keys
else if platform in platforms
userDB.setPlatform res.message.room, platform, (err) ->
if err
robot.logger.error err
else
res.reply 'Platform changed to ' + platform
else
res.reply 'Invalid platform'
robot.respond /track\s*(\w+)?/, (res) ->
type = res.match[1]
if not type
replyWithTrackSettingsKeyboard robot, res, 'Choose one', userDB
else if type in TRACKABLE
userDB.setItemTrack res.message.room, type, true, (err) ->
if err
robot.logger.error err
else
text = 'Tracking settings updated\n\nChoose one'
replyWithTrackSettingsKeyboard robot, res, text, userDB
else
res.reply 'Invalid argument'
robot.respond /untrack\s+(\w+)/, (res) ->
type = res.match[1]
if type in TRACKABLE
userDB.setItemTrack res.message.room, type, false, (err) ->
if err
robot.logger.error err
else
text = 'Tracking settings updated\n\nChoose one'
replyWithTrackSettingsKeyboard robot, res, text, userDB
else
res.reply 'Invalid argument'
# Telegram only
if robot.adapterName is 'telegram'
robot.respond /end/, (res) ->
opts =
chat_id: res.message.room
text: 'Done'
reply_markup:
hide_keyboard: true
selective: true
reply_to_message_id: res.message.id
robot.emit 'telegram:invoke', 'sendMessage', opts, (err, response) ->
robot.logger.error err if err
replyWithKeyboard = (robot, res, text, keys) ->
###
# Reply to res.message with a custom keyboard. Text is the text of the message,
# keys is an array of strings, each one being a key
#
# @param object robot
# @param object res
# @param string text
# @param array keys
###
# Add robot name or alias at the beginning of each key
name = robot.alias or (robot.name + ' ')
keys = (name + k for k in keys)
if robot.adapterName is 'telegram'
keys.push('/end')
# Divide keys in rows of 3 or less
keyboard = while keys.length > 4
keys.splice(0, 3)
keyboard.push keys
opts =
chat_id: res.message.room
text: text
reply_markup:
keyboard: keyboard
one_time_keyboard: true
selective: true
reply_to_message_id: res.message.id
robot.emit 'telegram:invoke', 'sendMessage', opts, (err, response) ->
robot.logger.error err if err
else
# Non-telegram adapter, send a list of commands
res.reply text + '\n\n' + keys.join('\n')
settingsToString = (settings) ->
###
# Return a string representation of an user's current settings
#
# @param object settings
#
# @return string
###
lines = []
lines.push 'Your platform is ' + settings.platform.replace('X1', 'Xbox One')
lines.push 'Alerts are ' + if 'alerts' in settings.items then 'ON' else 'OFF'
lines.push 'Invasions are ' + if 'invasions' in settings.items then 'ON' else 'OFF'
lines.push 'News are ' + if 'news' in settings.items then 'ON' else 'OFF'
lines.push '\nTracked rewards:'
trackedRewards = for i in settings.items when i not in \
['alerts', 'invasions', 'news']
Reward.typeToString(i)
return lines.concat(trackedRewards).join('\n')
replyWithTrackSettingsKeyboard = (robot, res, text, userDB) ->
###
# Send a track/untrack keyboard to the sender of res.message, based on his
# current settings. Convenience function
#
# @param object robot
# @param object res
# @param string text
# @param object userDB
###
userDB.getTrackedItems res.message.room, (err, tracked) ->
if err
robot.logger.error err
else
keys = for t in TRACKABLE
if t in tracked then 'untrack ' + t
else 'track ' + t
replyWithKeyboard robot, res, text, keys
| 166549 | # Description:
# Allows each user to customize their platform and tracked events/rewards
#
# Dependencies:
# None
#
# Configuration:
# MONGODB_URL - MongoDB url
# HUBOT_LINE_END - Configuragble line-return character
# HUBOT_BLOCK_END - Configuragble string for ending blocks
# HUBOT_DOUBLE_RET - Configurable string for double-line returns
#
# Commands:
# hubot settings - Display settings menu
# hubot platform <platform> - Change platform or display menu if no argument
# hubot track <reward or event> - Start tracking reward or event, menu if no argument
# hubot untrack <reward or event> - Stop tracking reward or event
# hubot end (telegram only) - Hide custom keyboard
#
# Author:
# nspacestd
platforms = require('./lib/platforms.json')
Reward = require('./lib/reward.js')
Users = require('./lib/users.js')
mongoURL = process.env.MONGODB_URL
TRACKABLE = (v for k, v of Reward.TYPES).concat ['alerts', 'invasions', 'news', 'all']
module.exports = (robot) ->
userDB = new Users(mongoURL)
robot.respond /settings/i, (res) ->
userDB.getSettings res.message.room, {}, true, (err, settings) ->
if err
robot.logger.error err
else
text = settingsToString settings
keys = ['<KEY>
replyWithKeyboard robot, res, text, keys
robot.respond /platform\s*(\w+)?/, (res) ->
platform = res.match[1]
if not platform
text = 'Choose your platform'
keys = ('<KEY> platforms<KEY>)
replyWithKeyboard robot, res, text, keys
else if platform in platforms
userDB.setPlatform res.message.room, platform, (err) ->
if err
robot.logger.error err
else
res.reply 'Platform changed to ' + platform
else
res.reply 'Invalid platform'
robot.respond /track\s*(\w+)?/, (res) ->
type = res.match[1]
if not type
replyWithTrackSettingsKeyboard robot, res, 'Choose one', userDB
else if type in TRACKABLE
userDB.setItemTrack res.message.room, type, true, (err) ->
if err
robot.logger.error err
else
text = 'Tracking settings updated\n\nChoose one'
replyWithTrackSettingsKeyboard robot, res, text, userDB
else
res.reply 'Invalid argument'
robot.respond /untrack\s+(\w+)/, (res) ->
type = res.match[1]
if type in TRACKABLE
userDB.setItemTrack res.message.room, type, false, (err) ->
if err
robot.logger.error err
else
text = 'Tracking settings updated\n\nChoose one'
replyWithTrackSettingsKeyboard robot, res, text, userDB
else
res.reply 'Invalid argument'
# Telegram only
if robot.adapterName is 'telegram'
robot.respond /end/, (res) ->
opts =
chat_id: res.message.room
text: 'Done'
reply_markup:
hide_keyboard: true
selective: true
reply_to_message_id: res.message.id
robot.emit 'telegram:invoke', 'sendMessage', opts, (err, response) ->
robot.logger.error err if err
replyWithKeyboard = (robot, res, text, keys) ->
###
# Reply to res.message with a custom keyboard. Text is the text of the message,
# keys is an array of strings, each one being a key
#
# @param object robot
# @param object res
# @param string text
# @param array keys
###
# Add robot name or alias at the beginning of each key
name = robot.alias or (robot.name + ' ')
keys = (name + k for k in keys)
if robot.adapterName is 'telegram'
keys.push('/<KEY>')
# Divide keys in rows of 3 or less
keyboard = while keys.length > 4
keys.splice(0, 3)
keyboard.push keys
opts =
chat_id: res.message.room
text: text
reply_markup:
keyboard: keyboard
one_time_keyboard: true
selective: true
reply_to_message_id: res.message.id
robot.emit 'telegram:invoke', 'sendMessage', opts, (err, response) ->
robot.logger.error err if err
else
# Non-telegram adapter, send a list of commands
res.reply text + '\n\n' + keys.join('\n')
settingsToString = (settings) ->
###
# Return a string representation of an user's current settings
#
# @param object settings
#
# @return string
###
lines = []
lines.push 'Your platform is ' + settings.platform.replace('X1', 'Xbox One')
lines.push 'Alerts are ' + if 'alerts' in settings.items then 'ON' else 'OFF'
lines.push 'Invasions are ' + if 'invasions' in settings.items then 'ON' else 'OFF'
lines.push 'News are ' + if 'news' in settings.items then 'ON' else 'OFF'
lines.push '\nTracked rewards:'
trackedRewards = for i in settings.items when i not in \
['alerts', 'invasions', 'news']
Reward.typeToString(i)
return lines.concat(trackedRewards).join('\n')
replyWithTrackSettingsKeyboard = (robot, res, text, userDB) ->
###
# Send a track/untrack keyboard to the sender of res.message, based on his
# current settings. Convenience function
#
# @param object robot
# @param object res
# @param string text
# @param object userDB
###
userDB.getTrackedItems res.message.room, (err, tracked) ->
if err
robot.logger.error err
else
keys = for t in TRACKABLE
if t in tracked then 'untrack ' + t
else 'track ' + t
replyWithKeyboard robot, res, text, keys
| true | # Description:
# Allows each user to customize their platform and tracked events/rewards
#
# Dependencies:
# None
#
# Configuration:
# MONGODB_URL - MongoDB url
# HUBOT_LINE_END - Configuragble line-return character
# HUBOT_BLOCK_END - Configuragble string for ending blocks
# HUBOT_DOUBLE_RET - Configurable string for double-line returns
#
# Commands:
# hubot settings - Display settings menu
# hubot platform <platform> - Change platform or display menu if no argument
# hubot track <reward or event> - Start tracking reward or event, menu if no argument
# hubot untrack <reward or event> - Stop tracking reward or event
# hubot end (telegram only) - Hide custom keyboard
#
# Author:
# nspacestd
platforms = require('./lib/platforms.json')
Reward = require('./lib/reward.js')
Users = require('./lib/users.js')
mongoURL = process.env.MONGODB_URL
TRACKABLE = (v for k, v of Reward.TYPES).concat ['alerts', 'invasions', 'news', 'all']
module.exports = (robot) ->
userDB = new Users(mongoURL)
robot.respond /settings/i, (res) ->
userDB.getSettings res.message.room, {}, true, (err, settings) ->
if err
robot.logger.error err
else
text = settingsToString settings
keys = ['PI:KEY:<KEY>END_PI
replyWithKeyboard robot, res, text, keys
robot.respond /platform\s*(\w+)?/, (res) ->
platform = res.match[1]
if not platform
text = 'Choose your platform'
keys = ('PI:KEY:<KEY>END_PI platformsPI:KEY:<KEY>END_PI)
replyWithKeyboard robot, res, text, keys
else if platform in platforms
userDB.setPlatform res.message.room, platform, (err) ->
if err
robot.logger.error err
else
res.reply 'Platform changed to ' + platform
else
res.reply 'Invalid platform'
robot.respond /track\s*(\w+)?/, (res) ->
type = res.match[1]
if not type
replyWithTrackSettingsKeyboard robot, res, 'Choose one', userDB
else if type in TRACKABLE
userDB.setItemTrack res.message.room, type, true, (err) ->
if err
robot.logger.error err
else
text = 'Tracking settings updated\n\nChoose one'
replyWithTrackSettingsKeyboard robot, res, text, userDB
else
res.reply 'Invalid argument'
robot.respond /untrack\s+(\w+)/, (res) ->
type = res.match[1]
if type in TRACKABLE
userDB.setItemTrack res.message.room, type, false, (err) ->
if err
robot.logger.error err
else
text = 'Tracking settings updated\n\nChoose one'
replyWithTrackSettingsKeyboard robot, res, text, userDB
else
res.reply 'Invalid argument'
# Telegram only
if robot.adapterName is 'telegram'
robot.respond /end/, (res) ->
opts =
chat_id: res.message.room
text: 'Done'
reply_markup:
hide_keyboard: true
selective: true
reply_to_message_id: res.message.id
robot.emit 'telegram:invoke', 'sendMessage', opts, (err, response) ->
robot.logger.error err if err
replyWithKeyboard = (robot, res, text, keys) ->
###
# Reply to res.message with a custom keyboard. Text is the text of the message,
# keys is an array of strings, each one being a key
#
# @param object robot
# @param object res
# @param string text
# @param array keys
###
# Add robot name or alias at the beginning of each key
name = robot.alias or (robot.name + ' ')
keys = (name + k for k in keys)
if robot.adapterName is 'telegram'
keys.push('/PI:KEY:<KEY>END_PI')
# Divide keys in rows of 3 or less
keyboard = while keys.length > 4
keys.splice(0, 3)
keyboard.push keys
opts =
chat_id: res.message.room
text: text
reply_markup:
keyboard: keyboard
one_time_keyboard: true
selective: true
reply_to_message_id: res.message.id
robot.emit 'telegram:invoke', 'sendMessage', opts, (err, response) ->
robot.logger.error err if err
else
# Non-telegram adapter, send a list of commands
res.reply text + '\n\n' + keys.join('\n')
settingsToString = (settings) ->
###
# Return a string representation of an user's current settings
#
# @param object settings
#
# @return string
###
lines = []
lines.push 'Your platform is ' + settings.platform.replace('X1', 'Xbox One')
lines.push 'Alerts are ' + if 'alerts' in settings.items then 'ON' else 'OFF'
lines.push 'Invasions are ' + if 'invasions' in settings.items then 'ON' else 'OFF'
lines.push 'News are ' + if 'news' in settings.items then 'ON' else 'OFF'
lines.push '\nTracked rewards:'
trackedRewards = for i in settings.items when i not in \
['alerts', 'invasions', 'news']
Reward.typeToString(i)
return lines.concat(trackedRewards).join('\n')
replyWithTrackSettingsKeyboard = (robot, res, text, userDB) ->
###
# Send a track/untrack keyboard to the sender of res.message, based on his
# current settings. Convenience function
#
# @param object robot
# @param object res
# @param string text
# @param object userDB
###
userDB.getTrackedItems res.message.room, (err, tracked) ->
if err
robot.logger.error err
else
keys = for t in TRACKABLE
if t in tracked then 'untrack ' + t
else 'track ' + t
replyWithKeyboard robot, res, text, keys
|
[
{
"context": "DEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' +\n 'nopqrstuvwxyz0123456789'\n while token.length < leng",
"end": 752,
"score": 0.5256242156028748,
"start": 751,
"tag": "KEY",
"value": "q"
},
{
"context": "NOPQRSTUVWXYZabcdefghijklm' +\n 'nopqrstuvwxyz0123456789'\n ... | lib/util.coffee | phuoctien/chatbox | 8 | uuid = require 'node-uuid'
geoip = require 'geoip'
url = require 'url'
$q = require 'q'
locationDB = new geoip.City __dirname + '/GeoLiteCity.dat'
module.exports =
inherits: (ctor, superCtor) ->
ctor.super_ = superCtor
ctor:: = Object.create superCtor::,
constructor:
value: ctor
enumerable: false
writeable: true
configurable: true
extend: (one, two) ->
# make sure valid objects
return {} if !one || !two || typeof two isnt 'object'
# iterate over keys, add to target object
one[k] = two[k] for k of two
# return object
return one
uuid: () ->
return uuid.v1()
random: (length) ->
token = ''
list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' +
'nopqrstuvwxyz0123456789'
while token.length < length
token += list.charAt(Math.floor(Math.random() * list.length))
return token
getClientAddr: (req) ->
return false if !req
(req.headers["x-forwarded-for"] or "")
.split(",")[0] || req.connection.remoteAddress
IPLookup: (clientAddr) ->
whitelist = [
'127.0.0.1'
]
deferred = $q.defer()
if !clientAddr || clientAddr in whitelist
promise = deferred.promise
deferred.resolve {}
return promise
locationDB.lookup clientAddr, (err, result) ->
if err
return deferred.reject err
return deferred.resolve result
return deferred.promise
sortArrayOfObjects: (objs, prop, desc) ->
sorted = []
while sorted.length < objs.length
next = null
for o in objs when !(o in sorted)
next = o if !next
next = o if next.prop < o.prop
sorted.push next
return sorted.reverse() if desc
return sorted
extractRequest: (req) ->
return url.parse(req.url, true).query
async: (fn) ->
setTimeout ->
fn
, 0
sluggify: (text) ->
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
translateKeys: (obj, map, strict) ->
return obj if !map || typeof map isnt 'object'
# new obj to hold keys + values
translated = {}
# translate keys
for k of map when obj.hasOwnProperty k
translated[ map[k] ] = obj[k]
# return if new obj should only have keys in keys obj
return translated if strict
# add keys that weren't in keys obj
for k of obj when !map.hasOwnProperty k
translated[k] = obj[k]
return translated
allowCrossDomain: (req, res, next) ->
res.setHeader 'Access-Control-Allow-Origin', '*'
res.setHeader 'Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE'
res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'
next()
| 149476 | uuid = require 'node-uuid'
geoip = require 'geoip'
url = require 'url'
$q = require 'q'
locationDB = new geoip.City __dirname + '/GeoLiteCity.dat'
module.exports =
inherits: (ctor, superCtor) ->
ctor.super_ = superCtor
ctor:: = Object.create superCtor::,
constructor:
value: ctor
enumerable: false
writeable: true
configurable: true
extend: (one, two) ->
# make sure valid objects
return {} if !one || !two || typeof two isnt 'object'
# iterate over keys, add to target object
one[k] = two[k] for k of two
# return object
return one
uuid: () ->
return uuid.v1()
random: (length) ->
token = ''
list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' +
'nop<KEY>rstuvwxyz<KEY>'
while token.length < length
token += list.charAt(Math.floor(Math.random() * list.length))
return token
getClientAddr: (req) ->
return false if !req
(req.headers["x-forwarded-for"] or "")
.split(",")[0] || req.connection.remoteAddress
IPLookup: (clientAddr) ->
whitelist = [
'127.0.0.1'
]
deferred = $q.defer()
if !clientAddr || clientAddr in whitelist
promise = deferred.promise
deferred.resolve {}
return promise
locationDB.lookup clientAddr, (err, result) ->
if err
return deferred.reject err
return deferred.resolve result
return deferred.promise
sortArrayOfObjects: (objs, prop, desc) ->
sorted = []
while sorted.length < objs.length
next = null
for o in objs when !(o in sorted)
next = o if !next
next = o if next.prop < o.prop
sorted.push next
return sorted.reverse() if desc
return sorted
extractRequest: (req) ->
return url.parse(req.url, true).query
async: (fn) ->
setTimeout ->
fn
, 0
sluggify: (text) ->
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
translateKeys: (obj, map, strict) ->
return obj if !map || typeof map isnt 'object'
# new obj to hold keys + values
translated = {}
# translate keys
for k of map when obj.hasOwnProperty k
translated[ map[k] ] = obj[k]
# return if new obj should only have keys in keys obj
return translated if strict
# add keys that weren't in keys obj
for k of obj when !map.hasOwnProperty k
translated[k] = obj[k]
return translated
allowCrossDomain: (req, res, next) ->
res.setHeader 'Access-Control-Allow-Origin', '*'
res.setHeader 'Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE'
res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'
next()
| true | uuid = require 'node-uuid'
geoip = require 'geoip'
url = require 'url'
$q = require 'q'
locationDB = new geoip.City __dirname + '/GeoLiteCity.dat'
module.exports =
inherits: (ctor, superCtor) ->
ctor.super_ = superCtor
ctor:: = Object.create superCtor::,
constructor:
value: ctor
enumerable: false
writeable: true
configurable: true
extend: (one, two) ->
# make sure valid objects
return {} if !one || !two || typeof two isnt 'object'
# iterate over keys, add to target object
one[k] = two[k] for k of two
# return object
return one
uuid: () ->
return uuid.v1()
random: (length) ->
token = ''
list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' +
'nopPI:KEY:<KEY>END_PIrstuvwxyzPI:KEY:<KEY>END_PI'
while token.length < length
token += list.charAt(Math.floor(Math.random() * list.length))
return token
getClientAddr: (req) ->
return false if !req
(req.headers["x-forwarded-for"] or "")
.split(",")[0] || req.connection.remoteAddress
IPLookup: (clientAddr) ->
whitelist = [
'127.0.0.1'
]
deferred = $q.defer()
if !clientAddr || clientAddr in whitelist
promise = deferred.promise
deferred.resolve {}
return promise
locationDB.lookup clientAddr, (err, result) ->
if err
return deferred.reject err
return deferred.resolve result
return deferred.promise
sortArrayOfObjects: (objs, prop, desc) ->
sorted = []
while sorted.length < objs.length
next = null
for o in objs when !(o in sorted)
next = o if !next
next = o if next.prop < o.prop
sorted.push next
return sorted.reverse() if desc
return sorted
extractRequest: (req) ->
return url.parse(req.url, true).query
async: (fn) ->
setTimeout ->
fn
, 0
sluggify: (text) ->
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
translateKeys: (obj, map, strict) ->
return obj if !map || typeof map isnt 'object'
# new obj to hold keys + values
translated = {}
# translate keys
for k of map when obj.hasOwnProperty k
translated[ map[k] ] = obj[k]
# return if new obj should only have keys in keys obj
return translated if strict
# add keys that weren't in keys obj
for k of obj when !map.hasOwnProperty k
translated[k] = obj[k]
return translated
allowCrossDomain: (req, res, next) ->
res.setHeader 'Access-Control-Allow-Origin', '*'
res.setHeader 'Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE'
res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'
next()
|
[
{
"context": " from: {\n id: \"ifel\",\n name: \"IFEL\"\n }\n to: [{\n id: sender_co",
"end": 2444,
"score": 0.9803280830383301,
"start": 2440,
"tag": "NAME",
"value": "IFEL"
}
] | plugins/starpeace-client/api/sandbox/sandbox-mail.coffee | starpeace-project/starpeace-client-website | 1 |
import moment from 'moment'
import _ from 'lodash'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
export default class SandboxMail
constructor: (@sandbox) ->
add_mail: (corporation, id, mail) ->
mail.id = id
if @sandbox.sandbox_data.corporation_id_cashflow[corporation.id]?
@sandbox.sandbox_data.corporation_id_cashflow[corporation.id].lastMailAt = moment(mail.sentAt)
@sandbox.sandbox_data.mail_by_corporation_id[corporation.id] = {} unless @sandbox.sandbox_data.mail_by_corporation_id[corporation.id]?
@sandbox.sandbox_data.mail_by_corporation_id[corporation.id][id] = mail
get: (corporation_id) ->
_.cloneDeep(_.orderBy(_.values(@sandbox.sandbox_data.mail_by_corporation_id[corporation_id]), 'sentAt'))
create: (corporation_id, parameters) ->
throw new Error(400) unless _.trim(parameters.to).length
throw new Error(400) unless _.trim(parameters.subject).length
throw new Error(400) unless _.trim(parameters.body).length
sender_corp = @sandbox.sandbox_data.corporation_by_id[corporation_id]
throw new Error(404) unless sender_corp?
other_corps = _.filter(_.values(@sandbox.sandbox_data.corporation_by_id), (c) -> c.planetId == sender_corp.planetId)
to_corps = []
undeliverable = []
for name in _.trim(parameters.to).split(';')
to_corp = _.find(other_corps, (c) => _.toLower(@sandbox.sandbox_data.tycoon_by_id[c.tycoonId].name) == _.toLower(_.trim(name)))
if to_corp?
to_corps.push to_corp
else
undeliverable.push name
for to_corp in to_corps
@add_mail(to_corp, Utils.uuid(), {
read: false
sentAt: moment().format()
planetSentAt: @sandbox.sandbox_data.planet_id_dates[sender_corp.planetId].format('YYYY-MM-DD')
from: {
id: sender_corp.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[sender_corp.tycoonId].name
}
to: _.map(to_corps, (c) => {
id: c.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[c.tycoonId].name
})
subject: _.trim(parameters.subject)
body: _.trim(parameters.body)
})
if undeliverable.length
@add_mail(sender_corp, Utils.uuid(), {
read: false
sentAt: moment().format()
planetSentAt: @sandbox.sandbox_data.planet_id_dates[sender_corp.planetId].format('YYYY-MM-DD')
from: {
id: "ifel",
name: "IFEL"
}
to: [{
id: sender_corp.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[sender_corp.tycoonId].name
}]
subject: "Undeliverable: #{_.trim(parameters.subject)}"
body: "Unable to deliver mail to #{undeliverable.join(', ')}"
})
_.cloneDeep({})
mark_read: (corporation_id, mail_id) ->
if @sandbox.sandbox_data.mail_by_corporation_id[corporation_id]?[mail_id]?
@sandbox.sandbox_data.mail_by_corporation_id[corporation_id][mail_id].read = true
return true
false
delete: (corporation_id, mail_id) ->
if @sandbox.sandbox_data.mail_by_corporation_id[corporation_id]?[mail_id]?
delete @sandbox.sandbox_data.mail_by_corporation_id[corporation_id][mail_id]
return true
false
| 130639 |
import moment from 'moment'
import _ from 'lodash'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
export default class SandboxMail
constructor: (@sandbox) ->
add_mail: (corporation, id, mail) ->
mail.id = id
if @sandbox.sandbox_data.corporation_id_cashflow[corporation.id]?
@sandbox.sandbox_data.corporation_id_cashflow[corporation.id].lastMailAt = moment(mail.sentAt)
@sandbox.sandbox_data.mail_by_corporation_id[corporation.id] = {} unless @sandbox.sandbox_data.mail_by_corporation_id[corporation.id]?
@sandbox.sandbox_data.mail_by_corporation_id[corporation.id][id] = mail
get: (corporation_id) ->
_.cloneDeep(_.orderBy(_.values(@sandbox.sandbox_data.mail_by_corporation_id[corporation_id]), 'sentAt'))
create: (corporation_id, parameters) ->
throw new Error(400) unless _.trim(parameters.to).length
throw new Error(400) unless _.trim(parameters.subject).length
throw new Error(400) unless _.trim(parameters.body).length
sender_corp = @sandbox.sandbox_data.corporation_by_id[corporation_id]
throw new Error(404) unless sender_corp?
other_corps = _.filter(_.values(@sandbox.sandbox_data.corporation_by_id), (c) -> c.planetId == sender_corp.planetId)
to_corps = []
undeliverable = []
for name in _.trim(parameters.to).split(';')
to_corp = _.find(other_corps, (c) => _.toLower(@sandbox.sandbox_data.tycoon_by_id[c.tycoonId].name) == _.toLower(_.trim(name)))
if to_corp?
to_corps.push to_corp
else
undeliverable.push name
for to_corp in to_corps
@add_mail(to_corp, Utils.uuid(), {
read: false
sentAt: moment().format()
planetSentAt: @sandbox.sandbox_data.planet_id_dates[sender_corp.planetId].format('YYYY-MM-DD')
from: {
id: sender_corp.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[sender_corp.tycoonId].name
}
to: _.map(to_corps, (c) => {
id: c.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[c.tycoonId].name
})
subject: _.trim(parameters.subject)
body: _.trim(parameters.body)
})
if undeliverable.length
@add_mail(sender_corp, Utils.uuid(), {
read: false
sentAt: moment().format()
planetSentAt: @sandbox.sandbox_data.planet_id_dates[sender_corp.planetId].format('YYYY-MM-DD')
from: {
id: "ifel",
name: "<NAME>"
}
to: [{
id: sender_corp.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[sender_corp.tycoonId].name
}]
subject: "Undeliverable: #{_.trim(parameters.subject)}"
body: "Unable to deliver mail to #{undeliverable.join(', ')}"
})
_.cloneDeep({})
mark_read: (corporation_id, mail_id) ->
if @sandbox.sandbox_data.mail_by_corporation_id[corporation_id]?[mail_id]?
@sandbox.sandbox_data.mail_by_corporation_id[corporation_id][mail_id].read = true
return true
false
delete: (corporation_id, mail_id) ->
if @sandbox.sandbox_data.mail_by_corporation_id[corporation_id]?[mail_id]?
delete @sandbox.sandbox_data.mail_by_corporation_id[corporation_id][mail_id]
return true
false
| true |
import moment from 'moment'
import _ from 'lodash'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
export default class SandboxMail
constructor: (@sandbox) ->
add_mail: (corporation, id, mail) ->
mail.id = id
if @sandbox.sandbox_data.corporation_id_cashflow[corporation.id]?
@sandbox.sandbox_data.corporation_id_cashflow[corporation.id].lastMailAt = moment(mail.sentAt)
@sandbox.sandbox_data.mail_by_corporation_id[corporation.id] = {} unless @sandbox.sandbox_data.mail_by_corporation_id[corporation.id]?
@sandbox.sandbox_data.mail_by_corporation_id[corporation.id][id] = mail
get: (corporation_id) ->
_.cloneDeep(_.orderBy(_.values(@sandbox.sandbox_data.mail_by_corporation_id[corporation_id]), 'sentAt'))
create: (corporation_id, parameters) ->
throw new Error(400) unless _.trim(parameters.to).length
throw new Error(400) unless _.trim(parameters.subject).length
throw new Error(400) unless _.trim(parameters.body).length
sender_corp = @sandbox.sandbox_data.corporation_by_id[corporation_id]
throw new Error(404) unless sender_corp?
other_corps = _.filter(_.values(@sandbox.sandbox_data.corporation_by_id), (c) -> c.planetId == sender_corp.planetId)
to_corps = []
undeliverable = []
for name in _.trim(parameters.to).split(';')
to_corp = _.find(other_corps, (c) => _.toLower(@sandbox.sandbox_data.tycoon_by_id[c.tycoonId].name) == _.toLower(_.trim(name)))
if to_corp?
to_corps.push to_corp
else
undeliverable.push name
for to_corp in to_corps
@add_mail(to_corp, Utils.uuid(), {
read: false
sentAt: moment().format()
planetSentAt: @sandbox.sandbox_data.planet_id_dates[sender_corp.planetId].format('YYYY-MM-DD')
from: {
id: sender_corp.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[sender_corp.tycoonId].name
}
to: _.map(to_corps, (c) => {
id: c.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[c.tycoonId].name
})
subject: _.trim(parameters.subject)
body: _.trim(parameters.body)
})
if undeliverable.length
@add_mail(sender_corp, Utils.uuid(), {
read: false
sentAt: moment().format()
planetSentAt: @sandbox.sandbox_data.planet_id_dates[sender_corp.planetId].format('YYYY-MM-DD')
from: {
id: "ifel",
name: "PI:NAME:<NAME>END_PI"
}
to: [{
id: sender_corp.tycoonId,
name: @sandbox.sandbox_data.tycoon_by_id[sender_corp.tycoonId].name
}]
subject: "Undeliverable: #{_.trim(parameters.subject)}"
body: "Unable to deliver mail to #{undeliverable.join(', ')}"
})
_.cloneDeep({})
mark_read: (corporation_id, mail_id) ->
if @sandbox.sandbox_data.mail_by_corporation_id[corporation_id]?[mail_id]?
@sandbox.sandbox_data.mail_by_corporation_id[corporation_id][mail_id].read = true
return true
false
delete: (corporation_id, mail_id) ->
if @sandbox.sandbox_data.mail_by_corporation_id[corporation_id]?[mail_id]?
delete @sandbox.sandbox_data.mail_by_corporation_id[corporation_id][mail_id]
return true
false
|
[
{
"context": "guration:\n# None\n#\n# Commands:\n#\n#\n# Author:\n# francho@spines.me\n\n\nmodule.exports = (robot) ->\n robot.router.get ",
"end": 140,
"score": 0.9999047517776489,
"start": 123,
"tag": "EMAIL",
"value": "francho@spines.me"
}
] | scripts/is-alive-url.coffee | francho/agilico | 1 | # Description:
# expose is alive?
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
#
#
# Author:
# francho@spines.me
module.exports = (robot) ->
robot.router.get '/hubot/is-alive', (req, res) ->
res.send 'OK'
| 147655 | # Description:
# expose is alive?
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
#
#
# Author:
# <EMAIL>
module.exports = (robot) ->
robot.router.get '/hubot/is-alive', (req, res) ->
res.send 'OK'
| true | # Description:
# expose is alive?
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
#
#
# Author:
# PI:EMAIL:<EMAIL>END_PI
module.exports = (robot) ->
robot.router.get '/hubot/is-alive', (req, res) ->
res.send 'OK'
|
[
{
"context": " @pusherKey ?= process.env.ONETEAM_PUSHER_KEY or 'd62fcfd64facee71a178'\n @connected = no\n @accessToken ?= null\n ",
"end": 431,
"score": 0.9996611475944519,
"start": 411,
"tag": "KEY",
"value": "d62fcfd64facee71a178"
}
] | src/client.coffee | oneteam-dev/node-oneteam-client | 1 | {PusherClient} = require 'pusher-node-client'
{EventEmitter} = require 'events'
Team = require './team'
crypto = require 'crypto'
request = require 'request'
class Client extends EventEmitter
constructor: ({ @accessToken, @clientSecret, @clientKey, @pusherKey, @baseURL }) ->
@baseURL ?= process.env.ONETEAM_BASE_API_URL or 'https://api.one-team.io'
@pusherKey ?= process.env.ONETEAM_PUSHER_KEY or 'd62fcfd64facee71a178'
@connected = no
@accessToken ?= null
@clientKey ?= null
@clientSecret ?= null
@pusherClient = null
connect: (callback) ->
return callback() if @connected
@pusherClient = new PusherClient
key: @pusherKey
authEndpoint: "#{@baseURL}/pusher/auth"
@pusherClient.on 'connect', =>
@connected = yes
@emit 'connected'
callback()
@pusherClient.connect()
# request(method, class, path, callback)
# request(method, class, path, data, callback)
# request(method, path, callback)
# request(method, path, data, callback)
request: (method, klass, path, data, callback) ->
if typeof klass is 'string'
callback = data
data = path
path = klass
klass = null
if typeof data is 'function' and not callback
callback = data
data = undefined
fn = =>
url = "#{@baseURL}#{path}"
headers = {}
headers['Authorization'] = "Bearer #{@accessToken}" if @accessToken
method = method.toUpperCase()
method = 'DELETE' if method is 'DEL'
opts = {method, headers}
if ['POST', 'PUT', 'PATCH'].indexOf(method) isnt -1
opts.body = data
opts.json = yes
request url, opts, (err, req, body) =>
if typeof body is 'string'
body = try JSON.parse body
err ?= @errorResponse body
if typeof klass is 'function' && !err && (key = body.key)
body = new klass @, key, body
callback err, req, body
if /\/tokens$/.test path
fn.call @
else
@fetchAccessToken fn
['get', 'post', 'put', 'patch', 'del'].forEach (m) =>
@prototype[m] = (args...) -> @request m, args...
fetchAccessToken: (callback) ->
if @accessToken
process.nextTick callback.bind this, null, @accessToken
return
unless @clientKey && @clientSecret
throw new Error 'accessToken or pair of clientKey + clientSecret is must be set.'
timestamp = @timestamp()
secret_token = crypto
.createHmac('sha256', @clientSecret)
.update("#{@clientKey}:#{timestamp}")
.digest('hex')
@post "/clients/#{@clientKey}/tokens", {timestamp, secret_token}, (err, httpResponse, body) =>
body ?= {}
{token} = body
return callback err, null if err ||= @errorResponse body
@accessToken = token || null
callback null, @accessToken
subscribeChannel: (channelName, callback) ->
@fetchAccessToken (err, accessToken) =>
return callbaack err, null if err
@connect =>
channel = @pusherClient.subscribe channelName, {accessToken}
channel.on 'success', -> callback null, channel
channel.on 'pusher:error', (e) -> callback e, null
errorResponse: (data) ->
{errors} = data
if msg = errors?[0].message
new Error msg
timestamp: -> Date.now()
team: (teamName, callback) ->
@get "/teams/#{teamName}", (err, res, body) =>
return callback err if err ||= @errorResponse body
callback null, new Team(@, teamName, body)
self: (callback) ->
@get '/clients/self', (err, res, body) =>
return callback err if err ||= @errorResponse body
callback null, body
module.exports = Client
| 63182 | {PusherClient} = require 'pusher-node-client'
{EventEmitter} = require 'events'
Team = require './team'
crypto = require 'crypto'
request = require 'request'
class Client extends EventEmitter
constructor: ({ @accessToken, @clientSecret, @clientKey, @pusherKey, @baseURL }) ->
@baseURL ?= process.env.ONETEAM_BASE_API_URL or 'https://api.one-team.io'
@pusherKey ?= process.env.ONETEAM_PUSHER_KEY or '<KEY>'
@connected = no
@accessToken ?= null
@clientKey ?= null
@clientSecret ?= null
@pusherClient = null
connect: (callback) ->
return callback() if @connected
@pusherClient = new PusherClient
key: @pusherKey
authEndpoint: "#{@baseURL}/pusher/auth"
@pusherClient.on 'connect', =>
@connected = yes
@emit 'connected'
callback()
@pusherClient.connect()
# request(method, class, path, callback)
# request(method, class, path, data, callback)
# request(method, path, callback)
# request(method, path, data, callback)
request: (method, klass, path, data, callback) ->
if typeof klass is 'string'
callback = data
data = path
path = klass
klass = null
if typeof data is 'function' and not callback
callback = data
data = undefined
fn = =>
url = "#{@baseURL}#{path}"
headers = {}
headers['Authorization'] = "Bearer #{@accessToken}" if @accessToken
method = method.toUpperCase()
method = 'DELETE' if method is 'DEL'
opts = {method, headers}
if ['POST', 'PUT', 'PATCH'].indexOf(method) isnt -1
opts.body = data
opts.json = yes
request url, opts, (err, req, body) =>
if typeof body is 'string'
body = try JSON.parse body
err ?= @errorResponse body
if typeof klass is 'function' && !err && (key = body.key)
body = new klass @, key, body
callback err, req, body
if /\/tokens$/.test path
fn.call @
else
@fetchAccessToken fn
['get', 'post', 'put', 'patch', 'del'].forEach (m) =>
@prototype[m] = (args...) -> @request m, args...
fetchAccessToken: (callback) ->
if @accessToken
process.nextTick callback.bind this, null, @accessToken
return
unless @clientKey && @clientSecret
throw new Error 'accessToken or pair of clientKey + clientSecret is must be set.'
timestamp = @timestamp()
secret_token = crypto
.createHmac('sha256', @clientSecret)
.update("#{@clientKey}:#{timestamp}")
.digest('hex')
@post "/clients/#{@clientKey}/tokens", {timestamp, secret_token}, (err, httpResponse, body) =>
body ?= {}
{token} = body
return callback err, null if err ||= @errorResponse body
@accessToken = token || null
callback null, @accessToken
subscribeChannel: (channelName, callback) ->
@fetchAccessToken (err, accessToken) =>
return callbaack err, null if err
@connect =>
channel = @pusherClient.subscribe channelName, {accessToken}
channel.on 'success', -> callback null, channel
channel.on 'pusher:error', (e) -> callback e, null
errorResponse: (data) ->
{errors} = data
if msg = errors?[0].message
new Error msg
timestamp: -> Date.now()
team: (teamName, callback) ->
@get "/teams/#{teamName}", (err, res, body) =>
return callback err if err ||= @errorResponse body
callback null, new Team(@, teamName, body)
self: (callback) ->
@get '/clients/self', (err, res, body) =>
return callback err if err ||= @errorResponse body
callback null, body
module.exports = Client
| true | {PusherClient} = require 'pusher-node-client'
{EventEmitter} = require 'events'
Team = require './team'
crypto = require 'crypto'
request = require 'request'
class Client extends EventEmitter
constructor: ({ @accessToken, @clientSecret, @clientKey, @pusherKey, @baseURL }) ->
@baseURL ?= process.env.ONETEAM_BASE_API_URL or 'https://api.one-team.io'
@pusherKey ?= process.env.ONETEAM_PUSHER_KEY or 'PI:KEY:<KEY>END_PI'
@connected = no
@accessToken ?= null
@clientKey ?= null
@clientSecret ?= null
@pusherClient = null
connect: (callback) ->
return callback() if @connected
@pusherClient = new PusherClient
key: @pusherKey
authEndpoint: "#{@baseURL}/pusher/auth"
@pusherClient.on 'connect', =>
@connected = yes
@emit 'connected'
callback()
@pusherClient.connect()
# request(method, class, path, callback)
# request(method, class, path, data, callback)
# request(method, path, callback)
# request(method, path, data, callback)
request: (method, klass, path, data, callback) ->
if typeof klass is 'string'
callback = data
data = path
path = klass
klass = null
if typeof data is 'function' and not callback
callback = data
data = undefined
fn = =>
url = "#{@baseURL}#{path}"
headers = {}
headers['Authorization'] = "Bearer #{@accessToken}" if @accessToken
method = method.toUpperCase()
method = 'DELETE' if method is 'DEL'
opts = {method, headers}
if ['POST', 'PUT', 'PATCH'].indexOf(method) isnt -1
opts.body = data
opts.json = yes
request url, opts, (err, req, body) =>
if typeof body is 'string'
body = try JSON.parse body
err ?= @errorResponse body
if typeof klass is 'function' && !err && (key = body.key)
body = new klass @, key, body
callback err, req, body
if /\/tokens$/.test path
fn.call @
else
@fetchAccessToken fn
['get', 'post', 'put', 'patch', 'del'].forEach (m) =>
@prototype[m] = (args...) -> @request m, args...
fetchAccessToken: (callback) ->
if @accessToken
process.nextTick callback.bind this, null, @accessToken
return
unless @clientKey && @clientSecret
throw new Error 'accessToken or pair of clientKey + clientSecret is must be set.'
timestamp = @timestamp()
secret_token = crypto
.createHmac('sha256', @clientSecret)
.update("#{@clientKey}:#{timestamp}")
.digest('hex')
@post "/clients/#{@clientKey}/tokens", {timestamp, secret_token}, (err, httpResponse, body) =>
body ?= {}
{token} = body
return callback err, null if err ||= @errorResponse body
@accessToken = token || null
callback null, @accessToken
subscribeChannel: (channelName, callback) ->
@fetchAccessToken (err, accessToken) =>
return callbaack err, null if err
@connect =>
channel = @pusherClient.subscribe channelName, {accessToken}
channel.on 'success', -> callback null, channel
channel.on 'pusher:error', (e) -> callback e, null
errorResponse: (data) ->
{errors} = data
if msg = errors?[0].message
new Error msg
timestamp: -> Date.now()
team: (teamName, callback) ->
@get "/teams/#{teamName}", (err, res, body) =>
return callback err if err ||= @errorResponse body
callback null, new Team(@, teamName, body)
self: (callback) ->
@get '/clients/self', (err, res, body) =>
return callback err if err ||= @errorResponse body
callback null, body
module.exports = Client
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999120831489563,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/profile-page/extra-header.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div, h2, i, span } from 'react-dom-factories'
el = React.createElement
export ExtraHeader = (props) ->
div null,
h2 className: 'title title--page-extra', osu.trans("users.show.extra.#{props.name}.title")
if props.withEdit
span className: 'page-extra__dragdrop-toggle hidden-xs js-profile-page-extra--sortable-handle',
i className: 'fas fa-bars'
| 213601 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div, h2, i, span } from 'react-dom-factories'
el = React.createElement
export ExtraHeader = (props) ->
div null,
h2 className: 'title title--page-extra', osu.trans("users.show.extra.#{props.name}.title")
if props.withEdit
span className: 'page-extra__dragdrop-toggle hidden-xs js-profile-page-extra--sortable-handle',
i className: 'fas fa-bars'
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div, h2, i, span } from 'react-dom-factories'
el = React.createElement
export ExtraHeader = (props) ->
div null,
h2 className: 'title title--page-extra', osu.trans("users.show.extra.#{props.name}.title")
if props.withEdit
span className: 'page-extra__dragdrop-toggle hidden-xs js-profile-page-extra--sortable-handle',
i className: 'fas fa-bars'
|
[
{
"context": "->\n transporter.sendMail\n from: 'Itservice ✔ <words@oleg-sidorkin.ru>'\n to: \"kalinon7@gmail.com\"\n subject: \"[Wor",
"end": 261,
"score": 0.9999315142631531,
"start": 239,
"tag": "EMAIL",
"value": "words@oleg-sidorkin.ru"
},
{
"context": ": 'Itservice ✔ <... | app/controllers/callback.server.controller.coffee | amIwho/words | 0 | nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport(require('nodemailer-sendmail-transport')(
path: '/usr/sbin/sendmail'
))
'use strict'
exports.send = (req, res) ->
transporter.sendMail
from: 'Itservice ✔ <words@oleg-sidorkin.ru>'
to: "kalinon7@gmail.com"
subject: "[Words]"
text: req.body.callback_text
, (err, info) ->
if err then console.error err
res.end('Сообщение успешно отправлено!')
#todo: save to database
| 78385 | nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport(require('nodemailer-sendmail-transport')(
path: '/usr/sbin/sendmail'
))
'use strict'
exports.send = (req, res) ->
transporter.sendMail
from: 'Itservice ✔ <<EMAIL>>'
to: "<EMAIL>"
subject: "[Words]"
text: req.body.callback_text
, (err, info) ->
if err then console.error err
res.end('Сообщение успешно отправлено!')
#todo: save to database
| true | nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport(require('nodemailer-sendmail-transport')(
path: '/usr/sbin/sendmail'
))
'use strict'
exports.send = (req, res) ->
transporter.sendMail
from: 'Itservice ✔ <PI:EMAIL:<EMAIL>END_PI>'
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[Words]"
text: req.body.callback_text
, (err, info) ->
if err then console.error err
res.end('Сообщение успешно отправлено!')
#todo: save to database
|
[
{
"context": " [\r\n {\r\n name: 'FirstName'\r\n displayName: 'Firstname'\r\n ",
"end": 1126,
"score": 0.9974489808082581,
"start": 1117,
"tag": "NAME",
"value": "FirstName"
},
{
"context": "e: 'FirstName'\r\n di... | AgeRanger/Scripts/age-ranger/age-ranger-grid-directive.coffee | ejbaling/AgeRanger | 0 | ranger = angular.module 'dbsAgeRanger'
ranger.directive 'dbsAgeRangerGrid', ->
restrict: 'E'
replace: true
scope:
templateUrl: './age-ranger-grid.tpl.html'
controllerAs: 'vm'
controller: ranger.cC
inject: ['$scope', '$timeout', '$window', '$element', '$http']
data:
rowHeight: 38
columnWidth: 100
init: ->
@$scope.gridOptions = {
#data: 'chargeLines'
enableSorting: false
enableColumnMenus: false
enableHorizontalScrollbar: @uiGridConstants.scrollbars.NEVER
enableVerticalScrollbar: @uiGridConstants.scrollbars.NEVER
rowHeight: @rowHeight
showFooter: false
minRowsToShow: 0
enableCellEditOnFocus: true
rowTemplate:'<div><div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ng-class="{ \'ui-grid-row-header-cell\': col.isRowHeader }" ui-grid-cell></div></div>'
columnDefs: [
{
name: 'FirstName'
displayName: 'Firstname'
enableCellEdit: true
cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scope"><span>{{row.entity.firstName}}</span></div>'
}
]
}
methods:
| 174275 | ranger = angular.module 'dbsAgeRanger'
ranger.directive 'dbsAgeRangerGrid', ->
restrict: 'E'
replace: true
scope:
templateUrl: './age-ranger-grid.tpl.html'
controllerAs: 'vm'
controller: ranger.cC
inject: ['$scope', '$timeout', '$window', '$element', '$http']
data:
rowHeight: 38
columnWidth: 100
init: ->
@$scope.gridOptions = {
#data: 'chargeLines'
enableSorting: false
enableColumnMenus: false
enableHorizontalScrollbar: @uiGridConstants.scrollbars.NEVER
enableVerticalScrollbar: @uiGridConstants.scrollbars.NEVER
rowHeight: @rowHeight
showFooter: false
minRowsToShow: 0
enableCellEditOnFocus: true
rowTemplate:'<div><div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ng-class="{ \'ui-grid-row-header-cell\': col.isRowHeader }" ui-grid-cell></div></div>'
columnDefs: [
{
name: '<NAME>'
displayName: '<NAME>'
enableCellEdit: true
cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scope"><span>{{row.entity.firstName}}</span></div>'
}
]
}
methods:
| true | ranger = angular.module 'dbsAgeRanger'
ranger.directive 'dbsAgeRangerGrid', ->
restrict: 'E'
replace: true
scope:
templateUrl: './age-ranger-grid.tpl.html'
controllerAs: 'vm'
controller: ranger.cC
inject: ['$scope', '$timeout', '$window', '$element', '$http']
data:
rowHeight: 38
columnWidth: 100
init: ->
@$scope.gridOptions = {
#data: 'chargeLines'
enableSorting: false
enableColumnMenus: false
enableHorizontalScrollbar: @uiGridConstants.scrollbars.NEVER
enableVerticalScrollbar: @uiGridConstants.scrollbars.NEVER
rowHeight: @rowHeight
showFooter: false
minRowsToShow: 0
enableCellEditOnFocus: true
rowTemplate:'<div><div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ng-class="{ \'ui-grid-row-header-cell\': col.isRowHeader }" ui-grid-cell></div></div>'
columnDefs: [
{
name: 'PI:NAME:<NAME>END_PI'
displayName: 'PI:NAME:<NAME>END_PI'
enableCellEdit: true
cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scope"><span>{{row.entity.firstName}}</span></div>'
}
]
}
methods:
|
[
{
"context": "\n stateSave: true\n columns: [\n {data: 'farmer_name'}\n {data: 'commodity'}\n {data: 'value'}",
"end": 217,
"score": 0.9706026315689087,
"start": 206,
"tag": "NAME",
"value": "farmer_name"
}
] | app/assets/javascripts/loans.coffee | wagura-maurice/glowing-umbrella | 0 | ready = ->
$('#loans-table').dataTable
processing: true
serverSide: true
ajax: $('#loans-table').data('source')
pagingType: 'full_numbers'
stateSave: true
columns: [
{data: 'farmer_name'}
{data: 'commodity'}
{data: 'value'}
{data: 'time_period'}
{data: 'interest_rate'}
{data: 'interest_period'}
{data: 'duration'}
{data: 'duration_unit'}
{data: 'status'}
{data: 'disbursed_date'}
{data: 'disbursal_method'}
{data: 'created_at'}
]
$(document).ready(ready)
$(document).on('turbolinks:load', ready) | 74419 | ready = ->
$('#loans-table').dataTable
processing: true
serverSide: true
ajax: $('#loans-table').data('source')
pagingType: 'full_numbers'
stateSave: true
columns: [
{data: '<NAME>'}
{data: 'commodity'}
{data: 'value'}
{data: 'time_period'}
{data: 'interest_rate'}
{data: 'interest_period'}
{data: 'duration'}
{data: 'duration_unit'}
{data: 'status'}
{data: 'disbursed_date'}
{data: 'disbursal_method'}
{data: 'created_at'}
]
$(document).ready(ready)
$(document).on('turbolinks:load', ready) | true | ready = ->
$('#loans-table').dataTable
processing: true
serverSide: true
ajax: $('#loans-table').data('source')
pagingType: 'full_numbers'
stateSave: true
columns: [
{data: 'PI:NAME:<NAME>END_PI'}
{data: 'commodity'}
{data: 'value'}
{data: 'time_period'}
{data: 'interest_rate'}
{data: 'interest_period'}
{data: 'duration'}
{data: 'duration_unit'}
{data: 'status'}
{data: 'disbursed_date'}
{data: 'disbursal_method'}
{data: 'created_at'}
]
$(document).ready(ready)
$(document).on('turbolinks:load', ready) |
[
{
"context": "{\n author:\n name: \"Bryant Williams\"\n email: \"b.n.williams@gmail.com\"\n collection",
"end": 38,
"score": 0.9998858571052551,
"start": 23,
"tag": "NAME",
"value": "Bryant Williams"
},
{
"context": " author:\n name: \"Bryant Williams\"\n email: \"b.n.... | bootstrap/app/config.cson | lessthan3/dobi | 5 | {
author:
name: "Bryant Williams"
email: "b.n.williams@gmail.com"
collections:
'projects': 'project'
core: '2.0.0'
description: "My first dobi app"
id: "bootstrap-app"
name: "My First Dobi App"
pages: [
'biography'
'instagram'
'soundcloud'
'project-gallery'
]
regions: [
'header'
'footer'
'mobile-nav'
]
type: 'app'
version: "1.0.0"
}
| 42191 | {
author:
name: "<NAME>"
email: "<EMAIL>"
collections:
'projects': 'project'
core: '2.0.0'
description: "My first dobi app"
id: "bootstrap-app"
name: "My First Dobi App"
pages: [
'biography'
'instagram'
'soundcloud'
'project-gallery'
]
regions: [
'header'
'footer'
'mobile-nav'
]
type: 'app'
version: "1.0.0"
}
| true | {
author:
name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
collections:
'projects': 'project'
core: '2.0.0'
description: "My first dobi app"
id: "bootstrap-app"
name: "My First Dobi App"
pages: [
'biography'
'instagram'
'soundcloud'
'project-gallery'
]
regions: [
'header'
'footer'
'mobile-nav'
]
type: 'app'
version: "1.0.0"
}
|
[
{
"context": "{}\n @turtles = [\n { id: 1, _id: 1, name: 'Donatello', resource: 'turtles' }\n { id: 2, _id: 2, na",
"end": 284,
"score": 0.9998051524162292,
"start": 275,
"tag": "NAME",
"value": "Donatello"
},
{
"context": "source: 'turtles' }\n { id: 2, _id: 2, nam... | test/plugin_nedb.coffee | mupat/hotcoffee-nedb | 0 | should = require 'should'
sinon = require 'sinon'
EventEmitter = require('events').EventEmitter
Plugin = require "#{__dirname}/../index"
describe 'plugin nedb', ->
beforeEach ->
@app = new EventEmitter()
@app.db = {}
@turtles = [
{ id: 1, _id: 1, name: 'Donatello', resource: 'turtles' }
{ id: 2, _id: 2, name: 'Leonardo', resource: 'turtles' }
{ id: 3, _id: 3, name: 'Michelangelo', resource: 'turtles2' }
{ id: 4, _id: 4, name: 'Raphael', resource: 'turtles2' }
]
@client =
loadDatabase: sinon.stub()
insert: sinon.stub()
remove: sinon.stub()
update: sinon.stub()
find: sinon.stub()
@client.loadDatabase.callsArgWith 0, null
@client.find.callsArgWith 1, null, @turtles
@client.insert.callsArgWith 1, null, {}
@client.update.callsArgWith 3, null, @turtles.length
@client.remove.callsArgWith 2, null, @turtles.length
it 'should provide the correct name', ->
@plugin = Plugin @app, {client: @client}
@plugin.name.should.equal 'nedb'
describe 'loadDatabase', ->
it 'should load the database', ->
@plugin = Plugin @app, {client: @client}
@client.loadDatabase.calledOnce.should.be.true
@client.find.calledOnce.should.be.true
it 'should throw the load database error', ->
@client.loadDatabase.callsArgWith 0, new Error('error')
try
@plugin = Plugin @app, {client: @client}
catch error
error.message.should.equal 'error'
describe 'loadDocuments', ->
it 'should add the documents to the app db', ->
@plugin = Plugin @app, {client: @client}
Object.keys(@app.db).should.eql ['turtles', 'turtles2']
it 'should throw the find error', ->
@client.find.callsArgWith 1, new Error('error')
try
@plugin = Plugin @app, {client: @client}
catch error
error.message.should.equal 'error'
describe 'registerEvents', ->
it 'should react on POST events', (done) ->
resource = 'beatles'
data = name: 'John Lennon'
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "new document inserted"
data.resource = resource
@client.insert.calledWith(data).should.be.true
done()
@app.emit 'POST', resource, data
it 'should emit the POST insert error', (done) ->
@client.insert.callsArgWith 1, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'POST', '', {}
it 'should react on PATCH events', (done) ->
resource = 'turtles'
items = @turtles
data = status: 'hungry'
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "#{@turtles.length} documents updated"
@client.update.calledOnce.should.be.true
done()
@app.emit 'PATCH', resource, items, data
it 'should emit the PATCH insert error', (done) ->
@client.update.callsArgWith 3, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'PATCH', '', [], {}
it 'should react on DELETE events', (done) ->
resource = 'turtles'
items = @turtles
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "#{@turtles.length} documents removed"
@client.remove.calledOnce.should.be.true
done()
@app.emit 'DELETE', resource, items
it 'should emit the DELETE insert error', (done) ->
@client.remove.callsArgWith 2, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'DELETE', '', []
| 136784 | should = require 'should'
sinon = require 'sinon'
EventEmitter = require('events').EventEmitter
Plugin = require "#{__dirname}/../index"
describe 'plugin nedb', ->
beforeEach ->
@app = new EventEmitter()
@app.db = {}
@turtles = [
{ id: 1, _id: 1, name: '<NAME>', resource: 'turtles' }
{ id: 2, _id: 2, name: '<NAME>', resource: 'turtles' }
{ id: 3, _id: 3, name: '<NAME>', resource: 'turtles2' }
{ id: 4, _id: 4, name: '<NAME>', resource: 'turtles2' }
]
@client =
loadDatabase: sinon.stub()
insert: sinon.stub()
remove: sinon.stub()
update: sinon.stub()
find: sinon.stub()
@client.loadDatabase.callsArgWith 0, null
@client.find.callsArgWith 1, null, @turtles
@client.insert.callsArgWith 1, null, {}
@client.update.callsArgWith 3, null, @turtles.length
@client.remove.callsArgWith 2, null, @turtles.length
it 'should provide the correct name', ->
@plugin = Plugin @app, {client: @client}
@plugin.name.should.equal 'nedb'
describe 'loadDatabase', ->
it 'should load the database', ->
@plugin = Plugin @app, {client: @client}
@client.loadDatabase.calledOnce.should.be.true
@client.find.calledOnce.should.be.true
it 'should throw the load database error', ->
@client.loadDatabase.callsArgWith 0, new Error('error')
try
@plugin = Plugin @app, {client: @client}
catch error
error.message.should.equal 'error'
describe 'loadDocuments', ->
it 'should add the documents to the app db', ->
@plugin = Plugin @app, {client: @client}
Object.keys(@app.db).should.eql ['turtles', 'turtles2']
it 'should throw the find error', ->
@client.find.callsArgWith 1, new Error('error')
try
@plugin = Plugin @app, {client: @client}
catch error
error.message.should.equal 'error'
describe 'registerEvents', ->
it 'should react on POST events', (done) ->
resource = 'beatles'
data = name: '<NAME>'
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "new document inserted"
data.resource = resource
@client.insert.calledWith(data).should.be.true
done()
@app.emit 'POST', resource, data
it 'should emit the POST insert error', (done) ->
@client.insert.callsArgWith 1, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'POST', '', {}
it 'should react on PATCH events', (done) ->
resource = 'turtles'
items = @turtles
data = status: 'hungry'
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "#{@turtles.length} documents updated"
@client.update.calledOnce.should.be.true
done()
@app.emit 'PATCH', resource, items, data
it 'should emit the PATCH insert error', (done) ->
@client.update.callsArgWith 3, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'PATCH', '', [], {}
it 'should react on DELETE events', (done) ->
resource = 'turtles'
items = @turtles
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "#{@turtles.length} documents removed"
@client.remove.calledOnce.should.be.true
done()
@app.emit 'DELETE', resource, items
it 'should emit the DELETE insert error', (done) ->
@client.remove.callsArgWith 2, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'DELETE', '', []
| true | should = require 'should'
sinon = require 'sinon'
EventEmitter = require('events').EventEmitter
Plugin = require "#{__dirname}/../index"
describe 'plugin nedb', ->
beforeEach ->
@app = new EventEmitter()
@app.db = {}
@turtles = [
{ id: 1, _id: 1, name: 'PI:NAME:<NAME>END_PI', resource: 'turtles' }
{ id: 2, _id: 2, name: 'PI:NAME:<NAME>END_PI', resource: 'turtles' }
{ id: 3, _id: 3, name: 'PI:NAME:<NAME>END_PI', resource: 'turtles2' }
{ id: 4, _id: 4, name: 'PI:NAME:<NAME>END_PI', resource: 'turtles2' }
]
@client =
loadDatabase: sinon.stub()
insert: sinon.stub()
remove: sinon.stub()
update: sinon.stub()
find: sinon.stub()
@client.loadDatabase.callsArgWith 0, null
@client.find.callsArgWith 1, null, @turtles
@client.insert.callsArgWith 1, null, {}
@client.update.callsArgWith 3, null, @turtles.length
@client.remove.callsArgWith 2, null, @turtles.length
it 'should provide the correct name', ->
@plugin = Plugin @app, {client: @client}
@plugin.name.should.equal 'nedb'
describe 'loadDatabase', ->
it 'should load the database', ->
@plugin = Plugin @app, {client: @client}
@client.loadDatabase.calledOnce.should.be.true
@client.find.calledOnce.should.be.true
it 'should throw the load database error', ->
@client.loadDatabase.callsArgWith 0, new Error('error')
try
@plugin = Plugin @app, {client: @client}
catch error
error.message.should.equal 'error'
describe 'loadDocuments', ->
it 'should add the documents to the app db', ->
@plugin = Plugin @app, {client: @client}
Object.keys(@app.db).should.eql ['turtles', 'turtles2']
it 'should throw the find error', ->
@client.find.callsArgWith 1, new Error('error')
try
@plugin = Plugin @app, {client: @client}
catch error
error.message.should.equal 'error'
describe 'registerEvents', ->
it 'should react on POST events', (done) ->
resource = 'beatles'
data = name: 'PI:NAME:<NAME>END_PI'
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "new document inserted"
data.resource = resource
@client.insert.calledWith(data).should.be.true
done()
@app.emit 'POST', resource, data
it 'should emit the POST insert error', (done) ->
@client.insert.callsArgWith 1, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'POST', '', {}
it 'should react on PATCH events', (done) ->
resource = 'turtles'
items = @turtles
data = status: 'hungry'
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "#{@turtles.length} documents updated"
@client.update.calledOnce.should.be.true
done()
@app.emit 'PATCH', resource, items, data
it 'should emit the PATCH insert error', (done) ->
@client.update.callsArgWith 3, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'PATCH', '', [], {}
it 'should react on DELETE events', (done) ->
resource = 'turtles'
items = @turtles
@plugin = Plugin @app, {client: @client}
@plugin.on 'info', (text) =>
text.should.equal "#{@turtles.length} documents removed"
@client.remove.calledOnce.should.be.true
done()
@app.emit 'DELETE', resource, items
it 'should emit the DELETE insert error', (done) ->
@client.remove.callsArgWith 2, new Error('error')
@plugin = Plugin @app, {client: @client}
@plugin.on 'error', (error) =>
error.message.should.equal "error"
done()
@app.emit 'DELETE', '', []
|
[
{
"context": "onsole.log(ec.n)\nconsole.log(\"here\")\nuser_pass = \"042611d8bbdefaf509fa4775dad17af0cb10e51f935092d246818479f70037d7e64cbb8fdfe2c17e3d8ea38001057b81340f80420718e2ca22793f5647b48cf0d2\"\n\npub = ec.keyFromPublic(user_pass,'hex'); \n\nprke",
"end": 320,
"score": 0.9768722057342529,
"s... | perfomance_simulations/idbp/test.coffee | lucy7li/compromised-credential-checking | 6 | crypto = require 'crypto';
ecc = require 'elliptic';
fs = require 'fs';
EC = ecc.ec;
BN = require 'bn.js';
ec = new EC('secp256k1');
console.log(ec.n)
console.log("here")
user_pass = "042611d8bbdefaf509fa4775dad17af0cb10e51f935092d246818479f70037d7e64cbb8fdfe2c17e3d8ea38001057b81340f80420718e2ca22793f5647b48cf0d2"
pub = ec.keyFromPublic(user_pass,'hex');
prkey = "8e8f61c213e6ad81888bca3972a3adac6df6f1f40303b910dd3a6b04a2137175"
key = ec.keyFromPrivate(prkey,'hex')
console.log(key.getPublic().getX().toString('hex'))
str = "Password456"
msg = crypto.createHash("sha256").update(str).digest('hex');
console.log(msg)
| 189708 | crypto = require 'crypto';
ecc = require 'elliptic';
fs = require 'fs';
EC = ecc.ec;
BN = require 'bn.js';
ec = new EC('secp256k1');
console.log(ec.n)
console.log("here")
user_pass = "<PASSWORD>"
pub = ec.keyFromPublic(user_pass,'hex');
prkey = "<KEY>"
key = ec.keyFromPrivate(prkey,'hex')
console.log(key.getPublic().getX().toString('hex'))
str = "Password456"
msg = crypto.createHash("sha256").update(str).digest('hex');
console.log(msg)
| true | crypto = require 'crypto';
ecc = require 'elliptic';
fs = require 'fs';
EC = ecc.ec;
BN = require 'bn.js';
ec = new EC('secp256k1');
console.log(ec.n)
console.log("here")
user_pass = "PI:PASSWORD:<PASSWORD>END_PI"
pub = ec.keyFromPublic(user_pass,'hex');
prkey = "PI:KEY:<KEY>END_PI"
key = ec.keyFromPrivate(prkey,'hex')
console.log(key.getPublic().getX().toString('hex'))
str = "Password456"
msg = crypto.createHash("sha256").update(str).digest('hex');
console.log(msg)
|
[
{
"context": "or data-mapping in the views.\n# Credit goes out to Alex MacCaw and his Spine framework for very\n# obvious inspir",
"end": 163,
"score": 0.9998148679733276,
"start": 152,
"tag": "NAME",
"value": "Alex MacCaw"
}
] | src/model.coffee | ShaunSpringer/Wraith | 2 | #
# Our data model used throughout the application. Currently it is requred
# to do any data-binding or data-mapping in the views.
# Credit goes out to Alex MacCaw and his Spine framework for very
# obvious inspiration.
#
class Wraith.Model extends Wraith.Base
#
# Sets up a field with the given name and options.
#
# @param [String] name The name of the field to setup
# @param [Object] opt The options object (optional). Used to setup defaults.
#
@field: (name, opt) ->
@fields ?= {}
@fields[name] = opt ? {}
#
# Sets up a collection given the {Wraith.Collection} object
# and options object.
#
# @param [Wraith.Collection] klass The collection object to use.
# @param [String] as The name of the collection within this model.
# @param [Object] opt The options to apply to this collection.
#
@hasMany: (klass, as, opt) ->
opt ?= {}
opt.klass ?= klass
opt.as ?= as
@collections ?= {}
@collections[as] = opt
#
# Constructor
#
# @param [Object] attributes An attributes object to apply to the model upon intialization.
#
constructor: (attributes) ->
Wraith.log '@Wraith.Model', 'constructor'
super()
# Create unique ID if one doesnt exist
# @todo Could use a refactor
@constructor.fields ?= {}
@constructor.fields['_id'] = { default: Wraith.uniqueId } unless attributes?['_id']
@errorCache_ = {}
@reset attributes
Wraith.models[@attributes['_id']] = @
@
#
# Perform a reset of the models attributes. Will trigger
# "change" events on each property that is reset.
#
# @param [Object] attributes Contains all default data to be
# applied to the object when being reset.
#
reset: (attributes) ->
@attributes = {}
for name, options of @constructor.fields
if attributes?[name]?
d = attributes[name]
else
d = if (Wraith.isFunction(options['default'])) then options['default']() else options['default']
@set name, d
for name, options of @constructor.collections
@attributes[name] = new Wraith.Collection(@, options.as, options.klass)
#
# Returns the value for the given key. Will return undefined if
# not found on the attributes list.
#
# @param [String] key The key to look up.
#
# @return [Object, String, Boolean, Number] The value stored at attributes.key
#
get: (key) => @attributes?[key]
#
# Sets the given attributes.key value to val. Warning: if the key is not found
# on attributes, it will throw an error.
#
# @params [String] key The key of the attributes object to set.
# @params [Object, String, Boolean, Number] val The value to update the given key to.
#
set: (key, val) =>
throw 'Trying to set an non-existent property!' unless field = @constructor.fields[key]
# Ignore a re-setting of the same value
return if val == @get(key)
isValid = false
validator = @constructor.fields[key]['type']
if validator and validator instanceof Wraith.Validator
isValid = validator.isValid(val)
if isValid isnt true
@errorCache_[key] = isValid
@emit('change', 'errors', isValid)
@emit('change:' + 'errors', isValid)
if isValid is true and cached = @errorCache_[key]
@emit('change', 'errors', isValid)
@emit('change:' + 'errors', isValid)
delete @errorCache_[key]
@attributes[key] = val
# Emit change events!
@emit('change', key, val)
@emit('change:' + key, val)
#
# Checks to see if there are any errors on the models.
# An error cache is stored privately so its as easy as checking
# if there is anything in that object.
#
# @return [Boolean] If the model is valid or not
#
isValid: =>
return false for key, msg of @errorCache_
return true
#
# Returns an object with errors stored on it.
# Errors are stored with key as the attribute name
# and the value as the error.
#
# @return [Object] The associative array of errors
#
errors: => @errorCache_
#
# "Serializes" the model's attributes as JSON.
# (Really just returns the attributes object)
#
# @return [Object] The attributes object belonging to this {Wraith.Model} instance.
#
toJSON: => @attributes
| 223749 | #
# Our data model used throughout the application. Currently it is requred
# to do any data-binding or data-mapping in the views.
# Credit goes out to <NAME> and his Spine framework for very
# obvious inspiration.
#
class Wraith.Model extends Wraith.Base
#
# Sets up a field with the given name and options.
#
# @param [String] name The name of the field to setup
# @param [Object] opt The options object (optional). Used to setup defaults.
#
@field: (name, opt) ->
@fields ?= {}
@fields[name] = opt ? {}
#
# Sets up a collection given the {Wraith.Collection} object
# and options object.
#
# @param [Wraith.Collection] klass The collection object to use.
# @param [String] as The name of the collection within this model.
# @param [Object] opt The options to apply to this collection.
#
@hasMany: (klass, as, opt) ->
opt ?= {}
opt.klass ?= klass
opt.as ?= as
@collections ?= {}
@collections[as] = opt
#
# Constructor
#
# @param [Object] attributes An attributes object to apply to the model upon intialization.
#
constructor: (attributes) ->
Wraith.log '@Wraith.Model', 'constructor'
super()
# Create unique ID if one doesnt exist
# @todo Could use a refactor
@constructor.fields ?= {}
@constructor.fields['_id'] = { default: Wraith.uniqueId } unless attributes?['_id']
@errorCache_ = {}
@reset attributes
Wraith.models[@attributes['_id']] = @
@
#
# Perform a reset of the models attributes. Will trigger
# "change" events on each property that is reset.
#
# @param [Object] attributes Contains all default data to be
# applied to the object when being reset.
#
reset: (attributes) ->
@attributes = {}
for name, options of @constructor.fields
if attributes?[name]?
d = attributes[name]
else
d = if (Wraith.isFunction(options['default'])) then options['default']() else options['default']
@set name, d
for name, options of @constructor.collections
@attributes[name] = new Wraith.Collection(@, options.as, options.klass)
#
# Returns the value for the given key. Will return undefined if
# not found on the attributes list.
#
# @param [String] key The key to look up.
#
# @return [Object, String, Boolean, Number] The value stored at attributes.key
#
get: (key) => @attributes?[key]
#
# Sets the given attributes.key value to val. Warning: if the key is not found
# on attributes, it will throw an error.
#
# @params [String] key The key of the attributes object to set.
# @params [Object, String, Boolean, Number] val The value to update the given key to.
#
set: (key, val) =>
throw 'Trying to set an non-existent property!' unless field = @constructor.fields[key]
# Ignore a re-setting of the same value
return if val == @get(key)
isValid = false
validator = @constructor.fields[key]['type']
if validator and validator instanceof Wraith.Validator
isValid = validator.isValid(val)
if isValid isnt true
@errorCache_[key] = isValid
@emit('change', 'errors', isValid)
@emit('change:' + 'errors', isValid)
if isValid is true and cached = @errorCache_[key]
@emit('change', 'errors', isValid)
@emit('change:' + 'errors', isValid)
delete @errorCache_[key]
@attributes[key] = val
# Emit change events!
@emit('change', key, val)
@emit('change:' + key, val)
#
# Checks to see if there are any errors on the models.
# An error cache is stored privately so its as easy as checking
# if there is anything in that object.
#
# @return [Boolean] If the model is valid or not
#
isValid: =>
return false for key, msg of @errorCache_
return true
#
# Returns an object with errors stored on it.
# Errors are stored with key as the attribute name
# and the value as the error.
#
# @return [Object] The associative array of errors
#
errors: => @errorCache_
#
# "Serializes" the model's attributes as JSON.
# (Really just returns the attributes object)
#
# @return [Object] The attributes object belonging to this {Wraith.Model} instance.
#
toJSON: => @attributes
| true | #
# Our data model used throughout the application. Currently it is requred
# to do any data-binding or data-mapping in the views.
# Credit goes out to PI:NAME:<NAME>END_PI and his Spine framework for very
# obvious inspiration.
#
class Wraith.Model extends Wraith.Base
#
# Sets up a field with the given name and options.
#
# @param [String] name The name of the field to setup
# @param [Object] opt The options object (optional). Used to setup defaults.
#
@field: (name, opt) ->
@fields ?= {}
@fields[name] = opt ? {}
#
# Sets up a collection given the {Wraith.Collection} object
# and options object.
#
# @param [Wraith.Collection] klass The collection object to use.
# @param [String] as The name of the collection within this model.
# @param [Object] opt The options to apply to this collection.
#
@hasMany: (klass, as, opt) ->
opt ?= {}
opt.klass ?= klass
opt.as ?= as
@collections ?= {}
@collections[as] = opt
#
# Constructor
#
# @param [Object] attributes An attributes object to apply to the model upon intialization.
#
constructor: (attributes) ->
Wraith.log '@Wraith.Model', 'constructor'
super()
# Create unique ID if one doesnt exist
# @todo Could use a refactor
@constructor.fields ?= {}
@constructor.fields['_id'] = { default: Wraith.uniqueId } unless attributes?['_id']
@errorCache_ = {}
@reset attributes
Wraith.models[@attributes['_id']] = @
@
#
# Perform a reset of the models attributes. Will trigger
# "change" events on each property that is reset.
#
# @param [Object] attributes Contains all default data to be
# applied to the object when being reset.
#
reset: (attributes) ->
@attributes = {}
for name, options of @constructor.fields
if attributes?[name]?
d = attributes[name]
else
d = if (Wraith.isFunction(options['default'])) then options['default']() else options['default']
@set name, d
for name, options of @constructor.collections
@attributes[name] = new Wraith.Collection(@, options.as, options.klass)
#
# Returns the value for the given key. Will return undefined if
# not found on the attributes list.
#
# @param [String] key The key to look up.
#
# @return [Object, String, Boolean, Number] The value stored at attributes.key
#
get: (key) => @attributes?[key]
#
# Sets the given attributes.key value to val. Warning: if the key is not found
# on attributes, it will throw an error.
#
# @params [String] key The key of the attributes object to set.
# @params [Object, String, Boolean, Number] val The value to update the given key to.
#
set: (key, val) =>
throw 'Trying to set an non-existent property!' unless field = @constructor.fields[key]
# Ignore a re-setting of the same value
return if val == @get(key)
isValid = false
validator = @constructor.fields[key]['type']
if validator and validator instanceof Wraith.Validator
isValid = validator.isValid(val)
if isValid isnt true
@errorCache_[key] = isValid
@emit('change', 'errors', isValid)
@emit('change:' + 'errors', isValid)
if isValid is true and cached = @errorCache_[key]
@emit('change', 'errors', isValid)
@emit('change:' + 'errors', isValid)
delete @errorCache_[key]
@attributes[key] = val
# Emit change events!
@emit('change', key, val)
@emit('change:' + key, val)
#
# Checks to see if there are any errors on the models.
# An error cache is stored privately so its as easy as checking
# if there is anything in that object.
#
# @return [Boolean] If the model is valid or not
#
isValid: =>
return false for key, msg of @errorCache_
return true
#
# Returns an object with errors stored on it.
# Errors are stored with key as the attribute name
# and the value as the error.
#
# @return [Object] The associative array of errors
#
errors: => @errorCache_
#
# "Serializes" the model's attributes as JSON.
# (Really just returns the attributes object)
#
# @return [Object] The attributes object belonging to this {Wraith.Model} instance.
#
toJSON: => @attributes
|
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998891949653625,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/taskboard/charts.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/taskboard/charts.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
toggleText = @.taiga.toggleText
scopeDefer = @.taiga.scopeDefer
bindOnce = @.taiga.bindOnce
groupBy = @.taiga.groupBy
timeout = @.taiga.timeout
module = angular.module("taigaTaskboard")
#############################################################################
## Sprint burndown graph directive
#############################################################################
SprintGraphDirective = ->
redrawChart = (element, dataToDraw) ->
width = element.width()
element.height(240)
days = _.map(dataToDraw, (x) -> moment(x.day))
data = []
data.unshift({
data: _.zip(days, _.map(dataToDraw, (d) -> d.optimal_points))
lines:
fillColor : "rgba(120,120,120,0.2)"
})
data.unshift({
data: _.zip(days, _.map(dataToDraw, (d) -> d.open_points))
lines:
fillColor : "rgba(102,153,51,0.3)"
})
options =
grid:
borderWidth: { top: 0, right: 1, left:0, bottom: 0 }
borderColor: '#ccc'
xaxis:
tickSize: [1, "day"]
min: days[0]
max: _.last(days)
mode: "time"
daysNames: days
axisLabel: 'Day'
axisLabelUseCanvas: true
axisLabelFontSizePixels: 12
axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif'
axisLabelPadding: 5
yaxis:
min: 0
series:
shadowSize: 0
lines:
show: true
fill: true
points:
show: true
fill: true
radius: 4
lineWidth: 2
colors: ["rgba(102,153,51,1)", "rgba(120,120,120,0.2)"]
element.empty()
element.plot(data, options).data("plot")
link = ($scope, $el, $attrs) ->
element = angular.element($el)
$scope.$on "resize", ->
redrawChart(element, $scope.stats.days) if $scope.stats
$scope.$on "taskboard:graph:toggle-visibility", ->
$el.parent().toggleClass('open')
# fix chart overflow
timeout(100, ->
redrawChart(element, $scope.stats.days) if $scope.stats
)
$scope.$watch 'stats', (value) ->
if not $scope.stats?
return
redrawChart(element, $scope.stats.days)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgSprintGraph", SprintGraphDirective)
| 60266 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/taskboard/charts.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
toggleText = @.taiga.toggleText
scopeDefer = @.taiga.scopeDefer
bindOnce = @.taiga.bindOnce
groupBy = @.taiga.groupBy
timeout = @.taiga.timeout
module = angular.module("taigaTaskboard")
#############################################################################
## Sprint burndown graph directive
#############################################################################
SprintGraphDirective = ->
redrawChart = (element, dataToDraw) ->
width = element.width()
element.height(240)
days = _.map(dataToDraw, (x) -> moment(x.day))
data = []
data.unshift({
data: _.zip(days, _.map(dataToDraw, (d) -> d.optimal_points))
lines:
fillColor : "rgba(120,120,120,0.2)"
})
data.unshift({
data: _.zip(days, _.map(dataToDraw, (d) -> d.open_points))
lines:
fillColor : "rgba(102,153,51,0.3)"
})
options =
grid:
borderWidth: { top: 0, right: 1, left:0, bottom: 0 }
borderColor: '#ccc'
xaxis:
tickSize: [1, "day"]
min: days[0]
max: _.last(days)
mode: "time"
daysNames: days
axisLabel: 'Day'
axisLabelUseCanvas: true
axisLabelFontSizePixels: 12
axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif'
axisLabelPadding: 5
yaxis:
min: 0
series:
shadowSize: 0
lines:
show: true
fill: true
points:
show: true
fill: true
radius: 4
lineWidth: 2
colors: ["rgba(102,153,51,1)", "rgba(120,120,120,0.2)"]
element.empty()
element.plot(data, options).data("plot")
link = ($scope, $el, $attrs) ->
element = angular.element($el)
$scope.$on "resize", ->
redrawChart(element, $scope.stats.days) if $scope.stats
$scope.$on "taskboard:graph:toggle-visibility", ->
$el.parent().toggleClass('open')
# fix chart overflow
timeout(100, ->
redrawChart(element, $scope.stats.days) if $scope.stats
)
$scope.$watch 'stats', (value) ->
if not $scope.stats?
return
redrawChart(element, $scope.stats.days)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgSprintGraph", SprintGraphDirective)
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/taskboard/charts.coffee
###
taiga = @.taiga
mixOf = @.taiga.mixOf
toggleText = @.taiga.toggleText
scopeDefer = @.taiga.scopeDefer
bindOnce = @.taiga.bindOnce
groupBy = @.taiga.groupBy
timeout = @.taiga.timeout
module = angular.module("taigaTaskboard")
#############################################################################
## Sprint burndown graph directive
#############################################################################
SprintGraphDirective = ->
redrawChart = (element, dataToDraw) ->
width = element.width()
element.height(240)
days = _.map(dataToDraw, (x) -> moment(x.day))
data = []
data.unshift({
data: _.zip(days, _.map(dataToDraw, (d) -> d.optimal_points))
lines:
fillColor : "rgba(120,120,120,0.2)"
})
data.unshift({
data: _.zip(days, _.map(dataToDraw, (d) -> d.open_points))
lines:
fillColor : "rgba(102,153,51,0.3)"
})
options =
grid:
borderWidth: { top: 0, right: 1, left:0, bottom: 0 }
borderColor: '#ccc'
xaxis:
tickSize: [1, "day"]
min: days[0]
max: _.last(days)
mode: "time"
daysNames: days
axisLabel: 'Day'
axisLabelUseCanvas: true
axisLabelFontSizePixels: 12
axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif'
axisLabelPadding: 5
yaxis:
min: 0
series:
shadowSize: 0
lines:
show: true
fill: true
points:
show: true
fill: true
radius: 4
lineWidth: 2
colors: ["rgba(102,153,51,1)", "rgba(120,120,120,0.2)"]
element.empty()
element.plot(data, options).data("plot")
link = ($scope, $el, $attrs) ->
element = angular.element($el)
$scope.$on "resize", ->
redrawChart(element, $scope.stats.days) if $scope.stats
$scope.$on "taskboard:graph:toggle-visibility", ->
$el.parent().toggleClass('open')
# fix chart overflow
timeout(100, ->
redrawChart(element, $scope.stats.days) if $scope.stats
)
$scope.$watch 'stats', (value) ->
if not $scope.stats?
return
redrawChart(element, $scope.stats.days)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgSprintGraph", SprintGraphDirective)
|
[
{
"context": "%H:%M:%S\", @x) + \"<br/>\" + Highcharts.numberFormat(@y, 2)\n\n legend:\n enabled: false\n\n ",
"end": 1821,
"score": 0.9824807047843933,
"start": 1819,
"tag": "USERNAME",
"value": "@y"
},
{
"context": " enabled: false\n\n series: [\n nam... | app/assets/javascripts/welcome.js.coffee | harryworld/cuhk-iot-workshop-win | 1 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
ts = 0
series = undefined
loadData = ->
url = "/points/latest.json?id=#{ts}"
if $('#container').data('group-id') isnt ''
url += "&group=" + $('#container').data('group-id')
# ts = (new Date()).getTime()
$.getJSON url, (data) ->
$.each data, (k, v) ->
ts = v.id
add v.created_ts, v.pm25
add = (x, y) ->
console.log x, y
# x = (new Date()).getTime() # current time
# y = Math.random()
series.addPoint [
x
y
], true, true
return
$ ->
Highcharts.setOptions
global:
useUTC: false
url = "/points/latest.json"
$.getJSON url, (data) ->
generate = ->
# generate an array of random data
results = []
$.each data, (k, v) ->
ts = v.id
time = v.created_ts
results.push
x: time
y: v.pm25
results
$("#container").highcharts
chart:
type: "spline"
animation: Highcharts.svg # don't animate in old IE
marginRight: 10
events:
load: ->
# set up the updating of the chart each second
series = @series[0]
setInterval loadData, 1000
return
title:
text: "PM2.5 collected over time"
xAxis:
type: "datetime"
tickPixelInterval: 150
yAxis:
title:
text: "Celsius"
plotLines: [
value: 0
width: 1
color: "#808080"
]
tooltip:
formatter: ->
"<b>" + @series.name + "</b><br/>" + Highcharts.dateFormat("%Y-%m-%d %H:%M:%S", @x) + "<br/>" + Highcharts.numberFormat(@y, 2)
legend:
enabled: false
exporting:
enabled: false
series: [
name: "Random data"
data: generate()
]
| 217537 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
ts = 0
series = undefined
loadData = ->
url = "/points/latest.json?id=#{ts}"
if $('#container').data('group-id') isnt ''
url += "&group=" + $('#container').data('group-id')
# ts = (new Date()).getTime()
$.getJSON url, (data) ->
$.each data, (k, v) ->
ts = v.id
add v.created_ts, v.pm25
add = (x, y) ->
console.log x, y
# x = (new Date()).getTime() # current time
# y = Math.random()
series.addPoint [
x
y
], true, true
return
$ ->
Highcharts.setOptions
global:
useUTC: false
url = "/points/latest.json"
$.getJSON url, (data) ->
generate = ->
# generate an array of random data
results = []
$.each data, (k, v) ->
ts = v.id
time = v.created_ts
results.push
x: time
y: v.pm25
results
$("#container").highcharts
chart:
type: "spline"
animation: Highcharts.svg # don't animate in old IE
marginRight: 10
events:
load: ->
# set up the updating of the chart each second
series = @series[0]
setInterval loadData, 1000
return
title:
text: "PM2.5 collected over time"
xAxis:
type: "datetime"
tickPixelInterval: 150
yAxis:
title:
text: "Celsius"
plotLines: [
value: 0
width: 1
color: "#808080"
]
tooltip:
formatter: ->
"<b>" + @series.name + "</b><br/>" + Highcharts.dateFormat("%Y-%m-%d %H:%M:%S", @x) + "<br/>" + Highcharts.numberFormat(@y, 2)
legend:
enabled: false
exporting:
enabled: false
series: [
name: "<NAME>"
data: generate()
]
| true | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
ts = 0
series = undefined
loadData = ->
url = "/points/latest.json?id=#{ts}"
if $('#container').data('group-id') isnt ''
url += "&group=" + $('#container').data('group-id')
# ts = (new Date()).getTime()
$.getJSON url, (data) ->
$.each data, (k, v) ->
ts = v.id
add v.created_ts, v.pm25
add = (x, y) ->
console.log x, y
# x = (new Date()).getTime() # current time
# y = Math.random()
series.addPoint [
x
y
], true, true
return
$ ->
Highcharts.setOptions
global:
useUTC: false
url = "/points/latest.json"
$.getJSON url, (data) ->
generate = ->
# generate an array of random data
results = []
$.each data, (k, v) ->
ts = v.id
time = v.created_ts
results.push
x: time
y: v.pm25
results
$("#container").highcharts
chart:
type: "spline"
animation: Highcharts.svg # don't animate in old IE
marginRight: 10
events:
load: ->
# set up the updating of the chart each second
series = @series[0]
setInterval loadData, 1000
return
title:
text: "PM2.5 collected over time"
xAxis:
type: "datetime"
tickPixelInterval: 150
yAxis:
title:
text: "Celsius"
plotLines: [
value: 0
width: 1
color: "#808080"
]
tooltip:
formatter: ->
"<b>" + @series.name + "</b><br/>" + Highcharts.dateFormat("%Y-%m-%d %H:%M:%S", @x) + "<br/>" + Highcharts.numberFormat(@y, 2)
legend:
enabled: false
exporting:
enabled: false
series: [
name: "PI:NAME:<NAME>END_PI"
data: generate()
]
|
[
{
"context": "ce: true\n .then ->\n person.create title: 'liana'\n .then (liana) ->\n cache.liana = lia",
"end": 1643,
"score": 0.9035847187042236,
"start": 1638,
"tag": "NAME",
"value": "liana"
},
{
"context": "romise.all [\n liana.createMother title: 'a... | test/orm.coffee | Oziabr/privateer | 7 | _ = require 'lodash'
Sequelize = require 'sequelize'
Promise = require 'bluebird'
config = require(__dirname + '/../server/config/config.json').test
inflection = require 'inflection'
mocha = require 'mocha'
debug = require('debug') 'test'
return
orm = new Sequelize config.db.database, config.db.username, config.db.password, config.db
cache = {}
describe 'orm', ->
before ->
person = orm.define 'person',
title: orm.Sequelize.STRING
# extra: orm.Sequelize.STRING
# attrr: orm.Sequelize.STRING
, timestamps: false
husband= orm.define 'husband',title: orm.Sequelize.STRING
mother = orm.define 'mother', title: orm.Sequelize.STRING
child = orm.define 'child', title: orm.Sequelize.STRING
friend = orm.define 'friend', title: orm.Sequelize.STRING
other = orm.define 'other', title: orm.Sequelize.STRING
# o2o person have special person as husband of wife
person.belongsTo person, as: 'husband'
person.hasOne person, as: 'wife', foreignKey: 'husband_id'
# o2m person have many persons as children of mother
# m2o person have common person as mother of children
person.belongsTo person, as: 'mother'
person.hasMany person, as: 'children', foreignKey: 'mother_id'
# m2m persons have many persons as pals of drugs
person.belongsToMany person, through: 'friendship', as: 'pals', foreignKey: 'drug_id'
person.belongsToMany person, through: 'friendship', as: 'drugs', foreignKey: 'pal_id'
# person.addScope 'defaultScope', {include: all: true}, override: true
orm.sync force: true
.then ->
person.create title: 'liana'
.then (liana) ->
cache.liana = liana
Promise.all [
liana.createMother title: 'anna'
liana.createChild title: 'john'
liana.createChild title: 'tom'
liana.createHusband title: 'josef'
liana.createPal title: 'kira'
liana.createPal title: 'ola'
liana.createDrug title: 'fi'
liana.createDrug title: 'toma'
]
describe 'associations', ->
it 'should get associations', ->
person = orm.models.person
debug person.associations
debug ( key for key of cache.liana when key.match /get/ )
person.addHook 'beforeFind', 'alternative_m2m', (opt) ->
return if !opt.includeExtra
opt.include = _.compact opt.includeExtra.map (rel) =>
if !(assoc = @.associations[rel.name])
# debug "unrecognized association #{rel.name} of #{@.tableName}"
return false
return false if ~['BelongsToMany', 'HasMany'].indexOf assoc.associationType
_.assign {}, rel.options, model: assoc.target, as: rel.name
person.addHook 'afterFind', 'alternative_m2m', (list, opt) ->
list = [list] if !_.isArray list
return if !opt.includeExtra
includes = _.filter opt.includeExtra, (rel) =>
(assoc = @.associations[rel.name]) && ~['BelongsToMany', 'HasMany'].indexOf assoc.associationType
ids = list.map (item) -> item.getDataValue 'id'
# debug 'sas', ids
Promise.each includes, (rel) =>
assoc = @.associations[rel.name]
(where = {})[assoc.foreignKey] = $in: ids
if assoc.associationType == 'HasMany'
(rel.options.attributes ?= []).splice 0, 0, assoc.foreignKey, 'id'
return assoc.target.findAll _.assign {}, rel.options, where: where
.then (links) -> links.forEach (link) -> list.forEach (item) ->
item.setDataValue assoc.as, [] if !_.isArray item.getDataValue assoc.as
return false if link[assoc.foreignKey] != item.id
(item.getDataValue assoc.as).push link.get(plain: true)
else if assoc.associationType == 'BelongsToMany'
# assoc.target.findAll _.assign {}, rel.options, where: where
return assoc.target.findAll( include:
model: assoc.source
as: inflection.pluralize(assoc.foreignKey.split('_')[0])
through: attributes: []
attributes: ['id']
where: id: $in: ids
).then (links) ->
debug '--', assoc.through, assoc.foreignKey, rel.name, JSON.stringify links.map (item) -> item.get plain: true
# list = [list] if !_.isArray list
# ids = (item.id for item in list)
# Promise.each opt.includeExtra, (rel) =>
# assoc = @.associations[rel.as]
# (where = {})[assoc.foreignKey] = $in: ids
# query = """
# SELECT #{assoc.target.tableName}.*, #{assoc.through.model.tableName}.#{assoc.foreignKey} as ___key
# FROM #{assoc.through.model.tableName} LEFT JOIN #{assoc.target.tableName}
# ON (#{assoc.through.model.tableName}.#{inflection.singularize rel.as}_id = #{assoc.target.tableName}.id)
# WHERE #{assoc.through.model.tableName}.#{assoc.foreignKey} IN(:ids)
# """
# debug 'query', query
# orm.query query, replacements: {ids: ids}, type: orm.QueryTypes.SELECT
# .then (results, metadata) ->
# for item in list
#
# item.setDataValue rel.as, (_.filter results, ___key: item.id).map (res) -> _.pick res, rel.attributes
options = attributes: ['id', 'title'], includeExtra: [
{name: 'notExisted'}
{name: 'broken', options: attributes: ['title']}
{name: 'husband', options: attributes: ['title']}
{name: 'wife', options: attributes: ['title']}
{name: 'mother', options: attributes: ['title']}
{name: 'children', options: attributes: ['title']}
{name: 'pals', options: attributes: ['title'], through: attributes: []}
{name: 'drugs', options: attributes: ['title'], through: attributes: []}
]
orm.models.person.findById 1, options
.then (item) -> debug 'itemById', item.get(plain: true)
# orm.models.person.findOne _.assign {}, options
# .then (item) -> debug 'itemOne', item.get(plain: true)
#
# orm.models.person.findAll _.assign {}, options
# .then (list) -> debug 'itemAll', list.map (item) -> item.get(plain: true)
# orm.models.person.findAll where: {id: $in: [1, 3, 4, 7]}, attributes: ['title'], include: [
# {attributes: ['title'], model: person, as: 'husband'}
# {attributes: ['title'], model: person, as: 'wife'}
# {attributes: ['title'], model: person, as: 'mother'}
# {attributes: ['title'], model: person, as: 'children'}
# {attributes: ['title'], model: person, as: 'pals', through: attributes: []}
# {attributes: ['title'], model: person, as: 'drugs', through: attributes: []}
# ]
# .then (list) -> debug 'list', list.map (item) -> item.get plain: true
#describe 'types of m2m'
#describe 'show/edit filters'
| 110860 | _ = require 'lodash'
Sequelize = require 'sequelize'
Promise = require 'bluebird'
config = require(__dirname + '/../server/config/config.json').test
inflection = require 'inflection'
mocha = require 'mocha'
debug = require('debug') 'test'
return
orm = new Sequelize config.db.database, config.db.username, config.db.password, config.db
cache = {}
describe 'orm', ->
before ->
person = orm.define 'person',
title: orm.Sequelize.STRING
# extra: orm.Sequelize.STRING
# attrr: orm.Sequelize.STRING
, timestamps: false
husband= orm.define 'husband',title: orm.Sequelize.STRING
mother = orm.define 'mother', title: orm.Sequelize.STRING
child = orm.define 'child', title: orm.Sequelize.STRING
friend = orm.define 'friend', title: orm.Sequelize.STRING
other = orm.define 'other', title: orm.Sequelize.STRING
# o2o person have special person as husband of wife
person.belongsTo person, as: 'husband'
person.hasOne person, as: 'wife', foreignKey: 'husband_id'
# o2m person have many persons as children of mother
# m2o person have common person as mother of children
person.belongsTo person, as: 'mother'
person.hasMany person, as: 'children', foreignKey: 'mother_id'
# m2m persons have many persons as pals of drugs
person.belongsToMany person, through: 'friendship', as: 'pals', foreignKey: 'drug_id'
person.belongsToMany person, through: 'friendship', as: 'drugs', foreignKey: 'pal_id'
# person.addScope 'defaultScope', {include: all: true}, override: true
orm.sync force: true
.then ->
person.create title: '<NAME>'
.then (liana) ->
cache.liana = liana
Promise.all [
liana.createMother title: '<NAME>'
liana.createChild title: '<NAME>'
liana.createChild title: '<NAME>'
liana.createHusband title: '<NAME>'
liana.createPal title: 'kira'
liana.createPal title: 'ola'
liana.createDrug title: 'fi'
liana.createDrug title: '<NAME>'
]
describe 'associations', ->
it 'should get associations', ->
person = orm.models.person
debug person.associations
debug ( key for key of cache.liana when key.match /get/ )
person.addHook 'beforeFind', 'alternative_m2m', (opt) ->
return if !opt.includeExtra
opt.include = _.compact opt.includeExtra.map (rel) =>
if !(assoc = @.associations[rel.name])
# debug "unrecognized association #{rel.name} of #{@.tableName}"
return false
return false if ~['BelongsToMany', 'HasMany'].indexOf assoc.associationType
_.assign {}, rel.options, model: assoc.target, as: rel.name
person.addHook 'afterFind', 'alternative_m2m', (list, opt) ->
list = [list] if !_.isArray list
return if !opt.includeExtra
includes = _.filter opt.includeExtra, (rel) =>
(assoc = @.associations[rel.name]) && ~['BelongsToMany', 'HasMany'].indexOf assoc.associationType
ids = list.map (item) -> item.getDataValue 'id'
# debug 'sas', ids
Promise.each includes, (rel) =>
assoc = @.associations[rel.name]
(where = {})[assoc.foreignKey] = $in: ids
if assoc.associationType == 'HasMany'
(rel.options.attributes ?= []).splice 0, 0, assoc.foreignKey, 'id'
return assoc.target.findAll _.assign {}, rel.options, where: where
.then (links) -> links.forEach (link) -> list.forEach (item) ->
item.setDataValue assoc.as, [] if !_.isArray item.getDataValue assoc.as
return false if link[assoc.foreignKey] != item.id
(item.getDataValue assoc.as).push link.get(plain: true)
else if assoc.associationType == 'BelongsToMany'
# assoc.target.findAll _.assign {}, rel.options, where: where
return assoc.target.findAll( include:
model: assoc.source
as: inflection.pluralize(assoc.foreignKey.split('_')[0])
through: attributes: []
attributes: ['id']
where: id: $in: ids
).then (links) ->
debug '--', assoc.through, assoc.foreignKey, rel.name, JSON.stringify links.map (item) -> item.get plain: true
# list = [list] if !_.isArray list
# ids = (item.id for item in list)
# Promise.each opt.includeExtra, (rel) =>
# assoc = @.associations[rel.as]
# (where = {})[assoc.foreignKey] = $in: ids
# query = """
# SELECT #{assoc.target.tableName}.*, #{assoc.through.model.tableName}.#{assoc.foreignKey} as ___key
# FROM #{assoc.through.model.tableName} LEFT JOIN #{assoc.target.tableName}
# ON (#{assoc.through.model.tableName}.#{inflection.singularize rel.as}_id = #{assoc.target.tableName}.id)
# WHERE #{assoc.through.model.tableName}.#{assoc.foreignKey} IN(:ids)
# """
# debug 'query', query
# orm.query query, replacements: {ids: ids}, type: orm.QueryTypes.SELECT
# .then (results, metadata) ->
# for item in list
#
# item.setDataValue rel.as, (_.filter results, ___key: item.id).map (res) -> _.pick res, rel.attributes
options = attributes: ['id', 'title'], includeExtra: [
{name: 'notExisted'}
{name: 'broken', options: attributes: ['title']}
{name: 'husband', options: attributes: ['title']}
{name: 'wife', options: attributes: ['title']}
{name: 'mother', options: attributes: ['title']}
{name: 'children', options: attributes: ['title']}
{name: 'pals', options: attributes: ['title'], through: attributes: []}
{name: '<NAME>', options: attributes: ['title'], through: attributes: []}
]
orm.models.person.findById 1, options
.then (item) -> debug 'itemById', item.get(plain: true)
# orm.models.person.findOne _.assign {}, options
# .then (item) -> debug 'itemOne', item.get(plain: true)
#
# orm.models.person.findAll _.assign {}, options
# .then (list) -> debug 'itemAll', list.map (item) -> item.get(plain: true)
# orm.models.person.findAll where: {id: $in: [1, 3, 4, 7]}, attributes: ['title'], include: [
# {attributes: ['title'], model: person, as: 'husband'}
# {attributes: ['title'], model: person, as: 'wife'}
# {attributes: ['title'], model: person, as: 'mother'}
# {attributes: ['title'], model: person, as: 'children'}
# {attributes: ['title'], model: person, as: 'pals', through: attributes: []}
# {attributes: ['title'], model: person, as: 'drugs', through: attributes: []}
# ]
# .then (list) -> debug 'list', list.map (item) -> item.get plain: true
#describe 'types of m2m'
#describe 'show/edit filters'
| true | _ = require 'lodash'
Sequelize = require 'sequelize'
Promise = require 'bluebird'
config = require(__dirname + '/../server/config/config.json').test
inflection = require 'inflection'
mocha = require 'mocha'
debug = require('debug') 'test'
return
orm = new Sequelize config.db.database, config.db.username, config.db.password, config.db
cache = {}
describe 'orm', ->
before ->
person = orm.define 'person',
title: orm.Sequelize.STRING
# extra: orm.Sequelize.STRING
# attrr: orm.Sequelize.STRING
, timestamps: false
husband= orm.define 'husband',title: orm.Sequelize.STRING
mother = orm.define 'mother', title: orm.Sequelize.STRING
child = orm.define 'child', title: orm.Sequelize.STRING
friend = orm.define 'friend', title: orm.Sequelize.STRING
other = orm.define 'other', title: orm.Sequelize.STRING
# o2o person have special person as husband of wife
person.belongsTo person, as: 'husband'
person.hasOne person, as: 'wife', foreignKey: 'husband_id'
# o2m person have many persons as children of mother
# m2o person have common person as mother of children
person.belongsTo person, as: 'mother'
person.hasMany person, as: 'children', foreignKey: 'mother_id'
# m2m persons have many persons as pals of drugs
person.belongsToMany person, through: 'friendship', as: 'pals', foreignKey: 'drug_id'
person.belongsToMany person, through: 'friendship', as: 'drugs', foreignKey: 'pal_id'
# person.addScope 'defaultScope', {include: all: true}, override: true
orm.sync force: true
.then ->
person.create title: 'PI:NAME:<NAME>END_PI'
.then (liana) ->
cache.liana = liana
Promise.all [
liana.createMother title: 'PI:NAME:<NAME>END_PI'
liana.createChild title: 'PI:NAME:<NAME>END_PI'
liana.createChild title: 'PI:NAME:<NAME>END_PI'
liana.createHusband title: 'PI:NAME:<NAME>END_PI'
liana.createPal title: 'kira'
liana.createPal title: 'ola'
liana.createDrug title: 'fi'
liana.createDrug title: 'PI:NAME:<NAME>END_PI'
]
describe 'associations', ->
it 'should get associations', ->
person = orm.models.person
debug person.associations
debug ( key for key of cache.liana when key.match /get/ )
person.addHook 'beforeFind', 'alternative_m2m', (opt) ->
return if !opt.includeExtra
opt.include = _.compact opt.includeExtra.map (rel) =>
if !(assoc = @.associations[rel.name])
# debug "unrecognized association #{rel.name} of #{@.tableName}"
return false
return false if ~['BelongsToMany', 'HasMany'].indexOf assoc.associationType
_.assign {}, rel.options, model: assoc.target, as: rel.name
person.addHook 'afterFind', 'alternative_m2m', (list, opt) ->
list = [list] if !_.isArray list
return if !opt.includeExtra
includes = _.filter opt.includeExtra, (rel) =>
(assoc = @.associations[rel.name]) && ~['BelongsToMany', 'HasMany'].indexOf assoc.associationType
ids = list.map (item) -> item.getDataValue 'id'
# debug 'sas', ids
Promise.each includes, (rel) =>
assoc = @.associations[rel.name]
(where = {})[assoc.foreignKey] = $in: ids
if assoc.associationType == 'HasMany'
(rel.options.attributes ?= []).splice 0, 0, assoc.foreignKey, 'id'
return assoc.target.findAll _.assign {}, rel.options, where: where
.then (links) -> links.forEach (link) -> list.forEach (item) ->
item.setDataValue assoc.as, [] if !_.isArray item.getDataValue assoc.as
return false if link[assoc.foreignKey] != item.id
(item.getDataValue assoc.as).push link.get(plain: true)
else if assoc.associationType == 'BelongsToMany'
# assoc.target.findAll _.assign {}, rel.options, where: where
return assoc.target.findAll( include:
model: assoc.source
as: inflection.pluralize(assoc.foreignKey.split('_')[0])
through: attributes: []
attributes: ['id']
where: id: $in: ids
).then (links) ->
debug '--', assoc.through, assoc.foreignKey, rel.name, JSON.stringify links.map (item) -> item.get plain: true
# list = [list] if !_.isArray list
# ids = (item.id for item in list)
# Promise.each opt.includeExtra, (rel) =>
# assoc = @.associations[rel.as]
# (where = {})[assoc.foreignKey] = $in: ids
# query = """
# SELECT #{assoc.target.tableName}.*, #{assoc.through.model.tableName}.#{assoc.foreignKey} as ___key
# FROM #{assoc.through.model.tableName} LEFT JOIN #{assoc.target.tableName}
# ON (#{assoc.through.model.tableName}.#{inflection.singularize rel.as}_id = #{assoc.target.tableName}.id)
# WHERE #{assoc.through.model.tableName}.#{assoc.foreignKey} IN(:ids)
# """
# debug 'query', query
# orm.query query, replacements: {ids: ids}, type: orm.QueryTypes.SELECT
# .then (results, metadata) ->
# for item in list
#
# item.setDataValue rel.as, (_.filter results, ___key: item.id).map (res) -> _.pick res, rel.attributes
options = attributes: ['id', 'title'], includeExtra: [
{name: 'notExisted'}
{name: 'broken', options: attributes: ['title']}
{name: 'husband', options: attributes: ['title']}
{name: 'wife', options: attributes: ['title']}
{name: 'mother', options: attributes: ['title']}
{name: 'children', options: attributes: ['title']}
{name: 'pals', options: attributes: ['title'], through: attributes: []}
{name: 'PI:NAME:<NAME>END_PI', options: attributes: ['title'], through: attributes: []}
]
orm.models.person.findById 1, options
.then (item) -> debug 'itemById', item.get(plain: true)
# orm.models.person.findOne _.assign {}, options
# .then (item) -> debug 'itemOne', item.get(plain: true)
#
# orm.models.person.findAll _.assign {}, options
# .then (list) -> debug 'itemAll', list.map (item) -> item.get(plain: true)
# orm.models.person.findAll where: {id: $in: [1, 3, 4, 7]}, attributes: ['title'], include: [
# {attributes: ['title'], model: person, as: 'husband'}
# {attributes: ['title'], model: person, as: 'wife'}
# {attributes: ['title'], model: person, as: 'mother'}
# {attributes: ['title'], model: person, as: 'children'}
# {attributes: ['title'], model: person, as: 'pals', through: attributes: []}
# {attributes: ['title'], model: person, as: 'drugs', through: attributes: []}
# ]
# .then (list) -> debug 'list', list.map (item) -> item.get plain: true
#describe 'types of m2m'
#describe 'show/edit filters'
|
[
{
"context": "?method=artist.getinfo&artist=' + art + '&api_key=a75bd15e529625f1fcc5eff85ddb2c05&format=json'\n\t\tjsonArr = JSON.parse(httpGet(url))",
"end": 898,
"score": 0.9997655749320984,
"start": 866,
"tag": "KEY",
"value": "a75bd15e529625f1fcc5eff85ddb2c05"
},
{
"context": "od... | app.coffee | ChipaKraken/angular-music | 2 | audio = ''
angular.module 'app', ['ui.router','ngSanitize']
.config ['$urlRouterProvider', '$stateProvider', ($urlRouterProvider, $stateProvider)->
$urlRouterProvider.otherwise('/')
$stateProvider
.state 'home',
url: '/',
templateUrl: 'artist.html',
controller: 'musicContr'
.state 'home.artist',
url: 'find/:artist',
controller: ['$scope', '$stateParams', ($scope, $stateParams)->
$scope.search $stateParams.artist
return]
return
]
.controller 'musicContr', ['$scope', '$state', '$sce', ($scope, $state, $sce) ->
$scope.songs = []
$scope.stream = ""
$scope.arts = []
$scope.imgs = []
audiojs.events.ready ()->
as = audiojs.createAll()
return
$scope.search = (art)->
$scope.artist = art
window.location.hash='#/find/' + $scope.artist
url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' + art + '&api_key=a75bd15e529625f1fcc5eff85ddb2c05&format=json'
jsonArr = JSON.parse(httpGet(url))
sim = jsonArr.artist.similar.artist
$scope.arts = get_sim_name(sim)
$scope.imgs = get_imgs(sim)
url_top_artist = 'http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&artist=' + art + '&api_key=a75bd15e529625f1fcc5eff85ddb2c05&format=json'
top_artist = JSON.parse(httpGet(url_top_artist))
$scope.songs = top_artist.toptracks.track
return
$scope.searchSongs = ()->
art = corrector $scope.artist
$scope.search(art)
return
$scope.play = (who, what, id)->
$(".active").removeClass("active")
this.sel = id
track = who + ' - ' + what
track = track.split(' ').join('%20')
track_url = 'http://ex.fm/api/v3/song/search/' + track + '?start=0&results=1'
track_json = JSON.parse(httpGet(track_url))
stream = track_json.songs[0]['url']
if stream.indexOf('api.soundcloud.com') != -1
stream += sc_api_key
$("#stream").attr("src", stream).trigger("play")
return
return
] | 212798 | audio = ''
angular.module 'app', ['ui.router','ngSanitize']
.config ['$urlRouterProvider', '$stateProvider', ($urlRouterProvider, $stateProvider)->
$urlRouterProvider.otherwise('/')
$stateProvider
.state 'home',
url: '/',
templateUrl: 'artist.html',
controller: 'musicContr'
.state 'home.artist',
url: 'find/:artist',
controller: ['$scope', '$stateParams', ($scope, $stateParams)->
$scope.search $stateParams.artist
return]
return
]
.controller 'musicContr', ['$scope', '$state', '$sce', ($scope, $state, $sce) ->
$scope.songs = []
$scope.stream = ""
$scope.arts = []
$scope.imgs = []
audiojs.events.ready ()->
as = audiojs.createAll()
return
$scope.search = (art)->
$scope.artist = art
window.location.hash='#/find/' + $scope.artist
url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' + art + '&api_key=<KEY>&format=json'
jsonArr = JSON.parse(httpGet(url))
sim = jsonArr.artist.similar.artist
$scope.arts = get_sim_name(sim)
$scope.imgs = get_imgs(sim)
url_top_artist = 'http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&artist=' + art + '&api_key=<KEY>&format=json'
top_artist = JSON.parse(httpGet(url_top_artist))
$scope.songs = top_artist.toptracks.track
return
$scope.searchSongs = ()->
art = corrector $scope.artist
$scope.search(art)
return
$scope.play = (who, what, id)->
$(".active").removeClass("active")
this.sel = id
track = who + ' - ' + what
track = track.split(' ').join('%20')
track_url = 'http://ex.fm/api/v3/song/search/' + track + '?start=0&results=1'
track_json = JSON.parse(httpGet(track_url))
stream = track_json.songs[0]['url']
if stream.indexOf('api.soundcloud.com') != -1
stream += sc_api_key
$("#stream").attr("src", stream).trigger("play")
return
return
] | true | audio = ''
angular.module 'app', ['ui.router','ngSanitize']
.config ['$urlRouterProvider', '$stateProvider', ($urlRouterProvider, $stateProvider)->
$urlRouterProvider.otherwise('/')
$stateProvider
.state 'home',
url: '/',
templateUrl: 'artist.html',
controller: 'musicContr'
.state 'home.artist',
url: 'find/:artist',
controller: ['$scope', '$stateParams', ($scope, $stateParams)->
$scope.search $stateParams.artist
return]
return
]
.controller 'musicContr', ['$scope', '$state', '$sce', ($scope, $state, $sce) ->
$scope.songs = []
$scope.stream = ""
$scope.arts = []
$scope.imgs = []
audiojs.events.ready ()->
as = audiojs.createAll()
return
$scope.search = (art)->
$scope.artist = art
window.location.hash='#/find/' + $scope.artist
url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' + art + '&api_key=PI:KEY:<KEY>END_PI&format=json'
jsonArr = JSON.parse(httpGet(url))
sim = jsonArr.artist.similar.artist
$scope.arts = get_sim_name(sim)
$scope.imgs = get_imgs(sim)
url_top_artist = 'http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&artist=' + art + '&api_key=PI:KEY:<KEY>END_PI&format=json'
top_artist = JSON.parse(httpGet(url_top_artist))
$scope.songs = top_artist.toptracks.track
return
$scope.searchSongs = ()->
art = corrector $scope.artist
$scope.search(art)
return
$scope.play = (who, what, id)->
$(".active").removeClass("active")
this.sel = id
track = who + ' - ' + what
track = track.split(' ').join('%20')
track_url = 'http://ex.fm/api/v3/song/search/' + track + '?start=0&results=1'
track_json = JSON.parse(httpGet(track_url))
stream = track_json.songs[0]['url']
if stream.indexOf('api.soundcloud.com') != -1
stream += sc_api_key
$("#stream").attr("src", stream).trigger("play")
return
return
] |
[
{
"context": "###\r\n\r\ngas-manager\r\nhttps://github.com/soundTricker/gas-manager\r\n\r\nCopyright (c) 2013 Keisuke Oohashi",
"end": 51,
"score": 0.9978228211402893,
"start": 39,
"tag": "USERNAME",
"value": "soundTricker"
},
{
"context": "com/soundTricker/gas-manager\r\n\r\nCopyrig... | src/lib/commands/init-command.coffee | unau/gas-minus-minus | 1 | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 Keisuke Oohashi
Licensed under the MIT license.
###
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('../gas-manager').Manager
util = require './util'
open = require 'open'
googleapis = require 'googleapis'
colors = require 'colors'
CALLBACK_URL = 'urn:ietf:wg:oauth:2.0:oob'
SCOPE = [
"https://www.googleapis.com/auth/drive"
"https://www.googleapis.com/auth/drive.file"
"https://www.googleapis.com/auth/drive.scripts"
].join(" ")
program = null
exports.init = (option)->
program = @
config = {}
start = (cb)->
console.log """
#{'''===================
Start gas-manager init
==================='''.green}
This utility is will walk you through creating a gas-manager's config file.
Press ^C at any time to quit.
""".green
program.confirm("Do you have client_id & client_secret for Google OAuth2? #{'[yes/no]'.green} ",(result)->
if result is yes
cb(null)
else
createConsumerKeyFlow(cb)
)
inputConsumerSecret = (cb)->
program.prompt("Please input client_secret: " , (result)->
if !result
inputConsumerSecret(cb)
return
config.client_secret = result
cb(null)
)
inputConsumerId = (cb)->
program.prompt("Please input client_id: " , (result)->
if !result
inputConsumerId(cb)
return
config.client_id = result
cb(null)
)
askRefreshToken = (cb)->
program.confirm "Do you create refresh_token now? if yes, open browser. #{'[yes/no]'.green} ", (result)->
if result is yes
createRefreshToken(cb)
else
program.prompt "Please input refresh_token: ",(result)->
return askRefreshToken(cb) if !result
config.refresh_token = result
cb(null)
createRefreshToken = (cb)->
#TODO
console.log """
#{'''===================
About a flow of creating refresh_token.
==================='''.green}
I'll open browser.
Then please do flow below.
#{' 1. Choose account of authorize.'.green}
#{' 2. Apploval an OAuth'.green}
#{' 3. Enter a code , that will be shown in blowser, to the console.'.green}
Then will create refresh_token.
Okay? Let's begin creating refresh_token.
"""
oauth2Client = new googleapis.OAuth2Client(config.client_id, config.client_secret, CALLBACK_URL)
url = oauth2Client.generateAuthUrl({
access_type: 'offline'
scope: SCOPE
})
program.prompt "Press Enter Key, Open Browser. ", ()->
open url , (err)->
cb(err) if err
enterCode = ()->
program.prompt "Enter code: " , (result)->
return enterCode() if !result
oauth2Client.getToken result, (err, tokens)->
cb(err) if err
config.refresh_token = tokens.refresh_token
cb(null)
enterCode()
saveCredentialToFile = (cb)->
program.prompt "Save settings to file please input file path #{('[Default: ' + program.config + ']').green}: ", (result)->
if !result
result = program.config
result = path.resolve(result)
if !fs.existsSync path.dirname(result)
fs.mkdirSync path.dirname(result)
fs.writeFileSync result, JSON.stringify(config, "", 2)
console.log "Created credential file to #{path.resolve(result).green}"
cb(null)
confirmCreatingProjectSetting = (cb)->
program.confirm "Do you want to creating Project settings? #{'[yes/no]'.green} ", (result)->
if result is yes
createProjectSettingFlow(config, cb)
else
cb(null)
createCredentialflow = [
start
inputConsumerId
inputConsumerSecret
askRefreshToken
saveCredentialToFile
confirmCreatingProjectSetting
]
if !option.onlyProject
async.waterfall(createCredentialflow, (err, result)->
throw err if err
console.log "Finish."
process.stdin.destroy()
process.exit(0)
)
else
createProjectSettingFlow(util.loadConfig(program), (err, result)->
throw err if err
console.log "Finish."
process.stdin.destroy()
process.exit(0)
)
createProjectSettingFlow = (config, callback)->
start = (cb)->
program.prompt("Enter your need managing fileId of Google Apps Script Project: " , (result)->
return start(cb) if !result
cb(null, result)
)
getProject = (fileId, cb)->
manager = new Manager config
manager.getProject(fileId, cb)
confirmProject = (project, response, cb)->
filenames = project.getFiles().map((file)-> "#{file.name} [type:#{file.type}]").join('\n ')
console.log """
Is it your needing project?
#{'Filename:'.green}
#{project.filename}
#{'Files:'.green}
#{filenames}
"""
program.confirm("Okay? #{'[yes/no]'.green} " , (result)->
if result is yes
cb(null, project)
else
cb("restart")
createProjectSettingFlow(config, callback)
)
setEnvironment = (project, cb)->
program.prompt("Enter your environment name #{('[Default: ' + program.env + ']').green} ", (result)->
if !result
result = program.env
cb(null, project, result)
)
askWhereToCreatingFiles = (project, env, cb)->
savedfiles = {}
askWhereToCreatingFile = (file, files, basePath, cb2)->
extension = if file.type == "server_js" then ".js" else ".html"
filename = file.name + extension
program.prompt(" > #{filename} #{('[Default: ' + path.resolve(basePath, filename) + ']').green}: ", (result)->
if !result
result = path.resolve(basePath , filename)
else
reuslt = path.resolve(result)
savedfiles[file.name] = {
path : result
type : file.type
}
cb2(null,files.pop(), files, basePath)
)
flow = []
flow.push (cb)->
program.prompt("Where is a base path of the project sources ? #{('[Default: ' + process.cwd() + ']').green}: ", (result)->
if !result
result = process.cwd()
files = project.getFiles()
console.log("Where do you want to create file to...")
cb(null,files.pop(), files, result)
)
for i in project.getFiles()
flow.push askWhereToCreatingFile
async.waterfall flow , (err)->
throw err if err
cb(null, project, env, savedfiles)
saveProjectSettingToFile = (project, env, files, cb)->
program.prompt "Save settings to file, Please input file path #{('[Default: ' + program.setting + ']').green}: ", (result)->
if !result
result = program.setting
result = path.resolve(result)
if !fs.existsSync path.dirname(result)
fs.mkdirSync path.dirname(result)
setting = {}
setting[env] =
fileId : project.fileId
files : files
fs.writeFileSync result, JSON.stringify(setting, "", 2)
console.log "Created project setting file to #{path.resolve(result).green}"
cb(null)
async.waterfall(
[
start
getProject
confirmProject
setEnvironment
askWhereToCreatingFiles
saveProjectSettingToFile
], (err)->
if err is "restart" then return
if err then throw err
if callback then callback(null)
)
createConsumerKeyFlow = (callback)->
start = (cb)->
program.confirm("Do you create client_id and client_secret, if yes, open browser. #{'[yes/no]'.green} ",(result)->
if result is yes
cb(null)
else
callback(null)
)
openBrowser = (cb)->
console.log """
#{'''===================
About a flow of creating client_id and client_secret.
==================='''.green}
I'll open browser to https://code.google.com/apis/console.
Then please do flow below.
#{'1. Creating new project in opened browser.'.green}
1-1. Choose [Create...] at the upper left menu.
1-2. Enter the name for your project in an opened dialog.
#{'2. Add [Drive API] service.'.green}
2-1. Click [Services] in the left sidebar.
2-2. Set status to [ON] in Drive API.
#{'3. Create client_id and client_secret.'.green}
3-1. Click [API Access] in the left sidebar.
3-2. Click [Create an OAuth2.0 client ID...]
3-3. Enter the your [Product name] in an opened dialog , then Click [Next].
3-4. Choose [Installed application] of 'Application Type'.
3-5. Choose [Other] of 'Installed application type'.
3-6. Click [Create client ID].
Then Client ID(client_id) and Client Secret(client_secret) will be created.
Okay? Let's begin creating client_id and client_secret.
"""
program.prompt "Press Enter Key, Open Browser.", ()->
open "https://code.google.com/apis/console" , (err)->
cb(err) if err
cb(null)
async.waterfall([
start
openBrowser
]
,(err)->
throw err if err
callback(null)
)
| 29046 | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
###
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('../gas-manager').Manager
util = require './util'
open = require 'open'
googleapis = require 'googleapis'
colors = require 'colors'
CALLBACK_URL = 'urn:ietf:wg:oauth:2.0:oob'
SCOPE = [
"https://www.googleapis.com/auth/drive"
"https://www.googleapis.com/auth/drive.file"
"https://www.googleapis.com/auth/drive.scripts"
].join(" ")
program = null
exports.init = (option)->
program = @
config = {}
start = (cb)->
console.log """
#{'''===================
Start gas-manager init
==================='''.green}
This utility is will walk you through creating a gas-manager's config file.
Press ^C at any time to quit.
""".green
program.confirm("Do you have client_id & client_secret for Google OAuth2? #{'[yes/no]'.green} ",(result)->
if result is yes
cb(null)
else
createConsumerKeyFlow(cb)
)
inputConsumerSecret = (cb)->
program.prompt("Please input client_secret: " , (result)->
if !result
inputConsumerSecret(cb)
return
config.client_secret = result
cb(null)
)
inputConsumerId = (cb)->
program.prompt("Please input client_id: " , (result)->
if !result
inputConsumerId(cb)
return
config.client_id = result
cb(null)
)
askRefreshToken = (cb)->
program.confirm "Do you create refresh_token now? if yes, open browser. #{'[yes/no]'.green} ", (result)->
if result is yes
createRefreshToken(cb)
else
program.prompt "Please input refresh_token: ",(result)->
return askRefreshToken(cb) if !result
config.refresh_token = result
cb(null)
createRefreshToken = (cb)->
#TODO
console.log """
#{'''===================
About a flow of creating refresh_token.
==================='''.green}
I'll open browser.
Then please do flow below.
#{' 1. Choose account of authorize.'.green}
#{' 2. Apploval an OAuth'.green}
#{' 3. Enter a code , that will be shown in blowser, to the console.'.green}
Then will create refresh_token.
Okay? Let's begin creating refresh_token.
"""
oauth2Client = new googleapis.OAuth2Client(config.client_id, config.client_secret, CALLBACK_URL)
url = oauth2Client.generateAuthUrl({
access_type: 'offline'
scope: SCOPE
})
program.prompt "Press Enter Key, Open Browser. ", ()->
open url , (err)->
cb(err) if err
enterCode = ()->
program.prompt "Enter code: " , (result)->
return enterCode() if !result
oauth2Client.getToken result, (err, tokens)->
cb(err) if err
config.refresh_token = tokens.refresh_token
cb(null)
enterCode()
saveCredentialToFile = (cb)->
program.prompt "Save settings to file please input file path #{('[Default: ' + program.config + ']').green}: ", (result)->
if !result
result = program.config
result = path.resolve(result)
if !fs.existsSync path.dirname(result)
fs.mkdirSync path.dirname(result)
fs.writeFileSync result, JSON.stringify(config, "", 2)
console.log "Created credential file to #{path.resolve(result).green}"
cb(null)
confirmCreatingProjectSetting = (cb)->
program.confirm "Do you want to creating Project settings? #{'[yes/no]'.green} ", (result)->
if result is yes
createProjectSettingFlow(config, cb)
else
cb(null)
createCredentialflow = [
start
inputConsumerId
inputConsumerSecret
askRefreshToken
saveCredentialToFile
confirmCreatingProjectSetting
]
if !option.onlyProject
async.waterfall(createCredentialflow, (err, result)->
throw err if err
console.log "Finish."
process.stdin.destroy()
process.exit(0)
)
else
createProjectSettingFlow(util.loadConfig(program), (err, result)->
throw err if err
console.log "Finish."
process.stdin.destroy()
process.exit(0)
)
createProjectSettingFlow = (config, callback)->
start = (cb)->
program.prompt("Enter your need managing fileId of Google Apps Script Project: " , (result)->
return start(cb) if !result
cb(null, result)
)
getProject = (fileId, cb)->
manager = new Manager config
manager.getProject(fileId, cb)
confirmProject = (project, response, cb)->
filenames = project.getFiles().map((file)-> "#{file.name} [type:#{file.type}]").join('\n ')
console.log """
Is it your needing project?
#{'Filename:'.green}
#{project.filename}
#{'Files:'.green}
#{filenames}
"""
program.confirm("Okay? #{'[yes/no]'.green} " , (result)->
if result is yes
cb(null, project)
else
cb("restart")
createProjectSettingFlow(config, callback)
)
setEnvironment = (project, cb)->
program.prompt("Enter your environment name #{('[Default: ' + program.env + ']').green} ", (result)->
if !result
result = program.env
cb(null, project, result)
)
askWhereToCreatingFiles = (project, env, cb)->
savedfiles = {}
askWhereToCreatingFile = (file, files, basePath, cb2)->
extension = if file.type == "server_js" then ".js" else ".html"
filename = file.name + extension
program.prompt(" > #{filename} #{('[Default: ' + path.resolve(basePath, filename) + ']').green}: ", (result)->
if !result
result = path.resolve(basePath , filename)
else
reuslt = path.resolve(result)
savedfiles[file.name] = {
path : result
type : file.type
}
cb2(null,files.pop(), files, basePath)
)
flow = []
flow.push (cb)->
program.prompt("Where is a base path of the project sources ? #{('[Default: ' + process.cwd() + ']').green}: ", (result)->
if !result
result = process.cwd()
files = project.getFiles()
console.log("Where do you want to create file to...")
cb(null,files.pop(), files, result)
)
for i in project.getFiles()
flow.push askWhereToCreatingFile
async.waterfall flow , (err)->
throw err if err
cb(null, project, env, savedfiles)
saveProjectSettingToFile = (project, env, files, cb)->
program.prompt "Save settings to file, Please input file path #{('[Default: ' + program.setting + ']').green}: ", (result)->
if !result
result = program.setting
result = path.resolve(result)
if !fs.existsSync path.dirname(result)
fs.mkdirSync path.dirname(result)
setting = {}
setting[env] =
fileId : project.fileId
files : files
fs.writeFileSync result, JSON.stringify(setting, "", 2)
console.log "Created project setting file to #{path.resolve(result).green}"
cb(null)
async.waterfall(
[
start
getProject
confirmProject
setEnvironment
askWhereToCreatingFiles
saveProjectSettingToFile
], (err)->
if err is "restart" then return
if err then throw err
if callback then callback(null)
)
createConsumerKeyFlow = (callback)->
start = (cb)->
program.confirm("Do you create client_id and client_secret, if yes, open browser. #{'[yes/no]'.green} ",(result)->
if result is yes
cb(null)
else
callback(null)
)
openBrowser = (cb)->
console.log """
#{'''===================
About a flow of creating client_id and client_secret.
==================='''.green}
I'll open browser to https://code.google.com/apis/console.
Then please do flow below.
#{'1. Creating new project in opened browser.'.green}
1-1. Choose [Create...] at the upper left menu.
1-2. Enter the name for your project in an opened dialog.
#{'2. Add [Drive API] service.'.green}
2-1. Click [Services] in the left sidebar.
2-2. Set status to [ON] in Drive API.
#{'3. Create client_id and client_secret.'.green}
3-1. Click [API Access] in the left sidebar.
3-2. Click [Create an OAuth2.0 client ID...]
3-3. Enter the your [Product name] in an opened dialog , then Click [Next].
3-4. Choose [Installed application] of 'Application Type'.
3-5. Choose [Other] of 'Installed application type'.
3-6. Click [Create client ID].
Then Client ID(client_id) and Client Secret(client_secret) will be created.
Okay? Let's begin creating client_id and client_secret.
"""
program.prompt "Press Enter Key, Open Browser.", ()->
open "https://code.google.com/apis/console" , (err)->
cb(err) if err
cb(null)
async.waterfall([
start
openBrowser
]
,(err)->
throw err if err
callback(null)
)
| true | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('../gas-manager').Manager
util = require './util'
open = require 'open'
googleapis = require 'googleapis'
colors = require 'colors'
CALLBACK_URL = 'urn:ietf:wg:oauth:2.0:oob'
SCOPE = [
"https://www.googleapis.com/auth/drive"
"https://www.googleapis.com/auth/drive.file"
"https://www.googleapis.com/auth/drive.scripts"
].join(" ")
program = null
exports.init = (option)->
program = @
config = {}
start = (cb)->
console.log """
#{'''===================
Start gas-manager init
==================='''.green}
This utility is will walk you through creating a gas-manager's config file.
Press ^C at any time to quit.
""".green
program.confirm("Do you have client_id & client_secret for Google OAuth2? #{'[yes/no]'.green} ",(result)->
if result is yes
cb(null)
else
createConsumerKeyFlow(cb)
)
inputConsumerSecret = (cb)->
program.prompt("Please input client_secret: " , (result)->
if !result
inputConsumerSecret(cb)
return
config.client_secret = result
cb(null)
)
inputConsumerId = (cb)->
program.prompt("Please input client_id: " , (result)->
if !result
inputConsumerId(cb)
return
config.client_id = result
cb(null)
)
askRefreshToken = (cb)->
program.confirm "Do you create refresh_token now? if yes, open browser. #{'[yes/no]'.green} ", (result)->
if result is yes
createRefreshToken(cb)
else
program.prompt "Please input refresh_token: ",(result)->
return askRefreshToken(cb) if !result
config.refresh_token = result
cb(null)
createRefreshToken = (cb)->
#TODO
console.log """
#{'''===================
About a flow of creating refresh_token.
==================='''.green}
I'll open browser.
Then please do flow below.
#{' 1. Choose account of authorize.'.green}
#{' 2. Apploval an OAuth'.green}
#{' 3. Enter a code , that will be shown in blowser, to the console.'.green}
Then will create refresh_token.
Okay? Let's begin creating refresh_token.
"""
oauth2Client = new googleapis.OAuth2Client(config.client_id, config.client_secret, CALLBACK_URL)
url = oauth2Client.generateAuthUrl({
access_type: 'offline'
scope: SCOPE
})
program.prompt "Press Enter Key, Open Browser. ", ()->
open url , (err)->
cb(err) if err
enterCode = ()->
program.prompt "Enter code: " , (result)->
return enterCode() if !result
oauth2Client.getToken result, (err, tokens)->
cb(err) if err
config.refresh_token = tokens.refresh_token
cb(null)
enterCode()
saveCredentialToFile = (cb)->
program.prompt "Save settings to file please input file path #{('[Default: ' + program.config + ']').green}: ", (result)->
if !result
result = program.config
result = path.resolve(result)
if !fs.existsSync path.dirname(result)
fs.mkdirSync path.dirname(result)
fs.writeFileSync result, JSON.stringify(config, "", 2)
console.log "Created credential file to #{path.resolve(result).green}"
cb(null)
confirmCreatingProjectSetting = (cb)->
program.confirm "Do you want to creating Project settings? #{'[yes/no]'.green} ", (result)->
if result is yes
createProjectSettingFlow(config, cb)
else
cb(null)
createCredentialflow = [
start
inputConsumerId
inputConsumerSecret
askRefreshToken
saveCredentialToFile
confirmCreatingProjectSetting
]
if !option.onlyProject
async.waterfall(createCredentialflow, (err, result)->
throw err if err
console.log "Finish."
process.stdin.destroy()
process.exit(0)
)
else
createProjectSettingFlow(util.loadConfig(program), (err, result)->
throw err if err
console.log "Finish."
process.stdin.destroy()
process.exit(0)
)
createProjectSettingFlow = (config, callback)->
start = (cb)->
program.prompt("Enter your need managing fileId of Google Apps Script Project: " , (result)->
return start(cb) if !result
cb(null, result)
)
getProject = (fileId, cb)->
manager = new Manager config
manager.getProject(fileId, cb)
confirmProject = (project, response, cb)->
filenames = project.getFiles().map((file)-> "#{file.name} [type:#{file.type}]").join('\n ')
console.log """
Is it your needing project?
#{'Filename:'.green}
#{project.filename}
#{'Files:'.green}
#{filenames}
"""
program.confirm("Okay? #{'[yes/no]'.green} " , (result)->
if result is yes
cb(null, project)
else
cb("restart")
createProjectSettingFlow(config, callback)
)
setEnvironment = (project, cb)->
program.prompt("Enter your environment name #{('[Default: ' + program.env + ']').green} ", (result)->
if !result
result = program.env
cb(null, project, result)
)
askWhereToCreatingFiles = (project, env, cb)->
savedfiles = {}
askWhereToCreatingFile = (file, files, basePath, cb2)->
extension = if file.type == "server_js" then ".js" else ".html"
filename = file.name + extension
program.prompt(" > #{filename} #{('[Default: ' + path.resolve(basePath, filename) + ']').green}: ", (result)->
if !result
result = path.resolve(basePath , filename)
else
reuslt = path.resolve(result)
savedfiles[file.name] = {
path : result
type : file.type
}
cb2(null,files.pop(), files, basePath)
)
flow = []
flow.push (cb)->
program.prompt("Where is a base path of the project sources ? #{('[Default: ' + process.cwd() + ']').green}: ", (result)->
if !result
result = process.cwd()
files = project.getFiles()
console.log("Where do you want to create file to...")
cb(null,files.pop(), files, result)
)
for i in project.getFiles()
flow.push askWhereToCreatingFile
async.waterfall flow , (err)->
throw err if err
cb(null, project, env, savedfiles)
saveProjectSettingToFile = (project, env, files, cb)->
program.prompt "Save settings to file, Please input file path #{('[Default: ' + program.setting + ']').green}: ", (result)->
if !result
result = program.setting
result = path.resolve(result)
if !fs.existsSync path.dirname(result)
fs.mkdirSync path.dirname(result)
setting = {}
setting[env] =
fileId : project.fileId
files : files
fs.writeFileSync result, JSON.stringify(setting, "", 2)
console.log "Created project setting file to #{path.resolve(result).green}"
cb(null)
async.waterfall(
[
start
getProject
confirmProject
setEnvironment
askWhereToCreatingFiles
saveProjectSettingToFile
], (err)->
if err is "restart" then return
if err then throw err
if callback then callback(null)
)
createConsumerKeyFlow = (callback)->
start = (cb)->
program.confirm("Do you create client_id and client_secret, if yes, open browser. #{'[yes/no]'.green} ",(result)->
if result is yes
cb(null)
else
callback(null)
)
openBrowser = (cb)->
console.log """
#{'''===================
About a flow of creating client_id and client_secret.
==================='''.green}
I'll open browser to https://code.google.com/apis/console.
Then please do flow below.
#{'1. Creating new project in opened browser.'.green}
1-1. Choose [Create...] at the upper left menu.
1-2. Enter the name for your project in an opened dialog.
#{'2. Add [Drive API] service.'.green}
2-1. Click [Services] in the left sidebar.
2-2. Set status to [ON] in Drive API.
#{'3. Create client_id and client_secret.'.green}
3-1. Click [API Access] in the left sidebar.
3-2. Click [Create an OAuth2.0 client ID...]
3-3. Enter the your [Product name] in an opened dialog , then Click [Next].
3-4. Choose [Installed application] of 'Application Type'.
3-5. Choose [Other] of 'Installed application type'.
3-6. Click [Create client ID].
Then Client ID(client_id) and Client Secret(client_secret) will be created.
Okay? Let's begin creating client_id and client_secret.
"""
program.prompt "Press Enter Key, Open Browser.", ()->
open "https://code.google.com/apis/console" , (err)->
cb(err) if err
cb(null)
async.waterfall([
start
openBrowser
]
,(err)->
throw err if err
callback(null)
)
|
[
{
"context": "uri\n binddn: ldap.config.binddn\n passwd: ldap.config.passwd\n suffix: ldap.suffix_dn\n {stdout} = await",
"end": 408,
"score": 0.9970625638961792,
"start": 390,
"tag": "PASSWORD",
"value": "ldap.config.passwd"
},
{
"context": "uri\n binddn: ldap... | packages/ldap/test/index.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config, ldap} = require './test'
they = require('mocha-they')(config)
utils = require '../src/utils'
return unless tags.ldap_index
describe 'ldap.index', ->
olcDatabase = olcDbIndexes = null
beforeEach ->
{database: olcDatabase} = await nikita.ldap.tools.database
uri: ldap.uri
binddn: ldap.config.binddn
passwd: ldap.config.passwd
suffix: ldap.suffix_dn
{stdout} = await nikita.ldap.search
uri: ldap.uri
binddn: ldap.config.binddn
passwd: ldap.config.passwd
base: "olcDatabase=#{olcDatabase},cn=config"
attributes:['olcDbIndex']
scope: 'base'
olcDbIndexes = utils.string.lines(stdout)
.filter (l) -> /^olcDbIndex: /.test l
.map (line) -> line.split(':')[1].trim()
afterEach ->
nikita.ldap.modify
uri: ldap.uri
binddn: ldap.config.binddn
passwd: ldap.config.passwd
operations:
dn: "olcDatabase=#{olcDatabase},cn=config"
changetype: 'modify'
attributes: [
type: 'delete'
name: 'olcDbIndex'
...(
type: 'add'
name: 'olcDbIndex'
value: olcDbIndex
) for olcDbIndex in olcDbIndexes
]
they 'create a new index from dn', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: ldap.config.passwd
$ssh: ssh
, ->
{dn} = await @ldap.tools.database
suffix: ldap.suffix_dn
{$status} = await @ldap.index
dn: dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.true()
{$status} = await @ldap.index
dn: dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.false()
they 'create a new index from suffix', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: ldap.config.passwd
$ssh: ssh
, ->
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.true()
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.false()
they 'update an existing index', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: ldap.config.passwd
$ssh: ssh
, ->
# Set initial value
await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
# Apply the update
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'pres,eq'
$status.should.be.true()
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'pres,eq'
$status.should.be.false()
| 14250 |
nikita = require '@nikitajs/core/lib'
{tags, config, ldap} = require './test'
they = require('mocha-they')(config)
utils = require '../src/utils'
return unless tags.ldap_index
describe 'ldap.index', ->
olcDatabase = olcDbIndexes = null
beforeEach ->
{database: olcDatabase} = await nikita.ldap.tools.database
uri: ldap.uri
binddn: ldap.config.binddn
passwd: <PASSWORD>
suffix: ldap.suffix_dn
{stdout} = await nikita.ldap.search
uri: ldap.uri
binddn: ldap.config.binddn
passwd: <PASSWORD>
base: "olcDatabase=#{olcDatabase},cn=config"
attributes:['olcDbIndex']
scope: 'base'
olcDbIndexes = utils.string.lines(stdout)
.filter (l) -> /^olcDbIndex: /.test l
.map (line) -> line.split(':')[1].trim()
afterEach ->
nikita.ldap.modify
uri: ldap.uri
binddn: ldap.config.binddn
passwd: <PASSWORD>
operations:
dn: "olcDatabase=#{olcDatabase},cn=config"
changetype: 'modify'
attributes: [
type: 'delete'
name: 'olcDbIndex'
...(
type: 'add'
name: 'olcDbIndex'
value: olcDbIndex
) for olcDbIndex in olcDbIndexes
]
they 'create a new index from dn', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: <PASSWORD>
$ssh: ssh
, ->
{dn} = await @ldap.tools.database
suffix: ldap.suffix_dn
{$status} = await @ldap.index
dn: dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.true()
{$status} = await @ldap.index
dn: dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.false()
they 'create a new index from suffix', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: <PASSWORD>
$ssh: ssh
, ->
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.true()
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.false()
they 'update an existing index', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: <PASSWORD>
$ssh: ssh
, ->
# Set initial value
await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
# Apply the update
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'pres,eq'
$status.should.be.true()
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'pres,eq'
$status.should.be.false()
| true |
nikita = require '@nikitajs/core/lib'
{tags, config, ldap} = require './test'
they = require('mocha-they')(config)
utils = require '../src/utils'
return unless tags.ldap_index
describe 'ldap.index', ->
olcDatabase = olcDbIndexes = null
beforeEach ->
{database: olcDatabase} = await nikita.ldap.tools.database
uri: ldap.uri
binddn: ldap.config.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
suffix: ldap.suffix_dn
{stdout} = await nikita.ldap.search
uri: ldap.uri
binddn: ldap.config.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
base: "olcDatabase=#{olcDatabase},cn=config"
attributes:['olcDbIndex']
scope: 'base'
olcDbIndexes = utils.string.lines(stdout)
.filter (l) -> /^olcDbIndex: /.test l
.map (line) -> line.split(':')[1].trim()
afterEach ->
nikita.ldap.modify
uri: ldap.uri
binddn: ldap.config.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
operations:
dn: "olcDatabase=#{olcDatabase},cn=config"
changetype: 'modify'
attributes: [
type: 'delete'
name: 'olcDbIndex'
...(
type: 'add'
name: 'olcDbIndex'
value: olcDbIndex
) for olcDbIndex in olcDbIndexes
]
they 'create a new index from dn', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
$ssh: ssh
, ->
{dn} = await @ldap.tools.database
suffix: ldap.suffix_dn
{$status} = await @ldap.index
dn: dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.true()
{$status} = await @ldap.index
dn: dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.false()
they 'create a new index from suffix', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
$ssh: ssh
, ->
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.true()
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
$status.should.be.false()
they 'update an existing index', ({ssh}) ->
nikita
ldap:
uri: ldap.uri
binddn: ldap.config.binddn
passwd: PI:PASSWORD:<PASSWORD>END_PI
$ssh: ssh
, ->
# Set initial value
await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'eq'
# Apply the update
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'pres,eq'
$status.should.be.true()
{$status} = await @ldap.index
suffix: ldap.suffix_dn
indexes:
aliasedEntryName: 'pres,eq'
$status.should.be.false()
|
[
{
"context": "st enforcement of lines around comments.\n# @author Jamund Ferguson\n###\n'use strict'\n\n#------------------------------",
"end": 89,
"score": 0.9998425245285034,
"start": 74,
"tag": "NAME",
"value": "Jamund Ferguson"
}
] | src/tests/rules/lines-around-comment.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Test enforcement of lines around comments.
# @author Jamund Ferguson
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/lines-around-comment'
{RuleTester} = require 'eslint'
path = require 'path'
afterMessage = 'Expected line after comment.'
beforeMessage = 'Expected line before comment.'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'lines-around-comment', rule,
valid: [
# default rules
'bar()\n\n###* block block block\n * block \n ###\n\na = 1'
'bar()\n\n###* block block block\n * block \n ###\na = 1'
'bar()\n# line line line \na = 1'
'bar()\n\n# line line line\na = 1'
'bar()\n# line line line\n\na = 1'
,
# line comments
code: 'bar()\n# line line line\n\na = 1'
options: [afterLineComment: yes]
,
code: 'foo()\n\n# line line line\na = 1'
options: [beforeLineComment: yes]
,
code: 'foo()\n\n# line line line\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
,
code: 'foo()\n\n# line line line\n# line line\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
,
code: '# line line line\n# line line'
options: [beforeLineComment: yes, afterLineComment: yes]
,
# block comments
code:
'bar()\n\n###* A Block comment with a an empty line after\n *\n ###\na = 1'
options: [afterBlockComment: no, beforeBlockComment: yes]
,
code: 'bar()\n\n###* block block block\n * block \n ###\na = 1'
options: [afterBlockComment: no]
,
code: '###* \nblock \nblock block\n ###\n### block \n block \n ###'
options: [afterBlockComment: yes, beforeBlockComment: yes]
,
code: 'bar()\n\n###* block block block\n * block \n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
,
# inline comments (should not ever warn)
code: 'foo() # An inline comment with a an empty line after\na = 1'
options: [afterLineComment: yes, beforeLineComment: yes]
,
code:
'foo()\nbar() ### An inline block comment with a an empty line after\n *\n ###\na = 1'
options: [beforeBlockComment: yes]
,
# mixed comment (some block & some line)
code:
'bar()\n\n###* block block block\n * block \n ###\n#line line line\na = 1'
options: [afterBlockComment: yes]
,
code:
'bar()\n\n###* block block block\n * block \n ###\n#line line line\na = 1'
options: [beforeLineComment: yes]
,
# check for block start comments
code: 'a\n\n# line\nb'
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
-># line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
foo = ->
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
foo = ->
# line at block start
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
bar()
else
# line at block start
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
break
else
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
break
else
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
->### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
foo = ->
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
if yes
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
if yes
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
while yes
###
block comment at block start
###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [allowBlockStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [allowClassStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [
allowBlockStart: no
allowClassStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch 'foo'
when 'foo'
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch 'foo'
when 'foo'
break
else
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch ('foo')
when 'foo'
break
else
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
->
g = 91
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
->
g = 61
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
foo = ->
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
beforeLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
foo = ->
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
### block comment at block end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
while yes
g = 1
###
block comment at block end
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowClassEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: no
allowClassEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
# check for object start comments
code: '''
obj = {
# line at object start
g: 1
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
->
return {
# hi
test: ->
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
# ,
# code: '''
# obj =
# ### block comment at object start###
# g: 1
# '''
# options: [
# beforeBlockComment: yes
# allowObjectStart: yes
# ]
# ,
code: '''
->
return {
###*
* hi
###
test: ->
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
# line at object start
g: a
} = {}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
# line at object start
g
} = {}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
### block comment at object-like start###
g: a
} = {}
'''
options: [
beforeBlockComment: yes
allowObjectStart: yes
]
,
code: '''
{
### block comment at object-like start###
g
} = {}
'''
options: [
beforeBlockComment: yes
allowObjectStart: yes
]
,
# check for object end comments
code: '''
obj = {
g: 1
# line at object end
}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
# ,
# code: '''
# obj =
# g: 1
# # line at object end
# '''
# options: [
# afterLineComment: yes
# allowObjectEnd: yes
# ]
code: '''
->
return {
test: ->
# hi
}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
obj = {
g: 1
### block comment at object end###
}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
->
return {
test: ->
###*
* hi
###
}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g: a
# line at object end
} = {}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g
# line at object end
} = {}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g: a
### block comment at object-like end###
} = {}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g
### block comment at object-like end###
} = {}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
# check for array start comments
code: '''
arr = [
# line at array start
1\
]
'''
options: [
beforeLineComment: yes
allowArrayStart: yes
]
,
code: '''
arr = [
### block comment at array start###
1
]
'''
options: [
beforeBlockComment: yes
allowArrayStart: yes
]
,
code: '''
[
# line at array start
a
] = []
'''
options: [
beforeLineComment: yes
allowArrayStart: yes
]
,
code: '''
[
### block comment at array start###
a
] = []
'''
options: [
beforeBlockComment: yes
allowArrayStart: yes
]
,
# check for array end comments
code: '''
arr = [
1
# line at array end
]
'''
options: [
afterLineComment: yes
allowArrayEnd: yes
]
,
code: '''
arr = [
1
### block comment at array end###
]
'''
options: [
afterBlockComment: yes
allowArrayEnd: yes
]
,
code: '''
[
a
# line at array end
] = []
'''
options: [
afterLineComment: yes
allowArrayEnd: yes
]
,
code: '''
[
a
### block comment at array end###
] = []
'''
options: [
afterBlockComment: yes
allowArrayEnd: yes
]
,
# ignorePattern
code: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
options: [
beforeBlockComment: yes
afterBlockComment: yes
]
,
'foo\n### eslint ###'
'foo\n### jshint ###'
'foo\n### jslint ###'
'foo\n### istanbul ###'
'foo\n### global ###'
'foo\n### globals ###'
'foo\n### exported ###'
'foo\n### jscs ###'
,
code: 'foo\n### this is pragmatic ###'
options: [ignorePattern: 'pragma']
,
code: 'foo\n### this is pragmatic ###'
options: [applyDefaultIgnorePatterns: no, ignorePattern: 'pragma']
]
invalid: [
# default rules
code: 'bar()\n###* block block block\n * block \n ###\na = 1'
output: 'bar()\n\n###* block block block\n * block \n ###\na = 1'
errors: [message: beforeMessage, type: 'Block']
,
# line comments
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n# A line comment with no empty line after\n\na = 1'
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line']
,
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n\n# A line comment with no empty line after\na = 1'
options: [beforeLineComment: yes, afterLineComment: no]
errors: [message: beforeMessage, type: 'Line']
,
code: '# A line comment with no empty line after\na = 1'
output: '# A line comment with no empty line after\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 1, column: 1]
,
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n\n# A line comment with no empty line after\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
errors: [
message: beforeMessage, type: 'Line', line: 2
,
message: afterMessage, type: 'Line', line: 2
]
,
# block comments
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n\n###*\n * block block block\n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code:
'bar()\n### first block comment ### ### second block comment ###\na = 1'
output:
'bar()\n\n### first block comment ### ### second block comment ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code:
'bar()\n### first block comment ### ### second block\n comment ###\na = 1'
output:
'bar()\n\n### first block comment ### ### second block\n comment ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n###*\n * block block block\n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: no]
errors: [message: afterMessage, type: 'Block', line: 2]
,
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n\n###*\n * block block block\n ###\na = 1'
options: [afterBlockComment: no, beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
->
a = 1
# line at block start
g = 1
'''
output: '''
->
a = 1
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
->
a = 1
# line at block start
g = 1
'''
output: '''
->
a = 1
# line at block start
g = 1
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
switch ('foo')
when 'foo'
# line at switch case start
break
'''
output: '''
switch ('foo')
when 'foo'
# line at switch case start
break
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
switch ('foo')
when 'foo'
break
else
# line at switch case start
break
'''
output: '''
switch ('foo')
when 'foo'
break
else
# line at switch case start
break
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 6]
,
code: '''
try
# line at block start and end
catch
'''
output: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockStart: yes
]
errors: [message: afterMessage, type: 'Line', line: 2]
,
code: '''
try
# line at block start and end
catch
'''
output: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockEnd: yes
]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class A
# line at class start
constructor: ->
'''
output: '''
class A
# line at class start
constructor: ->
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class A
# line at class start
constructor: ->
'''
output: '''
class A
# line at class start
constructor: ->
'''
options: [
allowBlockStart: yes
allowClassStart: no
beforeLineComment: yes
]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class B
constructor: ->
# line at class end
d
'''
output: '''
class B
constructor: ->
# line at class end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
class B
constructor: ->
# line at class end
d
'''
output: '''
class B
constructor: ->
# line at class end
d
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
allowClassEnd: no
]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
d
'''
output: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 5]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
d
'''
output: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 8]
,
# object start comments
code: '''
obj = {
# line at object start
g: 1
}
'''
output: '''
obj = {
# line at object start
g: 1
}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
obj =
# line at object start
g: 1
'''
output: '''
obj =
# line at object start
g: 1
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
->
return {
# hi
test: ->
}
'''
output: '''
->
return {
# hi
test: ->
}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
obj = {
### block comment at object start###
g: 1
}
'''
output: '''
obj = {
### block comment at object start###
g: 1
}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
->
return
###*
* hi
###
test: ->
'''
output: '''
->
return
###*
* hi
###
test: ->
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 3]
,
code: '''
{
# line at object start
g: a
} = {}
'''
output: '''
{
# line at object start
g: a
} = {}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
{
# line at object start
g
} = {}
'''
output: '''
{
# line at object start
g
} = {}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
{
### block comment at object-like start###
g: a
} = {}
'''
output: '''
{
### block comment at object-like start###
g: a
} = {}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
{
### block comment at object-like start###
g
} = {}
'''
output: '''
{
### block comment at object-like start###
g
} = {}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
# object end comments
code: '''
obj = {
g: 1
# line at object end
}
'''
output: '''
obj = {
g: 1
# line at object end
}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
obj =
g: 1
# line at object end
d
'''
output: '''
obj =
g: 1
# line at object end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
->
return {
test: ->
# hi
}
'''
output: '''
->
return {
test: ->
# hi
}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
obj = {
g: 1
### block comment at object end###
}
'''
output: '''
obj = {
g: 1
### block comment at object end###
}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
->
return {
test: ->
###*
* hi
###
}
'''
output: '''
->
return {
test: ->
###*
* hi
###
}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 5]
,
code: '''
{
g: a
# line at object end
} = {}
'''
output: '''
{
g: a
# line at object end
} = {}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
{
g
# line at object end
} = {}
'''
output: '''
{
g
# line at object end
} = {}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
{
g: a
### block comment at object-like end###
} = {}
'''
output: '''
{
g: a
### block comment at object-like end###
} = {}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
{
g
### block comment at object-like end###
} = {}
'''
output: '''
{
g
### block comment at object-like end###
} = {}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
# array start comments
code: '''
arr = [
# line at array start
1
]
'''
output: '''
arr = [
# line at array start
1
]
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
arr = [
### block comment at array start###
1
]
'''
output: '''
arr = [
### block comment at array start###
1
]
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
[
# line at array start
a
] = []
'''
output: '''
[
# line at array start
a
] = []
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
[
### block comment at array start###
a
] = []
'''
output: '''
[
### block comment at array start###
a
] = []
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
# array end comments
code: '''
arr = [
1
# line at array end
]
'''
output: '''
arr = [
1
# line at array end
]
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
arr = [
1
### block comment at array end###
]
'''
output: '''
arr = [
1
### block comment at array end###
]
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
[
a
# line at array end
] = []
'''
output: '''
[
a
# line at array end
] = []
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
[
a
### block comment at array end###
] = []
'''
output: '''
[
a
### block comment at array end###
] = []
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
# ignorePattern
code: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
output: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
options: [
beforeBlockComment: yes
afterBlockComment: yes
applyDefaultIgnorePatterns: no
]
errors: [
message: beforeMessage, type: 'Block', line: 7
,
message: afterMessage, type: 'Block', line: 7
]
,
code: 'foo\n### eslint ###'
output: 'foo\n\n### eslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jshint ###'
output: 'foo\n\n### jshint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jslint ###'
output: 'foo\n\n### jslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### istanbul ###'
output: 'foo\n\n### istanbul ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### global ###'
output: 'foo\n\n### global ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### globals ###'
output: 'foo\n\n### globals ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### exported ###'
output: 'foo\n\n### exported ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jscs ###'
output: 'foo\n\n### jscs ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### something else ###'
output: 'foo\n\n### something else ###'
options: [ignorePattern: 'pragma']
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### eslint ###'
output: 'foo\n\n### eslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
# "fallthrough" patterns are not ignored by default
code: 'foo\n### fallthrough ###'
output: 'foo\n\n### fallthrough ###'
options: []
errors: [message: beforeMessage, type: 'Block']
]
| 14478 | ###*
# @fileoverview Test enforcement of lines around comments.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/lines-around-comment'
{RuleTester} = require 'eslint'
path = require 'path'
afterMessage = 'Expected line after comment.'
beforeMessage = 'Expected line before comment.'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'lines-around-comment', rule,
valid: [
# default rules
'bar()\n\n###* block block block\n * block \n ###\n\na = 1'
'bar()\n\n###* block block block\n * block \n ###\na = 1'
'bar()\n# line line line \na = 1'
'bar()\n\n# line line line\na = 1'
'bar()\n# line line line\n\na = 1'
,
# line comments
code: 'bar()\n# line line line\n\na = 1'
options: [afterLineComment: yes]
,
code: 'foo()\n\n# line line line\na = 1'
options: [beforeLineComment: yes]
,
code: 'foo()\n\n# line line line\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
,
code: 'foo()\n\n# line line line\n# line line\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
,
code: '# line line line\n# line line'
options: [beforeLineComment: yes, afterLineComment: yes]
,
# block comments
code:
'bar()\n\n###* A Block comment with a an empty line after\n *\n ###\na = 1'
options: [afterBlockComment: no, beforeBlockComment: yes]
,
code: 'bar()\n\n###* block block block\n * block \n ###\na = 1'
options: [afterBlockComment: no]
,
code: '###* \nblock \nblock block\n ###\n### block \n block \n ###'
options: [afterBlockComment: yes, beforeBlockComment: yes]
,
code: 'bar()\n\n###* block block block\n * block \n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
,
# inline comments (should not ever warn)
code: 'foo() # An inline comment with a an empty line after\na = 1'
options: [afterLineComment: yes, beforeLineComment: yes]
,
code:
'foo()\nbar() ### An inline block comment with a an empty line after\n *\n ###\na = 1'
options: [beforeBlockComment: yes]
,
# mixed comment (some block & some line)
code:
'bar()\n\n###* block block block\n * block \n ###\n#line line line\na = 1'
options: [afterBlockComment: yes]
,
code:
'bar()\n\n###* block block block\n * block \n ###\n#line line line\na = 1'
options: [beforeLineComment: yes]
,
# check for block start comments
code: 'a\n\n# line\nb'
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
-># line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
foo = ->
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
foo = ->
# line at block start
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
bar()
else
# line at block start
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
break
else
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
break
else
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
->### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
foo = ->
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
if yes
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
if yes
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
while yes
###
block comment at block start
###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [allowBlockStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [allowClassStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [
allowBlockStart: no
allowClassStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch 'foo'
when 'foo'
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch 'foo'
when 'foo'
break
else
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch ('foo')
when 'foo'
break
else
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
->
g = 91
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
->
g = 61
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
foo = ->
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
beforeLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
foo = ->
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
### block comment at block end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
while yes
g = 1
###
block comment at block end
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowClassEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: no
allowClassEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
# check for object start comments
code: '''
obj = {
# line at object start
g: 1
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
->
return {
# hi
test: ->
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
# ,
# code: '''
# obj =
# ### block comment at object start###
# g: 1
# '''
# options: [
# beforeBlockComment: yes
# allowObjectStart: yes
# ]
# ,
code: '''
->
return {
###*
* hi
###
test: ->
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
# line at object start
g: a
} = {}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
# line at object start
g
} = {}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
### block comment at object-like start###
g: a
} = {}
'''
options: [
beforeBlockComment: yes
allowObjectStart: yes
]
,
code: '''
{
### block comment at object-like start###
g
} = {}
'''
options: [
beforeBlockComment: yes
allowObjectStart: yes
]
,
# check for object end comments
code: '''
obj = {
g: 1
# line at object end
}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
# ,
# code: '''
# obj =
# g: 1
# # line at object end
# '''
# options: [
# afterLineComment: yes
# allowObjectEnd: yes
# ]
code: '''
->
return {
test: ->
# hi
}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
obj = {
g: 1
### block comment at object end###
}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
->
return {
test: ->
###*
* hi
###
}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g: a
# line at object end
} = {}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g
# line at object end
} = {}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g: a
### block comment at object-like end###
} = {}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g
### block comment at object-like end###
} = {}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
# check for array start comments
code: '''
arr = [
# line at array start
1\
]
'''
options: [
beforeLineComment: yes
allowArrayStart: yes
]
,
code: '''
arr = [
### block comment at array start###
1
]
'''
options: [
beforeBlockComment: yes
allowArrayStart: yes
]
,
code: '''
[
# line at array start
a
] = []
'''
options: [
beforeLineComment: yes
allowArrayStart: yes
]
,
code: '''
[
### block comment at array start###
a
] = []
'''
options: [
beforeBlockComment: yes
allowArrayStart: yes
]
,
# check for array end comments
code: '''
arr = [
1
# line at array end
]
'''
options: [
afterLineComment: yes
allowArrayEnd: yes
]
,
code: '''
arr = [
1
### block comment at array end###
]
'''
options: [
afterBlockComment: yes
allowArrayEnd: yes
]
,
code: '''
[
a
# line at array end
] = []
'''
options: [
afterLineComment: yes
allowArrayEnd: yes
]
,
code: '''
[
a
### block comment at array end###
] = []
'''
options: [
afterBlockComment: yes
allowArrayEnd: yes
]
,
# ignorePattern
code: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
options: [
beforeBlockComment: yes
afterBlockComment: yes
]
,
'foo\n### eslint ###'
'foo\n### jshint ###'
'foo\n### jslint ###'
'foo\n### istanbul ###'
'foo\n### global ###'
'foo\n### globals ###'
'foo\n### exported ###'
'foo\n### jscs ###'
,
code: 'foo\n### this is pragmatic ###'
options: [ignorePattern: 'pragma']
,
code: 'foo\n### this is pragmatic ###'
options: [applyDefaultIgnorePatterns: no, ignorePattern: 'pragma']
]
invalid: [
# default rules
code: 'bar()\n###* block block block\n * block \n ###\na = 1'
output: 'bar()\n\n###* block block block\n * block \n ###\na = 1'
errors: [message: beforeMessage, type: 'Block']
,
# line comments
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n# A line comment with no empty line after\n\na = 1'
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line']
,
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n\n# A line comment with no empty line after\na = 1'
options: [beforeLineComment: yes, afterLineComment: no]
errors: [message: beforeMessage, type: 'Line']
,
code: '# A line comment with no empty line after\na = 1'
output: '# A line comment with no empty line after\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 1, column: 1]
,
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n\n# A line comment with no empty line after\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
errors: [
message: beforeMessage, type: 'Line', line: 2
,
message: afterMessage, type: 'Line', line: 2
]
,
# block comments
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n\n###*\n * block block block\n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code:
'bar()\n### first block comment ### ### second block comment ###\na = 1'
output:
'bar()\n\n### first block comment ### ### second block comment ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code:
'bar()\n### first block comment ### ### second block\n comment ###\na = 1'
output:
'bar()\n\n### first block comment ### ### second block\n comment ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n###*\n * block block block\n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: no]
errors: [message: afterMessage, type: 'Block', line: 2]
,
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n\n###*\n * block block block\n ###\na = 1'
options: [afterBlockComment: no, beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
->
a = 1
# line at block start
g = 1
'''
output: '''
->
a = 1
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
->
a = 1
# line at block start
g = 1
'''
output: '''
->
a = 1
# line at block start
g = 1
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
switch ('foo')
when 'foo'
# line at switch case start
break
'''
output: '''
switch ('foo')
when 'foo'
# line at switch case start
break
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
switch ('foo')
when 'foo'
break
else
# line at switch case start
break
'''
output: '''
switch ('foo')
when 'foo'
break
else
# line at switch case start
break
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 6]
,
code: '''
try
# line at block start and end
catch
'''
output: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockStart: yes
]
errors: [message: afterMessage, type: 'Line', line: 2]
,
code: '''
try
# line at block start and end
catch
'''
output: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockEnd: yes
]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class A
# line at class start
constructor: ->
'''
output: '''
class A
# line at class start
constructor: ->
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class A
# line at class start
constructor: ->
'''
output: '''
class A
# line at class start
constructor: ->
'''
options: [
allowBlockStart: yes
allowClassStart: no
beforeLineComment: yes
]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class B
constructor: ->
# line at class end
d
'''
output: '''
class B
constructor: ->
# line at class end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
class B
constructor: ->
# line at class end
d
'''
output: '''
class B
constructor: ->
# line at class end
d
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
allowClassEnd: no
]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
d
'''
output: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 5]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
d
'''
output: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 8]
,
# object start comments
code: '''
obj = {
# line at object start
g: 1
}
'''
output: '''
obj = {
# line at object start
g: 1
}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
obj =
# line at object start
g: 1
'''
output: '''
obj =
# line at object start
g: 1
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
->
return {
# hi
test: ->
}
'''
output: '''
->
return {
# hi
test: ->
}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
obj = {
### block comment at object start###
g: 1
}
'''
output: '''
obj = {
### block comment at object start###
g: 1
}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
->
return
###*
* hi
###
test: ->
'''
output: '''
->
return
###*
* hi
###
test: ->
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 3]
,
code: '''
{
# line at object start
g: a
} = {}
'''
output: '''
{
# line at object start
g: a
} = {}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
{
# line at object start
g
} = {}
'''
output: '''
{
# line at object start
g
} = {}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
{
### block comment at object-like start###
g: a
} = {}
'''
output: '''
{
### block comment at object-like start###
g: a
} = {}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
{
### block comment at object-like start###
g
} = {}
'''
output: '''
{
### block comment at object-like start###
g
} = {}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
# object end comments
code: '''
obj = {
g: 1
# line at object end
}
'''
output: '''
obj = {
g: 1
# line at object end
}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
obj =
g: 1
# line at object end
d
'''
output: '''
obj =
g: 1
# line at object end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
->
return {
test: ->
# hi
}
'''
output: '''
->
return {
test: ->
# hi
}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
obj = {
g: 1
### block comment at object end###
}
'''
output: '''
obj = {
g: 1
### block comment at object end###
}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
->
return {
test: ->
###*
* hi
###
}
'''
output: '''
->
return {
test: ->
###*
* hi
###
}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 5]
,
code: '''
{
g: a
# line at object end
} = {}
'''
output: '''
{
g: a
# line at object end
} = {}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
{
g
# line at object end
} = {}
'''
output: '''
{
g
# line at object end
} = {}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
{
g: a
### block comment at object-like end###
} = {}
'''
output: '''
{
g: a
### block comment at object-like end###
} = {}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
{
g
### block comment at object-like end###
} = {}
'''
output: '''
{
g
### block comment at object-like end###
} = {}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
# array start comments
code: '''
arr = [
# line at array start
1
]
'''
output: '''
arr = [
# line at array start
1
]
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
arr = [
### block comment at array start###
1
]
'''
output: '''
arr = [
### block comment at array start###
1
]
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
[
# line at array start
a
] = []
'''
output: '''
[
# line at array start
a
] = []
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
[
### block comment at array start###
a
] = []
'''
output: '''
[
### block comment at array start###
a
] = []
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
# array end comments
code: '''
arr = [
1
# line at array end
]
'''
output: '''
arr = [
1
# line at array end
]
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
arr = [
1
### block comment at array end###
]
'''
output: '''
arr = [
1
### block comment at array end###
]
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
[
a
# line at array end
] = []
'''
output: '''
[
a
# line at array end
] = []
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
[
a
### block comment at array end###
] = []
'''
output: '''
[
a
### block comment at array end###
] = []
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
# ignorePattern
code: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
output: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
options: [
beforeBlockComment: yes
afterBlockComment: yes
applyDefaultIgnorePatterns: no
]
errors: [
message: beforeMessage, type: 'Block', line: 7
,
message: afterMessage, type: 'Block', line: 7
]
,
code: 'foo\n### eslint ###'
output: 'foo\n\n### eslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jshint ###'
output: 'foo\n\n### jshint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jslint ###'
output: 'foo\n\n### jslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### istanbul ###'
output: 'foo\n\n### istanbul ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### global ###'
output: 'foo\n\n### global ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### globals ###'
output: 'foo\n\n### globals ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### exported ###'
output: 'foo\n\n### exported ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jscs ###'
output: 'foo\n\n### jscs ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### something else ###'
output: 'foo\n\n### something else ###'
options: [ignorePattern: 'pragma']
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### eslint ###'
output: 'foo\n\n### eslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
# "fallthrough" patterns are not ignored by default
code: 'foo\n### fallthrough ###'
output: 'foo\n\n### fallthrough ###'
options: []
errors: [message: beforeMessage, type: 'Block']
]
| true | ###*
# @fileoverview Test enforcement of lines around comments.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/lines-around-comment'
{RuleTester} = require 'eslint'
path = require 'path'
afterMessage = 'Expected line after comment.'
beforeMessage = 'Expected line before comment.'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'lines-around-comment', rule,
valid: [
# default rules
'bar()\n\n###* block block block\n * block \n ###\n\na = 1'
'bar()\n\n###* block block block\n * block \n ###\na = 1'
'bar()\n# line line line \na = 1'
'bar()\n\n# line line line\na = 1'
'bar()\n# line line line\n\na = 1'
,
# line comments
code: 'bar()\n# line line line\n\na = 1'
options: [afterLineComment: yes]
,
code: 'foo()\n\n# line line line\na = 1'
options: [beforeLineComment: yes]
,
code: 'foo()\n\n# line line line\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
,
code: 'foo()\n\n# line line line\n# line line\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
,
code: '# line line line\n# line line'
options: [beforeLineComment: yes, afterLineComment: yes]
,
# block comments
code:
'bar()\n\n###* A Block comment with a an empty line after\n *\n ###\na = 1'
options: [afterBlockComment: no, beforeBlockComment: yes]
,
code: 'bar()\n\n###* block block block\n * block \n ###\na = 1'
options: [afterBlockComment: no]
,
code: '###* \nblock \nblock block\n ###\n### block \n block \n ###'
options: [afterBlockComment: yes, beforeBlockComment: yes]
,
code: 'bar()\n\n###* block block block\n * block \n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
,
# inline comments (should not ever warn)
code: 'foo() # An inline comment with a an empty line after\na = 1'
options: [afterLineComment: yes, beforeLineComment: yes]
,
code:
'foo()\nbar() ### An inline block comment with a an empty line after\n *\n ###\na = 1'
options: [beforeBlockComment: yes]
,
# mixed comment (some block & some line)
code:
'bar()\n\n###* block block block\n * block \n ###\n#line line line\na = 1'
options: [afterBlockComment: yes]
,
code:
'bar()\n\n###* block block block\n * block \n ###\n#line line line\na = 1'
options: [beforeLineComment: yes]
,
# check for block start comments
code: 'a\n\n# line\nb'
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
-># line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
foo = ->
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
foo = ->
# line at block start
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
if yes
bar()
else
# line at block start
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
break
else
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
break
else
# line at switch case start
break
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
->### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
foo = ->
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
if yes
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
if yes
### block comment at block start ###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
while yes
###
block comment at block start
###
g = 1
'''
options: [allowBlockStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [allowBlockStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [allowClassStart: yes]
,
code: '''
class A
###*
* hi
###
constructor: ->
'''
options: [
allowBlockStart: no
allowClassStart: yes
]
,
code: '''
switch 'foo'
when 'foo'
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch 'foo'
when 'foo'
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch 'foo'
when 'foo'
break
else
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
switch ('foo')
when 'foo'
break
else
### block comment at switch case start ###
break
'''
options: [allowBlockStart: yes]
,
code: '''
->
g = 91
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
->
g = 61
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
foo = ->
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
# line at block end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
beforeLineComment: yes
allowBlockStart: yes
allowBlockEnd: yes
]
,
code: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
,
code: '''
->
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
foo = ->
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
### block comment at block end ###
'''
options: [
beforeBlockComment: no
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
if yes
g = 1
### block comment at block end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
while yes
g = 1
###
block comment at block end
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowClassEnd: yes
]
,
code: '''
class B
constructor: ->
###*
* hi
###
'''
options: [
afterBlockComment: yes
allowBlockEnd: no
allowClassEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
### block comment at switch case end ###
'''
options: [
afterBlockComment: yes
allowBlockEnd: yes
]
,
# check for object start comments
code: '''
obj = {
# line at object start
g: 1
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
->
return {
# hi
test: ->
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
# ,
# code: '''
# obj =
# ### block comment at object start###
# g: 1
# '''
# options: [
# beforeBlockComment: yes
# allowObjectStart: yes
# ]
# ,
code: '''
->
return {
###*
* hi
###
test: ->
}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
# line at object start
g: a
} = {}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
# line at object start
g
} = {}
'''
options: [
beforeLineComment: yes
allowObjectStart: yes
]
,
code: '''
{
### block comment at object-like start###
g: a
} = {}
'''
options: [
beforeBlockComment: yes
allowObjectStart: yes
]
,
code: '''
{
### block comment at object-like start###
g
} = {}
'''
options: [
beforeBlockComment: yes
allowObjectStart: yes
]
,
# check for object end comments
code: '''
obj = {
g: 1
# line at object end
}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
# ,
# code: '''
# obj =
# g: 1
# # line at object end
# '''
# options: [
# afterLineComment: yes
# allowObjectEnd: yes
# ]
code: '''
->
return {
test: ->
# hi
}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
obj = {
g: 1
### block comment at object end###
}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
->
return {
test: ->
###*
* hi
###
}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g: a
# line at object end
} = {}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g
# line at object end
} = {}
'''
options: [
afterLineComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g: a
### block comment at object-like end###
} = {}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
code: '''
{
g
### block comment at object-like end###
} = {}
'''
options: [
afterBlockComment: yes
allowObjectEnd: yes
]
,
# check for array start comments
code: '''
arr = [
# line at array start
1\
]
'''
options: [
beforeLineComment: yes
allowArrayStart: yes
]
,
code: '''
arr = [
### block comment at array start###
1
]
'''
options: [
beforeBlockComment: yes
allowArrayStart: yes
]
,
code: '''
[
# line at array start
a
] = []
'''
options: [
beforeLineComment: yes
allowArrayStart: yes
]
,
code: '''
[
### block comment at array start###
a
] = []
'''
options: [
beforeBlockComment: yes
allowArrayStart: yes
]
,
# check for array end comments
code: '''
arr = [
1
# line at array end
]
'''
options: [
afterLineComment: yes
allowArrayEnd: yes
]
,
code: '''
arr = [
1
### block comment at array end###
]
'''
options: [
afterBlockComment: yes
allowArrayEnd: yes
]
,
code: '''
[
a
# line at array end
] = []
'''
options: [
afterLineComment: yes
allowArrayEnd: yes
]
,
code: '''
[
a
### block comment at array end###
] = []
'''
options: [
afterBlockComment: yes
allowArrayEnd: yes
]
,
# ignorePattern
code: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
options: [
beforeBlockComment: yes
afterBlockComment: yes
]
,
'foo\n### eslint ###'
'foo\n### jshint ###'
'foo\n### jslint ###'
'foo\n### istanbul ###'
'foo\n### global ###'
'foo\n### globals ###'
'foo\n### exported ###'
'foo\n### jscs ###'
,
code: 'foo\n### this is pragmatic ###'
options: [ignorePattern: 'pragma']
,
code: 'foo\n### this is pragmatic ###'
options: [applyDefaultIgnorePatterns: no, ignorePattern: 'pragma']
]
invalid: [
# default rules
code: 'bar()\n###* block block block\n * block \n ###\na = 1'
output: 'bar()\n\n###* block block block\n * block \n ###\na = 1'
errors: [message: beforeMessage, type: 'Block']
,
# line comments
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n# A line comment with no empty line after\n\na = 1'
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line']
,
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n\n# A line comment with no empty line after\na = 1'
options: [beforeLineComment: yes, afterLineComment: no]
errors: [message: beforeMessage, type: 'Line']
,
code: '# A line comment with no empty line after\na = 1'
output: '# A line comment with no empty line after\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 1, column: 1]
,
code: 'baz()\n# A line comment with no empty line after\na = 1'
output: 'baz()\n\n# A line comment with no empty line after\n\na = 1'
options: [beforeLineComment: yes, afterLineComment: yes]
errors: [
message: beforeMessage, type: 'Line', line: 2
,
message: afterMessage, type: 'Line', line: 2
]
,
# block comments
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n\n###*\n * block block block\n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code:
'bar()\n### first block comment ### ### second block comment ###\na = 1'
output:
'bar()\n\n### first block comment ### ### second block comment ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code:
'bar()\n### first block comment ### ### second block\n comment ###\na = 1'
output:
'bar()\n\n### first block comment ### ### second block\n comment ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: yes]
errors: [
message: beforeMessage, type: 'Block', line: 2
,
message: afterMessage, type: 'Block', line: 2
]
,
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n###*\n * block block block\n ###\n\na = 1'
options: [afterBlockComment: yes, beforeBlockComment: no]
errors: [message: afterMessage, type: 'Block', line: 2]
,
code: 'bar()\n###*\n * block block block\n ###\na = 1'
output: 'bar()\n\n###*\n * block block block\n ###\na = 1'
options: [afterBlockComment: no, beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
->
a = 1
# line at block start
g = 1
'''
output: '''
->
a = 1
# line at block start
g = 1
'''
options: [
beforeLineComment: yes
allowBlockStart: yes
]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
->
a = 1
# line at block start
g = 1
'''
output: '''
->
a = 1
# line at block start
g = 1
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
switch ('foo')
when 'foo'
# line at switch case start
break
'''
output: '''
switch ('foo')
when 'foo'
# line at switch case start
break
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
switch ('foo')
when 'foo'
break
else
# line at switch case start
break
'''
output: '''
switch ('foo')
when 'foo'
break
else
# line at switch case start
break
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 6]
,
code: '''
try
# line at block start and end
catch
'''
output: '''
try
# line at block start and end
catch
'''
options: [
afterLineComment: yes
allowBlockStart: yes
]
errors: [message: afterMessage, type: 'Line', line: 2]
,
code: '''
try
# line at block start and end
catch
'''
output: '''
try
# line at block start and end
catch
'''
options: [
beforeLineComment: yes
allowBlockEnd: yes
]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class A
# line at class start
constructor: ->
'''
output: '''
class A
# line at class start
constructor: ->
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class A
# line at class start
constructor: ->
'''
output: '''
class A
# line at class start
constructor: ->
'''
options: [
allowBlockStart: yes
allowClassStart: no
beforeLineComment: yes
]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
class B
constructor: ->
# line at class end
d
'''
output: '''
class B
constructor: ->
# line at class end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
class B
constructor: ->
# line at class end
d
'''
output: '''
class B
constructor: ->
# line at class end
d
'''
options: [
afterLineComment: yes
allowBlockEnd: yes
allowClassEnd: no
]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
d
'''
output: '''
switch ('foo')
when 'foo'
g = 1
# line at switch case end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 5]
,
code: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
d
'''
output: '''
switch ('foo')
when 'foo'
break
else
g = 1
# line at switch case end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 8]
,
# object start comments
code: '''
obj = {
# line at object start
g: 1
}
'''
output: '''
obj = {
# line at object start
g: 1
}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
obj =
# line at object start
g: 1
'''
output: '''
obj =
# line at object start
g: 1
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
->
return {
# hi
test: ->
}
'''
output: '''
->
return {
# hi
test: ->
}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 3]
,
code: '''
obj = {
### block comment at object start###
g: 1
}
'''
output: '''
obj = {
### block comment at object start###
g: 1
}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
->
return
###*
* hi
###
test: ->
'''
output: '''
->
return
###*
* hi
###
test: ->
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 3]
,
code: '''
{
# line at object start
g: a
} = {}
'''
output: '''
{
# line at object start
g: a
} = {}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
{
# line at object start
g
} = {}
'''
output: '''
{
# line at object start
g
} = {}
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
{
### block comment at object-like start###
g: a
} = {}
'''
output: '''
{
### block comment at object-like start###
g: a
} = {}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
{
### block comment at object-like start###
g
} = {}
'''
output: '''
{
### block comment at object-like start###
g
} = {}
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
# object end comments
code: '''
obj = {
g: 1
# line at object end
}
'''
output: '''
obj = {
g: 1
# line at object end
}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
obj =
g: 1
# line at object end
d
'''
output: '''
obj =
g: 1
# line at object end
d
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
->
return {
test: ->
# hi
}
'''
output: '''
->
return {
test: ->
# hi
}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 4]
,
code: '''
obj = {
g: 1
### block comment at object end###
}
'''
output: '''
obj = {
g: 1
### block comment at object end###
}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
->
return {
test: ->
###*
* hi
###
}
'''
output: '''
->
return {
test: ->
###*
* hi
###
}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 5]
,
code: '''
{
g: a
# line at object end
} = {}
'''
output: '''
{
g: a
# line at object end
} = {}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
{
g
# line at object end
} = {}
'''
output: '''
{
g
# line at object end
} = {}
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
{
g: a
### block comment at object-like end###
} = {}
'''
output: '''
{
g: a
### block comment at object-like end###
} = {}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
{
g
### block comment at object-like end###
} = {}
'''
output: '''
{
g
### block comment at object-like end###
} = {}
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
# array start comments
code: '''
arr = [
# line at array start
1
]
'''
output: '''
arr = [
# line at array start
1
]
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
arr = [
### block comment at array start###
1
]
'''
output: '''
arr = [
### block comment at array start###
1
]
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
code: '''
[
# line at array start
a
] = []
'''
output: '''
[
# line at array start
a
] = []
'''
options: [beforeLineComment: yes]
errors: [message: beforeMessage, type: 'Line', line: 2]
,
code: '''
[
### block comment at array start###
a
] = []
'''
output: '''
[
### block comment at array start###
a
] = []
'''
options: [beforeBlockComment: yes]
errors: [message: beforeMessage, type: 'Block', line: 2]
,
# array end comments
code: '''
arr = [
1
# line at array end
]
'''
output: '''
arr = [
1
# line at array end
]
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
arr = [
1
### block comment at array end###
]
'''
output: '''
arr = [
1
### block comment at array end###
]
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
code: '''
[
a
# line at array end
] = []
'''
output: '''
[
a
# line at array end
] = []
'''
options: [afterLineComment: yes]
errors: [message: afterMessage, type: 'Line', line: 3]
,
code: '''
[
a
### block comment at array end###
] = []
'''
output: '''
[
a
### block comment at array end###
] = []
'''
options: [afterBlockComment: yes]
errors: [message: afterMessage, type: 'Block', line: 4]
,
# ignorePattern
code: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
output: '''
foo
### eslint-disable no-underscore-dangle ###
this._values = values
this._values2 = true
### eslint-enable no-underscore-dangle ###
bar
'''
options: [
beforeBlockComment: yes
afterBlockComment: yes
applyDefaultIgnorePatterns: no
]
errors: [
message: beforeMessage, type: 'Block', line: 7
,
message: afterMessage, type: 'Block', line: 7
]
,
code: 'foo\n### eslint ###'
output: 'foo\n\n### eslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jshint ###'
output: 'foo\n\n### jshint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jslint ###'
output: 'foo\n\n### jslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### istanbul ###'
output: 'foo\n\n### istanbul ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### global ###'
output: 'foo\n\n### global ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### globals ###'
output: 'foo\n\n### globals ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### exported ###'
output: 'foo\n\n### exported ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### jscs ###'
output: 'foo\n\n### jscs ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### something else ###'
output: 'foo\n\n### something else ###'
options: [ignorePattern: 'pragma']
errors: [message: beforeMessage, type: 'Block']
,
code: 'foo\n### eslint ###'
output: 'foo\n\n### eslint ###'
options: [applyDefaultIgnorePatterns: no]
errors: [message: beforeMessage, type: 'Block']
,
# "fallthrough" patterns are not ignored by default
code: 'foo\n### fallthrough ###'
output: 'foo\n\n### fallthrough ###'
options: []
errors: [message: beforeMessage, type: 'Block']
]
|
[
{
"context": "#\n# Image Picker source\n# by Rodrigo Vera\n#\njQuery.fn.extend({\n imagepicker: (opts = {}) -",
"end": 41,
"score": 0.9998701214790344,
"start": 29,
"tag": "NAME",
"value": "Rodrigo Vera"
}
] | source/coffee/image-picker.coffee | shukriti-swe/Rtsoft_exam | 610 | #
# Image Picker source
# by Rodrigo Vera
#
jQuery.fn.extend({
imagepicker: (opts = {}) ->
this.each () ->
select = jQuery(this)
select.data("picker").destroy() if select.data("picker")
select.data "picker", new ImagePicker(this, sanitized_options(opts))
opts.initialized.call(select.data("picker")) if opts.initialized?
})
sanitized_options = (opts) ->
default_options = {
hide_select: true,
show_label: false,
initialized: undefined,
changed: undefined,
clicked: undefined,
selected: undefined,
limit: undefined,
limit_reached: undefined,
font_awesome: false
}
jQuery.extend(default_options, opts)
both_array_are_equal = (a,b) ->
return false if (!a || !b) || (a.length != b.length)
a = a[..]
b = b[..]
a.sort()
b.sort()
for x, i in a
return false if b[i] != x
true
class ImagePicker
constructor: (select_element, @opts={}) ->
@select = jQuery(select_element)
@multiple = @select.attr("multiple") == "multiple"
@opts.limit = parseInt(@select.data("limit")) if @select.data("limit")?
@build_and_append_picker()
destroy: ->
for option in @picker_options
option.destroy()
@picker.remove()
@select.off("change", @sync_picker_with_select)
@select.removeData "picker"
@select.show()
build_and_append_picker: () ->
@select.hide() if @opts.hide_select
@select.on("change", @sync_picker_with_select)
@picker.remove() if @picker?
@create_picker()
@select.after(@picker)
@sync_picker_with_select()
sync_picker_with_select: () =>
for option in @picker_options
if option.is_selected()
option.mark_as_selected()
else
option.unmark_as_selected()
create_picker: () ->
@picker = jQuery("<ul class='thumbnails image_picker_selector'></ul>")
@picker_options = []
@recursively_parse_option_groups(@select, @picker)
@picker
recursively_parse_option_groups: (scoped_dom, target_container) ->
for option_group in scoped_dom.children("optgroup")
option_group = jQuery(option_group)
container = jQuery("<ul></ul>")
container.append jQuery("<li class='group_title'>#{option_group.attr("label")}</li>")
target_container.append jQuery("<li class='group'>").append(container)
@recursively_parse_option_groups(option_group, container)
for option in (new ImagePickerOption(option, this, @opts) for option in scoped_dom.children("option"))
@picker_options.push option
continue if !option.has_image()
target_container.append option.node
has_implicit_blanks: () ->
(option for option in @picker_options when (option.is_blank() && !option.has_image())).length > 0
selected_values: () ->
if @multiple
@select.val() || []
else
[@select.val()]
toggle: (imagepicker_option, original_event) ->
old_values = @selected_values()
selected_value = imagepicker_option.value().toString()
if @multiple
if selected_value in @selected_values()
new_values = @selected_values()
new_values.splice( jQuery.inArray(selected_value, old_values), 1)
@select.val []
@select.val new_values
else
if @opts.limit? && @selected_values().length >= @opts.limit
if @opts.limit_reached?
@opts.limit_reached.call(@select)
else
@select.val @selected_values().concat selected_value
else
if @has_implicit_blanks() && imagepicker_option.is_selected()
@select.val("")
else
@select.val(selected_value)
unless both_array_are_equal(old_values, @selected_values())
@select.change()
@opts.changed.call(@select, old_values, @selected_values(), original_event) if @opts.changed?
class ImagePickerOption
constructor: (option_element, @picker, @opts={}) ->
@option = jQuery(option_element)
@create_node()
destroy: ->
@node.find(".thumbnail").off("click", @clicked)
has_image: () ->
@option.data("img-src")?
is_blank: () ->
!(@value()? && @value() != "")
is_selected: () ->
select_value = @picker.select.val()
if @picker.multiple
jQuery.inArray(@value(), select_value) >= 0
else
@value() == select_value
mark_as_selected: () ->
@node.find(".thumbnail").addClass("selected")
unmark_as_selected: () ->
@node.find(".thumbnail").removeClass("selected")
value: () ->
@option.val()
label: () ->
if @option.data("img-label")
@option.data("img-label")
else
@option.text()
clicked: (event) =>
@picker.toggle(this, event)
@opts.clicked.call(@picker.select, this, event) if @opts.clicked?
@opts.selected.call(@picker.select, this, event) if @opts.selected? and @is_selected()
create_node: () ->
@node = jQuery("<li/>")
# font-awesome support
if @option.data("font_awesome")
image = jQuery("<i>")
image.attr("class", "fa-fw " + this.option.data("img-src"))
else
image = jQuery("<img class='image_picker_image'/>")
image.attr("src", @option.data("img-src"))
thumbnail = jQuery("<div class='thumbnail'>")
# Add custom class
imgClass = @option.data("img-class")
if imgClass
@node.addClass(imgClass)
image.addClass(imgClass)
thumbnail.addClass(imgClass)
# Add image alt
imgAlt = @option.data("img-alt")
if imgAlt
image.attr('alt', imgAlt);
thumbnail.on("click", @clicked)
thumbnail.append(image)
thumbnail.append(jQuery("<p/>").html(@label())) if @opts.show_label
@node.append( thumbnail )
@node
| 186860 | #
# Image Picker source
# by <NAME>
#
jQuery.fn.extend({
imagepicker: (opts = {}) ->
this.each () ->
select = jQuery(this)
select.data("picker").destroy() if select.data("picker")
select.data "picker", new ImagePicker(this, sanitized_options(opts))
opts.initialized.call(select.data("picker")) if opts.initialized?
})
sanitized_options = (opts) ->
default_options = {
hide_select: true,
show_label: false,
initialized: undefined,
changed: undefined,
clicked: undefined,
selected: undefined,
limit: undefined,
limit_reached: undefined,
font_awesome: false
}
jQuery.extend(default_options, opts)
both_array_are_equal = (a,b) ->
return false if (!a || !b) || (a.length != b.length)
a = a[..]
b = b[..]
a.sort()
b.sort()
for x, i in a
return false if b[i] != x
true
class ImagePicker
constructor: (select_element, @opts={}) ->
@select = jQuery(select_element)
@multiple = @select.attr("multiple") == "multiple"
@opts.limit = parseInt(@select.data("limit")) if @select.data("limit")?
@build_and_append_picker()
destroy: ->
for option in @picker_options
option.destroy()
@picker.remove()
@select.off("change", @sync_picker_with_select)
@select.removeData "picker"
@select.show()
build_and_append_picker: () ->
@select.hide() if @opts.hide_select
@select.on("change", @sync_picker_with_select)
@picker.remove() if @picker?
@create_picker()
@select.after(@picker)
@sync_picker_with_select()
sync_picker_with_select: () =>
for option in @picker_options
if option.is_selected()
option.mark_as_selected()
else
option.unmark_as_selected()
create_picker: () ->
@picker = jQuery("<ul class='thumbnails image_picker_selector'></ul>")
@picker_options = []
@recursively_parse_option_groups(@select, @picker)
@picker
recursively_parse_option_groups: (scoped_dom, target_container) ->
for option_group in scoped_dom.children("optgroup")
option_group = jQuery(option_group)
container = jQuery("<ul></ul>")
container.append jQuery("<li class='group_title'>#{option_group.attr("label")}</li>")
target_container.append jQuery("<li class='group'>").append(container)
@recursively_parse_option_groups(option_group, container)
for option in (new ImagePickerOption(option, this, @opts) for option in scoped_dom.children("option"))
@picker_options.push option
continue if !option.has_image()
target_container.append option.node
has_implicit_blanks: () ->
(option for option in @picker_options when (option.is_blank() && !option.has_image())).length > 0
selected_values: () ->
if @multiple
@select.val() || []
else
[@select.val()]
toggle: (imagepicker_option, original_event) ->
old_values = @selected_values()
selected_value = imagepicker_option.value().toString()
if @multiple
if selected_value in @selected_values()
new_values = @selected_values()
new_values.splice( jQuery.inArray(selected_value, old_values), 1)
@select.val []
@select.val new_values
else
if @opts.limit? && @selected_values().length >= @opts.limit
if @opts.limit_reached?
@opts.limit_reached.call(@select)
else
@select.val @selected_values().concat selected_value
else
if @has_implicit_blanks() && imagepicker_option.is_selected()
@select.val("")
else
@select.val(selected_value)
unless both_array_are_equal(old_values, @selected_values())
@select.change()
@opts.changed.call(@select, old_values, @selected_values(), original_event) if @opts.changed?
class ImagePickerOption
constructor: (option_element, @picker, @opts={}) ->
@option = jQuery(option_element)
@create_node()
destroy: ->
@node.find(".thumbnail").off("click", @clicked)
has_image: () ->
@option.data("img-src")?
is_blank: () ->
!(@value()? && @value() != "")
is_selected: () ->
select_value = @picker.select.val()
if @picker.multiple
jQuery.inArray(@value(), select_value) >= 0
else
@value() == select_value
mark_as_selected: () ->
@node.find(".thumbnail").addClass("selected")
unmark_as_selected: () ->
@node.find(".thumbnail").removeClass("selected")
value: () ->
@option.val()
label: () ->
if @option.data("img-label")
@option.data("img-label")
else
@option.text()
clicked: (event) =>
@picker.toggle(this, event)
@opts.clicked.call(@picker.select, this, event) if @opts.clicked?
@opts.selected.call(@picker.select, this, event) if @opts.selected? and @is_selected()
create_node: () ->
@node = jQuery("<li/>")
# font-awesome support
if @option.data("font_awesome")
image = jQuery("<i>")
image.attr("class", "fa-fw " + this.option.data("img-src"))
else
image = jQuery("<img class='image_picker_image'/>")
image.attr("src", @option.data("img-src"))
thumbnail = jQuery("<div class='thumbnail'>")
# Add custom class
imgClass = @option.data("img-class")
if imgClass
@node.addClass(imgClass)
image.addClass(imgClass)
thumbnail.addClass(imgClass)
# Add image alt
imgAlt = @option.data("img-alt")
if imgAlt
image.attr('alt', imgAlt);
thumbnail.on("click", @clicked)
thumbnail.append(image)
thumbnail.append(jQuery("<p/>").html(@label())) if @opts.show_label
@node.append( thumbnail )
@node
| true | #
# Image Picker source
# by PI:NAME:<NAME>END_PI
#
jQuery.fn.extend({
imagepicker: (opts = {}) ->
this.each () ->
select = jQuery(this)
select.data("picker").destroy() if select.data("picker")
select.data "picker", new ImagePicker(this, sanitized_options(opts))
opts.initialized.call(select.data("picker")) if opts.initialized?
})
sanitized_options = (opts) ->
default_options = {
hide_select: true,
show_label: false,
initialized: undefined,
changed: undefined,
clicked: undefined,
selected: undefined,
limit: undefined,
limit_reached: undefined,
font_awesome: false
}
jQuery.extend(default_options, opts)
both_array_are_equal = (a,b) ->
return false if (!a || !b) || (a.length != b.length)
a = a[..]
b = b[..]
a.sort()
b.sort()
for x, i in a
return false if b[i] != x
true
class ImagePicker
constructor: (select_element, @opts={}) ->
@select = jQuery(select_element)
@multiple = @select.attr("multiple") == "multiple"
@opts.limit = parseInt(@select.data("limit")) if @select.data("limit")?
@build_and_append_picker()
destroy: ->
for option in @picker_options
option.destroy()
@picker.remove()
@select.off("change", @sync_picker_with_select)
@select.removeData "picker"
@select.show()
build_and_append_picker: () ->
@select.hide() if @opts.hide_select
@select.on("change", @sync_picker_with_select)
@picker.remove() if @picker?
@create_picker()
@select.after(@picker)
@sync_picker_with_select()
sync_picker_with_select: () =>
for option in @picker_options
if option.is_selected()
option.mark_as_selected()
else
option.unmark_as_selected()
create_picker: () ->
@picker = jQuery("<ul class='thumbnails image_picker_selector'></ul>")
@picker_options = []
@recursively_parse_option_groups(@select, @picker)
@picker
recursively_parse_option_groups: (scoped_dom, target_container) ->
for option_group in scoped_dom.children("optgroup")
option_group = jQuery(option_group)
container = jQuery("<ul></ul>")
container.append jQuery("<li class='group_title'>#{option_group.attr("label")}</li>")
target_container.append jQuery("<li class='group'>").append(container)
@recursively_parse_option_groups(option_group, container)
for option in (new ImagePickerOption(option, this, @opts) for option in scoped_dom.children("option"))
@picker_options.push option
continue if !option.has_image()
target_container.append option.node
has_implicit_blanks: () ->
(option for option in @picker_options when (option.is_blank() && !option.has_image())).length > 0
selected_values: () ->
if @multiple
@select.val() || []
else
[@select.val()]
toggle: (imagepicker_option, original_event) ->
old_values = @selected_values()
selected_value = imagepicker_option.value().toString()
if @multiple
if selected_value in @selected_values()
new_values = @selected_values()
new_values.splice( jQuery.inArray(selected_value, old_values), 1)
@select.val []
@select.val new_values
else
if @opts.limit? && @selected_values().length >= @opts.limit
if @opts.limit_reached?
@opts.limit_reached.call(@select)
else
@select.val @selected_values().concat selected_value
else
if @has_implicit_blanks() && imagepicker_option.is_selected()
@select.val("")
else
@select.val(selected_value)
unless both_array_are_equal(old_values, @selected_values())
@select.change()
@opts.changed.call(@select, old_values, @selected_values(), original_event) if @opts.changed?
class ImagePickerOption
constructor: (option_element, @picker, @opts={}) ->
@option = jQuery(option_element)
@create_node()
destroy: ->
@node.find(".thumbnail").off("click", @clicked)
has_image: () ->
@option.data("img-src")?
is_blank: () ->
!(@value()? && @value() != "")
is_selected: () ->
select_value = @picker.select.val()
if @picker.multiple
jQuery.inArray(@value(), select_value) >= 0
else
@value() == select_value
mark_as_selected: () ->
@node.find(".thumbnail").addClass("selected")
unmark_as_selected: () ->
@node.find(".thumbnail").removeClass("selected")
value: () ->
@option.val()
label: () ->
if @option.data("img-label")
@option.data("img-label")
else
@option.text()
clicked: (event) =>
@picker.toggle(this, event)
@opts.clicked.call(@picker.select, this, event) if @opts.clicked?
@opts.selected.call(@picker.select, this, event) if @opts.selected? and @is_selected()
create_node: () ->
@node = jQuery("<li/>")
# font-awesome support
if @option.data("font_awesome")
image = jQuery("<i>")
image.attr("class", "fa-fw " + this.option.data("img-src"))
else
image = jQuery("<img class='image_picker_image'/>")
image.attr("src", @option.data("img-src"))
thumbnail = jQuery("<div class='thumbnail'>")
# Add custom class
imgClass = @option.data("img-class")
if imgClass
@node.addClass(imgClass)
image.addClass(imgClass)
thumbnail.addClass(imgClass)
# Add image alt
imgAlt = @option.data("img-alt")
if imgAlt
image.attr('alt', imgAlt);
thumbnail.on("click", @clicked)
thumbnail.append(image)
thumbnail.append(jQuery("<p/>").html(@label())) if @opts.show_label
@node.append( thumbnail )
@node
|
[
{
"context": "ffee: Github repository class\n#\n# Copyright © 2011 Pavan Kumar Sunkara. All rights reserved\n#\n\n# Requiring modules\n\n# In",
"end": 81,
"score": 0.9998732209205627,
"start": 62,
"tag": "NAME",
"value": "Pavan Kumar Sunkara"
},
{
"context": "\n\n # Get the README f... | src/octonode/repo.coffee | troupe/octonode | 0 | #
# repo.coffee: Github repository class
#
# Copyright © 2011 Pavan Kumar Sunkara. All rights reserved
#
# Requiring modules
# Initiate class
class Repo
constructor: (@name, @client) ->
# Get a repository
# '/repos/pksunkara/hub' GET
info: (cb) ->
@client.get "/repos/#{@name}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo info error")) else cb null, b
# Get the collaborators for a repository
# '/repos/pksunkara/hub/collaborators
collaborators: (cbOrUser, cb) ->
if cb? and typeof cbOrUser isnt 'function'
@hasCollaborator cbOrUser, cb
else
cb = cbOrUser
@client.get "repos/#{@name}/collaborators", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo collaborators error")) else cb null, b
# Check if user is collaborator for a repository
# '/repos/pksunkara/hub/collaborators/pksunkara
hasCollaborator: (user, cb) ->
@client.get "repos/#{@name}/collaborators/#{user}", (err, s, b) ->
return cb(err) if err
if s isnt 204 and s isnt 404 then cb(new Error("Repo hasCollaborator error")) else cb null, b
# Get the commits for a repository
# '/repos/pksunkara/hub/commits' GET
commits: (cb) ->
@client.get "/repos/#{@name}/commits", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b
# Get the commits for a repository
# '/repos/pksunkara/hub/commits/SHA' GET
commit: (sha, cb) ->
@client.get "/repos/#{@name}/commits/#{sha}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b
# Get the tags for a repository
# '/repos/pksunkara/hub/tags' GET
tags: (cb) ->
@client.get "/repos/#{@name}/tags", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tags error")) else cb null, b
# Get the languages for a repository
# '/repos/pksunkara/hub/languages' GET
languages: (cb) ->
@client.get "/repos/#{@name}/languages", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo languages error")) else cb null, b
# Get the contributors for a repository
# '/repos/pksunkara/hub/contributors' GET
contributors: (cb) ->
@client.get "/repos/#{@name}/contributors", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contributors error")) else cb null, b
# Get the teams for a repository
# '/repos/pksunkara/hub/teams' GET
teams: (cb) ->
@client.get "/repos/#{@name}/teams", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo teams error")) else cb null, b
# Get the branches for a repository
# '/repos/pksunkara/hub/branches' GET
branches: (cb) ->
@client.get "/repos/#{@name}/branches", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branches error")) else cb null, b
# Get the issues for a repository
# '/repos/pksunkara/hub/issues' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
issues: (params..., cb) ->
@client.get "/repos/#{@name}/issues", params..., (err, s, b, headers) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo issues error")) else cb null, b, headers
# Get the README for a repository
# '/repos/pksunkara/hub/readme' GET
readme: (cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/readme?ref=#{cbOrRef}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo readme error")) else cb null, b
# Get the contents of a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' GET
contents: (path, cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/contents/#{path}?ref=#{cbOrRef}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contents error")) else cb null, b
# Get archive link for a repository
# '/repos/pksunkara/hub/tarball/v0.1.0' GET
archive: (format, cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/#{format}/#{cbOrRef}", (err, s, b, h) ->
return cb(err) if err
if s isnt 302 then cb(new Error("Repo archive error")) else cb null, h['Location']
# Get the forks for a repository
# '/repos/pksunkara/hub/forks' GET
forks: (cb) ->
@client.get "/repos/#{@name}/forks", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo forks error")) else cb null, b
# Get the blob for a repository
# '/repos/pksunkara/hub/git/blobs/SHA' GET
blob: (sha, cb) ->
@client.get "/repos/#{@name}/git/blobs/#{sha}",
Accept: 'application/vnd.github.raw'
, (err, s, b) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo blob error")) else cb null, b
# Get a git tree
# '/repos/pksunkara/hub/git/trees/SHA' GET
# '/repos/pksunkara/hub/git/trees/SHA?recursive=1' GET
tree: (sha, cbOrRecursive, cb) ->
if !cb? and cbOrRecursive
cb = cbOrRecursive
cbOrRecursive = false
url = "/repos/#{@name}/git/trees/#{sha}"
url += "?recursive=1" if cbOrRecursive
@client.get url, (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tree error")) else cb null, b
# Delete the repository
# '/repos/pksunkara/hub' DELETE
destroy: ->
@client.del "/repos/#{@name}", {}, (err, s, b) =>
@destroy() if err? or s isnt 204
# Get pull-request instance for repo
pr: (number) ->
@client.pr @name, number
# List pull requests
# '/repos/pksunkara/hub/pulls' GET
prs: (cbOrPr, cb) ->
if typeof cb is 'function' and typeof cbOrPr is 'object'
@createPr cbOrPr, cb
else
cb = cbOrPr
@client.get "/repos/#{@name}/pulls", (err, s, b) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo prs error")) else cb null, b
# Create a pull request
# '/repos/pksunkara/hub/pulls' POST
createPr: (pr, cb) ->
@client.post "/repos/#{@name}/pulls", pr, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createPr error")) else cb null, b
# List statuses for a specific ref
# '/repos/pksunkara/hub/statuses/master' GET
statuses: (ref, cb) ->
@client.get "/repos/#{@name}/statuses/#{ref}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b
# Create a status
# '/repos/pksunkara/hub/statuses/18e129c213848c7f239b93fe5c67971a64f183ff' POST
status: (sha, obj, cb) ->
@client.post "/repos/#{@name}/statuses/#{sha}", obj, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo status error")) else cb null, b
# List Stargazers
# '/repos/:owner/:repo/stargazers' GET
# - page, optional - params[0]
# - per_page, optional - params[1]
stargazers: (params..., cb)->
page = params[0] || 1
per_page = params[1] || 30
@client.get "/repos/#{@name}/stargazers", page, per_page, (err, s, b, headers) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo stargazers error")) else cb null, b, headers
# Export module
module.exports = Repo
| 23513 | #
# repo.coffee: Github repository class
#
# Copyright © 2011 <NAME>. All rights reserved
#
# Requiring modules
# Initiate class
class Repo
constructor: (@name, @client) ->
# Get a repository
# '/repos/pksunkara/hub' GET
info: (cb) ->
@client.get "/repos/#{@name}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo info error")) else cb null, b
# Get the collaborators for a repository
# '/repos/pksunkara/hub/collaborators
collaborators: (cbOrUser, cb) ->
if cb? and typeof cbOrUser isnt 'function'
@hasCollaborator cbOrUser, cb
else
cb = cbOrUser
@client.get "repos/#{@name}/collaborators", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo collaborators error")) else cb null, b
# Check if user is collaborator for a repository
# '/repos/pksunkara/hub/collaborators/pksunkara
hasCollaborator: (user, cb) ->
@client.get "repos/#{@name}/collaborators/#{user}", (err, s, b) ->
return cb(err) if err
if s isnt 204 and s isnt 404 then cb(new Error("Repo hasCollaborator error")) else cb null, b
# Get the commits for a repository
# '/repos/pksunkara/hub/commits' GET
commits: (cb) ->
@client.get "/repos/#{@name}/commits", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b
# Get the commits for a repository
# '/repos/pksunkara/hub/commits/SHA' GET
commit: (sha, cb) ->
@client.get "/repos/#{@name}/commits/#{sha}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b
# Get the tags for a repository
# '/repos/pksunkara/hub/tags' GET
tags: (cb) ->
@client.get "/repos/#{@name}/tags", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tags error")) else cb null, b
# Get the languages for a repository
# '/repos/pksunkara/hub/languages' GET
languages: (cb) ->
@client.get "/repos/#{@name}/languages", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo languages error")) else cb null, b
# Get the contributors for a repository
# '/repos/pksunkara/hub/contributors' GET
contributors: (cb) ->
@client.get "/repos/#{@name}/contributors", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contributors error")) else cb null, b
# Get the teams for a repository
# '/repos/pksunkara/hub/teams' GET
teams: (cb) ->
@client.get "/repos/#{@name}/teams", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo teams error")) else cb null, b
# Get the branches for a repository
# '/repos/pksunkara/hub/branches' GET
branches: (cb) ->
@client.get "/repos/#{@name}/branches", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branches error")) else cb null, b
# Get the issues for a repository
# '/repos/pksunkara/hub/issues' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
issues: (params..., cb) ->
@client.get "/repos/#{@name}/issues", params..., (err, s, b, headers) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo issues error")) else cb null, b, headers
# Get the README for a repository
# '/repos/pksunkara/hub/readme' GET
readme: (cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/readme?ref=#{cbOrRef}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo readme error")) else cb null, b
# Get the contents of a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' GET
contents: (path, cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/contents/#{path}?ref=#{cbOrRef}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contents error")) else cb null, b
# Get archive link for a repository
# '/repos/pksunkara/hub/tarball/v0.1.0' GET
archive: (format, cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/#{format}/#{cbOrRef}", (err, s, b, h) ->
return cb(err) if err
if s isnt 302 then cb(new Error("Repo archive error")) else cb null, h['Location']
# Get the forks for a repository
# '/repos/pksunkara/hub/forks' GET
forks: (cb) ->
@client.get "/repos/#{@name}/forks", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo forks error")) else cb null, b
# Get the blob for a repository
# '/repos/pksunkara/hub/git/blobs/SHA' GET
blob: (sha, cb) ->
@client.get "/repos/#{@name}/git/blobs/#{sha}",
Accept: 'application/vnd.github.raw'
, (err, s, b) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo blob error")) else cb null, b
# Get a git tree
# '/repos/pksunkara/hub/git/trees/SHA' GET
# '/repos/pksunkara/hub/git/trees/SHA?recursive=1' GET
tree: (sha, cbOrRecursive, cb) ->
if !cb? and cbOrRecursive
cb = cbOrRecursive
cbOrRecursive = false
url = "/repos/#{@name}/git/trees/#{sha}"
url += "?recursive=1" if cbOrRecursive
@client.get url, (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tree error")) else cb null, b
# Delete the repository
# '/repos/pksunkara/hub' DELETE
destroy: ->
@client.del "/repos/#{@name}", {}, (err, s, b) =>
@destroy() if err? or s isnt 204
# Get pull-request instance for repo
pr: (number) ->
@client.pr @name, number
# List pull requests
# '/repos/pksunkara/hub/pulls' GET
prs: (cbOrPr, cb) ->
if typeof cb is 'function' and typeof cbOrPr is 'object'
@createPr cbOrPr, cb
else
cb = cbOrPr
@client.get "/repos/#{@name}/pulls", (err, s, b) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo prs error")) else cb null, b
# Create a pull request
# '/repos/pksunkara/hub/pulls' POST
createPr: (pr, cb) ->
@client.post "/repos/#{@name}/pulls", pr, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createPr error")) else cb null, b
# List statuses for a specific ref
# '/repos/pksunkara/hub/statuses/master' GET
statuses: (ref, cb) ->
@client.get "/repos/#{@name}/statuses/#{ref}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b
# Create a status
# '/repos/pksunkara/hub/statuses/18e129c213848c7f239b93fe5c67971a64f183ff' POST
status: (sha, obj, cb) ->
@client.post "/repos/#{@name}/statuses/#{sha}", obj, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo status error")) else cb null, b
# List Stargazers
# '/repos/:owner/:repo/stargazers' GET
# - page, optional - params[0]
# - per_page, optional - params[1]
stargazers: (params..., cb)->
page = params[0] || 1
per_page = params[1] || 30
@client.get "/repos/#{@name}/stargazers", page, per_page, (err, s, b, headers) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo stargazers error")) else cb null, b, headers
# Export module
module.exports = Repo
| true | #
# repo.coffee: Github repository class
#
# Copyright © 2011 PI:NAME:<NAME>END_PI. All rights reserved
#
# Requiring modules
# Initiate class
class Repo
constructor: (@name, @client) ->
# Get a repository
# '/repos/pksunkara/hub' GET
info: (cb) ->
@client.get "/repos/#{@name}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo info error")) else cb null, b
# Get the collaborators for a repository
# '/repos/pksunkara/hub/collaborators
collaborators: (cbOrUser, cb) ->
if cb? and typeof cbOrUser isnt 'function'
@hasCollaborator cbOrUser, cb
else
cb = cbOrUser
@client.get "repos/#{@name}/collaborators", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo collaborators error")) else cb null, b
# Check if user is collaborator for a repository
# '/repos/pksunkara/hub/collaborators/pksunkara
hasCollaborator: (user, cb) ->
@client.get "repos/#{@name}/collaborators/#{user}", (err, s, b) ->
return cb(err) if err
if s isnt 204 and s isnt 404 then cb(new Error("Repo hasCollaborator error")) else cb null, b
# Get the commits for a repository
# '/repos/pksunkara/hub/commits' GET
commits: (cb) ->
@client.get "/repos/#{@name}/commits", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b
# Get the commits for a repository
# '/repos/pksunkara/hub/commits/SHA' GET
commit: (sha, cb) ->
@client.get "/repos/#{@name}/commits/#{sha}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b
# Get the tags for a repository
# '/repos/pksunkara/hub/tags' GET
tags: (cb) ->
@client.get "/repos/#{@name}/tags", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tags error")) else cb null, b
# Get the languages for a repository
# '/repos/pksunkara/hub/languages' GET
languages: (cb) ->
@client.get "/repos/#{@name}/languages", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo languages error")) else cb null, b
# Get the contributors for a repository
# '/repos/pksunkara/hub/contributors' GET
contributors: (cb) ->
@client.get "/repos/#{@name}/contributors", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contributors error")) else cb null, b
# Get the teams for a repository
# '/repos/pksunkara/hub/teams' GET
teams: (cb) ->
@client.get "/repos/#{@name}/teams", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo teams error")) else cb null, b
# Get the branches for a repository
# '/repos/pksunkara/hub/branches' GET
branches: (cb) ->
@client.get "/repos/#{@name}/branches", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branches error")) else cb null, b
# Get the issues for a repository
# '/repos/pksunkara/hub/issues' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
issues: (params..., cb) ->
@client.get "/repos/#{@name}/issues", params..., (err, s, b, headers) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo issues error")) else cb null, b, headers
# Get the README for a repository
# '/repos/pksunkara/hub/readme' GET
readme: (cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/readme?ref=#{cbOrRef}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo readme error")) else cb null, b
# Get the contents of a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' GET
contents: (path, cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/contents/#{path}?ref=#{cbOrRef}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contents error")) else cb null, b
# Get archive link for a repository
# '/repos/pksunkara/hub/tarball/v0.1.0' GET
archive: (format, cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = 'master'
@client.get "/repos/#{@name}/#{format}/#{cbOrRef}", (err, s, b, h) ->
return cb(err) if err
if s isnt 302 then cb(new Error("Repo archive error")) else cb null, h['Location']
# Get the forks for a repository
# '/repos/pksunkara/hub/forks' GET
forks: (cb) ->
@client.get "/repos/#{@name}/forks", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo forks error")) else cb null, b
# Get the blob for a repository
# '/repos/pksunkara/hub/git/blobs/SHA' GET
blob: (sha, cb) ->
@client.get "/repos/#{@name}/git/blobs/#{sha}",
Accept: 'application/vnd.github.raw'
, (err, s, b) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo blob error")) else cb null, b
# Get a git tree
# '/repos/pksunkara/hub/git/trees/SHA' GET
# '/repos/pksunkara/hub/git/trees/SHA?recursive=1' GET
tree: (sha, cbOrRecursive, cb) ->
if !cb? and cbOrRecursive
cb = cbOrRecursive
cbOrRecursive = false
url = "/repos/#{@name}/git/trees/#{sha}"
url += "?recursive=1" if cbOrRecursive
@client.get url, (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tree error")) else cb null, b
# Delete the repository
# '/repos/pksunkara/hub' DELETE
destroy: ->
@client.del "/repos/#{@name}", {}, (err, s, b) =>
@destroy() if err? or s isnt 204
# Get pull-request instance for repo
pr: (number) ->
@client.pr @name, number
# List pull requests
# '/repos/pksunkara/hub/pulls' GET
prs: (cbOrPr, cb) ->
if typeof cb is 'function' and typeof cbOrPr is 'object'
@createPr cbOrPr, cb
else
cb = cbOrPr
@client.get "/repos/#{@name}/pulls", (err, s, b) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo prs error")) else cb null, b
# Create a pull request
# '/repos/pksunkara/hub/pulls' POST
createPr: (pr, cb) ->
@client.post "/repos/#{@name}/pulls", pr, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createPr error")) else cb null, b
# List statuses for a specific ref
# '/repos/pksunkara/hub/statuses/master' GET
statuses: (ref, cb) ->
@client.get "/repos/#{@name}/statuses/#{ref}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b
# Create a status
# '/repos/pksunkara/hub/statuses/18e129c213848c7f239b93fe5c67971a64f183ff' POST
status: (sha, obj, cb) ->
@client.post "/repos/#{@name}/statuses/#{sha}", obj, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo status error")) else cb null, b
# List Stargazers
# '/repos/:owner/:repo/stargazers' GET
# - page, optional - params[0]
# - per_page, optional - params[1]
stargazers: (params..., cb)->
page = params[0] || 1
per_page = params[1] || 30
@client.get "/repos/#{@name}/stargazers", page, per_page, (err, s, b, headers) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo stargazers error")) else cb null, b, headers
# Export module
module.exports = Repo
|
[
{
"context": "(dataset, f) ->\n assert.equal 'Bezirk', dataset.column(0).name()\n\n\n .export module",
"end": 4682,
"score": 0.9926953911781311,
"start": 4676,
"tag": "NAME",
"value": "Bezirk"
}
] | dw.js/test/datasource-delimited-test.coffee | skeptycal/datawrapper | 1 |
global._ = require 'underscore'
JSDOM = require('jsdom').JSDOM
dom = new JSDOM '<html></html>'
global.$ = require("jquery") dom.window
# root.$ = require 'jquery'
global.Globalize = require 'globalize'
vows = require 'vows'
assert = require 'assert'
dw = require '../dw-2.0.js'
_types = (c) -> c.type()
vows
.describe('Reading different CSV datasets')
.addBatch
'The tsv "women-in-parliament"':
topic: dw.datasource.delimited
csv: 'Party\tWomen\tMen\tTotal\nCDU/CSU\t45\t192\t237\nSPD\t57\t89\t146\nFDP\t24\t69\t93\nLINKE\t42\t34\t76\nGRÜNE\t36\t32\t68\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 5
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['text', 'number', 'number', 'number']
'A nasty tsv with new lines in quoted values':
topic: dw.datasource.delimited
csv: 'Party\t"Women\n\tfoo"\t"\"Men\""\t"Total"\n"CDU/CSU"\t45\t192\t237\n"SPD"\t57\t89\t146\n"FDP"\t24\t69\t93\n"LINKE"\t42\t34\t76\n"GRÜNE"\t36\t32\t68\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 5
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['text', 'number', 'number', 'number']
'The csv "german-debt"':
topic: dw.datasource.delimited
transpose: true
csv: '"","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"\n"New debt in Bio.","14,3","11,5","34,1","44","17,3","34,8","19,6","14,6","10,3","1,1"\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has two columns': (dataset, f) ->
assert.equal dataset.numColumns(), 2
'has ten rows': (dataset, f) ->
assert.equal dataset.numRows(), 10
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['date', 'number']
'was correctly parsed': (dataset, f) ->
assert.equal dataset.column(1).val(0), 14.3
'Another one':
topic: dw.datasource.delimited
csv: "ags\tlabel\tshort\tohne.2013.proz\n1001\tFlensburg, Kreisfreie Stadt\tFlensburg\t0.076\n1002\tKiel, Landeshauptstadt, Kreisfreie Stadt\tKiel\t0.077\n1003\tLübeck, Hansestadt, Kreisfreie Stadt\tLübeck\t0.086\n1004\tNeumünster, Kreisfreie Stadt\tNeumünster\t0.088\n1051\tDithmarschen, Landkreis\tDithmarschen\t0.086\n1053\tHerzogtum Lauenburg, Landkreis\tHerzogtum Lauenburg 0.086\n1054\tNordfriesland, Landkreis\tNordfriesland\t0.072\n1055\tOstholstein, Landkreis\tOstholstein 0.087\n1056\tPinneberg, Landkreis\tPinneberg\t0.065\n1057\tPlön, Landkreis\tPlön\t0.081\n1058\tRendsburg-Eckernförde, Landkreis\tRendsburg-Eckernförde\t0.081"
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 11
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['number', 'text', 'text', 'number']
'everything is quoted':
topic: dw.datasource.delimited
csv: '"Bezirk","Anzahl","Mittelwert Miete Euro pro qm"\n"Charlottenburg-Wilmersdorf","609.0","17.573844996618483"\n"Friedrichshain-Kreuzberg","366.0","18.732384651551758"'
'when loaded as dataset':
topic: (src) ->
console.log(src)
src.dataset().done @callback
return
'the first column name is correct': (dataset, f) ->
assert.equal 'Bezirk', dataset.column(0).name()
.export module | 103186 |
global._ = require 'underscore'
JSDOM = require('jsdom').JSDOM
dom = new JSDOM '<html></html>'
global.$ = require("jquery") dom.window
# root.$ = require 'jquery'
global.Globalize = require 'globalize'
vows = require 'vows'
assert = require 'assert'
dw = require '../dw-2.0.js'
_types = (c) -> c.type()
vows
.describe('Reading different CSV datasets')
.addBatch
'The tsv "women-in-parliament"':
topic: dw.datasource.delimited
csv: 'Party\tWomen\tMen\tTotal\nCDU/CSU\t45\t192\t237\nSPD\t57\t89\t146\nFDP\t24\t69\t93\nLINKE\t42\t34\t76\nGRÜNE\t36\t32\t68\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 5
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['text', 'number', 'number', 'number']
'A nasty tsv with new lines in quoted values':
topic: dw.datasource.delimited
csv: 'Party\t"Women\n\tfoo"\t"\"Men\""\t"Total"\n"CDU/CSU"\t45\t192\t237\n"SPD"\t57\t89\t146\n"FDP"\t24\t69\t93\n"LINKE"\t42\t34\t76\n"GRÜNE"\t36\t32\t68\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 5
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['text', 'number', 'number', 'number']
'The csv "german-debt"':
topic: dw.datasource.delimited
transpose: true
csv: '"","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"\n"New debt in Bio.","14,3","11,5","34,1","44","17,3","34,8","19,6","14,6","10,3","1,1"\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has two columns': (dataset, f) ->
assert.equal dataset.numColumns(), 2
'has ten rows': (dataset, f) ->
assert.equal dataset.numRows(), 10
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['date', 'number']
'was correctly parsed': (dataset, f) ->
assert.equal dataset.column(1).val(0), 14.3
'Another one':
topic: dw.datasource.delimited
csv: "ags\tlabel\tshort\tohne.2013.proz\n1001\tFlensburg, Kreisfreie Stadt\tFlensburg\t0.076\n1002\tKiel, Landeshauptstadt, Kreisfreie Stadt\tKiel\t0.077\n1003\tLübeck, Hansestadt, Kreisfreie Stadt\tLübeck\t0.086\n1004\tNeumünster, Kreisfreie Stadt\tNeumünster\t0.088\n1051\tDithmarschen, Landkreis\tDithmarschen\t0.086\n1053\tHerzogtum Lauenburg, Landkreis\tHerzogtum Lauenburg 0.086\n1054\tNordfriesland, Landkreis\tNordfriesland\t0.072\n1055\tOstholstein, Landkreis\tOstholstein 0.087\n1056\tPinneberg, Landkreis\tPinneberg\t0.065\n1057\tPlön, Landkreis\tPlön\t0.081\n1058\tRendsburg-Eckernförde, Landkreis\tRendsburg-Eckernförde\t0.081"
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 11
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['number', 'text', 'text', 'number']
'everything is quoted':
topic: dw.datasource.delimited
csv: '"Bezirk","Anzahl","Mittelwert Miete Euro pro qm"\n"Charlottenburg-Wilmersdorf","609.0","17.573844996618483"\n"Friedrichshain-Kreuzberg","366.0","18.732384651551758"'
'when loaded as dataset':
topic: (src) ->
console.log(src)
src.dataset().done @callback
return
'the first column name is correct': (dataset, f) ->
assert.equal '<NAME>', dataset.column(0).name()
.export module | true |
global._ = require 'underscore'
JSDOM = require('jsdom').JSDOM
dom = new JSDOM '<html></html>'
global.$ = require("jquery") dom.window
# root.$ = require 'jquery'
global.Globalize = require 'globalize'
vows = require 'vows'
assert = require 'assert'
dw = require '../dw-2.0.js'
_types = (c) -> c.type()
vows
.describe('Reading different CSV datasets')
.addBatch
'The tsv "women-in-parliament"':
topic: dw.datasource.delimited
csv: 'Party\tWomen\tMen\tTotal\nCDU/CSU\t45\t192\t237\nSPD\t57\t89\t146\nFDP\t24\t69\t93\nLINKE\t42\t34\t76\nGRÜNE\t36\t32\t68\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 5
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['text', 'number', 'number', 'number']
'A nasty tsv with new lines in quoted values':
topic: dw.datasource.delimited
csv: 'Party\t"Women\n\tfoo"\t"\"Men\""\t"Total"\n"CDU/CSU"\t45\t192\t237\n"SPD"\t57\t89\t146\n"FDP"\t24\t69\t93\n"LINKE"\t42\t34\t76\n"GRÜNE"\t36\t32\t68\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 5
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['text', 'number', 'number', 'number']
'The csv "german-debt"':
topic: dw.datasource.delimited
transpose: true
csv: '"","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"\n"New debt in Bio.","14,3","11,5","34,1","44","17,3","34,8","19,6","14,6","10,3","1,1"\n'
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has two columns': (dataset, f) ->
assert.equal dataset.numColumns(), 2
'has ten rows': (dataset, f) ->
assert.equal dataset.numRows(), 10
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['date', 'number']
'was correctly parsed': (dataset, f) ->
assert.equal dataset.column(1).val(0), 14.3
'Another one':
topic: dw.datasource.delimited
csv: "ags\tlabel\tshort\tohne.2013.proz\n1001\tFlensburg, Kreisfreie Stadt\tFlensburg\t0.076\n1002\tKiel, Landeshauptstadt, Kreisfreie Stadt\tKiel\t0.077\n1003\tLübeck, Hansestadt, Kreisfreie Stadt\tLübeck\t0.086\n1004\tNeumünster, Kreisfreie Stadt\tNeumünster\t0.088\n1051\tDithmarschen, Landkreis\tDithmarschen\t0.086\n1053\tHerzogtum Lauenburg, Landkreis\tHerzogtum Lauenburg 0.086\n1054\tNordfriesland, Landkreis\tNordfriesland\t0.072\n1055\tOstholstein, Landkreis\tOstholstein 0.087\n1056\tPinneberg, Landkreis\tPinneberg\t0.065\n1057\tPlön, Landkreis\tPlön\t0.081\n1058\tRendsburg-Eckernförde, Landkreis\tRendsburg-Eckernförde\t0.081"
'when loaded as dataset':
topic: (src) ->
src.dataset().done @callback
return
'has four columns': (dataset, f) ->
assert.equal dataset.numColumns(), 4
'has five rows': (dataset, f) ->
assert.equal dataset.numRows(), 11
'has correct column types': (dataset, f) ->
assert.deepEqual _.map(dataset.columns(), _types), ['number', 'text', 'text', 'number']
'everything is quoted':
topic: dw.datasource.delimited
csv: '"Bezirk","Anzahl","Mittelwert Miete Euro pro qm"\n"Charlottenburg-Wilmersdorf","609.0","17.573844996618483"\n"Friedrichshain-Kreuzberg","366.0","18.732384651551758"'
'when loaded as dataset':
topic: (src) ->
console.log(src)
src.dataset().done @callback
return
'the first column name is correct': (dataset, f) ->
assert.equal 'PI:NAME:<NAME>END_PI', dataset.column(0).name()
.export module |
[
{
"context": "lse\n console.log 'hello constructor!'\n #@add_points\n #@default_map_position = opt.default_map_posi",
"end": 224,
"score": 0.8578494787216187,
"start": 218,
"tag": "USERNAME",
"value": "points"
},
{
"context": "lte lat, lng, und zoom von der aktuellen Karte\n... | app/assets/javascripts/map_builder.js.coffee | Bjoernsen/geopoints | 0 | # TODO: geht so leider nicht, da das MapBuilder object in e.g. buildMap verloren geht
class MapBuilder
constructor: (@map_id, @opt, @points) ->
@map_handler = false
console.log 'hello constructor!'
#@add_points
#@default_map_position = opt.default_map_position
#@infowindow_base_url = opt.infowindow_base_url
#@picture_base_url = opt.picture_base_url
draw: ()->
# das ding soll die Map dann zeichnen
@map_handler = Gmaps.build("Google")
@map_handler.buildMap
internal:
id: @map_id
, ->
if navigator.geolocation
navigator.geolocation.getCurrentPosition @add_points
else
# position = {coords: {latitude: 52.36132, longitude: 9.628606}}
@add_points(@opt.default_map_position)
return
@map_handler.getMap().setZoom(@opt.default_zoom)
add_points: (position)->
# dieses ding soll die points zu @map_handler hinzufügen
# a) ersten den point auf den die map zentiert wird
center_on_marker = @map_handler.addMarker(
lat: position.coords.latitude
lng: position.coords.longitude
infowindow: if position.default then 'Default start position' else 'Your current position'
)
@map_handler.map.centerOn center_on_marker
# b) dann 'alle' points, die sich im Umkreis des point aus a) befinden --> ajax
@map_handler.addMarker(@get_points())
# c) wenn @points schon points beinhaltet, dann diese auch rendern
if @points.length > 0
@map_handler.addMarker(@points)
update_points: ()->
new_points = @get_points()
# entweder lösche alle bestehenden Marker aus der Karte und fülle diese neu auf
# oder schecke, ob new_marker schon vorhanden ist
get_points: ()->
# erhalte lat, lng, und zoom von der aktuellen Karte
#@map_handler.getMap().getCenter(); // --> .lat(), .lng()
#@map_handler.getMap().getZoom(); //--> e.g. 9
# rufe eine URL mit lat, lng und zoom auf und erhalte json
return []
window.MapBuilder = MapBuilder | 38914 | # TODO: geht so leider nicht, da das MapBuilder object in e.g. buildMap verloren geht
class MapBuilder
constructor: (@map_id, @opt, @points) ->
@map_handler = false
console.log 'hello constructor!'
#@add_points
#@default_map_position = opt.default_map_position
#@infowindow_base_url = opt.infowindow_base_url
#@picture_base_url = opt.picture_base_url
draw: ()->
# das ding soll die Map dann zeichnen
@map_handler = Gmaps.build("Google")
@map_handler.buildMap
internal:
id: @map_id
, ->
if navigator.geolocation
navigator.geolocation.getCurrentPosition @add_points
else
# position = {coords: {latitude: 52.36132, longitude: 9.628606}}
@add_points(@opt.default_map_position)
return
@map_handler.getMap().setZoom(@opt.default_zoom)
add_points: (position)->
# dieses ding soll die points zu @map_handler hinzufügen
# a) ersten den point auf den die map zentiert wird
center_on_marker = @map_handler.addMarker(
lat: position.coords.latitude
lng: position.coords.longitude
infowindow: if position.default then 'Default start position' else 'Your current position'
)
@map_handler.map.centerOn center_on_marker
# b) dann 'alle' points, die sich im Umkreis des point aus a) befinden --> ajax
@map_handler.addMarker(@get_points())
# c) wenn @points schon points beinhaltet, dann diese auch rendern
if @points.length > 0
@map_handler.addMarker(@points)
update_points: ()->
new_points = @get_points()
# entweder lösche alle bestehenden Marker aus der Karte und fülle diese neu auf
# oder schecke, ob new_marker schon vorhanden ist
get_points: ()->
# erhalte lat, lng, und zoom von der aktuellen Karte
<EMAIL>().getCenter(); // --> .lat(), .lng()
<EMAIL>().getZoom(); //--> e.g. 9
# rufe eine URL mit lat, lng und zoom auf und erhalte json
return []
window.MapBuilder = MapBuilder | true | # TODO: geht so leider nicht, da das MapBuilder object in e.g. buildMap verloren geht
class MapBuilder
constructor: (@map_id, @opt, @points) ->
@map_handler = false
console.log 'hello constructor!'
#@add_points
#@default_map_position = opt.default_map_position
#@infowindow_base_url = opt.infowindow_base_url
#@picture_base_url = opt.picture_base_url
draw: ()->
# das ding soll die Map dann zeichnen
@map_handler = Gmaps.build("Google")
@map_handler.buildMap
internal:
id: @map_id
, ->
if navigator.geolocation
navigator.geolocation.getCurrentPosition @add_points
else
# position = {coords: {latitude: 52.36132, longitude: 9.628606}}
@add_points(@opt.default_map_position)
return
@map_handler.getMap().setZoom(@opt.default_zoom)
add_points: (position)->
# dieses ding soll die points zu @map_handler hinzufügen
# a) ersten den point auf den die map zentiert wird
center_on_marker = @map_handler.addMarker(
lat: position.coords.latitude
lng: position.coords.longitude
infowindow: if position.default then 'Default start position' else 'Your current position'
)
@map_handler.map.centerOn center_on_marker
# b) dann 'alle' points, die sich im Umkreis des point aus a) befinden --> ajax
@map_handler.addMarker(@get_points())
# c) wenn @points schon points beinhaltet, dann diese auch rendern
if @points.length > 0
@map_handler.addMarker(@points)
update_points: ()->
new_points = @get_points()
# entweder lösche alle bestehenden Marker aus der Karte und fülle diese neu auf
# oder schecke, ob new_marker schon vorhanden ist
get_points: ()->
# erhalte lat, lng, und zoom von der aktuellen Karte
PI:EMAIL:<EMAIL>END_PI().getCenter(); // --> .lat(), .lng()
PI:EMAIL:<EMAIL>END_PI().getZoom(); //--> e.g. 9
# rufe eine URL mit lat, lng und zoom auf und erhalte json
return []
window.MapBuilder = MapBuilder |
[
{
"context": "andler ) ->\n help 'show_routes_of_agency'\n key = \"%|gtfs/routes|gtfs/agency/#{agency_id}\"\n query =\n 'gte': key\n 'lte': ",
"end": 2152,
"score": 0.9992467761039734,
"start": 2112,
"tag": "KEY",
"value": "\"%|gtfs/routes|gtfs/agency/#{agency_id}\""
... | src/scratch/show-db.coffee | loveencounterflow/timetable | 1 |
############################################################################################################
TRM = require 'coffeenode-trm'
rpr = TRM.rpr.bind TRM
badge = 'TIMETABLE/main'
log = TRM.get_logger 'plain', badge
info = TRM.get_logger 'info', badge
whisper = TRM.get_logger 'whisper', badge
alert = TRM.get_logger 'alert', badge
debug = TRM.get_logger 'debug', badge
warn = TRM.get_logger 'warn', badge
help = TRM.get_logger 'help', badge
urge = TRM.get_logger 'urge', badge
echo = TRM.echo.bind TRM
rainbow = TRM.rainbow.bind TRM
#...........................................................................................................
ASYNC = require 'async'
#...........................................................................................................
# GTFS_READER = require '../GTFS-READER'
# READER = require '../READER'
REGISTRY = require '../REGISTRY'
KEY = require '../KEY'
options = require '../../options'
#...........................................................................................................
P = require 'pipedreams'
$ = P.$.bind P
# debug new Buffer '\x00\uffff\x00'
# debug new Buffer '\x00𠀀\x00'
# debug rpr ( new Buffer 'abcö' )
#-----------------------------------------------------------------------------------------------------------
new_lte = ( text ) ->
length = Buffer.byteLength text
R = new Buffer 1 + length
R.write text
R[ length ] = 0xff
return R
#-----------------------------------------------------------------------------------------------------------
@show_routes_of_agency = ( db, agency_id, handler ) ->
help 'show_routes_of_agency'
key = "%|gtfs/routes|gtfs/agency/#{agency_id}"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
help query
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
handler null, record
.pipe P.$show()
.pipe P.$on_end ->
return handler null, db
#-----------------------------------------------------------------------------------------------------------
$filter = ( f ) ->
return $ ( record, handler ) ->
try
return handler() unless f record
catch error
return handler error
return handler null, record
#-----------------------------------------------------------------------------------------------------------
@show_subway_routes = ( db, handler ) ->
help 'show_subway_routes'
seen_stops = {}
### TAINT must escape name ###
key = "%|gtfs/routes|name:U"
key = "gtfs/routes/"
query =
'gte': key
'lte': new_lte key
'keys': no
'values': yes
help key
input = ( db.createReadStream query )
.pipe $filter ( record ) ->
if /^U/.test name = record[ 'name' ]
return true
# whisper name
return false
.pipe P.$show()
#-----------------------------------------------------------------------------------------------------------
@show_db_sample = ( db, O..., handler ) ->
O = O[ 0 ] ? {}
ratio = O[ 'ratio' ] ? 1 / 1e4
stream_options = {}
if ( prefix = O[ 'prefix' ] )?
stream_options[ 'gte' ] = prefix
stream_options[ 'lte' ] = new_lte prefix
whisper "ratio: #{ratio}"
whisper "stream: #{rpr stream_options}"
db.createKeyStream stream_options
.pipe P.$count ( _, count ) -> help "walked over #{count} entries"
.pipe P.$sample ratio, seed: 5
# .pipe $ ( { key, value, }, handler ) ->
# return handler null, key if value is true
# return handler null, value
.pipe P.$show()
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@show_stops_of_route = ( db, route_name, handler ) ->
help 'show_stops_of_route'
seen_stops = {}
### TAINT must escape name ###
key = "%|gtfs/routes|name:#{route_name}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
[ ..., route_id ] = record.split '|'
key = "%|gtfs/trips|gtfs/routes/#{route_id}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
input = ( db.createReadStream query )
# .pipe P.$show()
.pipe $ ( record ) ->
[ ..., trip_id ] = record.split '|'
# whisper trip_id
key = "%|gtfs/stop_times|gtfs/trips/#{trip_id}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper key
input = ( db.createReadStream query )
# .pipe P.$show()
.pipe $ ( record ) ->
[ _, type, _, id ] = record.split '|'
stoptime_key = "#{type}/#{id}"
# whisper stoptime_key
db.get stoptime_key, ( error, record ) ->
return handler error if error?
stop_key = "gtfs/stops/#{record[ 'gtfs-stops-id' ]}"
db.get stop_key, ( error, record ) ->
return handler error if error?
name = record[ 'name' ]
return if name of seen_stops
seen_stops[ name ] = 1
help name
#-----------------------------------------------------------------------------------------------------------
$_XXX_show = ( label ) ->
return $ ( record, handler ) ->
log ( TRM.grey label ), ( TRM.lime record )
handler null, record
#-----------------------------------------------------------------------------------------------------------
$read_trips_from_route = ( db ) ->
help 'read_trips_from_route'
return P.through ( record_1 ) ->
[ ..., route_id ] = record_1.split '|'
key = "%|gtfs/trips|gtfs/routes/#{route_id}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
emit = @emit.bind @
# emit 'data', 'starting nested search'
count = 0
db.createReadStream query
# .pipe $_XXX_show '2'
.pipe P.through ( record_2 ) ->
# whisper record_2
emit 'data', record_2
count += 1
,
-> whisper count
# @emit 'data', record_2
# handler_1 null, record_2
# for idx in [ 0 .. 5 ]
# do ( idx ) ->
# setTimeout ( -> emit 'data', idx ), 0
# #-----------------------------------------------------------------------------------------------------------
# @_pass_on = ( handler ) ->
# return ( record ) ->
# handler null, record
# @emit 'data', record
# #-----------------------------------------------------------------------------------------------------------
# @_signal_end = ( handler ) ->
# return ( record ) ->
# handler null, null
# @emit 'end'
# #-----------------------------------------------------------------------------------------------------------
# @read_routes_id_from_name = ( db, route_name, handler ) ->
# help 'read_routes_id_from_name'
# seen_stops = {}
# ### TAINT must escape name ###
# key = "%|gtfs/routes|name:#{route_name}"
# query =
# 'gte': key
# 'lte': new_lte key
# 'keys': yes
# 'values': no
# whisper key
# #.........................................................................................................
# pass_on = ( record ) ->
# [ _, _, facet, id, ] = record.split '|'
# [ _, name, ] = facet.split ':'
# record_id = "gtfs/routes/#{id}"
# Z = 'id': record_id
# Z[ 'name' ] = name
# handler null, Z
# @emit 'data', Z
# #.........................................................................................................
# ( db.createReadStream query ).pipe P.through pass_on, ( @_signal_end handler )
#-----------------------------------------------------------------------------------------------------------
@$read_trips_from_route = ( db ) ->
help 'read_trips_from_route'
return P.through ( record_1 ) ->
[ ..., route_id ] = record_1.split '|'
key = "%|gtfs/trips|gtfs/routes/#{route_id}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
emit = @emit.bind @
# emit 'data', 'starting nested search'
count = 0
db.createReadStream query
# .pipe $_XXX_show '2'
.pipe P.through ( record_2 ) ->
# whisper record_2
emit 'data', record_2
count += 1
,
-> whisper count
#-----------------------------------------------------------------------------------------------------------
@read_routes_id_from_name = ( db, route_name, handler ) ->
help 'read_routes_id_from_name'
### TAINT must escape name ###
key = "%|gtfs/routes|name:#{route_name}"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
[ _, _, facet, id, ] = record.split '|'
[ _, name, ] = facet.split ':'
record_id = "gtfs/routes/#{id}"
Z = 'id': record_id
Z[ 'name' ] = name
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@read_trips_id_from_route_id = ( db, route_id, handler ) ->
help 'read_trips_id_from_route_id'
### TAINT must escape name ###
key = "%|gtfs/trips|#{route_id}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper '5', key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
# whisper record
[ _, gtfs_type, _, id, ] = record.split '|'
record_id = "#{gtfs_type}/#{id}"
Z = 'id': record_id
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@read_stoptimes_id_from_trips_id = ( db, trip_id, handler ) ->
help 'read_stoptimes_id_from_trips_id'
key = "%|gtfs/stop_times|#{trip_id}|"
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper '5', key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
# whisper '7', record
[ _, gtfs_type, _, id, ] = record.split '|'
record_id = "#{gtfs_type}/#{id}"
Z = 'id': record_id
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@f = ( db, route_name, handler ) ->
@read_routes_id_from_name db, route_name, ( error, record ) =>
return handler error if error?
return if record is null
{ id: route_id, name } = record
whisper '1', route_id, name
@read_trips_id_from_route_id db, route_id, ( error, record ) =>
return handler error if error?
return if record is null
trip_id = record[ 'id' ]
@read_stoptimes_id_from_trips_id db, trip_id, ( error, record ) =>
return handler error if error?
return if record is null
stoptimes_id = record[ 'id' ]
db.get stoptimes_id, ( error, record ) =>
return handler error if error?
debug record
# return handler null, null if record is null
# %|gtfs/agency|name:A. Reich GmbH Busbetrieb|REI---
# %|gtfs/routes|gtfs/agency/0NV___|11
# %|gtfs/routes|name:1%2F411|1392
# %|gtfs/routes|name:|811
# %|gtfs/stop_times|gtfs/stops/8012117|181
# %|gtfs/stop_times|gtfs/trips/100497|141
# %|gtfs/stops|name:Aalemannufer (Berlin)|9027205
# %|gtfs/trips|gtfs/routes/1001|124813
# %|gtfs/trips|gtfs/service/000000|105962
# %|gtfs/stop_times>gtfs/stops/8012117|181
# %|gtfs/stops<gtfs/stop_times/181|8012117
#-----------------------------------------------------------------------------------------------------------
@show_unique_indexes = ( db, handler ) ->
help 'show_unique_indexes'
seen = {}
count = 0
query =
'gte': '%|gtfs'
'lte': new_lte '%|gtfs'
# 'gte': 'gtfs/stops'
# 'lte': 'gtfs/stops/\xff'
'keys': yes
'values': no
# 'keyEncoding': 'binary'
# input = ( db.createReadStream options[ 'levelup' ][ 'new' ] )
help query
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
count += 1
handler null, record
.pipe $ ( record, handler ) ->
[ _, gtfs_type, gtfs_ref_id, gtfs_id ] = record.split '|'
gtfs_ref_type = gtfs_ref_id.replace /[\/:][^\/:]+$/, ''
key = gtfs_type + '|' + gtfs_ref_type
return handler() if key of seen
seen[ key ] = 1
handler null, record
.pipe P.$show()
.pipe P.$on_end ->
help count, "records in DB"
return handler null, db
#-----------------------------------------------------------------------------------------------------------
@test = ( registry, method_name, handler ) ->
prefixes = [
'$.|gtfs/'
'$.|gtfs/routes'
'%^|gtfs/stop_times' ]
tasks = []
#.........................................................................................................
for prefix in prefixes
do ( prefix ) =>
tasks.push ( handler ) =>
registry.createKeyStream gte: prefix, lte: ( KEY.lte_from_gte prefix )
.pipe P.$count ( _, count ) -> help "#{method_name} #{prefix}...: #{count} entries"
.on 'end', -> handler null, null
#.........................................................................................................
ASYNC[ method_name ] tasks, ( error ) ->
return handler error, null
#-----------------------------------------------------------------------------------------------------------
@main = ( handler ) ->
registry = REGISTRY.new_registry()
# @show_unique_indexes registry, handler
# @show_routes_of_agency registry, 'BVB---', handler
# @show_subway_routes registry, handler
# @show_stops_of_route registry, 'U4', handler
# @show_stops_of_route_2 registry, 'U4', handler
# @f registry, 'U1', ( error, record ) -> debug record
# @show_db_sample registry, ratio: 1 / 1, prefix: '%^|gtfs/stop_times|0|gtfs/trips/', handler
# @show_db_sample registry, ratio: 1 / 1, prefix: '$.|gtfs/trips/9174', handler
# @test registry, 'parallel', handler
# @test registry, 'series', handler
@show_db_sample registry, ratio: 1 / 1, prefix: '%^|gtfs/stoptime|1', handler
return null
############################################################################################################
unless module.parent?
@main ( error, registry ) =>
throw error if error?
help 'ok'
| 129313 |
############################################################################################################
TRM = require 'coffeenode-trm'
rpr = TRM.rpr.bind TRM
badge = 'TIMETABLE/main'
log = TRM.get_logger 'plain', badge
info = TRM.get_logger 'info', badge
whisper = TRM.get_logger 'whisper', badge
alert = TRM.get_logger 'alert', badge
debug = TRM.get_logger 'debug', badge
warn = TRM.get_logger 'warn', badge
help = TRM.get_logger 'help', badge
urge = TRM.get_logger 'urge', badge
echo = TRM.echo.bind TRM
rainbow = TRM.rainbow.bind TRM
#...........................................................................................................
ASYNC = require 'async'
#...........................................................................................................
# GTFS_READER = require '../GTFS-READER'
# READER = require '../READER'
REGISTRY = require '../REGISTRY'
KEY = require '../KEY'
options = require '../../options'
#...........................................................................................................
P = require 'pipedreams'
$ = P.$.bind P
# debug new Buffer '\x00\uffff\x00'
# debug new Buffer '\x00𠀀\x00'
# debug rpr ( new Buffer 'abcö' )
#-----------------------------------------------------------------------------------------------------------
new_lte = ( text ) ->
length = Buffer.byteLength text
R = new Buffer 1 + length
R.write text
R[ length ] = 0xff
return R
#-----------------------------------------------------------------------------------------------------------
@show_routes_of_agency = ( db, agency_id, handler ) ->
help 'show_routes_of_agency'
key = <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
help query
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
handler null, record
.pipe P.$show()
.pipe P.$on_end ->
return handler null, db
#-----------------------------------------------------------------------------------------------------------
$filter = ( f ) ->
return $ ( record, handler ) ->
try
return handler() unless f record
catch error
return handler error
return handler null, record
#-----------------------------------------------------------------------------------------------------------
@show_subway_routes = ( db, handler ) ->
help 'show_subway_routes'
seen_stops = {}
### TAINT must escape name ###
key = <KEY>"
key = "<KEY>
query =
'gte': key
'lte': new_lte key
'keys': no
'values': yes
help key
input = ( db.createReadStream query )
.pipe $filter ( record ) ->
if /^U/.test name = record[ 'name' ]
return true
# whisper name
return false
.pipe P.$show()
#-----------------------------------------------------------------------------------------------------------
@show_db_sample = ( db, O..., handler ) ->
O = O[ 0 ] ? {}
ratio = O[ 'ratio' ] ? 1 / 1e4
stream_options = {}
if ( prefix = O[ 'prefix' ] )?
stream_options[ 'gte' ] = prefix
stream_options[ 'lte' ] = new_lte prefix
whisper "ratio: #{ratio}"
whisper "stream: #{rpr stream_options}"
db.createKeyStream stream_options
.pipe P.$count ( _, count ) -> help "walked over #{count} entries"
.pipe P.$sample ratio, seed: 5
# .pipe $ ( { key, value, }, handler ) ->
# return handler null, key if value is true
# return handler null, value
.pipe P.$show()
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@show_stops_of_route = ( db, route_name, handler ) ->
help 'show_stops_of_route'
seen_stops = {}
### TAINT must escape name ###
key = <KEY>route_<KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
[ ..., route_id ] = record.split '|'
key = <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
input = ( db.createReadStream query )
# .pipe P.$show()
.pipe $ ( record ) ->
[ ..., trip_id ] = record.split '|'
# whisper trip_id
key = <KEY> <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper key
input = ( db.createReadStream query )
# .pipe P.$show()
.pipe $ ( record ) ->
[ _, type, _, id ] = record.split '|'
stoptime_key = <KEY>}"
# whisper stoptime_key
db.get stoptime_key, ( error, record ) ->
return handler error if error?
stop_key = "gt<KEY>stops/#{record[ 'gtfs-stops-id' ]}"
db.get stop_key, ( error, record ) ->
return handler error if error?
name = record[ 'name' ]
return if name of seen_stops
seen_stops[ name ] = 1
help name
#-----------------------------------------------------------------------------------------------------------
$_XXX_show = ( label ) ->
return $ ( record, handler ) ->
log ( TRM.grey label ), ( TRM.lime record )
handler null, record
#-----------------------------------------------------------------------------------------------------------
$read_trips_from_route = ( db ) ->
help 'read_trips_from_route'
return P.through ( record_1 ) ->
[ ..., route_id ] = record_1.split '|'
key = <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
emit = @emit.bind @
# emit 'data', 'starting nested search'
count = 0
db.createReadStream query
# .pipe $_XXX_show '2'
.pipe P.through ( record_2 ) ->
# whisper record_2
emit 'data', record_2
count += 1
,
-> whisper count
# @emit 'data', record_2
# handler_1 null, record_2
# for idx in [ 0 .. 5 ]
# do ( idx ) ->
# setTimeout ( -> emit 'data', idx ), 0
# #-----------------------------------------------------------------------------------------------------------
# @_pass_on = ( handler ) ->
# return ( record ) ->
# handler null, record
# @emit 'data', record
# #-----------------------------------------------------------------------------------------------------------
# @_signal_end = ( handler ) ->
# return ( record ) ->
# handler null, null
# @emit 'end'
# #-----------------------------------------------------------------------------------------------------------
# @read_routes_id_from_name = ( db, route_name, handler ) ->
# help 'read_routes_id_from_name'
# seen_stops = {}
# ### TAINT must escape name ###
# key = <KEY>route_<KEY>
# query =
# 'gte': key
# 'lte': new_lte key
# 'keys': yes
# 'values': no
# whisper key
# #.........................................................................................................
# pass_on = ( record ) ->
# [ _, _, facet, id, ] = record.split '|'
# [ _, name, ] = facet.split ':'
# record_id = "gtfs/routes/#{id}"
# Z = 'id': record_id
# Z[ 'name' ] = name
# handler null, Z
# @emit 'data', Z
# #.........................................................................................................
# ( db.createReadStream query ).pipe P.through pass_on, ( @_signal_end handler )
#-----------------------------------------------------------------------------------------------------------
@$read_trips_from_route = ( db ) ->
help 'read_trips_from_route'
return P.through ( record_1 ) ->
[ ..., route_id ] = record_1.split '|'
key = <KEY>_<KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
emit = @emit.bind @
# emit 'data', 'starting nested search'
count = 0
db.createReadStream query
# .pipe $_XXX_show '2'
.pipe P.through ( record_2 ) ->
# whisper record_2
emit 'data', record_2
count += 1
,
-> whisper count
#-----------------------------------------------------------------------------------------------------------
@read_routes_id_from_name = ( db, route_name, handler ) ->
help 'read_routes_id_from_name'
### TAINT must escape name ###
key = <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
[ _, _, facet, id, ] = record.split '|'
[ _, name, ] = facet.split ':'
record_id = "gtfs/routes/#{id}"
Z = 'id': record_id
Z[ 'name' ] = name
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@read_trips_id_from_route_id = ( db, route_id, handler ) ->
help 'read_trips_id_from_route_id'
### TAINT must escape name ###
key = <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper '5', key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
# whisper record
[ _, gtfs_type, _, id, ] = record.split '|'
record_id = "#{gtfs_type}/#{id}"
Z = 'id': record_id
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@read_stoptimes_id_from_trips_id = ( db, trip_id, handler ) ->
help 'read_stoptimes_id_from_trips_id'
key = <KEY>
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper '5', key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
# whisper '7', record
[ _, gtfs_type, _, id, ] = record.split '|'
record_id = "#{gtfs_type}/#{id}"
Z = 'id': record_id
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@f = ( db, route_name, handler ) ->
@read_routes_id_from_name db, route_name, ( error, record ) =>
return handler error if error?
return if record is null
{ id: route_id, name } = record
whisper '1', route_id, name
@read_trips_id_from_route_id db, route_id, ( error, record ) =>
return handler error if error?
return if record is null
trip_id = record[ 'id' ]
@read_stoptimes_id_from_trips_id db, trip_id, ( error, record ) =>
return handler error if error?
return if record is null
stoptimes_id = record[ 'id' ]
db.get stoptimes_id, ( error, record ) =>
return handler error if error?
debug record
# return handler null, null if record is null
# %|gtfs/agency|name:A. Reich GmbH Busbetrieb|REI---
# %|gtfs/routes|gtfs/agency/0NV___|11
# %|gtfs/routes|name:1%2F411|1392
# %|gtfs/routes|name:|811
# %|gtfs/stop_times|gtfs/stops/8012117|181
# %|gtfs/stop_times|gtfs/trips/100497|141
# %|gtfs/stops|name:Aalemannufer (Berlin)|9027205
# %|gtfs/trips|gtfs/routes/1001|124813
# %|gtfs/trips|gtfs/service/000000|105962
# %|gtfs/stop_times>gtfs/stops/8012117|181
# %|gtfs/stops<gtfs/stop_times/181|8012117
#-----------------------------------------------------------------------------------------------------------
@show_unique_indexes = ( db, handler ) ->
help 'show_unique_indexes'
seen = {}
count = 0
query =
'gte': '%|gtfs'
'lte': new_lte '%|gtfs'
# 'gte': 'gtfs/stops'
# 'lte': 'gtfs/stops/\xff'
'keys': yes
'values': no
# 'keyEncoding': 'binary'
# input = ( db.createReadStream options[ 'levelup' ][ 'new' ] )
help query
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
count += 1
handler null, record
.pipe $ ( record, handler ) ->
[ _, gtfs_type, gtfs_ref_id, gtfs_id ] = record.split '|'
gtfs_ref_type = gtfs_ref_id.replace /[\/:][^\/:]+$/, ''
key = gtfs_type + '|' + gtfs_ref_type
return handler() if key of seen
seen[ key ] = 1
handler null, record
.pipe P.$show()
.pipe P.$on_end ->
help count, "records in DB"
return handler null, db
#-----------------------------------------------------------------------------------------------------------
@test = ( registry, method_name, handler ) ->
prefixes = [
'$.|gtfs/'
'$.|gtfs/routes'
'%^|gtfs/stop_times' ]
tasks = []
#.........................................................................................................
for prefix in prefixes
do ( prefix ) =>
tasks.push ( handler ) =>
registry.createKeyStream gte: prefix, lte: ( KEY.lte_from_gte prefix )
.pipe P.$count ( _, count ) -> help "#{method_name} #{prefix}...: #{count} entries"
.on 'end', -> handler null, null
#.........................................................................................................
ASYNC[ method_name ] tasks, ( error ) ->
return handler error, null
#-----------------------------------------------------------------------------------------------------------
@main = ( handler ) ->
registry = REGISTRY.new_registry()
# @show_unique_indexes registry, handler
# @show_routes_of_agency registry, 'BVB---', handler
# @show_subway_routes registry, handler
# @show_stops_of_route registry, 'U4', handler
# @show_stops_of_route_2 registry, 'U4', handler
# @f registry, 'U1', ( error, record ) -> debug record
# @show_db_sample registry, ratio: 1 / 1, prefix: '%^|gtfs/stop_times|0|gtfs/trips/', handler
# @show_db_sample registry, ratio: 1 / 1, prefix: '$.|gtfs/trips/9174', handler
# @test registry, 'parallel', handler
# @test registry, 'series', handler
@show_db_sample registry, ratio: 1 / 1, prefix: '%^|gtfs/stoptime|1', handler
return null
############################################################################################################
unless module.parent?
@main ( error, registry ) =>
throw error if error?
help 'ok'
| true |
############################################################################################################
TRM = require 'coffeenode-trm'
rpr = TRM.rpr.bind TRM
badge = 'TIMETABLE/main'
log = TRM.get_logger 'plain', badge
info = TRM.get_logger 'info', badge
whisper = TRM.get_logger 'whisper', badge
alert = TRM.get_logger 'alert', badge
debug = TRM.get_logger 'debug', badge
warn = TRM.get_logger 'warn', badge
help = TRM.get_logger 'help', badge
urge = TRM.get_logger 'urge', badge
echo = TRM.echo.bind TRM
rainbow = TRM.rainbow.bind TRM
#...........................................................................................................
ASYNC = require 'async'
#...........................................................................................................
# GTFS_READER = require '../GTFS-READER'
# READER = require '../READER'
REGISTRY = require '../REGISTRY'
KEY = require '../KEY'
options = require '../../options'
#...........................................................................................................
P = require 'pipedreams'
$ = P.$.bind P
# debug new Buffer '\x00\uffff\x00'
# debug new Buffer '\x00𠀀\x00'
# debug rpr ( new Buffer 'abcö' )
#-----------------------------------------------------------------------------------------------------------
new_lte = ( text ) ->
length = Buffer.byteLength text
R = new Buffer 1 + length
R.write text
R[ length ] = 0xff
return R
#-----------------------------------------------------------------------------------------------------------
@show_routes_of_agency = ( db, agency_id, handler ) ->
help 'show_routes_of_agency'
key = PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
help query
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
handler null, record
.pipe P.$show()
.pipe P.$on_end ->
return handler null, db
#-----------------------------------------------------------------------------------------------------------
$filter = ( f ) ->
return $ ( record, handler ) ->
try
return handler() unless f record
catch error
return handler error
return handler null, record
#-----------------------------------------------------------------------------------------------------------
@show_subway_routes = ( db, handler ) ->
help 'show_subway_routes'
seen_stops = {}
### TAINT must escape name ###
key = PI:KEY:<KEY>END_PI"
key = "PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': no
'values': yes
help key
input = ( db.createReadStream query )
.pipe $filter ( record ) ->
if /^U/.test name = record[ 'name' ]
return true
# whisper name
return false
.pipe P.$show()
#-----------------------------------------------------------------------------------------------------------
@show_db_sample = ( db, O..., handler ) ->
O = O[ 0 ] ? {}
ratio = O[ 'ratio' ] ? 1 / 1e4
stream_options = {}
if ( prefix = O[ 'prefix' ] )?
stream_options[ 'gte' ] = prefix
stream_options[ 'lte' ] = new_lte prefix
whisper "ratio: #{ratio}"
whisper "stream: #{rpr stream_options}"
db.createKeyStream stream_options
.pipe P.$count ( _, count ) -> help "walked over #{count} entries"
.pipe P.$sample ratio, seed: 5
# .pipe $ ( { key, value, }, handler ) ->
# return handler null, key if value is true
# return handler null, value
.pipe P.$show()
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@show_stops_of_route = ( db, route_name, handler ) ->
help 'show_stops_of_route'
seen_stops = {}
### TAINT must escape name ###
key = PI:KEY:<KEY>END_PIroute_PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
[ ..., route_id ] = record.split '|'
key = PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
input = ( db.createReadStream query )
# .pipe P.$show()
.pipe $ ( record ) ->
[ ..., trip_id ] = record.split '|'
# whisper trip_id
key = PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper key
input = ( db.createReadStream query )
# .pipe P.$show()
.pipe $ ( record ) ->
[ _, type, _, id ] = record.split '|'
stoptime_key = PI:KEY:<KEY>END_PI}"
# whisper stoptime_key
db.get stoptime_key, ( error, record ) ->
return handler error if error?
stop_key = "gtPI:KEY:<KEY>END_PIstops/#{record[ 'gtfs-stops-id' ]}"
db.get stop_key, ( error, record ) ->
return handler error if error?
name = record[ 'name' ]
return if name of seen_stops
seen_stops[ name ] = 1
help name
#-----------------------------------------------------------------------------------------------------------
$_XXX_show = ( label ) ->
return $ ( record, handler ) ->
log ( TRM.grey label ), ( TRM.lime record )
handler null, record
#-----------------------------------------------------------------------------------------------------------
$read_trips_from_route = ( db ) ->
help 'read_trips_from_route'
return P.through ( record_1 ) ->
[ ..., route_id ] = record_1.split '|'
key = PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
emit = @emit.bind @
# emit 'data', 'starting nested search'
count = 0
db.createReadStream query
# .pipe $_XXX_show '2'
.pipe P.through ( record_2 ) ->
# whisper record_2
emit 'data', record_2
count += 1
,
-> whisper count
# @emit 'data', record_2
# handler_1 null, record_2
# for idx in [ 0 .. 5 ]
# do ( idx ) ->
# setTimeout ( -> emit 'data', idx ), 0
# #-----------------------------------------------------------------------------------------------------------
# @_pass_on = ( handler ) ->
# return ( record ) ->
# handler null, record
# @emit 'data', record
# #-----------------------------------------------------------------------------------------------------------
# @_signal_end = ( handler ) ->
# return ( record ) ->
# handler null, null
# @emit 'end'
# #-----------------------------------------------------------------------------------------------------------
# @read_routes_id_from_name = ( db, route_name, handler ) ->
# help 'read_routes_id_from_name'
# seen_stops = {}
# ### TAINT must escape name ###
# key = PI:KEY:<KEY>END_PIroute_PI:KEY:<KEY>END_PI
# query =
# 'gte': key
# 'lte': new_lte key
# 'keys': yes
# 'values': no
# whisper key
# #.........................................................................................................
# pass_on = ( record ) ->
# [ _, _, facet, id, ] = record.split '|'
# [ _, name, ] = facet.split ':'
# record_id = "gtfs/routes/#{id}"
# Z = 'id': record_id
# Z[ 'name' ] = name
# handler null, Z
# @emit 'data', Z
# #.........................................................................................................
# ( db.createReadStream query ).pipe P.through pass_on, ( @_signal_end handler )
#-----------------------------------------------------------------------------------------------------------
@$read_trips_from_route = ( db ) ->
help 'read_trips_from_route'
return P.through ( record_1 ) ->
[ ..., route_id ] = record_1.split '|'
key = PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
emit = @emit.bind @
# emit 'data', 'starting nested search'
count = 0
db.createReadStream query
# .pipe $_XXX_show '2'
.pipe P.through ( record_2 ) ->
# whisper record_2
emit 'data', record_2
count += 1
,
-> whisper count
#-----------------------------------------------------------------------------------------------------------
@read_routes_id_from_name = ( db, route_name, handler ) ->
help 'read_routes_id_from_name'
### TAINT must escape name ###
key = PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
whisper key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
[ _, _, facet, id, ] = record.split '|'
[ _, name, ] = facet.split ':'
record_id = "gtfs/routes/#{id}"
Z = 'id': record_id
Z[ 'name' ] = name
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@read_trips_id_from_route_id = ( db, route_id, handler ) ->
help 'read_trips_id_from_route_id'
### TAINT must escape name ###
key = PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper '5', key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
# whisper record
[ _, gtfs_type, _, id, ] = record.split '|'
record_id = "#{gtfs_type}/#{id}"
Z = 'id': record_id
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@read_stoptimes_id_from_trips_id = ( db, trip_id, handler ) ->
help 'read_stoptimes_id_from_trips_id'
key = PI:KEY:<KEY>END_PI
query =
'gte': key
'lte': new_lte key
'keys': yes
'values': no
# whisper '5', key
#.........................................................................................................
db.createReadStream query
#.......................................................................................................
.on 'data', ( record ) ->
# whisper '7', record
[ _, gtfs_type, _, id, ] = record.split '|'
record_id = "#{gtfs_type}/#{id}"
Z = 'id': record_id
handler null, Z
#.......................................................................................................
.on 'end', -> handler null, null
#-----------------------------------------------------------------------------------------------------------
@f = ( db, route_name, handler ) ->
@read_routes_id_from_name db, route_name, ( error, record ) =>
return handler error if error?
return if record is null
{ id: route_id, name } = record
whisper '1', route_id, name
@read_trips_id_from_route_id db, route_id, ( error, record ) =>
return handler error if error?
return if record is null
trip_id = record[ 'id' ]
@read_stoptimes_id_from_trips_id db, trip_id, ( error, record ) =>
return handler error if error?
return if record is null
stoptimes_id = record[ 'id' ]
db.get stoptimes_id, ( error, record ) =>
return handler error if error?
debug record
# return handler null, null if record is null
# %|gtfs/agency|name:A. Reich GmbH Busbetrieb|REI---
# %|gtfs/routes|gtfs/agency/0NV___|11
# %|gtfs/routes|name:1%2F411|1392
# %|gtfs/routes|name:|811
# %|gtfs/stop_times|gtfs/stops/8012117|181
# %|gtfs/stop_times|gtfs/trips/100497|141
# %|gtfs/stops|name:Aalemannufer (Berlin)|9027205
# %|gtfs/trips|gtfs/routes/1001|124813
# %|gtfs/trips|gtfs/service/000000|105962
# %|gtfs/stop_times>gtfs/stops/8012117|181
# %|gtfs/stops<gtfs/stop_times/181|8012117
#-----------------------------------------------------------------------------------------------------------
@show_unique_indexes = ( db, handler ) ->
help 'show_unique_indexes'
seen = {}
count = 0
query =
'gte': '%|gtfs'
'lte': new_lte '%|gtfs'
# 'gte': 'gtfs/stops'
# 'lte': 'gtfs/stops/\xff'
'keys': yes
'values': no
# 'keyEncoding': 'binary'
# input = ( db.createReadStream options[ 'levelup' ][ 'new' ] )
help query
input = ( db.createReadStream query )
.pipe $ ( record, handler ) ->
count += 1
handler null, record
.pipe $ ( record, handler ) ->
[ _, gtfs_type, gtfs_ref_id, gtfs_id ] = record.split '|'
gtfs_ref_type = gtfs_ref_id.replace /[\/:][^\/:]+$/, ''
key = gtfs_type + '|' + gtfs_ref_type
return handler() if key of seen
seen[ key ] = 1
handler null, record
.pipe P.$show()
.pipe P.$on_end ->
help count, "records in DB"
return handler null, db
#-----------------------------------------------------------------------------------------------------------
@test = ( registry, method_name, handler ) ->
prefixes = [
'$.|gtfs/'
'$.|gtfs/routes'
'%^|gtfs/stop_times' ]
tasks = []
#.........................................................................................................
for prefix in prefixes
do ( prefix ) =>
tasks.push ( handler ) =>
registry.createKeyStream gte: prefix, lte: ( KEY.lte_from_gte prefix )
.pipe P.$count ( _, count ) -> help "#{method_name} #{prefix}...: #{count} entries"
.on 'end', -> handler null, null
#.........................................................................................................
ASYNC[ method_name ] tasks, ( error ) ->
return handler error, null
#-----------------------------------------------------------------------------------------------------------
@main = ( handler ) ->
registry = REGISTRY.new_registry()
# @show_unique_indexes registry, handler
# @show_routes_of_agency registry, 'BVB---', handler
# @show_subway_routes registry, handler
# @show_stops_of_route registry, 'U4', handler
# @show_stops_of_route_2 registry, 'U4', handler
# @f registry, 'U1', ( error, record ) -> debug record
# @show_db_sample registry, ratio: 1 / 1, prefix: '%^|gtfs/stop_times|0|gtfs/trips/', handler
# @show_db_sample registry, ratio: 1 / 1, prefix: '$.|gtfs/trips/9174', handler
# @test registry, 'parallel', handler
# @test registry, 'series', handler
@show_db_sample registry, ratio: 1 / 1, prefix: '%^|gtfs/stoptime|1', handler
return null
############################################################################################################
unless module.parent?
@main ( error, registry ) =>
throw error if error?
help 'ok'
|
[
{
"context": "{}\n\n\n user = new User\n _id: 'uuid'\n name: 'name'\n givenName: 'givenName'\n familyName: 'fami",
"end": 479,
"score": 0.9411723613739014,
"start": 475,
"tag": "NAME",
"value": "name"
},
{
"context": "\n _id: 'uuid'\n name: 'name'\n givenName: '... | test/unit/oidc/getUserInfo.coffee | Zacaria/connect | 0 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
proxyquire = require('proxyquire').noCallThru()
chai.use sinonChai
chai.should()
User = proxyquire('../../../models/User', {
'../boot/redis': {
getClient: () => {}
}
})
getUserInfo = proxyquire('../../../oidc/getUserInfo', {
'../models/User': User
})
describe 'UserInfo', ->
{ req, res, next, err, json } = {}
user = new User
_id: 'uuid'
name: 'name'
givenName: 'givenName'
familyName: 'familyName'
middleName: 'middleName'
nickname: 'nickname'
preferredUsername: 'preferredUsername'
profile: 'profile'
picture: 'picture'
website: 'website'
email: 'email'
emailVerified: true
dateEmailVerified: Date.now()
gender: 'gender'
birthdate: 'birthdate'
zoneinfo: 'zoneinfo'
locale: 'locale'
phoneNumber: 'phoneNumber'
phoneNumberVerified: true
address:
test: 'hello world'
scopes =
openid:
name: 'openid'
description: 'View your identity'
restricted: false
profile:
name: 'profile'
description: 'View your basic account info'
restricted: false
attributes:
user: [
'name', 'family_name', 'given_name',
'middle_name', 'nickname',
'preferred_username', 'profile', 'picture',
'website', 'gender',
'birthdate', 'zoneinfo', 'locale', 'updated_at'
]
email:
name: 'email',
description: 'View your email address',
restricted: false,
attributes:
user: ['email', 'email_verified']
address:
name: 'address',
description: 'View your address',
restricted: false,
attributes:
user: ['address']
phone:
name: 'phone',
description: 'View your phone number',
restricted: false,
attributes:
user: ['phone_number', 'phone_number_verified']
describe 'with a valid token', ->
before (done) ->
sinon.stub(User, 'get').callsArgWith(1, null, user)
json = sinon.spy()
req =
claims:
sub: 'uuid'
scopes: [scopes.openid, scopes.profile]
res =
status: sinon.spy -> { json: json }
next = sinon.spy()
getUserInfo req, res, next
done()
after ->
User.get.restore()
it 'should respond with the sub claim', ->
json.should.have.been.calledWith sinon.match({
sub: 'uuid'
})
it 'should respond with permitted attributes', ->
json.should.have.been.calledWith sinon.match({
sub: sinon.match.string
name: sinon.match.string
family_name: sinon.match.string
middle_name: sinon.match.string
given_name: sinon.match.string
nickname: sinon.match.string
preferred_username: sinon.match.string
profile: sinon.match.string
picture: sinon.match.string
website: sinon.match.string
gender: sinon.match.string
birthdate: sinon.match.string
zoneinfo: sinon.match.string
locale: sinon.match.string
updated_at: sinon.match.number
})
it 'should not respond with attributes not permitted', ->
json.should.not.have.been.calledWith sinon.match({
email: sinon.match.string
})
| 167721 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
proxyquire = require('proxyquire').noCallThru()
chai.use sinonChai
chai.should()
User = proxyquire('../../../models/User', {
'../boot/redis': {
getClient: () => {}
}
})
getUserInfo = proxyquire('../../../oidc/getUserInfo', {
'../models/User': User
})
describe 'UserInfo', ->
{ req, res, next, err, json } = {}
user = new User
_id: 'uuid'
name: '<NAME>'
givenName: '<NAME>Name'
familyName: '<NAME>Name'
middleName: '<NAME>Name'
nickname: 'nickname'
preferredUsername: 'preferredUsername'
profile: 'profile'
picture: 'picture'
website: 'website'
email: 'email'
emailVerified: true
dateEmailVerified: Date.now()
gender: 'gender'
birthdate: 'birthdate'
zoneinfo: 'zoneinfo'
locale: 'locale'
phoneNumber: 'phoneNumber'
phoneNumberVerified: true
address:
test: 'hello world'
scopes =
openid:
name: 'openid'
description: 'View your identity'
restricted: false
profile:
name: 'profile'
description: 'View your basic account info'
restricted: false
attributes:
user: [
'name', 'family_name', 'given_name',
'middle_name', 'nickname',
'preferred_username', 'profile', 'picture',
'website', 'gender',
'birthdate', 'zoneinfo', 'locale', 'updated_at'
]
email:
name: 'email',
description: 'View your email address',
restricted: false,
attributes:
user: ['email', 'email_verified']
address:
name: 'address',
description: 'View your address',
restricted: false,
attributes:
user: ['address']
phone:
name: 'phone',
description: 'View your phone number',
restricted: false,
attributes:
user: ['phone_number', 'phone_number_verified']
describe 'with a valid token', ->
before (done) ->
sinon.stub(User, 'get').callsArgWith(1, null, user)
json = sinon.spy()
req =
claims:
sub: 'uuid'
scopes: [scopes.openid, scopes.profile]
res =
status: sinon.spy -> { json: json }
next = sinon.spy()
getUserInfo req, res, next
done()
after ->
User.get.restore()
it 'should respond with the sub claim', ->
json.should.have.been.calledWith sinon.match({
sub: 'uuid'
})
it 'should respond with permitted attributes', ->
json.should.have.been.calledWith sinon.match({
sub: sinon.match.string
name: sinon.match.string
family_name: sinon.match.string
middle_name: sinon.match.string
given_name: sinon.match.string
nickname: sinon.match.string
preferred_username: sinon.match.string
profile: sinon.match.string
picture: sinon.match.string
website: sinon.match.string
gender: sinon.match.string
birthdate: sinon.match.string
zoneinfo: sinon.match.string
locale: sinon.match.string
updated_at: sinon.match.number
})
it 'should not respond with attributes not permitted', ->
json.should.not.have.been.calledWith sinon.match({
email: sinon.match.string
})
| true | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
proxyquire = require('proxyquire').noCallThru()
chai.use sinonChai
chai.should()
User = proxyquire('../../../models/User', {
'../boot/redis': {
getClient: () => {}
}
})
getUserInfo = proxyquire('../../../oidc/getUserInfo', {
'../models/User': User
})
describe 'UserInfo', ->
{ req, res, next, err, json } = {}
user = new User
_id: 'uuid'
name: 'PI:NAME:<NAME>END_PI'
givenName: 'PI:NAME:<NAME>END_PIName'
familyName: 'PI:NAME:<NAME>END_PIName'
middleName: 'PI:NAME:<NAME>END_PIName'
nickname: 'nickname'
preferredUsername: 'preferredUsername'
profile: 'profile'
picture: 'picture'
website: 'website'
email: 'email'
emailVerified: true
dateEmailVerified: Date.now()
gender: 'gender'
birthdate: 'birthdate'
zoneinfo: 'zoneinfo'
locale: 'locale'
phoneNumber: 'phoneNumber'
phoneNumberVerified: true
address:
test: 'hello world'
scopes =
openid:
name: 'openid'
description: 'View your identity'
restricted: false
profile:
name: 'profile'
description: 'View your basic account info'
restricted: false
attributes:
user: [
'name', 'family_name', 'given_name',
'middle_name', 'nickname',
'preferred_username', 'profile', 'picture',
'website', 'gender',
'birthdate', 'zoneinfo', 'locale', 'updated_at'
]
email:
name: 'email',
description: 'View your email address',
restricted: false,
attributes:
user: ['email', 'email_verified']
address:
name: 'address',
description: 'View your address',
restricted: false,
attributes:
user: ['address']
phone:
name: 'phone',
description: 'View your phone number',
restricted: false,
attributes:
user: ['phone_number', 'phone_number_verified']
describe 'with a valid token', ->
before (done) ->
sinon.stub(User, 'get').callsArgWith(1, null, user)
json = sinon.spy()
req =
claims:
sub: 'uuid'
scopes: [scopes.openid, scopes.profile]
res =
status: sinon.spy -> { json: json }
next = sinon.spy()
getUserInfo req, res, next
done()
after ->
User.get.restore()
it 'should respond with the sub claim', ->
json.should.have.been.calledWith sinon.match({
sub: 'uuid'
})
it 'should respond with permitted attributes', ->
json.should.have.been.calledWith sinon.match({
sub: sinon.match.string
name: sinon.match.string
family_name: sinon.match.string
middle_name: sinon.match.string
given_name: sinon.match.string
nickname: sinon.match.string
preferred_username: sinon.match.string
profile: sinon.match.string
picture: sinon.match.string
website: sinon.match.string
gender: sinon.match.string
birthdate: sinon.match.string
zoneinfo: sinon.match.string
locale: sinon.match.string
updated_at: sinon.match.number
})
it 'should not respond with attributes not permitted', ->
json.should.not.have.been.calledWith sinon.match({
email: sinon.match.string
})
|
[
{
"context": "y',\n typeLabel:'Bundesland'\n defaultKey:'XXX0'\n .attr 'land',['land'], defaultLookupEntries 'S",
"end": 2985,
"score": 0.8645009398460388,
"start": 2984,
"tag": "KEY",
"value": "0"
},
{
"context": "ame'\n .attr 'ort', 'Ortsname'\n .attr 'ortKey', 'DEU12potsd... | spec/helpers/factory.coffee | lxfrdl/irma | 1 | Rosie = require "rosie"
Factory = Rosie.Factory
extend = Factory.util.extend
module.exports = Factory
lpad = (pad,num)->(""+pad+num).slice -pad.length
Factory.define 'LookupEntry'
.option 'typeLabel', "Something"
.option 'padding', ""
.option 'defaultKey', null
.sequence 'id'
.attr 'type', ['typeLabel'], (tl)->tl.toLowerCase()
.attr 'key', ['key','padding','id','defaultKey'], (key,padding,id,defaultKey)->
key ? defaultKey ? (lpad padding, id)
Factory.define 'SimpleEntry'
.extend 'LookupEntry'
.attr 'label',['label','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl}"
en: "Label #{tl}"
Factory.define 'ShortLongEntry'
.extend 'LookupEntry'
.attr 'labelShort',['labelShort','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (kurz)"
en: "Label #{tl} (short)"
.attr 'labelLong',['labelLong','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (lang)"
en: "Label #{tl} (long)"
Factory.define 'MaleFemaleEntry'
.extend 'LookupEntry'
.attr 'labelFemale',['labelFemale','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (weibl.)"
en: "Label #{tl} (female)"
.attr 'labelMale',['labelMale','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (männl.)"
en: "Label #{tl} (male)"
defaultLookupEntries = (factory, opts)->
(entries0)->
entries0 ?=
'0': id: 0
entries = {}
for id,entry of entries0
entries[id] = Factory.build factory, entry ,opts
entries
titelEntries = (entries0)->
entries0 ?=
'0':
id: 0
labelMale: de: "Prof."
labelFemale: de: "Prof."
'1':
id: 1
labelMale: de: "Dr."
labelFemale: de:"Dr."
entries = {}
for id,entry of entries0
entries[id] = Factory.build "MaleFemaleEntry", entry , typeLabel:'Titel'
entries
Factory.define 'RawLookup'
.attr 'fach',['fach'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fach'
padding:'00000'
.attr 'fachkollegium', ['fachkollegium'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fachkollegium'
padding:'000'
.attr 'fachgebiet', ['fachgebiet'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fachgebiet'
padding:'00'
.attr 'wissenschaftsbereich', ['wissenschaftsbereich'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Wissenschaftsbereich'
padding:'0'
.attr 'peu', ['peu'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEU'
defaultKey:'XXX'
.attr 'pemu', ['pemu'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEMU'
defaultKey:'XXX'
.attr 'peo', ['peo'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEO'
defaultKey:'XXXX'
.attr 'titel',['titel'], titelEntries
.attr 'bundesland',['bundesland'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Bundesland'
defaultKey:'XXX0'
.attr 'land',['land'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Land'
defaultKey:'XXX'
.attr 'kontinent',['kontinent'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Kontinent'
defaultKey:'0'
.attr 'teilkontinent',['teilkontinent'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Teilkontinent'
defaultKey:'00'
Factory.define 'RawFachklassifikation'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partType', 'FACHSYSTEMATIK'
.attr 'prioritaet', false
.attr 'wissenschaftsbereich'
.attr 'fachgebiet'
.attr 'fachkollegium'
.attr 'fach'
Factory.define 'RawProgrammklassifikation'
.attr 'peo',0
.attr 'pemu',0
.attr 'peu',0
Factory.define 'Bilingual'
.attr 'de'
.attr 'en'
Factory.define 'RawPersonenbeteiligung'
.attr '_partSn',['personId'], (id)->id
.sequence 'personId'
.attr '_partType', 'PER_BETEILIGUNG'
.attr '_partDeleted', false
.attr 'referent',false
.attr 'verstorben',false
.attr 'showInProjektResultEntry',true
.attr 'style', 'L'
.attr 'btrKey', "PAN"
Factory.define 'RawInstitutionsbeteiligung'
.sequence '_partSn'
.attr '_partType', 'INS_BETEILIGUNG'
.attr 'btrKey', 'IAN'
.attr 'style', 'L'
.sequence 'institutionId'
Factory.define 'TitelTupel'
.attr 'anrede',0
.attr 'teilname',1
Factory.define 'InsTitel'
.attr 'nameRoot', ['nameRoot'], (name)->
Factory.build "Bilingual", name ?
de: 'Name der Wurzelinstitution'
en: 'Name of Root Institution'
.attr 'namePostanschrift', 'Name der Wurzelinstitution, Abteilung, usw'
Factory.define 'GeoLocation'
.attr 'lon'
.attr 'lat'
Factory.define 'RawRahmenprojekt'
.sequence 'id'
.attr 'gz', 'FOO 08/15'
.attr 'gzAnzeigen', false
.attr 'titel', ['titel'], (titel)->
Factory.build "Bilingual", titel ?
de: "Rahmenprojekttitel"
en: "Title of Framework Project"
Factory.define 'RawBeteiligtePerson'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partDeleted', false
.attr '_partType', 'PER'
.attr 'privatanschrift',false
.attr 'vorname', 'Vorname'
.attr 'nachname', 'Nachname'
.attr 'ort', 'Ortsname'
.attr 'ortKey', 'DEU12potsdam'
.attr 'plzVorOrt', '00000'
.attr 'plzNachOrt',null
.attr 'titel',['titel'], (titel)->Factory.build 'TitelTupel',titel ? {}
.attr 'geschlecht','m'
.attr 'institution',['institution'], (ins)->Factory.build 'InsTitel', ins ? {}
.attr 'geolocation',['geolocation'], (loc)-> if loc? then Factory.build 'GeoLocation', loc
.attr 'bundesland',0
.attr 'land',0
Factory.define 'RawBeteiligteInstitution'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partType', 'INS'
.attr 'rootId'
.attr 'einrichtungsart', 5
.attr 'bundesland', 'DEU12'
.attr 'ortKey', 'DEU12potsdam'
.attr 'ort', 'Potsdam'
.attr 'name',['name'], (name)->
Factory.build 'Bilingual', name ?
de: 'Name der Institution'
en: 'Name of Institution'
.attr 'nameRoot', ['nameRoot'], (name)->
Factory.build "Bilingual", name ?
de: 'Name der Wurzelinstitution'
en: 'Name of Root Institution'
.attr 'namePostanschrift', 'Name der Wurzelinstitution, Abteilung, usw'
.attr 'geolocation',['geolocation'], (loc)-> if loc? then Factory.build 'GeoLocation', loc
Factory.define 'RawAbschlussbericht'
.attr 'datum', 0
.attr 'abstract', ['abstract'], (abs)->
Factory.build 'Bilingual',abs ?
de:'Deutscher AB Abstract'
en:'Englischer AB Abstract'
.attr 'publikationen',['publikationen'], (pubs)->
(pubs ? []).map (pub)->
Factory.build 'RawPublikation',pub
Factory.define 'RawPublikation'
.sequence '_partSn'
.attr '_partType', 'PUBLIKATION'
.attr '_partDeleted'
.attr 'titel', 'Publikationstitel'
.attr 'position',0
.attr 'autorHrsg', "Autor / Hrsg."
.attr 'verweis', null
.attr 'jahr', 1984
Factory.define 'RawNationaleZuordnung'
.sequence '_partSn'
.attr '_partType', 'LAND_BEZUG'
.attr 'kontinent',1
.attr 'teilkontinent',12
.attr 'land',1
Factory.define 'RawProjekt'
.attr '_partType', 'PRJ'
.attr '_partSn', -1
.attr '_partDeleted', false
.sequence 'id'
.attr 'hasAb',['abschlussbericht'], (ab)-> ab?
.attr 'isRahmenprojekt', false
.attr 'isTeilprojekt',['rahmenprojekt'], (rp)->rp?
.attr 'pstKey', 'ABG'
.attr 'gz', 'GZ 08/15'
.attr 'gzAnzeigen', false
.attr 'wwwAdresse', "http://www.mein-projekt.de"
.attr 'rahmenprojekt',['rahmenprojekt'], (rp)->
if rp? then Factory.build 'RawRahmenprojekt', rp
.attr 'beginn'
.attr 'ende'
.attr 'beteiligteFachrichtungen'
.attr 'titel', ['titel'], (titel)->
Factory.build 'Bilingual', titel ?
de: "Projekttitel"
en: "Project Title"
.attr 'antragsart', 'EIN'
.attr 'abstract', ['abstract'], (abstract)->
if abstract? then Factory.build 'Bilingual', abstract
.attr 'fachklassifikationen', ['fachklassifikationen'], (fks)->
prioSet = (fks ? []).some (fk)->fk.prioritaet
(fks ? [{wissenschaftsbereich:0,fachkollegium:0,fach:0}]).map (d,i)->
if not prioSet and not d.prioritaet?
prioSet=true
d.prioritaet=true
Factory.build 'RawFachklassifikation', d
.attr 'internationalerBezug',['internationalerBezug'], (zs)->
(zs ? []).map (z)->Factory.build 'RawNationaleZuordnung', z
.attr 'programmklassifikation', ['programmklassifikation'], (pkl)->
Factory.build('RawProgrammklassifikation', pkl ? {})
.attr 'perBeteiligungen', ['perBeteiligungen'] , (bets)->
(bets ? []).map (bet)->Factory.build 'RawPersonenbeteiligung', bet
.attr 'insBeteiligungen', ['insBeteiligungen'] , (bets)->
(bets ? []).map (bet)->Factory.build 'RawInstitutionsbeteiligung', bet
.attr 'personen',['perBeteiligungen','personen'], (bets,personen0)->
personen0 ?= {}
personen = {}
for bet in bets
personen[bet.personId]=Factory.build 'RawBeteiligtePerson', {id:bet.personId}
for perId, person of personen0
personen[perId] = Factory.build 'RawBeteiligtePerson', person
personen
.attr 'institutionen',['insBeteiligungen','institutionen'], (bets,institutionen0)->
institutionen0 ?= {}
institutionen = {}
for bet in bets
institutionen[bet.institutionId]=Factory.build 'RawBeteiligteInstitution', {id:bet.institutionId}
for insId, institution of institutionen0
institutionen[insId] = Factory.build 'RawBeteiligteInstitution', institution
institutionen
.attr 'abschlussbericht',['abschlussbericht'],(ab)->
if ab? then Factory.build 'RawAbschlussbericht', ab
postProcess = (name,factory)->
factory.after (obj)->
for attr,value of obj
# raise error if user 'invented' any new attributes
throw new Error("Undeclared attribute #{attr} for factory #{name}") if not factory.attrs[attr]
# remove attributes with undefined value
delete obj[attr] if typeof value == "undefined"
obj
postProcess(name,factory) for name, factory of Factory.factories
| 50998 | Rosie = require "rosie"
Factory = Rosie.Factory
extend = Factory.util.extend
module.exports = Factory
lpad = (pad,num)->(""+pad+num).slice -pad.length
Factory.define 'LookupEntry'
.option 'typeLabel', "Something"
.option 'padding', ""
.option 'defaultKey', null
.sequence 'id'
.attr 'type', ['typeLabel'], (tl)->tl.toLowerCase()
.attr 'key', ['key','padding','id','defaultKey'], (key,padding,id,defaultKey)->
key ? defaultKey ? (lpad padding, id)
Factory.define 'SimpleEntry'
.extend 'LookupEntry'
.attr 'label',['label','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl}"
en: "Label #{tl}"
Factory.define 'ShortLongEntry'
.extend 'LookupEntry'
.attr 'labelShort',['labelShort','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (kurz)"
en: "Label #{tl} (short)"
.attr 'labelLong',['labelLong','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (lang)"
en: "Label #{tl} (long)"
Factory.define 'MaleFemaleEntry'
.extend 'LookupEntry'
.attr 'labelFemale',['labelFemale','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (weibl.)"
en: "Label #{tl} (female)"
.attr 'labelMale',['labelMale','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (männl.)"
en: "Label #{tl} (male)"
defaultLookupEntries = (factory, opts)->
(entries0)->
entries0 ?=
'0': id: 0
entries = {}
for id,entry of entries0
entries[id] = Factory.build factory, entry ,opts
entries
titelEntries = (entries0)->
entries0 ?=
'0':
id: 0
labelMale: de: "Prof."
labelFemale: de: "Prof."
'1':
id: 1
labelMale: de: "Dr."
labelFemale: de:"Dr."
entries = {}
for id,entry of entries0
entries[id] = Factory.build "MaleFemaleEntry", entry , typeLabel:'Titel'
entries
Factory.define 'RawLookup'
.attr 'fach',['fach'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fach'
padding:'00000'
.attr 'fachkollegium', ['fachkollegium'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fachkollegium'
padding:'000'
.attr 'fachgebiet', ['fachgebiet'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fachgebiet'
padding:'00'
.attr 'wissenschaftsbereich', ['wissenschaftsbereich'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Wissenschaftsbereich'
padding:'0'
.attr 'peu', ['peu'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEU'
defaultKey:'XXX'
.attr 'pemu', ['pemu'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEMU'
defaultKey:'XXX'
.attr 'peo', ['peo'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEO'
defaultKey:'XXXX'
.attr 'titel',['titel'], titelEntries
.attr 'bundesland',['bundesland'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Bundesland'
defaultKey:'XXX<KEY>'
.attr 'land',['land'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Land'
defaultKey:'XXX'
.attr 'kontinent',['kontinent'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Kontinent'
defaultKey:'0'
.attr 'teilkontinent',['teilkontinent'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Teilkontinent'
defaultKey:'00'
Factory.define 'RawFachklassifikation'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partType', 'FACHSYSTEMATIK'
.attr 'prioritaet', false
.attr 'wissenschaftsbereich'
.attr 'fachgebiet'
.attr 'fachkollegium'
.attr 'fach'
Factory.define 'RawProgrammklassifikation'
.attr 'peo',0
.attr 'pemu',0
.attr 'peu',0
Factory.define 'Bilingual'
.attr 'de'
.attr 'en'
Factory.define 'RawPersonenbeteiligung'
.attr '_partSn',['personId'], (id)->id
.sequence 'personId'
.attr '_partType', 'PER_BETEILIGUNG'
.attr '_partDeleted', false
.attr 'referent',false
.attr 'verstorben',false
.attr 'showInProjektResultEntry',true
.attr 'style', 'L'
.attr 'btrKey', "PAN"
Factory.define 'RawInstitutionsbeteiligung'
.sequence '_partSn'
.attr '_partType', 'INS_BETEILIGUNG'
.attr 'btrKey', 'IAN'
.attr 'style', 'L'
.sequence 'institutionId'
Factory.define 'TitelTupel'
.attr 'anrede',0
.attr 'teilname',1
Factory.define 'InsTitel'
.attr 'nameRoot', ['nameRoot'], (name)->
Factory.build "Bilingual", name ?
de: 'Name der Wurzelinstitution'
en: 'Name of Root Institution'
.attr 'namePostanschrift', 'Name der Wurzelinstitution, Abteilung, usw'
Factory.define 'GeoLocation'
.attr 'lon'
.attr 'lat'
Factory.define 'RawRahmenprojekt'
.sequence 'id'
.attr 'gz', 'FOO 08/15'
.attr 'gzAnzeigen', false
.attr 'titel', ['titel'], (titel)->
Factory.build "Bilingual", titel ?
de: "Rahmenprojekttitel"
en: "Title of Framework Project"
Factory.define 'RawBeteiligtePerson'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partDeleted', false
.attr '_partType', 'PER'
.attr 'privatanschrift',false
.attr 'vorname', 'Vorname'
.attr 'nachname', 'Nachname'
.attr 'ort', 'Ortsname'
.attr 'ortKey', '<KEY>'
.attr 'plzVorOrt', '00000'
.attr 'plzNachOrt',null
.attr 'titel',['titel'], (titel)->Factory.build 'TitelTupel',titel ? {}
.attr 'geschlecht','m'
.attr 'institution',['institution'], (ins)->Factory.build 'InsTitel', ins ? {}
.attr 'geolocation',['geolocation'], (loc)-> if loc? then Factory.build 'GeoLocation', loc
.attr 'bundesland',0
.attr 'land',0
Factory.define 'RawBeteiligteInstitution'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partType', 'INS'
.attr 'rootId'
.attr 'einrichtungsart', 5
.attr 'bundesland', 'DEU12'
.attr 'ortKey', '<KEY>'
.attr 'ort', 'Potsdam'
.attr 'name',['name'], (name)->
Factory.build 'Bilingual', name ?
de: 'Name der Institution'
en: 'Name of Institution'
.attr 'nameRoot', ['nameRoot'], (name)->
Factory.build "Bilingual", name ?
de: 'Name der Wurzelinstitution'
en: 'Name of Root Institution'
.attr 'namePostanschrift', 'Name der Wurzelinstitution, Abteilung, usw'
.attr 'geolocation',['geolocation'], (loc)-> if loc? then Factory.build 'GeoLocation', loc
Factory.define 'RawAbschlussbericht'
.attr 'datum', 0
.attr 'abstract', ['abstract'], (abs)->
Factory.build 'Bilingual',abs ?
de:'Deutscher AB Abstract'
en:'Englischer AB Abstract'
.attr 'publikationen',['publikationen'], (pubs)->
(pubs ? []).map (pub)->
Factory.build 'RawPublikation',pub
Factory.define 'RawPublikation'
.sequence '_partSn'
.attr '_partType', 'PUBLIKATION'
.attr '_partDeleted'
.attr 'titel', 'Publikationstitel'
.attr 'position',0
.attr 'autorHrsg', "Autor / Hrsg."
.attr 'verweis', null
.attr 'jahr', 1984
Factory.define 'RawNationaleZuordnung'
.sequence '_partSn'
.attr '_partType', 'LAND_BEZUG'
.attr 'kontinent',1
.attr 'teilkontinent',12
.attr 'land',1
Factory.define 'RawProjekt'
.attr '_partType', 'PRJ'
.attr '_partSn', -1
.attr '_partDeleted', false
.sequence 'id'
.attr 'hasAb',['abschlussbericht'], (ab)-> ab?
.attr 'isRahmenprojekt', false
.attr 'isTeilprojekt',['rahmenprojekt'], (rp)->rp?
.attr 'pstKey', '<KEY>'
.attr 'gz', 'GZ 08/15'
.attr 'gzAnzeigen', false
.attr 'wwwAdresse', "http://www.mein-projekt.de"
.attr 'rahmenprojekt',['rahmenprojekt'], (rp)->
if rp? then Factory.build 'RawRahmenprojekt', rp
.attr 'beginn'
.attr 'ende'
.attr 'beteiligteFachrichtungen'
.attr 'titel', ['titel'], (titel)->
Factory.build 'Bilingual', titel ?
de: "Projekttitel"
en: "Project Title"
.attr 'antragsart', 'EIN'
.attr 'abstract', ['abstract'], (abstract)->
if abstract? then Factory.build 'Bilingual', abstract
.attr 'fachklassifikationen', ['fachklassifikationen'], (fks)->
prioSet = (fks ? []).some (fk)->fk.prioritaet
(fks ? [{wissenschaftsbereich:0,fachkollegium:0,fach:0}]).map (d,i)->
if not prioSet and not d.prioritaet?
prioSet=true
d.prioritaet=true
Factory.build 'RawFachklassifikation', d
.attr 'internationalerBezug',['internationalerBezug'], (zs)->
(zs ? []).map (z)->Factory.build 'RawNationaleZuordnung', z
.attr 'programmklassifikation', ['programmklassifikation'], (pkl)->
Factory.build('RawProgrammklassifikation', pkl ? {})
.attr 'perBeteiligungen', ['perBeteiligungen'] , (bets)->
(bets ? []).map (bet)->Factory.build 'RawPersonenbeteiligung', bet
.attr 'insBeteiligungen', ['insBeteiligungen'] , (bets)->
(bets ? []).map (bet)->Factory.build 'RawInstitutionsbeteiligung', bet
.attr 'personen',['perBeteiligungen','personen'], (bets,personen0)->
personen0 ?= {}
personen = {}
for bet in bets
personen[bet.personId]=Factory.build 'RawBeteiligtePerson', {id:bet.personId}
for perId, person of personen0
personen[perId] = Factory.build 'RawBeteiligtePerson', person
personen
.attr 'institutionen',['insBeteiligungen','institutionen'], (bets,institutionen0)->
institutionen0 ?= {}
institutionen = {}
for bet in bets
institutionen[bet.institutionId]=Factory.build 'RawBeteiligteInstitution', {id:bet.institutionId}
for insId, institution of institutionen0
institutionen[insId] = Factory.build 'RawBeteiligteInstitution', institution
institutionen
.attr 'abschlussbericht',['abschlussbericht'],(ab)->
if ab? then Factory.build 'RawAbschlussbericht', ab
postProcess = (name,factory)->
factory.after (obj)->
for attr,value of obj
# raise error if user 'invented' any new attributes
throw new Error("Undeclared attribute #{attr} for factory #{name}") if not factory.attrs[attr]
# remove attributes with undefined value
delete obj[attr] if typeof value == "undefined"
obj
postProcess(name,factory) for name, factory of Factory.factories
| true | Rosie = require "rosie"
Factory = Rosie.Factory
extend = Factory.util.extend
module.exports = Factory
lpad = (pad,num)->(""+pad+num).slice -pad.length
Factory.define 'LookupEntry'
.option 'typeLabel', "Something"
.option 'padding', ""
.option 'defaultKey', null
.sequence 'id'
.attr 'type', ['typeLabel'], (tl)->tl.toLowerCase()
.attr 'key', ['key','padding','id','defaultKey'], (key,padding,id,defaultKey)->
key ? defaultKey ? (lpad padding, id)
Factory.define 'SimpleEntry'
.extend 'LookupEntry'
.attr 'label',['label','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl}"
en: "Label #{tl}"
Factory.define 'ShortLongEntry'
.extend 'LookupEntry'
.attr 'labelShort',['labelShort','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (kurz)"
en: "Label #{tl} (short)"
.attr 'labelLong',['labelLong','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (lang)"
en: "Label #{tl} (long)"
Factory.define 'MaleFemaleEntry'
.extend 'LookupEntry'
.attr 'labelFemale',['labelFemale','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (weibl.)"
en: "Label #{tl} (female)"
.attr 'labelMale',['labelMale','typeLabel'], (label,tl)->
Factory.build 'Bilingual', label ?
de: "Bezeichnung #{tl} (männl.)"
en: "Label #{tl} (male)"
defaultLookupEntries = (factory, opts)->
(entries0)->
entries0 ?=
'0': id: 0
entries = {}
for id,entry of entries0
entries[id] = Factory.build factory, entry ,opts
entries
titelEntries = (entries0)->
entries0 ?=
'0':
id: 0
labelMale: de: "Prof."
labelFemale: de: "Prof."
'1':
id: 1
labelMale: de: "Dr."
labelFemale: de:"Dr."
entries = {}
for id,entry of entries0
entries[id] = Factory.build "MaleFemaleEntry", entry , typeLabel:'Titel'
entries
Factory.define 'RawLookup'
.attr 'fach',['fach'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fach'
padding:'00000'
.attr 'fachkollegium', ['fachkollegium'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fachkollegium'
padding:'000'
.attr 'fachgebiet', ['fachgebiet'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Fachgebiet'
padding:'00'
.attr 'wissenschaftsbereich', ['wissenschaftsbereich'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Wissenschaftsbereich'
padding:'0'
.attr 'peu', ['peu'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEU'
defaultKey:'XXX'
.attr 'pemu', ['pemu'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEMU'
defaultKey:'XXX'
.attr 'peo', ['peo'], defaultLookupEntries 'SimpleEntry',
typeLabel:'PEO'
defaultKey:'XXXX'
.attr 'titel',['titel'], titelEntries
.attr 'bundesland',['bundesland'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Bundesland'
defaultKey:'XXXPI:KEY:<KEY>END_PI'
.attr 'land',['land'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Land'
defaultKey:'XXX'
.attr 'kontinent',['kontinent'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Kontinent'
defaultKey:'0'
.attr 'teilkontinent',['teilkontinent'], defaultLookupEntries 'SimpleEntry',
typeLabel:'Teilkontinent'
defaultKey:'00'
Factory.define 'RawFachklassifikation'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partType', 'FACHSYSTEMATIK'
.attr 'prioritaet', false
.attr 'wissenschaftsbereich'
.attr 'fachgebiet'
.attr 'fachkollegium'
.attr 'fach'
Factory.define 'RawProgrammklassifikation'
.attr 'peo',0
.attr 'pemu',0
.attr 'peu',0
Factory.define 'Bilingual'
.attr 'de'
.attr 'en'
Factory.define 'RawPersonenbeteiligung'
.attr '_partSn',['personId'], (id)->id
.sequence 'personId'
.attr '_partType', 'PER_BETEILIGUNG'
.attr '_partDeleted', false
.attr 'referent',false
.attr 'verstorben',false
.attr 'showInProjektResultEntry',true
.attr 'style', 'L'
.attr 'btrKey', "PAN"
Factory.define 'RawInstitutionsbeteiligung'
.sequence '_partSn'
.attr '_partType', 'INS_BETEILIGUNG'
.attr 'btrKey', 'IAN'
.attr 'style', 'L'
.sequence 'institutionId'
Factory.define 'TitelTupel'
.attr 'anrede',0
.attr 'teilname',1
Factory.define 'InsTitel'
.attr 'nameRoot', ['nameRoot'], (name)->
Factory.build "Bilingual", name ?
de: 'Name der Wurzelinstitution'
en: 'Name of Root Institution'
.attr 'namePostanschrift', 'Name der Wurzelinstitution, Abteilung, usw'
Factory.define 'GeoLocation'
.attr 'lon'
.attr 'lat'
Factory.define 'RawRahmenprojekt'
.sequence 'id'
.attr 'gz', 'FOO 08/15'
.attr 'gzAnzeigen', false
.attr 'titel', ['titel'], (titel)->
Factory.build "Bilingual", titel ?
de: "Rahmenprojekttitel"
en: "Title of Framework Project"
Factory.define 'RawBeteiligtePerson'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partDeleted', false
.attr '_partType', 'PER'
.attr 'privatanschrift',false
.attr 'vorname', 'Vorname'
.attr 'nachname', 'Nachname'
.attr 'ort', 'Ortsname'
.attr 'ortKey', 'PI:KEY:<KEY>END_PI'
.attr 'plzVorOrt', '00000'
.attr 'plzNachOrt',null
.attr 'titel',['titel'], (titel)->Factory.build 'TitelTupel',titel ? {}
.attr 'geschlecht','m'
.attr 'institution',['institution'], (ins)->Factory.build 'InsTitel', ins ? {}
.attr 'geolocation',['geolocation'], (loc)-> if loc? then Factory.build 'GeoLocation', loc
.attr 'bundesland',0
.attr 'land',0
Factory.define 'RawBeteiligteInstitution'
.sequence 'id'
.attr '_partSn',['id'], (id)->id
.attr '_partType', 'INS'
.attr 'rootId'
.attr 'einrichtungsart', 5
.attr 'bundesland', 'DEU12'
.attr 'ortKey', 'PI:KEY:<KEY>END_PI'
.attr 'ort', 'Potsdam'
.attr 'name',['name'], (name)->
Factory.build 'Bilingual', name ?
de: 'Name der Institution'
en: 'Name of Institution'
.attr 'nameRoot', ['nameRoot'], (name)->
Factory.build "Bilingual", name ?
de: 'Name der Wurzelinstitution'
en: 'Name of Root Institution'
.attr 'namePostanschrift', 'Name der Wurzelinstitution, Abteilung, usw'
.attr 'geolocation',['geolocation'], (loc)-> if loc? then Factory.build 'GeoLocation', loc
Factory.define 'RawAbschlussbericht'
.attr 'datum', 0
.attr 'abstract', ['abstract'], (abs)->
Factory.build 'Bilingual',abs ?
de:'Deutscher AB Abstract'
en:'Englischer AB Abstract'
.attr 'publikationen',['publikationen'], (pubs)->
(pubs ? []).map (pub)->
Factory.build 'RawPublikation',pub
Factory.define 'RawPublikation'
.sequence '_partSn'
.attr '_partType', 'PUBLIKATION'
.attr '_partDeleted'
.attr 'titel', 'Publikationstitel'
.attr 'position',0
.attr 'autorHrsg', "Autor / Hrsg."
.attr 'verweis', null
.attr 'jahr', 1984
Factory.define 'RawNationaleZuordnung'
.sequence '_partSn'
.attr '_partType', 'LAND_BEZUG'
.attr 'kontinent',1
.attr 'teilkontinent',12
.attr 'land',1
Factory.define 'RawProjekt'
.attr '_partType', 'PRJ'
.attr '_partSn', -1
.attr '_partDeleted', false
.sequence 'id'
.attr 'hasAb',['abschlussbericht'], (ab)-> ab?
.attr 'isRahmenprojekt', false
.attr 'isTeilprojekt',['rahmenprojekt'], (rp)->rp?
.attr 'pstKey', 'PI:KEY:<KEY>END_PI'
.attr 'gz', 'GZ 08/15'
.attr 'gzAnzeigen', false
.attr 'wwwAdresse', "http://www.mein-projekt.de"
.attr 'rahmenprojekt',['rahmenprojekt'], (rp)->
if rp? then Factory.build 'RawRahmenprojekt', rp
.attr 'beginn'
.attr 'ende'
.attr 'beteiligteFachrichtungen'
.attr 'titel', ['titel'], (titel)->
Factory.build 'Bilingual', titel ?
de: "Projekttitel"
en: "Project Title"
.attr 'antragsart', 'EIN'
.attr 'abstract', ['abstract'], (abstract)->
if abstract? then Factory.build 'Bilingual', abstract
.attr 'fachklassifikationen', ['fachklassifikationen'], (fks)->
prioSet = (fks ? []).some (fk)->fk.prioritaet
(fks ? [{wissenschaftsbereich:0,fachkollegium:0,fach:0}]).map (d,i)->
if not prioSet and not d.prioritaet?
prioSet=true
d.prioritaet=true
Factory.build 'RawFachklassifikation', d
.attr 'internationalerBezug',['internationalerBezug'], (zs)->
(zs ? []).map (z)->Factory.build 'RawNationaleZuordnung', z
.attr 'programmklassifikation', ['programmklassifikation'], (pkl)->
Factory.build('RawProgrammklassifikation', pkl ? {})
.attr 'perBeteiligungen', ['perBeteiligungen'] , (bets)->
(bets ? []).map (bet)->Factory.build 'RawPersonenbeteiligung', bet
.attr 'insBeteiligungen', ['insBeteiligungen'] , (bets)->
(bets ? []).map (bet)->Factory.build 'RawInstitutionsbeteiligung', bet
.attr 'personen',['perBeteiligungen','personen'], (bets,personen0)->
personen0 ?= {}
personen = {}
for bet in bets
personen[bet.personId]=Factory.build 'RawBeteiligtePerson', {id:bet.personId}
for perId, person of personen0
personen[perId] = Factory.build 'RawBeteiligtePerson', person
personen
.attr 'institutionen',['insBeteiligungen','institutionen'], (bets,institutionen0)->
institutionen0 ?= {}
institutionen = {}
for bet in bets
institutionen[bet.institutionId]=Factory.build 'RawBeteiligteInstitution', {id:bet.institutionId}
for insId, institution of institutionen0
institutionen[insId] = Factory.build 'RawBeteiligteInstitution', institution
institutionen
.attr 'abschlussbericht',['abschlussbericht'],(ab)->
if ab? then Factory.build 'RawAbschlussbericht', ab
postProcess = (name,factory)->
factory.after (obj)->
for attr,value of obj
# raise error if user 'invented' any new attributes
throw new Error("Undeclared attribute #{attr} for factory #{name}") if not factory.attrs[attr]
# remove attributes with undefined value
delete obj[attr] if typeof value == "undefined"
obj
postProcess(name,factory) for name, factory of Factory.factories
|
[
{
"context": "ptLogin: ->\n @xession.login \n email: \"test@test.test\"\n password: \"password123\"\n\n transitionT",
"end": 577,
"score": 0.9999039769172668,
"start": 563,
"tag": "EMAIL",
"value": "test@test.test"
},
{
"context": " email: \"test@test.test... | tests/dummy/app/routes/application.coffee | foxnewsnetwork/autox | 0 | `import Ember from 'ember'`
`import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'`
{Route, inject} = Ember
ApplicationRoute = Route.extend ApplicationRouteMixin,
session: inject.service("session")
socket: inject.service("socket")
model: ->
if @get("session.isAuthenicated")
@get "socket"
.connect()
sessionAuthenticated: ->
@refresh()
sessionInvalidated: ->
@refresh()
actions:
attemptLogout: ->
@get("session").invalidate()
attemptLogin: ->
@xession.login
email: "test@test.test"
password: "password123"
transitionTo: ({routeName, model}) ->
@transitionTo routeName, model
shopBubble: ->
console.log "shop bubble in the application"
`export default ApplicationRoute`
| 136732 | `import Ember from 'ember'`
`import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'`
{Route, inject} = Ember
ApplicationRoute = Route.extend ApplicationRouteMixin,
session: inject.service("session")
socket: inject.service("socket")
model: ->
if @get("session.isAuthenicated")
@get "socket"
.connect()
sessionAuthenticated: ->
@refresh()
sessionInvalidated: ->
@refresh()
actions:
attemptLogout: ->
@get("session").invalidate()
attemptLogin: ->
@xession.login
email: "<EMAIL>"
password: "<PASSWORD>"
transitionTo: ({routeName, model}) ->
@transitionTo routeName, model
shopBubble: ->
console.log "shop bubble in the application"
`export default ApplicationRoute`
| true | `import Ember from 'ember'`
`import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'`
{Route, inject} = Ember
ApplicationRoute = Route.extend ApplicationRouteMixin,
session: inject.service("session")
socket: inject.service("socket")
model: ->
if @get("session.isAuthenicated")
@get "socket"
.connect()
sessionAuthenticated: ->
@refresh()
sessionInvalidated: ->
@refresh()
actions:
attemptLogout: ->
@get("session").invalidate()
attemptLogin: ->
@xession.login
email: "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
transitionTo: ({routeName, model}) ->
@transitionTo routeName, model
shopBubble: ->
console.log "shop bubble in the application"
`export default ApplicationRoute`
|
[
{
"context": "base64 encoded or not).\n# Adopted from filer.js by Eric Bidelman (ebidel@gmail.com)\nRW.dataURLToBlob = (dataURL) -",
"end": 4509,
"score": 0.9998682737350464,
"start": 4496,
"tag": "NAME",
"value": "Eric Bidelman"
},
{
"context": "r not).\n# Adopted from filer.js by E... | client/src/app/redWireCommon.coffee | bcfuchs/RedWire | 0 | # Get alias for the global scope
globals = @
# All will be in the "RW" namespace
RW = globals.RW ? {}
globals.RW = RW
# Can be used to mimic enums in JS
# Since this is called by the RW namspace definition below, it must be defined first
RW.makeConstantSet = (values...) ->
obj =
# Checks if the value is in the set
contains: (value) -> return value of obj
for value in values then obj[value] = value
return Object.freeze(obj)
RW.logLevels = RW.makeConstantSet("ERROR", "WARN", "INFO")
RW.signals = RW.makeConstantSet("DONE", "ERROR")
RW.extensions =
IMAGE: ["png", "gif", "jpeg", "jpg"]
JS: ["js"]
CSS: ["css"]
HTML: ["html"]
# Looks for the first element in the array or object which is equal to value, using the _.isEqual() test
# If no element exists, returns -1
RW.indexOf = (collection, value) ->
for k, v of collection
if _.isEqual(v, value) then return k
return -1
# Returns true if the value is in the collection, using the _.isEqual() test
# If no element exists, returns -1
RW.contains = (collection, value) -> RW.indexOf(collection, value) != -1
# Similar to _.uniq(), but tests using the _.isEqual() method
RW.uniq = (array) ->
results = []
seen = []
_.each array, (value, index) ->
if not RW.contains(seen, value)
seen.push(value)
results.push(array[index])
return results
# There is probably a faster way to do this
RW.cloneData = (o) ->
try
JSON.parse(JSON.stringify(o))
catch e
throw new Error("Unable to clone, perhaps it is not plain old data: #{e}")
# Create new array with the value of these arrays
RW.concatenate = (rest...) -> [].concat(rest...)
# Return an array with the new value added
RW.appendToArray = (array, value) -> RW.concatenate(array, [value])
# Return an array with all instances of the element removed
RW.removeFromArray = (array, value) -> return (element for element in array when not _.isEqual(value, element))
# Return an array with a given element removed (by index)
RW.removeIndexFromArray = (array, index) -> return (element for key, element of array when String(index) isnt key)
# If the value is not in the array, then add it, else remove it
RW.toggleValueInArray = (array, value) ->
return if RW.contains(array, value) then RW.removeFromArray(array, value) else RW.appendToArray(array, value)
# Like Underscore's method, but uses RW.indexOf()
RW.intersection = (array) ->
rest = Array.prototype.slice.call(arguments, 1)
return _.filter _.uniq(array), (item) ->
return _.every rest, (other) ->
return RW.indexOf(other, item) >= 0
# Like Underscore's method, but uses RW.contains()
RW.difference = (array) ->
rest = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1))
return _.filter array, (value) ->
return not RW.contains(rest, value)
# Shortcut for timeout function, to avoid trailing the time at the end
RW.doLater = (f) -> setTimeout(f, 0)
# Freeze an object recursively
# Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/freeze
RW.deepFreeze = (o) ->
# First freeze the object
Object.freeze(o)
# Recursively freeze all the object properties
for own key, prop of o
if _.isObject(prop) and not Object.isFrozen(prop) then RW.deepFreeze(prop)
return o
# Shortcut to clone and then freeze result
RW.cloneFrozen = (o) -> return RW.deepFreeze(RW.cloneData(o))
# Adds value to the given object, associating it with an unique (and meaningless) key
# Returns
RW.addUnique = (obj, value) -> obj[_.uniqueId()] = value
# Creates a new object based on the keys and values of the given one.
# Calls f(value, key) for each key
RW.mapObject = (obj, f) ->
mapped = {}
for key, value of obj
mapped[key] = f(value, key)
return mapped
# Creates an object with the provided keys, where map[key] = f(key)
RW.mapToObject = (keys, f) ->
mapped = {}
for key in keys
mapped[key] = f(key)
return mapped
# Returns an object { mimeType: String, base64: Bool, data: String}
RW.splitDataUrl = (url) ->
matches = url.match(/data:([^;]+);([^,]*),(.*)/)
return {
mimeType: matches[1]
base64: matches[2] == "base64"
data: matches[3]
}
# Combine data returned by RW.splitDataUrl back into data url
RW.combineDataUrl = ({ mimeType, base64, data }) ->
return "data:#{mimeType};#{base64 and 'base64' or ''},#{data}"
# Creates and returns a blob from a data URL (either base64 encoded or not).
# Adopted from filer.js by Eric Bidelman (ebidel@gmail.com)
RW.dataURLToBlob = (dataURL) ->
splitUrl = RW.splitDataUrl(dataURL)
if not splitUrl.base64
# Easy case when not Base64 encoded
return new Blob([splitUrl.data], {type: splitUrl.mimeType})
else
# Decode from Base64
raw = window.atob(splitUrl.data)
rawLength = raw.length
uInt8Array = new Uint8Array(rawLength)
for i in [0..rawLength - 1]
uInt8Array[i] = raw.charCodeAt(i)
return new Blob([uInt8Array], {type: splitUrl.mimeType})
# Creates and returns an array buffer (either base64 encoded or not).
# Adopted from filer.js by Eric Bidelman (ebidel@gmail.com)
RW.dataURLToArrayBuffer = (dataURL) ->
splitUrl = RW.splitDataUrl(dataURL)
if not splitUrl.base64
# TODO
throw new Error("not implemented")
# Easy case when not Base64 encoded
return new Blob([splitUrl.data], {type: splitUrl.mimeType})
else
# Decode from Base64
raw = window.atob(splitUrl.data)
rawLength = raw.length
uInt8Array = new Uint8Array(rawLength)
for i in [0..rawLength - 1]
uInt8Array[i] = raw.charCodeAt(i)
return uInt8Array
# For accessing a value within an embedded object or array
# Takes a parent object/array and the "path" as an array
# Returns [parent, key] where parent is the array/object and key is last one required to access the child
RW.getParentAndKey = (parent, pathParts) ->
if pathParts.length is 0 then return [parent, null]
if pathParts.length is 1 then return [parent, pathParts[0]]
if pathParts[0] of parent then return RW.getParentAndKey(parent[pathParts[0]], _.rest(pathParts))
throw new Error("Cannot find intermediate key '#{pathParts[0]}'")
# Return the beginning of a string, up to the first newline
RW.firstLine = (str) ->
index = str.indexOf("\n")
return if index is -1 then str else str.slice(0, index)
# Returns a new object like the old one, but with the new key-value pair set
RW.addToObject = (obj, key, value) ->
newObj = RW.cloneData(obj)
newObj[key] = value
return newObj
# Returns a new object like the old one, but with the value set at a unique key
RW.addUniqueToObject = (obj, value) -> RW.addToObject(obj, _.uniqueId(), value)
# Like _.filter(), but preserves object indexes
RW.filterObject = (obj, predicate) ->
newObj = {}
for key, value of obj
if predicate(value, key) then newObj[key] = value
return newObj
# Returns a string representation of the exception, including stacktrace if available
RW.formatStackTrace = (error) ->
# On Chrome, the stack trace contains everything
if window.chrome then return error.stack
# Otherwise break it down
stack = "#{error.name}: #{error.message}"
if error.stack then stack += "\n" + error.stack
else if error.fileName then stack += " (#{error.fileName}:#{error.lineNumber}.#{error.columnNumber})"
return stack
# Reverses the order of the 1st and 2nd level keys of nested objects
RW.reverseKeys = (obj) ->
newObj = {}
for keyA, valA of obj
for keyB, valB of valA
if keyB not of newObj then newObj[keyB] = {}
newObj[keyB][keyA] = valB
return newObj
# Plucks a single attribute out of the values of obj, compiles them into an object
RW.pluckToObject = (obj, attribute) ->
newObj = {}
for key, val of obj
newObj[key] = val[attribute]
return newObj
# From http://stackoverflow.com/a/2117523/209505
RW.makeGuid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = Math.random()*16|0
v = if c == 'x' then r else (r&0x3|0x8)
return v.toString(16)
| 37038 | # Get alias for the global scope
globals = @
# All will be in the "RW" namespace
RW = globals.RW ? {}
globals.RW = RW
# Can be used to mimic enums in JS
# Since this is called by the RW namspace definition below, it must be defined first
RW.makeConstantSet = (values...) ->
obj =
# Checks if the value is in the set
contains: (value) -> return value of obj
for value in values then obj[value] = value
return Object.freeze(obj)
RW.logLevels = RW.makeConstantSet("ERROR", "WARN", "INFO")
RW.signals = RW.makeConstantSet("DONE", "ERROR")
RW.extensions =
IMAGE: ["png", "gif", "jpeg", "jpg"]
JS: ["js"]
CSS: ["css"]
HTML: ["html"]
# Looks for the first element in the array or object which is equal to value, using the _.isEqual() test
# If no element exists, returns -1
RW.indexOf = (collection, value) ->
for k, v of collection
if _.isEqual(v, value) then return k
return -1
# Returns true if the value is in the collection, using the _.isEqual() test
# If no element exists, returns -1
RW.contains = (collection, value) -> RW.indexOf(collection, value) != -1
# Similar to _.uniq(), but tests using the _.isEqual() method
RW.uniq = (array) ->
results = []
seen = []
_.each array, (value, index) ->
if not RW.contains(seen, value)
seen.push(value)
results.push(array[index])
return results
# There is probably a faster way to do this
RW.cloneData = (o) ->
try
JSON.parse(JSON.stringify(o))
catch e
throw new Error("Unable to clone, perhaps it is not plain old data: #{e}")
# Create new array with the value of these arrays
RW.concatenate = (rest...) -> [].concat(rest...)
# Return an array with the new value added
RW.appendToArray = (array, value) -> RW.concatenate(array, [value])
# Return an array with all instances of the element removed
RW.removeFromArray = (array, value) -> return (element for element in array when not _.isEqual(value, element))
# Return an array with a given element removed (by index)
RW.removeIndexFromArray = (array, index) -> return (element for key, element of array when String(index) isnt key)
# If the value is not in the array, then add it, else remove it
RW.toggleValueInArray = (array, value) ->
return if RW.contains(array, value) then RW.removeFromArray(array, value) else RW.appendToArray(array, value)
# Like Underscore's method, but uses RW.indexOf()
RW.intersection = (array) ->
rest = Array.prototype.slice.call(arguments, 1)
return _.filter _.uniq(array), (item) ->
return _.every rest, (other) ->
return RW.indexOf(other, item) >= 0
# Like Underscore's method, but uses RW.contains()
RW.difference = (array) ->
rest = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1))
return _.filter array, (value) ->
return not RW.contains(rest, value)
# Shortcut for timeout function, to avoid trailing the time at the end
RW.doLater = (f) -> setTimeout(f, 0)
# Freeze an object recursively
# Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/freeze
RW.deepFreeze = (o) ->
# First freeze the object
Object.freeze(o)
# Recursively freeze all the object properties
for own key, prop of o
if _.isObject(prop) and not Object.isFrozen(prop) then RW.deepFreeze(prop)
return o
# Shortcut to clone and then freeze result
RW.cloneFrozen = (o) -> return RW.deepFreeze(RW.cloneData(o))
# Adds value to the given object, associating it with an unique (and meaningless) key
# Returns
RW.addUnique = (obj, value) -> obj[_.uniqueId()] = value
# Creates a new object based on the keys and values of the given one.
# Calls f(value, key) for each key
RW.mapObject = (obj, f) ->
mapped = {}
for key, value of obj
mapped[key] = f(value, key)
return mapped
# Creates an object with the provided keys, where map[key] = f(key)
RW.mapToObject = (keys, f) ->
mapped = {}
for key in keys
mapped[key] = f(key)
return mapped
# Returns an object { mimeType: String, base64: Bool, data: String}
RW.splitDataUrl = (url) ->
matches = url.match(/data:([^;]+);([^,]*),(.*)/)
return {
mimeType: matches[1]
base64: matches[2] == "base64"
data: matches[3]
}
# Combine data returned by RW.splitDataUrl back into data url
RW.combineDataUrl = ({ mimeType, base64, data }) ->
return "data:#{mimeType};#{base64 and 'base64' or ''},#{data}"
# Creates and returns a blob from a data URL (either base64 encoded or not).
# Adopted from filer.js by <NAME> (<EMAIL>)
RW.dataURLToBlob = (dataURL) ->
splitUrl = RW.splitDataUrl(dataURL)
if not splitUrl.base64
# Easy case when not Base64 encoded
return new Blob([splitUrl.data], {type: splitUrl.mimeType})
else
# Decode from Base64
raw = window.atob(splitUrl.data)
rawLength = raw.length
uInt8Array = new Uint8Array(rawLength)
for i in [0..rawLength - 1]
uInt8Array[i] = raw.charCodeAt(i)
return new Blob([uInt8Array], {type: splitUrl.mimeType})
# Creates and returns an array buffer (either base64 encoded or not).
# Adopted from filer.js by <NAME> (<EMAIL>)
RW.dataURLToArrayBuffer = (dataURL) ->
splitUrl = RW.splitDataUrl(dataURL)
if not splitUrl.base64
# TODO
throw new Error("not implemented")
# Easy case when not Base64 encoded
return new Blob([splitUrl.data], {type: splitUrl.mimeType})
else
# Decode from Base64
raw = window.atob(splitUrl.data)
rawLength = raw.length
uInt8Array = new Uint8Array(rawLength)
for i in [0..rawLength - 1]
uInt8Array[i] = raw.charCodeAt(i)
return uInt8Array
# For accessing a value within an embedded object or array
# Takes a parent object/array and the "path" as an array
# Returns [parent, key] where parent is the array/object and key is last one required to access the child
RW.getParentAndKey = (parent, pathParts) ->
if pathParts.length is 0 then return [parent, null]
if pathParts.length is 1 then return [parent, pathParts[0]]
if pathParts[0] of parent then return RW.getParentAndKey(parent[pathParts[0]], _.rest(pathParts))
throw new Error("Cannot find intermediate key '#{pathParts[0]}'")
# Return the beginning of a string, up to the first newline
RW.firstLine = (str) ->
index = str.indexOf("\n")
return if index is -1 then str else str.slice(0, index)
# Returns a new object like the old one, but with the new key-value pair set
RW.addToObject = (obj, key, value) ->
newObj = RW.cloneData(obj)
newObj[key] = value
return newObj
# Returns a new object like the old one, but with the value set at a unique key
RW.addUniqueToObject = (obj, value) -> RW.addToObject(obj, _.uniqueId(), value)
# Like _.filter(), but preserves object indexes
RW.filterObject = (obj, predicate) ->
newObj = {}
for key, value of obj
if predicate(value, key) then newObj[key] = value
return newObj
# Returns a string representation of the exception, including stacktrace if available
RW.formatStackTrace = (error) ->
# On Chrome, the stack trace contains everything
if window.chrome then return error.stack
# Otherwise break it down
stack = "#{error.name}: #{error.message}"
if error.stack then stack += "\n" + error.stack
else if error.fileName then stack += " (#{error.fileName}:#{error.lineNumber}.#{error.columnNumber})"
return stack
# Reverses the order of the 1st and 2nd level keys of nested objects
RW.reverseKeys = (obj) ->
newObj = {}
for keyA, valA of obj
for keyB, valB of valA
if keyB not of newObj then newObj[keyB] = {}
newObj[keyB][keyA] = valB
return newObj
# Plucks a single attribute out of the values of obj, compiles them into an object
RW.pluckToObject = (obj, attribute) ->
newObj = {}
for key, val of obj
newObj[key] = val[attribute]
return newObj
# From http://stackoverflow.com/a/2117523/209505
RW.makeGuid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = Math.random()*16|0
v = if c == 'x' then r else (r&0x3|0x8)
return v.toString(16)
| true | # Get alias for the global scope
globals = @
# All will be in the "RW" namespace
RW = globals.RW ? {}
globals.RW = RW
# Can be used to mimic enums in JS
# Since this is called by the RW namspace definition below, it must be defined first
RW.makeConstantSet = (values...) ->
obj =
# Checks if the value is in the set
contains: (value) -> return value of obj
for value in values then obj[value] = value
return Object.freeze(obj)
RW.logLevels = RW.makeConstantSet("ERROR", "WARN", "INFO")
RW.signals = RW.makeConstantSet("DONE", "ERROR")
RW.extensions =
IMAGE: ["png", "gif", "jpeg", "jpg"]
JS: ["js"]
CSS: ["css"]
HTML: ["html"]
# Looks for the first element in the array or object which is equal to value, using the _.isEqual() test
# If no element exists, returns -1
RW.indexOf = (collection, value) ->
for k, v of collection
if _.isEqual(v, value) then return k
return -1
# Returns true if the value is in the collection, using the _.isEqual() test
# If no element exists, returns -1
RW.contains = (collection, value) -> RW.indexOf(collection, value) != -1
# Similar to _.uniq(), but tests using the _.isEqual() method
RW.uniq = (array) ->
results = []
seen = []
_.each array, (value, index) ->
if not RW.contains(seen, value)
seen.push(value)
results.push(array[index])
return results
# There is probably a faster way to do this
RW.cloneData = (o) ->
try
JSON.parse(JSON.stringify(o))
catch e
throw new Error("Unable to clone, perhaps it is not plain old data: #{e}")
# Create new array with the value of these arrays
RW.concatenate = (rest...) -> [].concat(rest...)
# Return an array with the new value added
RW.appendToArray = (array, value) -> RW.concatenate(array, [value])
# Return an array with all instances of the element removed
RW.removeFromArray = (array, value) -> return (element for element in array when not _.isEqual(value, element))
# Return an array with a given element removed (by index)
RW.removeIndexFromArray = (array, index) -> return (element for key, element of array when String(index) isnt key)
# If the value is not in the array, then add it, else remove it
RW.toggleValueInArray = (array, value) ->
return if RW.contains(array, value) then RW.removeFromArray(array, value) else RW.appendToArray(array, value)
# Like Underscore's method, but uses RW.indexOf()
RW.intersection = (array) ->
rest = Array.prototype.slice.call(arguments, 1)
return _.filter _.uniq(array), (item) ->
return _.every rest, (other) ->
return RW.indexOf(other, item) >= 0
# Like Underscore's method, but uses RW.contains()
RW.difference = (array) ->
rest = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1))
return _.filter array, (value) ->
return not RW.contains(rest, value)
# Shortcut for timeout function, to avoid trailing the time at the end
RW.doLater = (f) -> setTimeout(f, 0)
# Freeze an object recursively
# Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/freeze
RW.deepFreeze = (o) ->
# First freeze the object
Object.freeze(o)
# Recursively freeze all the object properties
for own key, prop of o
if _.isObject(prop) and not Object.isFrozen(prop) then RW.deepFreeze(prop)
return o
# Shortcut to clone and then freeze result
RW.cloneFrozen = (o) -> return RW.deepFreeze(RW.cloneData(o))
# Adds value to the given object, associating it with an unique (and meaningless) key
# Returns
RW.addUnique = (obj, value) -> obj[_.uniqueId()] = value
# Creates a new object based on the keys and values of the given one.
# Calls f(value, key) for each key
RW.mapObject = (obj, f) ->
mapped = {}
for key, value of obj
mapped[key] = f(value, key)
return mapped
# Creates an object with the provided keys, where map[key] = f(key)
RW.mapToObject = (keys, f) ->
mapped = {}
for key in keys
mapped[key] = f(key)
return mapped
# Returns an object { mimeType: String, base64: Bool, data: String}
RW.splitDataUrl = (url) ->
matches = url.match(/data:([^;]+);([^,]*),(.*)/)
return {
mimeType: matches[1]
base64: matches[2] == "base64"
data: matches[3]
}
# Combine data returned by RW.splitDataUrl back into data url
RW.combineDataUrl = ({ mimeType, base64, data }) ->
return "data:#{mimeType};#{base64 and 'base64' or ''},#{data}"
# Creates and returns a blob from a data URL (either base64 encoded or not).
# Adopted from filer.js by PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
RW.dataURLToBlob = (dataURL) ->
splitUrl = RW.splitDataUrl(dataURL)
if not splitUrl.base64
# Easy case when not Base64 encoded
return new Blob([splitUrl.data], {type: splitUrl.mimeType})
else
# Decode from Base64
raw = window.atob(splitUrl.data)
rawLength = raw.length
uInt8Array = new Uint8Array(rawLength)
for i in [0..rawLength - 1]
uInt8Array[i] = raw.charCodeAt(i)
return new Blob([uInt8Array], {type: splitUrl.mimeType})
# Creates and returns an array buffer (either base64 encoded or not).
# Adopted from filer.js by PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
RW.dataURLToArrayBuffer = (dataURL) ->
splitUrl = RW.splitDataUrl(dataURL)
if not splitUrl.base64
# TODO
throw new Error("not implemented")
# Easy case when not Base64 encoded
return new Blob([splitUrl.data], {type: splitUrl.mimeType})
else
# Decode from Base64
raw = window.atob(splitUrl.data)
rawLength = raw.length
uInt8Array = new Uint8Array(rawLength)
for i in [0..rawLength - 1]
uInt8Array[i] = raw.charCodeAt(i)
return uInt8Array
# For accessing a value within an embedded object or array
# Takes a parent object/array and the "path" as an array
# Returns [parent, key] where parent is the array/object and key is last one required to access the child
RW.getParentAndKey = (parent, pathParts) ->
if pathParts.length is 0 then return [parent, null]
if pathParts.length is 1 then return [parent, pathParts[0]]
if pathParts[0] of parent then return RW.getParentAndKey(parent[pathParts[0]], _.rest(pathParts))
throw new Error("Cannot find intermediate key '#{pathParts[0]}'")
# Return the beginning of a string, up to the first newline
RW.firstLine = (str) ->
index = str.indexOf("\n")
return if index is -1 then str else str.slice(0, index)
# Returns a new object like the old one, but with the new key-value pair set
RW.addToObject = (obj, key, value) ->
newObj = RW.cloneData(obj)
newObj[key] = value
return newObj
# Returns a new object like the old one, but with the value set at a unique key
RW.addUniqueToObject = (obj, value) -> RW.addToObject(obj, _.uniqueId(), value)
# Like _.filter(), but preserves object indexes
RW.filterObject = (obj, predicate) ->
newObj = {}
for key, value of obj
if predicate(value, key) then newObj[key] = value
return newObj
# Returns a string representation of the exception, including stacktrace if available
RW.formatStackTrace = (error) ->
# On Chrome, the stack trace contains everything
if window.chrome then return error.stack
# Otherwise break it down
stack = "#{error.name}: #{error.message}"
if error.stack then stack += "\n" + error.stack
else if error.fileName then stack += " (#{error.fileName}:#{error.lineNumber}.#{error.columnNumber})"
return stack
# Reverses the order of the 1st and 2nd level keys of nested objects
RW.reverseKeys = (obj) ->
newObj = {}
for keyA, valA of obj
for keyB, valB of valA
if keyB not of newObj then newObj[keyB] = {}
newObj[keyB][keyA] = valB
return newObj
# Plucks a single attribute out of the values of obj, compiles them into an object
RW.pluckToObject = (obj, attribute) ->
newObj = {}
for key, val of obj
newObj[key] = val[attribute]
return newObj
# From http://stackoverflow.com/a/2117523/209505
RW.makeGuid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = Math.random()*16|0
v = if c == 'x' then r else (r&0x3|0x8)
return v.toString(16)
|
[
{
"context": "\n for key in ['pagePerformanceKey', 'requestsKey']\n if tagOptions[key]?.toString().toLowerC",
"end": 2464,
"score": 0.6361239552497864,
"start": 2461,
"tag": "KEY",
"value": "Key"
}
] | public/bower_components/bucky/bucky.coffee | itsdrewmiller/drewmiller.net | 1 | isServer = module? and not window?.module
if isServer
{XMLHttpRequest} = require('xmlhttprequest')
now = ->
time = process.hrtime()
(time[0] + time[1] / 1e9) * 1000
else
now = ->
window.performance?.now?() ? (+new Date)
# This is used if we can't get the navigationStart time from
# window.performance
initTime = +new Date
extend = (a, objs...) ->
for obj in objs.reverse()
for key, val of obj
a[key] = val
a
log = (msgs...) ->
if console?.log?.call?
console.log msgs...
log.error = (msgs...) ->
if console?.error?.call?
console.error msgs...
exportDef = ->
defaults =
# Where is the Bucky server hosted. This should be both the host and the APP_ROOT (if you've
# defined one). This default assumes its at the same host as your app.
#
# Keep in mind that if you use a different host, CORS will come into play.
host: '/bucky'
# The max time we should wait between sends
maxInterval: 30000
# How long we should wait from getting the last datapoint
# to do a send, if datapoints keep coming in eventually
# the MAX_INTERVAL will trigger a send.
aggregationInterval: 5000
# How many decimal digits should we include in our
# times?
decimalPrecision: 3
# Bucky can automatically report a datapoint of what its response time
# is. This is useful because Bucky returns almost immediately, making
# it's response time a good measure of the user's connection latency.
sendLatency: false
# Downsampling will cause Bucky to only send data 100*SAMPLE percent
# of the time. It is used to reduce the amount of data sent to the backend.
#
# It's not done per datapoint, but per client, so you probably don't want to downsample
# on node (you would be telling a percentage of your servers to not send data).
sample: 1
# Set to false to disable sends (in dev mode for example)
active: true
tagOptions = {}
if not isServer
$tag = document.querySelector('[data-bucky-host],[data-bucky-page],[data-bucky-requests]')
if $tag
tagOptions = {
host: $tag.getAttribute('data-bucky-host')
# These are to allow you to send page peformance data without having to manually call
# the methods.
pagePerformanceKey: $tag.getAttribute('data-bucky-page')
requestsKey: $tag.getAttribute('data-bucky-requests')
}
for key in ['pagePerformanceKey', 'requestsKey']
if tagOptions[key]?.toString().toLowerCase() is 'true' or tagOptions[key] is ''
tagOptions[key] = true
else if tagOptions[key]?.toString().toLowerCase is 'false'
tagOptions[key] = null
options = extend {}, defaults, tagOptions
TYPE_MAP =
'timer': 'ms'
'gauge': 'g'
'counter': 'c'
ACTIVE = options.active
do updateActive = ->
ACTIVE = options.active and Math.random() < options.sample
HISTORY = []
setOptions = (opts) ->
extend options, opts
if 'sample' of opts or 'active' of opts
updateActive()
options
round = (num, precision=options.decimalPrecision) ->
Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision)
queue = {}
enqueue = (path, value, type) ->
return unless ACTIVE
count = 1
if path of queue
# We have multiple of the same datapoint in this queue
if type is 'counter'
# Sum the queue
value += queue[path].value
else
# If it's a timer or a gauge, calculate a running average
count = queue[path].count ? count
count++
value = queue[path].value + (value - queue[path].value) / count
queue[path] = {value, type, count}
do considerSending
sendTimeout = null
maxTimeout = null
flush = ->
clearTimeout sendTimeout
clearTimeout maxTimeout
maxTimeout = null
sendTimeout = null
do sendQueue
considerSending = ->
# We set two different timers, one which resets with every request
# to try to get as many datapoints into each send, and another which
# will force a send if too much time has gone by with continuous
# points coming in.
clearTimeout sendTimeout
sendTimeout = setTimeout flush, options.aggregationInterval
unless maxTimeout?
maxTimeout = setTimeout flush, options.maxInterval
makeRequest = (data) ->
corsSupport = isServer or (window.XMLHttpRequest and (window.XMLHttpRequest.defake or 'withCredentials' of new window.XMLHttpRequest()))
if isServer
sameOrigin = true
else
match = /^(https?:\/\/[^\/]+)/i.exec options.host
if match
# FQDN
origin = match[1]
if origin is "#{ document.location.protocol }//#{ document.location.host }"
sameOrigin = true
else
sameOrigin = false
else
# Relative URL
sameOrigin = true
sendStart = now()
body = ''
for name, val of data
body += "#{ name }:#{ val }\n"
if not sameOrigin and not corsSupport and window?.XDomainRequest?
# CORS support for IE9
req = new window.XDomainRequest
else
req = new (window?.XMLHttpRequest ? XMLHttpRequest)
# Don't track this request with Bucky, as we'd be tracking our own
# sends forever. The latency of this request is independently tracked
# by updateLatency.
req.bucky = {track: false}
req.open 'POST', "#{ options.host }/v1/send", true
req.setRequestHeader 'Content-Type', 'text/plain'
req.addEventListener 'load', ->
updateLatency(now() - sendStart)
, false
req.send body
req
sendQueue = ->
if not ACTIVE
log "Would send bucky queue"
return
out = {}
for key, point of queue
HISTORY.push
path: key
count: point.count
type: point.type
value: point.value
unless TYPE_MAP[point.type]?
log.error "Type #{ point.type } not understood by Bucky"
continue
value = point.value
if point.type in ['gauge', 'timer']
value = round(value)
out[key] = "#{ value }|#{ TYPE_MAP[point.type] }"
if point.count isnt 1
out[key] += "@#{ round(1 / point.count, 5) }"
makeRequest out
queue = {}
latencySent = false
updateLatency = (time) ->
Bucky.latency = time
if options.sendLatency and not latencySent
enqueue 'bucky.latency', time, 'timer'
latencySent = true
# We may be running on node where this process could be around for
# a while, let's send latency updates every five minutes.
setTimeout ->
latencySent = false
, 5*60*1000
makeClient = (prefix='') ->
buildPath = (path) ->
if prefix?.length
prefix + '.' + path
path
send = (path, value, type='gauge') ->
if not value? or not path?
log.error "Can't log #{ path }:#{ value }"
return
enqueue buildPath(path), value, type
timer = {
TIMES: {}
send: (path, duration) ->
send path, duration, 'timer'
time: (path, action, ctx, args...) ->
timer.start path
done = =>
timer.stop path
args.splice(0, 0, done)
action.apply(ctx, args)
timeSync: (path, action, ctx, args...) ->
timer.start path
ret = action.apply(ctx, args)
timer.stop path
ret
wrap: (path, action) ->
if action?
return (args...) ->
timer.timeSync path, action, @, args...
else
return (action) ->
return (args...) ->
timer.timeSync path, action, @, args...
start: (path) ->
timer.TIMES[path] = now()
stop: (path) ->
if not timer.TIMES[path]?
log.error "Timer #{ path } ended without having been started"
return
duration = now() - timer.TIMES[path]
timer.TIMES[path] = undefined
timer.send path, duration
stopwatch: (prefix, start) ->
# A timer that can be stopped multiple times
# If a start time is passed in, it's assumed
# to be millis since the epoch, not the special
# start time `now` uses.
if start?
_now = -> +new Date
else
_now = now
start = _now()
last = start
{
mark: (path, offset=0) ->
end = _now()
if prefix
path = prefix + '.' + path
timer.send path, (end - start + offset)
split: (path, offset=0) ->
end = _now()
if prefix
path = prefix + '.' + path
timer.send path, (end - last + offset)
last = end
}
mark: (path, time) ->
# A timer which always begins at page load
time ?= +new Date
start = timer.navigationStart()
timer.send path, (time - start)
navigationStart: ->
window?.performance?.timing?.navigationStart ? initTime
responseEnd: ->
window?.performance?.timing?.responseEnd ? initTime
now: ->
now()
}
count = (path, count=1) ->
send(path, count, 'counter')
sentPerformanceData = false
sendPagePerformance = (path) ->
return false unless window?.performance?.timing?
return false if sentPerformanceData
if not path or path is true
path = requests.urlToKey(document.location.toString()) + '.page'
if document.readyState in ['uninitialized', 'loading']
# The data isn't fully ready until document load
document.addEventListener? 'DOMContentLoaded', =>
sendPagePerformance.call(@, path)
, false
return false
sentPerformanceData = true
start = window.performance.timing.navigationStart
for key, time of window.performance.timing when time
timer.send "#{ path }.#{ key }", (time - start)
return true
requests = {
transforms:
mapping:
guid: /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ig
sha1: /\/[0-9a-f]{40}/ig
md5: /\/[0-9a-f]{32}/ig
id: /\/[0-9;_\-]+/g
email: /\/[^/]+@[^/]+/g
domain: [/\/[^/]+\.[a-z]{2,3}\//ig, '/']
enabled: ['guid', 'sha1', 'md5', 'id', 'email', 'domain']
enable: (name, test, replacement='') ->
if test?
@mapping[name] = [test, replacement]
@enabled.splice 0, 0, name
disable: (name) ->
for val, i of @enabled
if val is name
@enabled.splice i, 1
return
sendReadyStateTimes: (path, times) ->
return unless times?
codeMapping =
1: 'sending'
2: 'headers'
3: 'waiting'
4: 'receiving'
diffs = {}
last = null
for code, time of times
if last? and codeMapping[code]?
diffs[codeMapping[code]] = time - last
last = time
for status, val of diffs
timer.send "#{ path }.#{ status }", val
urlToKey: (url, type, root) ->
url = url.replace /https?:\/\//i, ''
parsedUrl = /([^/:]*)(?::\d+)?(\/[^\?#]*)?.*/i.exec(url)
host = parsedUrl[1]
path = parsedUrl[2] ? ''
for mappingName in requests.transforms.enabled
mapping = requests.transforms.mapping[mappingName]
if not mapping?
log.error "Bucky Error: Attempted to enable a mapping which is not defined: #{ mappingName }"
continue
if typeof mapping is 'function'
path = mapping path, url, type, root
continue
if mapping instanceof RegExp
mapping = [mapping, '']
path = path.replace(mapping[0], mapping[1])
path = decodeURIComponent(path)
path = path.replace(/[^a-zA-Z0-9\-\.\/ ]+/g, '_')
stat = host + path.replace(/[\/ ]/g, '.')
stat = stat.replace /(^\.)|(\.$)/g, ''
stat = stat.replace /\.com/, ''
stat = stat.replace /www\./, ''
if root
stat = root + '.' + stat
if type
stat = stat + '.' + type.toLowerCase()
stat = stat.replace /\.\./g, '.'
stat
getFullUrl: (url, location=document.location) ->
if /^\//.test(url)
location.hostname + url
else if not /https?:\/\//i.test(url)
location.toString() + url
else
url
monitor: (root) ->
if not root or root is true
root = requests.urlToKey(document.location.toString()) + '.requests'
self = this
done = ({type, url, event, request, readyStateTimes, startTime}) ->
if startTime?
dur = now() - startTime
else
return
url = self.getFullUrl url
stat = self.urlToKey url, type, root
send(stat, dur, 'timer')
self.sendReadyStateTimes stat, readyStateTimes
if request?.status?
if request.status > 12000
# Most browsers return status code 0 for aborted/failed requests. IE returns
# special status codes over 12000: http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx
#
# We'll track the 12xxx code, but also store it as a 0
count("#{ stat }.0")
else if request.status isnt 0
count("#{ stat }.#{ request.status.toString().charAt(0) }xx")
count("#{ stat }.#{ request.status }")
_XMLHttpRequest = window.XMLHttpRequest
window.XMLHttpRequest = ->
req = new _XMLHttpRequest
try
startTime = null
readyStateTimes = {}
_open = req.open
req.open = (type, url, async) ->
try
readyStateTimes[0] = now()
req.addEventListener 'readystatechange', ->
readyStateTimes[req.readyState] = now()
, false
req.addEventListener 'loadend', (event) ->
if not req.bucky? or req.bucky.track isnt false
done {type, url, event, startTime, readyStateTimes, request: req}
, false
catch e
log.error "Bucky error monitoring XHR open call", e
_open.apply req, arguments
_send = req.send
req.send = ->
startTime = now()
_send.apply req, arguments
catch e
log.error "Bucky error monitoring XHR", e
req
}
nextMakeClient = (nextPrefix='') ->
path = prefix ? ''
path += '.' if path and nextPrefix
path += nextPrefix if nextPrefix
makeClient(path)
exports = {
send,
count,
timer,
now,
requests,
sendPagePerformance,
flush,
setOptions,
options,
history: HISTORY,
active: ACTIVE
}
for key, val of exports
nextMakeClient[key] = val
nextMakeClient
client = makeClient()
if options.pagePerformanceKey
client.sendPagePerformance(options.pagePerformanceKey)
if options.requestsKey
client.requests.monitor(options.requestsKey)
client
if typeof define is 'function' and define.amd
# AMD
define exportDef
else if typeof exports is 'object'
# Node
module.exports = exportDef()
else
# Global
window.Bucky = exportDef()
| 182378 | isServer = module? and not window?.module
if isServer
{XMLHttpRequest} = require('xmlhttprequest')
now = ->
time = process.hrtime()
(time[0] + time[1] / 1e9) * 1000
else
now = ->
window.performance?.now?() ? (+new Date)
# This is used if we can't get the navigationStart time from
# window.performance
initTime = +new Date
extend = (a, objs...) ->
for obj in objs.reverse()
for key, val of obj
a[key] = val
a
log = (msgs...) ->
if console?.log?.call?
console.log msgs...
log.error = (msgs...) ->
if console?.error?.call?
console.error msgs...
exportDef = ->
defaults =
# Where is the Bucky server hosted. This should be both the host and the APP_ROOT (if you've
# defined one). This default assumes its at the same host as your app.
#
# Keep in mind that if you use a different host, CORS will come into play.
host: '/bucky'
# The max time we should wait between sends
maxInterval: 30000
# How long we should wait from getting the last datapoint
# to do a send, if datapoints keep coming in eventually
# the MAX_INTERVAL will trigger a send.
aggregationInterval: 5000
# How many decimal digits should we include in our
# times?
decimalPrecision: 3
# Bucky can automatically report a datapoint of what its response time
# is. This is useful because Bucky returns almost immediately, making
# it's response time a good measure of the user's connection latency.
sendLatency: false
# Downsampling will cause Bucky to only send data 100*SAMPLE percent
# of the time. It is used to reduce the amount of data sent to the backend.
#
# It's not done per datapoint, but per client, so you probably don't want to downsample
# on node (you would be telling a percentage of your servers to not send data).
sample: 1
# Set to false to disable sends (in dev mode for example)
active: true
tagOptions = {}
if not isServer
$tag = document.querySelector('[data-bucky-host],[data-bucky-page],[data-bucky-requests]')
if $tag
tagOptions = {
host: $tag.getAttribute('data-bucky-host')
# These are to allow you to send page peformance data without having to manually call
# the methods.
pagePerformanceKey: $tag.getAttribute('data-bucky-page')
requestsKey: $tag.getAttribute('data-bucky-requests')
}
for key in ['pagePerformanceKey', 'requests<KEY>']
if tagOptions[key]?.toString().toLowerCase() is 'true' or tagOptions[key] is ''
tagOptions[key] = true
else if tagOptions[key]?.toString().toLowerCase is 'false'
tagOptions[key] = null
options = extend {}, defaults, tagOptions
TYPE_MAP =
'timer': 'ms'
'gauge': 'g'
'counter': 'c'
ACTIVE = options.active
do updateActive = ->
ACTIVE = options.active and Math.random() < options.sample
HISTORY = []
setOptions = (opts) ->
extend options, opts
if 'sample' of opts or 'active' of opts
updateActive()
options
round = (num, precision=options.decimalPrecision) ->
Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision)
queue = {}
enqueue = (path, value, type) ->
return unless ACTIVE
count = 1
if path of queue
# We have multiple of the same datapoint in this queue
if type is 'counter'
# Sum the queue
value += queue[path].value
else
# If it's a timer or a gauge, calculate a running average
count = queue[path].count ? count
count++
value = queue[path].value + (value - queue[path].value) / count
queue[path] = {value, type, count}
do considerSending
sendTimeout = null
maxTimeout = null
flush = ->
clearTimeout sendTimeout
clearTimeout maxTimeout
maxTimeout = null
sendTimeout = null
do sendQueue
considerSending = ->
# We set two different timers, one which resets with every request
# to try to get as many datapoints into each send, and another which
# will force a send if too much time has gone by with continuous
# points coming in.
clearTimeout sendTimeout
sendTimeout = setTimeout flush, options.aggregationInterval
unless maxTimeout?
maxTimeout = setTimeout flush, options.maxInterval
makeRequest = (data) ->
corsSupport = isServer or (window.XMLHttpRequest and (window.XMLHttpRequest.defake or 'withCredentials' of new window.XMLHttpRequest()))
if isServer
sameOrigin = true
else
match = /^(https?:\/\/[^\/]+)/i.exec options.host
if match
# FQDN
origin = match[1]
if origin is "#{ document.location.protocol }//#{ document.location.host }"
sameOrigin = true
else
sameOrigin = false
else
# Relative URL
sameOrigin = true
sendStart = now()
body = ''
for name, val of data
body += "#{ name }:#{ val }\n"
if not sameOrigin and not corsSupport and window?.XDomainRequest?
# CORS support for IE9
req = new window.XDomainRequest
else
req = new (window?.XMLHttpRequest ? XMLHttpRequest)
# Don't track this request with Bucky, as we'd be tracking our own
# sends forever. The latency of this request is independently tracked
# by updateLatency.
req.bucky = {track: false}
req.open 'POST', "#{ options.host }/v1/send", true
req.setRequestHeader 'Content-Type', 'text/plain'
req.addEventListener 'load', ->
updateLatency(now() - sendStart)
, false
req.send body
req
sendQueue = ->
if not ACTIVE
log "Would send bucky queue"
return
out = {}
for key, point of queue
HISTORY.push
path: key
count: point.count
type: point.type
value: point.value
unless TYPE_MAP[point.type]?
log.error "Type #{ point.type } not understood by Bucky"
continue
value = point.value
if point.type in ['gauge', 'timer']
value = round(value)
out[key] = "#{ value }|#{ TYPE_MAP[point.type] }"
if point.count isnt 1
out[key] += "@#{ round(1 / point.count, 5) }"
makeRequest out
queue = {}
latencySent = false
updateLatency = (time) ->
Bucky.latency = time
if options.sendLatency and not latencySent
enqueue 'bucky.latency', time, 'timer'
latencySent = true
# We may be running on node where this process could be around for
# a while, let's send latency updates every five minutes.
setTimeout ->
latencySent = false
, 5*60*1000
makeClient = (prefix='') ->
buildPath = (path) ->
if prefix?.length
prefix + '.' + path
path
send = (path, value, type='gauge') ->
if not value? or not path?
log.error "Can't log #{ path }:#{ value }"
return
enqueue buildPath(path), value, type
timer = {
TIMES: {}
send: (path, duration) ->
send path, duration, 'timer'
time: (path, action, ctx, args...) ->
timer.start path
done = =>
timer.stop path
args.splice(0, 0, done)
action.apply(ctx, args)
timeSync: (path, action, ctx, args...) ->
timer.start path
ret = action.apply(ctx, args)
timer.stop path
ret
wrap: (path, action) ->
if action?
return (args...) ->
timer.timeSync path, action, @, args...
else
return (action) ->
return (args...) ->
timer.timeSync path, action, @, args...
start: (path) ->
timer.TIMES[path] = now()
stop: (path) ->
if not timer.TIMES[path]?
log.error "Timer #{ path } ended without having been started"
return
duration = now() - timer.TIMES[path]
timer.TIMES[path] = undefined
timer.send path, duration
stopwatch: (prefix, start) ->
# A timer that can be stopped multiple times
# If a start time is passed in, it's assumed
# to be millis since the epoch, not the special
# start time `now` uses.
if start?
_now = -> +new Date
else
_now = now
start = _now()
last = start
{
mark: (path, offset=0) ->
end = _now()
if prefix
path = prefix + '.' + path
timer.send path, (end - start + offset)
split: (path, offset=0) ->
end = _now()
if prefix
path = prefix + '.' + path
timer.send path, (end - last + offset)
last = end
}
mark: (path, time) ->
# A timer which always begins at page load
time ?= +new Date
start = timer.navigationStart()
timer.send path, (time - start)
navigationStart: ->
window?.performance?.timing?.navigationStart ? initTime
responseEnd: ->
window?.performance?.timing?.responseEnd ? initTime
now: ->
now()
}
count = (path, count=1) ->
send(path, count, 'counter')
sentPerformanceData = false
sendPagePerformance = (path) ->
return false unless window?.performance?.timing?
return false if sentPerformanceData
if not path or path is true
path = requests.urlToKey(document.location.toString()) + '.page'
if document.readyState in ['uninitialized', 'loading']
# The data isn't fully ready until document load
document.addEventListener? 'DOMContentLoaded', =>
sendPagePerformance.call(@, path)
, false
return false
sentPerformanceData = true
start = window.performance.timing.navigationStart
for key, time of window.performance.timing when time
timer.send "#{ path }.#{ key }", (time - start)
return true
requests = {
transforms:
mapping:
guid: /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ig
sha1: /\/[0-9a-f]{40}/ig
md5: /\/[0-9a-f]{32}/ig
id: /\/[0-9;_\-]+/g
email: /\/[^/]+@[^/]+/g
domain: [/\/[^/]+\.[a-z]{2,3}\//ig, '/']
enabled: ['guid', 'sha1', 'md5', 'id', 'email', 'domain']
enable: (name, test, replacement='') ->
if test?
@mapping[name] = [test, replacement]
@enabled.splice 0, 0, name
disable: (name) ->
for val, i of @enabled
if val is name
@enabled.splice i, 1
return
sendReadyStateTimes: (path, times) ->
return unless times?
codeMapping =
1: 'sending'
2: 'headers'
3: 'waiting'
4: 'receiving'
diffs = {}
last = null
for code, time of times
if last? and codeMapping[code]?
diffs[codeMapping[code]] = time - last
last = time
for status, val of diffs
timer.send "#{ path }.#{ status }", val
urlToKey: (url, type, root) ->
url = url.replace /https?:\/\//i, ''
parsedUrl = /([^/:]*)(?::\d+)?(\/[^\?#]*)?.*/i.exec(url)
host = parsedUrl[1]
path = parsedUrl[2] ? ''
for mappingName in requests.transforms.enabled
mapping = requests.transforms.mapping[mappingName]
if not mapping?
log.error "Bucky Error: Attempted to enable a mapping which is not defined: #{ mappingName }"
continue
if typeof mapping is 'function'
path = mapping path, url, type, root
continue
if mapping instanceof RegExp
mapping = [mapping, '']
path = path.replace(mapping[0], mapping[1])
path = decodeURIComponent(path)
path = path.replace(/[^a-zA-Z0-9\-\.\/ ]+/g, '_')
stat = host + path.replace(/[\/ ]/g, '.')
stat = stat.replace /(^\.)|(\.$)/g, ''
stat = stat.replace /\.com/, ''
stat = stat.replace /www\./, ''
if root
stat = root + '.' + stat
if type
stat = stat + '.' + type.toLowerCase()
stat = stat.replace /\.\./g, '.'
stat
getFullUrl: (url, location=document.location) ->
if /^\//.test(url)
location.hostname + url
else if not /https?:\/\//i.test(url)
location.toString() + url
else
url
monitor: (root) ->
if not root or root is true
root = requests.urlToKey(document.location.toString()) + '.requests'
self = this
done = ({type, url, event, request, readyStateTimes, startTime}) ->
if startTime?
dur = now() - startTime
else
return
url = self.getFullUrl url
stat = self.urlToKey url, type, root
send(stat, dur, 'timer')
self.sendReadyStateTimes stat, readyStateTimes
if request?.status?
if request.status > 12000
# Most browsers return status code 0 for aborted/failed requests. IE returns
# special status codes over 12000: http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx
#
# We'll track the 12xxx code, but also store it as a 0
count("#{ stat }.0")
else if request.status isnt 0
count("#{ stat }.#{ request.status.toString().charAt(0) }xx")
count("#{ stat }.#{ request.status }")
_XMLHttpRequest = window.XMLHttpRequest
window.XMLHttpRequest = ->
req = new _XMLHttpRequest
try
startTime = null
readyStateTimes = {}
_open = req.open
req.open = (type, url, async) ->
try
readyStateTimes[0] = now()
req.addEventListener 'readystatechange', ->
readyStateTimes[req.readyState] = now()
, false
req.addEventListener 'loadend', (event) ->
if not req.bucky? or req.bucky.track isnt false
done {type, url, event, startTime, readyStateTimes, request: req}
, false
catch e
log.error "Bucky error monitoring XHR open call", e
_open.apply req, arguments
_send = req.send
req.send = ->
startTime = now()
_send.apply req, arguments
catch e
log.error "Bucky error monitoring XHR", e
req
}
nextMakeClient = (nextPrefix='') ->
path = prefix ? ''
path += '.' if path and nextPrefix
path += nextPrefix if nextPrefix
makeClient(path)
exports = {
send,
count,
timer,
now,
requests,
sendPagePerformance,
flush,
setOptions,
options,
history: HISTORY,
active: ACTIVE
}
for key, val of exports
nextMakeClient[key] = val
nextMakeClient
client = makeClient()
if options.pagePerformanceKey
client.sendPagePerformance(options.pagePerformanceKey)
if options.requestsKey
client.requests.monitor(options.requestsKey)
client
if typeof define is 'function' and define.amd
# AMD
define exportDef
else if typeof exports is 'object'
# Node
module.exports = exportDef()
else
# Global
window.Bucky = exportDef()
| true | isServer = module? and not window?.module
if isServer
{XMLHttpRequest} = require('xmlhttprequest')
now = ->
time = process.hrtime()
(time[0] + time[1] / 1e9) * 1000
else
now = ->
window.performance?.now?() ? (+new Date)
# This is used if we can't get the navigationStart time from
# window.performance
initTime = +new Date
extend = (a, objs...) ->
for obj in objs.reverse()
for key, val of obj
a[key] = val
a
log = (msgs...) ->
if console?.log?.call?
console.log msgs...
log.error = (msgs...) ->
if console?.error?.call?
console.error msgs...
exportDef = ->
defaults =
# Where is the Bucky server hosted. This should be both the host and the APP_ROOT (if you've
# defined one). This default assumes its at the same host as your app.
#
# Keep in mind that if you use a different host, CORS will come into play.
host: '/bucky'
# The max time we should wait between sends
maxInterval: 30000
# How long we should wait from getting the last datapoint
# to do a send, if datapoints keep coming in eventually
# the MAX_INTERVAL will trigger a send.
aggregationInterval: 5000
# How many decimal digits should we include in our
# times?
decimalPrecision: 3
# Bucky can automatically report a datapoint of what its response time
# is. This is useful because Bucky returns almost immediately, making
# it's response time a good measure of the user's connection latency.
sendLatency: false
# Downsampling will cause Bucky to only send data 100*SAMPLE percent
# of the time. It is used to reduce the amount of data sent to the backend.
#
# It's not done per datapoint, but per client, so you probably don't want to downsample
# on node (you would be telling a percentage of your servers to not send data).
sample: 1
# Set to false to disable sends (in dev mode for example)
active: true
tagOptions = {}
if not isServer
$tag = document.querySelector('[data-bucky-host],[data-bucky-page],[data-bucky-requests]')
if $tag
tagOptions = {
host: $tag.getAttribute('data-bucky-host')
# These are to allow you to send page peformance data without having to manually call
# the methods.
pagePerformanceKey: $tag.getAttribute('data-bucky-page')
requestsKey: $tag.getAttribute('data-bucky-requests')
}
for key in ['pagePerformanceKey', 'requestsPI:KEY:<KEY>END_PI']
if tagOptions[key]?.toString().toLowerCase() is 'true' or tagOptions[key] is ''
tagOptions[key] = true
else if tagOptions[key]?.toString().toLowerCase is 'false'
tagOptions[key] = null
options = extend {}, defaults, tagOptions
TYPE_MAP =
'timer': 'ms'
'gauge': 'g'
'counter': 'c'
ACTIVE = options.active
do updateActive = ->
ACTIVE = options.active and Math.random() < options.sample
HISTORY = []
setOptions = (opts) ->
extend options, opts
if 'sample' of opts or 'active' of opts
updateActive()
options
round = (num, precision=options.decimalPrecision) ->
Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision)
queue = {}
enqueue = (path, value, type) ->
return unless ACTIVE
count = 1
if path of queue
# We have multiple of the same datapoint in this queue
if type is 'counter'
# Sum the queue
value += queue[path].value
else
# If it's a timer or a gauge, calculate a running average
count = queue[path].count ? count
count++
value = queue[path].value + (value - queue[path].value) / count
queue[path] = {value, type, count}
do considerSending
sendTimeout = null
maxTimeout = null
flush = ->
clearTimeout sendTimeout
clearTimeout maxTimeout
maxTimeout = null
sendTimeout = null
do sendQueue
considerSending = ->
# We set two different timers, one which resets with every request
# to try to get as many datapoints into each send, and another which
# will force a send if too much time has gone by with continuous
# points coming in.
clearTimeout sendTimeout
sendTimeout = setTimeout flush, options.aggregationInterval
unless maxTimeout?
maxTimeout = setTimeout flush, options.maxInterval
makeRequest = (data) ->
corsSupport = isServer or (window.XMLHttpRequest and (window.XMLHttpRequest.defake or 'withCredentials' of new window.XMLHttpRequest()))
if isServer
sameOrigin = true
else
match = /^(https?:\/\/[^\/]+)/i.exec options.host
if match
# FQDN
origin = match[1]
if origin is "#{ document.location.protocol }//#{ document.location.host }"
sameOrigin = true
else
sameOrigin = false
else
# Relative URL
sameOrigin = true
sendStart = now()
body = ''
for name, val of data
body += "#{ name }:#{ val }\n"
if not sameOrigin and not corsSupport and window?.XDomainRequest?
# CORS support for IE9
req = new window.XDomainRequest
else
req = new (window?.XMLHttpRequest ? XMLHttpRequest)
# Don't track this request with Bucky, as we'd be tracking our own
# sends forever. The latency of this request is independently tracked
# by updateLatency.
req.bucky = {track: false}
req.open 'POST', "#{ options.host }/v1/send", true
req.setRequestHeader 'Content-Type', 'text/plain'
req.addEventListener 'load', ->
updateLatency(now() - sendStart)
, false
req.send body
req
sendQueue = ->
if not ACTIVE
log "Would send bucky queue"
return
out = {}
for key, point of queue
HISTORY.push
path: key
count: point.count
type: point.type
value: point.value
unless TYPE_MAP[point.type]?
log.error "Type #{ point.type } not understood by Bucky"
continue
value = point.value
if point.type in ['gauge', 'timer']
value = round(value)
out[key] = "#{ value }|#{ TYPE_MAP[point.type] }"
if point.count isnt 1
out[key] += "@#{ round(1 / point.count, 5) }"
makeRequest out
queue = {}
latencySent = false
updateLatency = (time) ->
Bucky.latency = time
if options.sendLatency and not latencySent
enqueue 'bucky.latency', time, 'timer'
latencySent = true
# We may be running on node where this process could be around for
# a while, let's send latency updates every five minutes.
setTimeout ->
latencySent = false
, 5*60*1000
makeClient = (prefix='') ->
buildPath = (path) ->
if prefix?.length
prefix + '.' + path
path
send = (path, value, type='gauge') ->
if not value? or not path?
log.error "Can't log #{ path }:#{ value }"
return
enqueue buildPath(path), value, type
timer = {
TIMES: {}
send: (path, duration) ->
send path, duration, 'timer'
time: (path, action, ctx, args...) ->
timer.start path
done = =>
timer.stop path
args.splice(0, 0, done)
action.apply(ctx, args)
timeSync: (path, action, ctx, args...) ->
timer.start path
ret = action.apply(ctx, args)
timer.stop path
ret
wrap: (path, action) ->
if action?
return (args...) ->
timer.timeSync path, action, @, args...
else
return (action) ->
return (args...) ->
timer.timeSync path, action, @, args...
start: (path) ->
timer.TIMES[path] = now()
stop: (path) ->
if not timer.TIMES[path]?
log.error "Timer #{ path } ended without having been started"
return
duration = now() - timer.TIMES[path]
timer.TIMES[path] = undefined
timer.send path, duration
stopwatch: (prefix, start) ->
# A timer that can be stopped multiple times
# If a start time is passed in, it's assumed
# to be millis since the epoch, not the special
# start time `now` uses.
if start?
_now = -> +new Date
else
_now = now
start = _now()
last = start
{
mark: (path, offset=0) ->
end = _now()
if prefix
path = prefix + '.' + path
timer.send path, (end - start + offset)
split: (path, offset=0) ->
end = _now()
if prefix
path = prefix + '.' + path
timer.send path, (end - last + offset)
last = end
}
mark: (path, time) ->
# A timer which always begins at page load
time ?= +new Date
start = timer.navigationStart()
timer.send path, (time - start)
navigationStart: ->
window?.performance?.timing?.navigationStart ? initTime
responseEnd: ->
window?.performance?.timing?.responseEnd ? initTime
now: ->
now()
}
count = (path, count=1) ->
send(path, count, 'counter')
sentPerformanceData = false
sendPagePerformance = (path) ->
return false unless window?.performance?.timing?
return false if sentPerformanceData
if not path or path is true
path = requests.urlToKey(document.location.toString()) + '.page'
if document.readyState in ['uninitialized', 'loading']
# The data isn't fully ready until document load
document.addEventListener? 'DOMContentLoaded', =>
sendPagePerformance.call(@, path)
, false
return false
sentPerformanceData = true
start = window.performance.timing.navigationStart
for key, time of window.performance.timing when time
timer.send "#{ path }.#{ key }", (time - start)
return true
requests = {
transforms:
mapping:
guid: /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ig
sha1: /\/[0-9a-f]{40}/ig
md5: /\/[0-9a-f]{32}/ig
id: /\/[0-9;_\-]+/g
email: /\/[^/]+@[^/]+/g
domain: [/\/[^/]+\.[a-z]{2,3}\//ig, '/']
enabled: ['guid', 'sha1', 'md5', 'id', 'email', 'domain']
enable: (name, test, replacement='') ->
if test?
@mapping[name] = [test, replacement]
@enabled.splice 0, 0, name
disable: (name) ->
for val, i of @enabled
if val is name
@enabled.splice i, 1
return
sendReadyStateTimes: (path, times) ->
return unless times?
codeMapping =
1: 'sending'
2: 'headers'
3: 'waiting'
4: 'receiving'
diffs = {}
last = null
for code, time of times
if last? and codeMapping[code]?
diffs[codeMapping[code]] = time - last
last = time
for status, val of diffs
timer.send "#{ path }.#{ status }", val
urlToKey: (url, type, root) ->
url = url.replace /https?:\/\//i, ''
parsedUrl = /([^/:]*)(?::\d+)?(\/[^\?#]*)?.*/i.exec(url)
host = parsedUrl[1]
path = parsedUrl[2] ? ''
for mappingName in requests.transforms.enabled
mapping = requests.transforms.mapping[mappingName]
if not mapping?
log.error "Bucky Error: Attempted to enable a mapping which is not defined: #{ mappingName }"
continue
if typeof mapping is 'function'
path = mapping path, url, type, root
continue
if mapping instanceof RegExp
mapping = [mapping, '']
path = path.replace(mapping[0], mapping[1])
path = decodeURIComponent(path)
path = path.replace(/[^a-zA-Z0-9\-\.\/ ]+/g, '_')
stat = host + path.replace(/[\/ ]/g, '.')
stat = stat.replace /(^\.)|(\.$)/g, ''
stat = stat.replace /\.com/, ''
stat = stat.replace /www\./, ''
if root
stat = root + '.' + stat
if type
stat = stat + '.' + type.toLowerCase()
stat = stat.replace /\.\./g, '.'
stat
getFullUrl: (url, location=document.location) ->
if /^\//.test(url)
location.hostname + url
else if not /https?:\/\//i.test(url)
location.toString() + url
else
url
monitor: (root) ->
if not root or root is true
root = requests.urlToKey(document.location.toString()) + '.requests'
self = this
done = ({type, url, event, request, readyStateTimes, startTime}) ->
if startTime?
dur = now() - startTime
else
return
url = self.getFullUrl url
stat = self.urlToKey url, type, root
send(stat, dur, 'timer')
self.sendReadyStateTimes stat, readyStateTimes
if request?.status?
if request.status > 12000
# Most browsers return status code 0 for aborted/failed requests. IE returns
# special status codes over 12000: http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx
#
# We'll track the 12xxx code, but also store it as a 0
count("#{ stat }.0")
else if request.status isnt 0
count("#{ stat }.#{ request.status.toString().charAt(0) }xx")
count("#{ stat }.#{ request.status }")
_XMLHttpRequest = window.XMLHttpRequest
window.XMLHttpRequest = ->
req = new _XMLHttpRequest
try
startTime = null
readyStateTimes = {}
_open = req.open
req.open = (type, url, async) ->
try
readyStateTimes[0] = now()
req.addEventListener 'readystatechange', ->
readyStateTimes[req.readyState] = now()
, false
req.addEventListener 'loadend', (event) ->
if not req.bucky? or req.bucky.track isnt false
done {type, url, event, startTime, readyStateTimes, request: req}
, false
catch e
log.error "Bucky error monitoring XHR open call", e
_open.apply req, arguments
_send = req.send
req.send = ->
startTime = now()
_send.apply req, arguments
catch e
log.error "Bucky error monitoring XHR", e
req
}
nextMakeClient = (nextPrefix='') ->
path = prefix ? ''
path += '.' if path and nextPrefix
path += nextPrefix if nextPrefix
makeClient(path)
exports = {
send,
count,
timer,
now,
requests,
sendPagePerformance,
flush,
setOptions,
options,
history: HISTORY,
active: ACTIVE
}
for key, val of exports
nextMakeClient[key] = val
nextMakeClient
client = makeClient()
if options.pagePerformanceKey
client.sendPagePerformance(options.pagePerformanceKey)
if options.requestsKey
client.requests.monitor(options.requestsKey)
client
if typeof define is 'function' and define.amd
# AMD
define exportDef
else if typeof exports is 'object'
# Node
module.exports = exportDef()
else
# Global
window.Bucky = exportDef()
|
[
{
"context": "m/mapfiles/place_api/icons/geocode-71.png\"\n id: \"7eae6a016a9c6f58e2044573fb8f14227b6e1f96\"\n name: \"New York\"\n reference: \"CoQBdAAAACZimk_",
"end": 1007,
"score": 0.7752581238746643,
"start": 967,
"tag": "KEY",
"value": "7eae6a016a9c6f58e2044573fb8f14227b6e1f96"
},... | src/desktop/test/models/mixins/geo.coffee | kanaabe/force | 1 | _ = require 'underscore'
sinon = require 'sinon'
Backbone = require 'backbone'
benv = require 'benv'
rewire = require 'rewire'
googleyAddress =
address_components: [
long_name: "New York"
short_name: "New York"
types: ["locality", "political"]
,
long_name: "New York"
short_name: "NY"
types: ["administrative_area_level_1", "political"]
,
long_name: "United States"
short_name: "US"
types: ["country", "political"]
]
adr_address: "<span class=\"locality\">New York</span>, <span class=\"region\">NY</span>, <span class=\"country-name\">USA</span>"
formatted_address: "New York, NY, USA"
geometry:
location:
lb: 40.7143528
mb: -74.0059731
lat: -> 40.7143528
lng: -> -74.0059731
viewport:
ea:
d: 40.496006
b: 40.91525559999999
fa:
b: -74.2557349
d: -73.7002721
icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png"
id: "7eae6a016a9c6f58e2044573fb8f14227b6e1f96"
name: "New York"
reference: "CoQBdAAAACZimk_9WwuhIeWFwtMeNqiAV2daRpsJ41qmyqgBQjVJiuokc6XecHVoogAisPTRLsOQNz0UOo2hfGM2I40TUkRNYveLwyiLX_EdSiFWUPNGBGkciwDInfQa7DCg2qdIkzKf5Q8YI_eCa8NbSTcJWxWTJk3cOUq4N82u3aDaGEMXEhCEDqVRiEBNj1FktOhIJ21XGhRhPghlJuXsUpx_cmTfrW34g9T8Pg"
types: ["locality", "political"]
url: "https://maps.google.com/maps/place?q=New+York&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62"
vicinity: "New York"
html_attributions: []
geoFormatter =
getCity: -> 'My city'
getState: -> 'My state'
getStateCode: -> 'My statecode'
getPostalCode: -> 'My postalcode'
getCoordinates: -> [0, 0]
getCountry: -> 'My country'
Geo = rewire '../../../models/mixins/geo'
Geo.__set__ 'geo', locate: (locateStub = sinon.stub().yieldsTo 'success', geoFormatter)
class User extends Backbone.Model
_.extend @prototype, Geo
describe 'Geo Mixin', ->
beforeEach ->
@user = new User
describe '#hasLocation', ->
it 'determines whether or not there is a valid location', ->
@user.hasLocation().should.be.false()
@user.set location: city: 'existy'
@user.hasLocation().should.be.true()
describe '#approximateLocation, #setGeo', ->
it 'gets the approximate location by geolocating the IP address', ->
@user.approximateLocation()
@user.get('location').city.should.equal 'My city'
@user.get('location').state.should.equal 'My state'
@user.get('location').coordinates.should.eql [0, 0]
it 'accepts a success callback', (done) ->
@user.approximateLocation success: done
describe '#setLocation', ->
it 'should allow a user to set a location object that Google returns', ->
@user.setLocation googleyAddress
@user.location().cityStateCountry().should.equal 'New York, New York, United States'
it 'should allow a user to set a non-standard name as their location', ->
@user.setLocation name: 'Foobar'
@user.location().cityStateCountry().should.equal 'Foobar'
it 'should allow a user to clear their location', ->
@user.setLocation name: ''
@user.location().cityStateCountry().should.equal ''
| 91190 | _ = require 'underscore'
sinon = require 'sinon'
Backbone = require 'backbone'
benv = require 'benv'
rewire = require 'rewire'
googleyAddress =
address_components: [
long_name: "New York"
short_name: "New York"
types: ["locality", "political"]
,
long_name: "New York"
short_name: "NY"
types: ["administrative_area_level_1", "political"]
,
long_name: "United States"
short_name: "US"
types: ["country", "political"]
]
adr_address: "<span class=\"locality\">New York</span>, <span class=\"region\">NY</span>, <span class=\"country-name\">USA</span>"
formatted_address: "New York, NY, USA"
geometry:
location:
lb: 40.7143528
mb: -74.0059731
lat: -> 40.7143528
lng: -> -74.0059731
viewport:
ea:
d: 40.496006
b: 40.91525559999999
fa:
b: -74.2557349
d: -73.7002721
icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png"
id: "<KEY>"
name: "New York"
reference: "<KEY>"
types: ["locality", "political"]
url: "https://maps.google.com/maps/place?q=New+York&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62"
vicinity: "New York"
html_attributions: []
geoFormatter =
getCity: -> 'My city'
getState: -> 'My state'
getStateCode: -> 'My statecode'
getPostalCode: -> 'My postalcode'
getCoordinates: -> [0, 0]
getCountry: -> 'My country'
Geo = rewire '../../../models/mixins/geo'
Geo.__set__ 'geo', locate: (locateStub = sinon.stub().yieldsTo 'success', geoFormatter)
class User extends Backbone.Model
_.extend @prototype, Geo
describe 'Geo Mixin', ->
beforeEach ->
@user = new User
describe '#hasLocation', ->
it 'determines whether or not there is a valid location', ->
@user.hasLocation().should.be.false()
@user.set location: city: 'existy'
@user.hasLocation().should.be.true()
describe '#approximateLocation, #setGeo', ->
it 'gets the approximate location by geolocating the IP address', ->
@user.approximateLocation()
@user.get('location').city.should.equal 'My city'
@user.get('location').state.should.equal 'My state'
@user.get('location').coordinates.should.eql [0, 0]
it 'accepts a success callback', (done) ->
@user.approximateLocation success: done
describe '#setLocation', ->
it 'should allow a user to set a location object that Google returns', ->
@user.setLocation googleyAddress
@user.location().cityStateCountry().should.equal 'New York, New York, United States'
it 'should allow a user to set a non-standard name as their location', ->
@user.setLocation name: '<NAME>'
@user.location().cityStateCountry().should.equal 'Foobar'
it 'should allow a user to clear their location', ->
@user.setLocation name: ''
@user.location().cityStateCountry().should.equal ''
| true | _ = require 'underscore'
sinon = require 'sinon'
Backbone = require 'backbone'
benv = require 'benv'
rewire = require 'rewire'
googleyAddress =
address_components: [
long_name: "New York"
short_name: "New York"
types: ["locality", "political"]
,
long_name: "New York"
short_name: "NY"
types: ["administrative_area_level_1", "political"]
,
long_name: "United States"
short_name: "US"
types: ["country", "political"]
]
adr_address: "<span class=\"locality\">New York</span>, <span class=\"region\">NY</span>, <span class=\"country-name\">USA</span>"
formatted_address: "New York, NY, USA"
geometry:
location:
lb: 40.7143528
mb: -74.0059731
lat: -> 40.7143528
lng: -> -74.0059731
viewport:
ea:
d: 40.496006
b: 40.91525559999999
fa:
b: -74.2557349
d: -73.7002721
icon: "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png"
id: "PI:KEY:<KEY>END_PI"
name: "New York"
reference: "PI:KEY:<KEY>END_PI"
types: ["locality", "political"]
url: "https://maps.google.com/maps/place?q=New+York&ftid=0x89c24fa5d33f083b:0xc80b8f06e177fe62"
vicinity: "New York"
html_attributions: []
geoFormatter =
getCity: -> 'My city'
getState: -> 'My state'
getStateCode: -> 'My statecode'
getPostalCode: -> 'My postalcode'
getCoordinates: -> [0, 0]
getCountry: -> 'My country'
Geo = rewire '../../../models/mixins/geo'
Geo.__set__ 'geo', locate: (locateStub = sinon.stub().yieldsTo 'success', geoFormatter)
class User extends Backbone.Model
_.extend @prototype, Geo
describe 'Geo Mixin', ->
beforeEach ->
@user = new User
describe '#hasLocation', ->
it 'determines whether or not there is a valid location', ->
@user.hasLocation().should.be.false()
@user.set location: city: 'existy'
@user.hasLocation().should.be.true()
describe '#approximateLocation, #setGeo', ->
it 'gets the approximate location by geolocating the IP address', ->
@user.approximateLocation()
@user.get('location').city.should.equal 'My city'
@user.get('location').state.should.equal 'My state'
@user.get('location').coordinates.should.eql [0, 0]
it 'accepts a success callback', (done) ->
@user.approximateLocation success: done
describe '#setLocation', ->
it 'should allow a user to set a location object that Google returns', ->
@user.setLocation googleyAddress
@user.location().cityStateCountry().should.equal 'New York, New York, United States'
it 'should allow a user to set a non-standard name as their location', ->
@user.setLocation name: 'PI:NAME:<NAME>END_PI'
@user.location().cityStateCountry().should.equal 'Foobar'
it 'should allow a user to clear their location', ->
@user.setLocation name: ''
@user.location().cityStateCountry().should.equal ''
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998514652252197,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/nucleus/extends.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
uuid = require "node-uuid"
strace = require "stack-trace"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{cc, ec} = require "../membrane/remote"
# This class encapsulates arbitrary definition that extend built in
# data types or similar to it. This is a small collection of the handy
# routines that are used throughout the code. These definitions are
# placed in this class in order to transfer it to the remote call site.
# Some of them depend on other subsystems, such as dynamic composition.
module.exports.Extending = cc -> class Extending extends Object
# Determine if the object that is bound to this invocation is a
# subclass of the supplied archetype class (as argument). Of course
# it is assumed that you should be invoking this method only on the
# objects that are valid CoffeeSscript classes with necessary attrs.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "derives",
enumerable: no, value: (archetype, loose) ->
notObject = "supplied acrhetype not object"
notClass = "the invocation target not class"
noTree = "cannot retrieve the hierarchy tree"
assert _.isObject(archetype or 0), notObject
assert _.isFunction arche = archetype # alias
predicate = (x) -> x.similarWith arche, loose
assert _.isObject(@__super__ or 0), notClass
return yes if predicate(this or null) is yes
assert hierarchy = (try this.hierarchy()) or 0
assert _.isArray(hierarchy or null), noTree
return try _.any hierarchy or [], predicate
# Determine if the object that is bound to this invocation is an
# object of the supplied archetype class (as argument). Of course
# if is assumed that you should be invoking this only on instances
# of some class in order to yield positive results. Please refer
# to the `compose` module for more information on how this works.
Object.defineProperty Object::, "objectOf",
enumerable: no, value: (archetype, loose) ->
notObject = "supplied acrhetype not object"
notInst = "the invocation target not instance"
noTree = "cannot retrieve the hierarchy tree"
assert _.isObject(archetype or 0), notObject
assert _.isFunction arche = archetype # alias
predicate = (x) -> x.similarWith arche, loose
assert _.isObject(@constructor or 0), notInst
assert hierarchy = @constructor?.hierarchy()
assert _.isArray(hierarchy or null), noTree
return yes if predicate(@constructor) is yes
return try _.any hierarchy or [], predicate
# A method for comparing different classes for equality. Be careful
# as this method is very loose in terms of comparison and its main
# purpose is aiding in implementation of the composition mechanism
# rather than any else. Comparison algorithms is likely to change.
# This is used internally in the composition system implementation.
Object.defineProperty Object::, "similarWith",
enumerable: no, value: (archetype, loose) ->
isClass = _.isObject this.prototype
noClass = "the subject is not a class"
throw new Error noClass unless isClass
return yes if this is archetype or no
return yes if @watermark is archetype
return undefined unless loose is yes
return yes if @name is archetype.name
return yes if @nick is archetype.nick
# This extension provides a convenient interface for looking up and
# setting up the object identifification tag. This tag is usually a
# class or function name, nick or an arbitraty name set with this
# method. If nothing found, the methods falls back to some default.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "identify",
enumerable: no, value: (identificator) ->
shadowed = _.isObject this.watermark
set = => this.$identify = identificator
nclass = "an invoke target is not class"
assert _.isObject(@constructor), nclass
return set() if _.isString identificator
return @$identify if _.isString @$identify
return @name unless _.isEmpty this.name
return this.watermark.name if shadowed
return this.identify typeof this # gen
# A universal method to both check and set the indicator of whether
# an object is an abstract class or not. This is very useful for
# implementing proper architectural abstractions and concretizations.
# Use this method rather than directly setting and check for markers.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "abstract",
enumerable: no, value: (boolean) ->
isAbstract = try this.$abstract is this
wrong = "arg has to be a boolean value"
nclass = "an invoke target is not class"
assert _.isObject(@constructor), nclass
return isAbstract unless boolean? or null
assert _.isBoolean(boolean or 0), wrong
return this.$abstract = this if boolean
delete @$abstract; @$abstract is this
# Extend the native RegExp object to implement method for escaping
# a supplied string. Escaping here means substituting all the RE
# characters so that it can be used inside of the regular expression
# pattern. The implementation was borrowed from StackOverflow thread.
# Otherwise, an exception will be triggered to indicare usage error.
RegExp.escape = regexpEscape = (string) ->
empty = "the supplied argument is empty"
noString = "please supply the valid input"
fail = "unexpected error while processing"
assert _.isString(string or null), noString
assert not _.isEmpty(string or 0), empty
assert primary = /[-\/\\^$*+?.()|[\]{}]/g
replaced = string.replace primary, "\\$&"
assert not _.isEmpty(replaced or 0), fail
return replaced # return the escape str
# Collect all the matches of the regular expression against of the
# supplied string. This method basically gathers all the matches that
# sequentially matches against the input string and packs them into
# an array which is handed to the invoker. Be sure to set the G flag.
# Please see the implementation source code for the more information.
RegExp::collect = regexpCollect = (string) ->
assert matches = new Array, "acc error"
empty = "the supplied argument is empty"
noString = "got no valid string supplied"
broken = "got a broken regular expression"
assert _.isString(@source or null), broken
assert _.isString(string or 0), noString
assert not _.isEmpty(string or 0), empty
matches.push mx while mx = @exec string
assert _.isArray matches; return matches
# Extend the native RegExp object to implement method for unescaping
# a supplied string. Unscaping here means substituting all the RE back
# characters so that it cannot be used inside of the regular expression
# pattern. The implementation was borrowed from StackOverflow thread.
# Please see the implementation source code for the more information.
RegExp::unescape = regexpUnescape = ->
broken = "got a broken regular expression"
failure = "unexpected error while process"
esource = "the source reg patter is empty"
assert _.isString(@source or null), broken
assert not _.isEmpty(@source or 0), esource
string = this.source.replace /\\\//g, "/"
string = try string.replace /[\$\^]/g, ""
assert _.isString(string or null), failure
return string # return the unescpaed str
| 94960 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
uuid = require "node-uuid"
strace = require "stack-trace"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{cc, ec} = require "../membrane/remote"
# This class encapsulates arbitrary definition that extend built in
# data types or similar to it. This is a small collection of the handy
# routines that are used throughout the code. These definitions are
# placed in this class in order to transfer it to the remote call site.
# Some of them depend on other subsystems, such as dynamic composition.
module.exports.Extending = cc -> class Extending extends Object
# Determine if the object that is bound to this invocation is a
# subclass of the supplied archetype class (as argument). Of course
# it is assumed that you should be invoking this method only on the
# objects that are valid CoffeeSscript classes with necessary attrs.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "derives",
enumerable: no, value: (archetype, loose) ->
notObject = "supplied acrhetype not object"
notClass = "the invocation target not class"
noTree = "cannot retrieve the hierarchy tree"
assert _.isObject(archetype or 0), notObject
assert _.isFunction arche = archetype # alias
predicate = (x) -> x.similarWith arche, loose
assert _.isObject(@__super__ or 0), notClass
return yes if predicate(this or null) is yes
assert hierarchy = (try this.hierarchy()) or 0
assert _.isArray(hierarchy or null), noTree
return try _.any hierarchy or [], predicate
# Determine if the object that is bound to this invocation is an
# object of the supplied archetype class (as argument). Of course
# if is assumed that you should be invoking this only on instances
# of some class in order to yield positive results. Please refer
# to the `compose` module for more information on how this works.
Object.defineProperty Object::, "objectOf",
enumerable: no, value: (archetype, loose) ->
notObject = "supplied acrhetype not object"
notInst = "the invocation target not instance"
noTree = "cannot retrieve the hierarchy tree"
assert _.isObject(archetype or 0), notObject
assert _.isFunction arche = archetype # alias
predicate = (x) -> x.similarWith arche, loose
assert _.isObject(@constructor or 0), notInst
assert hierarchy = @constructor?.hierarchy()
assert _.isArray(hierarchy or null), noTree
return yes if predicate(@constructor) is yes
return try _.any hierarchy or [], predicate
# A method for comparing different classes for equality. Be careful
# as this method is very loose in terms of comparison and its main
# purpose is aiding in implementation of the composition mechanism
# rather than any else. Comparison algorithms is likely to change.
# This is used internally in the composition system implementation.
Object.defineProperty Object::, "similarWith",
enumerable: no, value: (archetype, loose) ->
isClass = _.isObject this.prototype
noClass = "the subject is not a class"
throw new Error noClass unless isClass
return yes if this is archetype or no
return yes if @watermark is archetype
return undefined unless loose is yes
return yes if @name is archetype.name
return yes if @nick is archetype.nick
# This extension provides a convenient interface for looking up and
# setting up the object identifification tag. This tag is usually a
# class or function name, nick or an arbitraty name set with this
# method. If nothing found, the methods falls back to some default.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "identify",
enumerable: no, value: (identificator) ->
shadowed = _.isObject this.watermark
set = => this.$identify = identificator
nclass = "an invoke target is not class"
assert _.isObject(@constructor), nclass
return set() if _.isString identificator
return @$identify if _.isString @$identify
return @name unless _.isEmpty this.name
return this.watermark.name if shadowed
return this.identify typeof this # gen
# A universal method to both check and set the indicator of whether
# an object is an abstract class or not. This is very useful for
# implementing proper architectural abstractions and concretizations.
# Use this method rather than directly setting and check for markers.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "abstract",
enumerable: no, value: (boolean) ->
isAbstract = try this.$abstract is this
wrong = "arg has to be a boolean value"
nclass = "an invoke target is not class"
assert _.isObject(@constructor), nclass
return isAbstract unless boolean? or null
assert _.isBoolean(boolean or 0), wrong
return this.$abstract = this if boolean
delete @$abstract; @$abstract is this
# Extend the native RegExp object to implement method for escaping
# a supplied string. Escaping here means substituting all the RE
# characters so that it can be used inside of the regular expression
# pattern. The implementation was borrowed from StackOverflow thread.
# Otherwise, an exception will be triggered to indicare usage error.
RegExp.escape = regexpEscape = (string) ->
empty = "the supplied argument is empty"
noString = "please supply the valid input"
fail = "unexpected error while processing"
assert _.isString(string or null), noString
assert not _.isEmpty(string or 0), empty
assert primary = /[-\/\\^$*+?.()|[\]{}]/g
replaced = string.replace primary, "\\$&"
assert not _.isEmpty(replaced or 0), fail
return replaced # return the escape str
# Collect all the matches of the regular expression against of the
# supplied string. This method basically gathers all the matches that
# sequentially matches against the input string and packs them into
# an array which is handed to the invoker. Be sure to set the G flag.
# Please see the implementation source code for the more information.
RegExp::collect = regexpCollect = (string) ->
assert matches = new Array, "acc error"
empty = "the supplied argument is empty"
noString = "got no valid string supplied"
broken = "got a broken regular expression"
assert _.isString(@source or null), broken
assert _.isString(string or 0), noString
assert not _.isEmpty(string or 0), empty
matches.push mx while mx = @exec string
assert _.isArray matches; return matches
# Extend the native RegExp object to implement method for unescaping
# a supplied string. Unscaping here means substituting all the RE back
# characters so that it cannot be used inside of the regular expression
# pattern. The implementation was borrowed from StackOverflow thread.
# Please see the implementation source code for the more information.
RegExp::unescape = regexpUnescape = ->
broken = "got a broken regular expression"
failure = "unexpected error while process"
esource = "the source reg patter is empty"
assert _.isString(@source or null), broken
assert not _.isEmpty(@source or 0), esource
string = this.source.replace /\\\//g, "/"
string = try string.replace /[\$\^]/g, ""
assert _.isString(string or null), failure
return string # return the unescpaed str
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
uuid = require "node-uuid"
strace = require "stack-trace"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{cc, ec} = require "../membrane/remote"
# This class encapsulates arbitrary definition that extend built in
# data types or similar to it. This is a small collection of the handy
# routines that are used throughout the code. These definitions are
# placed in this class in order to transfer it to the remote call site.
# Some of them depend on other subsystems, such as dynamic composition.
module.exports.Extending = cc -> class Extending extends Object
# Determine if the object that is bound to this invocation is a
# subclass of the supplied archetype class (as argument). Of course
# it is assumed that you should be invoking this method only on the
# objects that are valid CoffeeSscript classes with necessary attrs.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "derives",
enumerable: no, value: (archetype, loose) ->
notObject = "supplied acrhetype not object"
notClass = "the invocation target not class"
noTree = "cannot retrieve the hierarchy tree"
assert _.isObject(archetype or 0), notObject
assert _.isFunction arche = archetype # alias
predicate = (x) -> x.similarWith arche, loose
assert _.isObject(@__super__ or 0), notClass
return yes if predicate(this or null) is yes
assert hierarchy = (try this.hierarchy()) or 0
assert _.isArray(hierarchy or null), noTree
return try _.any hierarchy or [], predicate
# Determine if the object that is bound to this invocation is an
# object of the supplied archetype class (as argument). Of course
# if is assumed that you should be invoking this only on instances
# of some class in order to yield positive results. Please refer
# to the `compose` module for more information on how this works.
Object.defineProperty Object::, "objectOf",
enumerable: no, value: (archetype, loose) ->
notObject = "supplied acrhetype not object"
notInst = "the invocation target not instance"
noTree = "cannot retrieve the hierarchy tree"
assert _.isObject(archetype or 0), notObject
assert _.isFunction arche = archetype # alias
predicate = (x) -> x.similarWith arche, loose
assert _.isObject(@constructor or 0), notInst
assert hierarchy = @constructor?.hierarchy()
assert _.isArray(hierarchy or null), noTree
return yes if predicate(@constructor) is yes
return try _.any hierarchy or [], predicate
# A method for comparing different classes for equality. Be careful
# as this method is very loose in terms of comparison and its main
# purpose is aiding in implementation of the composition mechanism
# rather than any else. Comparison algorithms is likely to change.
# This is used internally in the composition system implementation.
Object.defineProperty Object::, "similarWith",
enumerable: no, value: (archetype, loose) ->
isClass = _.isObject this.prototype
noClass = "the subject is not a class"
throw new Error noClass unless isClass
return yes if this is archetype or no
return yes if @watermark is archetype
return undefined unless loose is yes
return yes if @name is archetype.name
return yes if @nick is archetype.nick
# This extension provides a convenient interface for looking up and
# setting up the object identifification tag. This tag is usually a
# class or function name, nick or an arbitraty name set with this
# method. If nothing found, the methods falls back to some default.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "identify",
enumerable: no, value: (identificator) ->
shadowed = _.isObject this.watermark
set = => this.$identify = identificator
nclass = "an invoke target is not class"
assert _.isObject(@constructor), nclass
return set() if _.isString identificator
return @$identify if _.isString @$identify
return @name unless _.isEmpty this.name
return this.watermark.name if shadowed
return this.identify typeof this # gen
# A universal method to both check and set the indicator of whether
# an object is an abstract class or not. This is very useful for
# implementing proper architectural abstractions and concretizations.
# Use this method rather than directly setting and check for markers.
# Otherwise, an exception will be triggered to indicare usage error.
Object.defineProperty Object::, "abstract",
enumerable: no, value: (boolean) ->
isAbstract = try this.$abstract is this
wrong = "arg has to be a boolean value"
nclass = "an invoke target is not class"
assert _.isObject(@constructor), nclass
return isAbstract unless boolean? or null
assert _.isBoolean(boolean or 0), wrong
return this.$abstract = this if boolean
delete @$abstract; @$abstract is this
# Extend the native RegExp object to implement method for escaping
# a supplied string. Escaping here means substituting all the RE
# characters so that it can be used inside of the regular expression
# pattern. The implementation was borrowed from StackOverflow thread.
# Otherwise, an exception will be triggered to indicare usage error.
RegExp.escape = regexpEscape = (string) ->
empty = "the supplied argument is empty"
noString = "please supply the valid input"
fail = "unexpected error while processing"
assert _.isString(string or null), noString
assert not _.isEmpty(string or 0), empty
assert primary = /[-\/\\^$*+?.()|[\]{}]/g
replaced = string.replace primary, "\\$&"
assert not _.isEmpty(replaced or 0), fail
return replaced # return the escape str
# Collect all the matches of the regular expression against of the
# supplied string. This method basically gathers all the matches that
# sequentially matches against the input string and packs them into
# an array which is handed to the invoker. Be sure to set the G flag.
# Please see the implementation source code for the more information.
RegExp::collect = regexpCollect = (string) ->
assert matches = new Array, "acc error"
empty = "the supplied argument is empty"
noString = "got no valid string supplied"
broken = "got a broken regular expression"
assert _.isString(@source or null), broken
assert _.isString(string or 0), noString
assert not _.isEmpty(string or 0), empty
matches.push mx while mx = @exec string
assert _.isArray matches; return matches
# Extend the native RegExp object to implement method for unescaping
# a supplied string. Unscaping here means substituting all the RE back
# characters so that it cannot be used inside of the regular expression
# pattern. The implementation was borrowed from StackOverflow thread.
# Please see the implementation source code for the more information.
RegExp::unescape = regexpUnescape = ->
broken = "got a broken regular expression"
failure = "unexpected error while process"
esource = "the source reg patter is empty"
assert _.isString(@source or null), broken
assert not _.isEmpty(@source or 0), esource
string = this.source.replace /\\\//g, "/"
string = try string.replace /[\$\^]/g, ""
assert _.isString(string or null), failure
return string # return the unescpaed str
|
[
{
"context": "ry.ajax(\n type: 'GET'\n url: \"http://127.0.0.1:8080/www/js/status.json\"\n no_error: false\n",
"end": 1012,
"score": 0.9185774326324463,
"start": 1003,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "Testing Coffeedesktop npapi wrapper\... | app/assets/javascripts/oa.js.coffee | CoffeeDesktop/coffeedesktop-rails | 0 | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require gui
#= require glue
#= require localstorage
#= require usecase
class Templates
main: ->
"You can test here coffeedesktop wrapper<br>
Pluginstatus: <div class='plugin_status'></div><br>
Server status: <div class='server_status'></div><br>
<button class='start_server_button'>Start localserver</button>
<object id='plugin0' type='application/x-cdw' width='0' height='0'>
</object>
"
class Backend
constructor: () ->
stupidPost: ->
$.post("/coffeedesktop/stupid_post" );
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
constructor: (@gui) ->
@windows = []
@status = false
startServer: () ->
console.log "Starting local server"
@gui.plugin_object.startServer()
exitSignal: ->
@gui.closeMainWindow()
checkStatus: ->
jQuery.ajax(
type: 'GET'
url: "http://127.0.0.1:8080/www/js/status.json"
no_error: false
dataType:"jsonp"
error:(event, jqXHR, ajaxSettings, thrownError) =>
if event.status == 200
@status=true
else
@status=false
xhrFields:
withCredentials: false
)
@gui.setServerStatus(@status)
start: (args) =>
@gui.createWindow("Sample Application","main")
@status_int= setInterval((=> @checkStatus()) ,1000)
pluginStatus: ->
@gui.setPluginStatus(@gui.plugin_object.valid)
class Gui extends @GuiClass
constructor: (@templates) ->
createWindow: (title=false,template="main") =>
rand=UUIDjs.randomUI48()
id=UUIDjs.randomUI48() if !id #if undefined just throw sth random
div_id = id+"-"+rand
$.newWindow({id:div_id,title:title,width:500,height:350})
$.updateWindowContent(div_id,@templates[template]())
@div_id = div_id
@element = $("##{@div_id}")
$("##{div_id} .window-closeButton").click( =>
@exitApp()
)
@plugin_object= document.getElementById('plugin0');
console.log @plugin_object
@setBindings(template,div_id)
closeWindow: (id) ->
console.log "closing window #{id}"
$.closeWindow(id)
@removeWindow(id)
updateChild: (id) ->
$.updateWindowContent(id,@templates.updated_child())
@setBindings('updated_child',id)
setBindings: (template,div_id) ->
if template == "main"
$( "##{div_id} .sa_drag_button" ).button()
$( "##{div_id} .start_server_button").click( => @startServer())
closeMainWindow: ->
$("##{@div_id} .window-closeButton").click()
setPluginStatus: (status)->
if status
$( "##{@div_id} .plugin_status").text("OK")
else
$( "##{@div_id} .plugin_status").text("NOT OK")
setServerStatus: (status)->
if status
$( "##{@div_id} .server_status").text("OK")
else
$( "##{@div_id} .server_status").text("NOT OK")
#aop events
startServer: ->
exitApp: ->
class Glue extends @GlueClass
constructor: (@useCase, @gui, @storage, @app, @backend) ->
After(@gui, 'exitApp', => @app.exitApp())
After(@gui, 'createWindow', => @useCase.pluginStatus())
After(@gui, 'startServer', => @useCase.startServer())
After(@app, 'exitSignal', => @useCase.exitSignal())
# LogAll(@useCase)
# LogAll(@gui)
class @OfflineApp
fullname = "Offline Application"
description = "Testing Coffeedesktop npapi wrapper"
@fullname = fullname
@description = description
exitSignal: ->
exitApp: ->
CoffeeDesktop.processKill(@id)
getDivID: ->
@gui.div_id
constructor: (@id, args) ->
@fullname = fullname
@description = description
templates = new Templates()
backend = new Backend()
@gui = new Gui(templates)
useCase = new UseCase(@gui)
localStorage = new LocalStorage("CoffeeDesktop")
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, @gui, localStorage,this,backend)
# ^ this this is this ugly this
useCase.start(args)
window.oa = {}
window.sa.UseCase = UseCase
window.sa.Gui = Gui
window.sa.Templates = Templates
window.sa.SampleApp = SampleApp
window.CoffeeDesktop.appAdd('oa',@OfflineApp, ) | 107626 | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require gui
#= require glue
#= require localstorage
#= require usecase
class Templates
main: ->
"You can test here coffeedesktop wrapper<br>
Pluginstatus: <div class='plugin_status'></div><br>
Server status: <div class='server_status'></div><br>
<button class='start_server_button'>Start localserver</button>
<object id='plugin0' type='application/x-cdw' width='0' height='0'>
</object>
"
class Backend
constructor: () ->
stupidPost: ->
$.post("/coffeedesktop/stupid_post" );
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
constructor: (@gui) ->
@windows = []
@status = false
startServer: () ->
console.log "Starting local server"
@gui.plugin_object.startServer()
exitSignal: ->
@gui.closeMainWindow()
checkStatus: ->
jQuery.ajax(
type: 'GET'
url: "http://127.0.0.1:8080/www/js/status.json"
no_error: false
dataType:"jsonp"
error:(event, jqXHR, ajaxSettings, thrownError) =>
if event.status == 200
@status=true
else
@status=false
xhrFields:
withCredentials: false
)
@gui.setServerStatus(@status)
start: (args) =>
@gui.createWindow("Sample Application","main")
@status_int= setInterval((=> @checkStatus()) ,1000)
pluginStatus: ->
@gui.setPluginStatus(@gui.plugin_object.valid)
class Gui extends @GuiClass
constructor: (@templates) ->
createWindow: (title=false,template="main") =>
rand=UUIDjs.randomUI48()
id=UUIDjs.randomUI48() if !id #if undefined just throw sth random
div_id = id+"-"+rand
$.newWindow({id:div_id,title:title,width:500,height:350})
$.updateWindowContent(div_id,@templates[template]())
@div_id = div_id
@element = $("##{@div_id}")
$("##{div_id} .window-closeButton").click( =>
@exitApp()
)
@plugin_object= document.getElementById('plugin0');
console.log @plugin_object
@setBindings(template,div_id)
closeWindow: (id) ->
console.log "closing window #{id}"
$.closeWindow(id)
@removeWindow(id)
updateChild: (id) ->
$.updateWindowContent(id,@templates.updated_child())
@setBindings('updated_child',id)
setBindings: (template,div_id) ->
if template == "main"
$( "##{div_id} .sa_drag_button" ).button()
$( "##{div_id} .start_server_button").click( => @startServer())
closeMainWindow: ->
$("##{@div_id} .window-closeButton").click()
setPluginStatus: (status)->
if status
$( "##{@div_id} .plugin_status").text("OK")
else
$( "##{@div_id} .plugin_status").text("NOT OK")
setServerStatus: (status)->
if status
$( "##{@div_id} .server_status").text("OK")
else
$( "##{@div_id} .server_status").text("NOT OK")
#aop events
startServer: ->
exitApp: ->
class Glue extends @GlueClass
constructor: (@useCase, @gui, @storage, @app, @backend) ->
After(@gui, 'exitApp', => @app.exitApp())
After(@gui, 'createWindow', => @useCase.pluginStatus())
After(@gui, 'startServer', => @useCase.startServer())
After(@app, 'exitSignal', => @useCase.exitSignal())
# LogAll(@useCase)
# LogAll(@gui)
class @OfflineApp
fullname = "Offline Application"
description = "Testing Coffeedesktop npapi wrapper"
@fullname = <NAME>
@description = description
exitSignal: ->
exitApp: ->
CoffeeDesktop.processKill(@id)
getDivID: ->
@gui.div_id
constructor: (@id, args) ->
@fullname = <NAME>
@description = description
templates = new Templates()
backend = new Backend()
@gui = new Gui(templates)
useCase = new UseCase(@gui)
localStorage = new LocalStorage("CoffeeDesktop")
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, @gui, localStorage,this,backend)
# ^ this this is this ugly this
useCase.start(args)
window.oa = {}
window.sa.UseCase = UseCase
window.sa.Gui = Gui
window.sa.Templates = Templates
window.sa.SampleApp = SampleApp
window.CoffeeDesktop.appAdd('oa',@OfflineApp, ) | true | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require gui
#= require glue
#= require localstorage
#= require usecase
class Templates
main: ->
"You can test here coffeedesktop wrapper<br>
Pluginstatus: <div class='plugin_status'></div><br>
Server status: <div class='server_status'></div><br>
<button class='start_server_button'>Start localserver</button>
<object id='plugin0' type='application/x-cdw' width='0' height='0'>
</object>
"
class Backend
constructor: () ->
stupidPost: ->
$.post("/coffeedesktop/stupid_post" );
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
constructor: (@gui) ->
@windows = []
@status = false
startServer: () ->
console.log "Starting local server"
@gui.plugin_object.startServer()
exitSignal: ->
@gui.closeMainWindow()
checkStatus: ->
jQuery.ajax(
type: 'GET'
url: "http://127.0.0.1:8080/www/js/status.json"
no_error: false
dataType:"jsonp"
error:(event, jqXHR, ajaxSettings, thrownError) =>
if event.status == 200
@status=true
else
@status=false
xhrFields:
withCredentials: false
)
@gui.setServerStatus(@status)
start: (args) =>
@gui.createWindow("Sample Application","main")
@status_int= setInterval((=> @checkStatus()) ,1000)
pluginStatus: ->
@gui.setPluginStatus(@gui.plugin_object.valid)
class Gui extends @GuiClass
constructor: (@templates) ->
createWindow: (title=false,template="main") =>
rand=UUIDjs.randomUI48()
id=UUIDjs.randomUI48() if !id #if undefined just throw sth random
div_id = id+"-"+rand
$.newWindow({id:div_id,title:title,width:500,height:350})
$.updateWindowContent(div_id,@templates[template]())
@div_id = div_id
@element = $("##{@div_id}")
$("##{div_id} .window-closeButton").click( =>
@exitApp()
)
@plugin_object= document.getElementById('plugin0');
console.log @plugin_object
@setBindings(template,div_id)
closeWindow: (id) ->
console.log "closing window #{id}"
$.closeWindow(id)
@removeWindow(id)
updateChild: (id) ->
$.updateWindowContent(id,@templates.updated_child())
@setBindings('updated_child',id)
setBindings: (template,div_id) ->
if template == "main"
$( "##{div_id} .sa_drag_button" ).button()
$( "##{div_id} .start_server_button").click( => @startServer())
closeMainWindow: ->
$("##{@div_id} .window-closeButton").click()
setPluginStatus: (status)->
if status
$( "##{@div_id} .plugin_status").text("OK")
else
$( "##{@div_id} .plugin_status").text("NOT OK")
setServerStatus: (status)->
if status
$( "##{@div_id} .server_status").text("OK")
else
$( "##{@div_id} .server_status").text("NOT OK")
#aop events
startServer: ->
exitApp: ->
class Glue extends @GlueClass
constructor: (@useCase, @gui, @storage, @app, @backend) ->
After(@gui, 'exitApp', => @app.exitApp())
After(@gui, 'createWindow', => @useCase.pluginStatus())
After(@gui, 'startServer', => @useCase.startServer())
After(@app, 'exitSignal', => @useCase.exitSignal())
# LogAll(@useCase)
# LogAll(@gui)
class @OfflineApp
fullname = "Offline Application"
description = "Testing Coffeedesktop npapi wrapper"
@fullname = PI:NAME:<NAME>END_PI
@description = description
exitSignal: ->
exitApp: ->
CoffeeDesktop.processKill(@id)
getDivID: ->
@gui.div_id
constructor: (@id, args) ->
@fullname = PI:NAME:<NAME>END_PI
@description = description
templates = new Templates()
backend = new Backend()
@gui = new Gui(templates)
useCase = new UseCase(@gui)
localStorage = new LocalStorage("CoffeeDesktop")
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, @gui, localStorage,this,backend)
# ^ this this is this ugly this
useCase.start(args)
window.oa = {}
window.sa.UseCase = UseCase
window.sa.Gui = Gui
window.sa.Templates = Templates
window.sa.SampleApp = SampleApp
window.CoffeeDesktop.appAdd('oa',@OfflineApp, ) |
[
{
"context": " @fileoverview Tests for id-length rule.\n# @author Burak Yigit Kaya\n###\n\n'use strict'\n\n#-----------------------------",
"end": 73,
"score": 0.9998506307601929,
"start": 57,
"tag": "NAME",
"value": "Burak Yigit Kaya"
}
] | src/tests/rules/id-length.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for id-length rule.
# @author Burak Yigit Kaya
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/id-length'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'id-length', rule,
valid: [
'xyz'
'xy = 1'
'xyz = ->'
'xyz = (abc, de) ->'
'obj = { abc: 1, de: 2 }'
"obj = { 'a': 1, bc: 2 }"
'''
obj = {}
obj['a'] = 2
'''
'abc = d'
'''
try
blah()
catch err
### pass ###
'''
'handler = ($e) ->'
'_a = 2'
'_ad$$ = new $'
'xyz = new ΣΣ()'
'unrelatedExpressionThatNeedsToBeIgnored()'
'''
obj = { 'a': 1, bc: 2 }
obj.tk = obj.a
'''
"query = location.query.q or ''"
"query = if location.query.q then location.query.q else ''"
,
code: 'x = Foo(42)', options: [min: 1]
,
code: 'x = Foo(42)', options: [min: 0]
,
code: 'foo.$x = Foo(42)', options: [min: 1]
,
code: 'lalala = Foo(42)', options: [max: 6]
,
code: '''
for q, h in list
console.log(h)
'''
options: [exceptions: ['h', 'q']]
,
code: '(num) => num * num'
,
code: 'foo = (num = 0) ->'
,
code: 'class MyClass'
,
code: '''
class Foo
method: ->
'''
,
code: 'foo = (...args) ->'
,
code: '{ prop } = {}'
,
code: '{ a: prop } = {}'
,
code: '{ x: [prop] } = {}'
,
code: "import something from 'y'"
,
code: 'export num = 0'
,
code: '{ prop: obj.x.y.something } = {}'
,
code: '{ prop: obj.longName } = {}'
,
code: 'obj = { a: 1, bc: 2 }', options: [properties: 'never']
,
code: '''
obj = {}
obj.a = 1
obj.bc = 2
'''
options: [properties: 'never']
,
code: '{ a: obj.x.y.z } = {}'
options: [properties: 'never']
,
code: '{ prop: obj.x } = {}'
options: [properties: 'never']
,
code: 'obj = { aaaaa: 1 }', options: [max: 4, properties: 'never']
,
code: '''
obj = {}
obj.aaaaa = 1
'''
options: [max: 4, properties: 'never']
,
code: '{ a: obj.x.y.z } = {}'
options: [max: 4, properties: 'never']
,
code: '{ prop: obj.xxxxx } = {}'
options: [max: 4, properties: 'never']
]
invalid: [
code: 'x = 1'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = null'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'obj.e = document.body'
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'xyz = (a) ->'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: 'obj = { a: 1, bc: 2 }'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: a } = {}'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: [x] } = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
try
blah()
catch e
### pass ###
'''
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'handler = (e) ->'
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'console.log i for i in [0...10]'
errors: [
message: "Identifier name 'i' is too short (< 2).", type: 'Identifier'
]
,
code: '''
j = 0
while j > -10
console.log --j
'''
errors: [
message: "Identifier name 'j' is too short (< 2).", type: 'Identifier'
]
,
code: '_$xt_$ = Foo(42)'
options: [min: 2, max: 4]
errors: [
message: "Identifier name '_$xt_$' is too long (> 4).", type: 'Identifier'
]
,
code: '_$x$_t$ = Foo(42)'
options: [min: 2, max: 4]
errors: [
message: "Identifier name '_$x$_t$' is too long (> 4)."
type: 'Identifier'
]
,
code: '(a) => a * a'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: 'foo = (x = 0) ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'class x'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
class Foo
x: ->
'''
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'foo = (...x) ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ x} = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ x: a} = {}'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ a: [x]} = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: "import x from 'y'"
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'export x = 0'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ a: obj.x.y.z } = {}'
errors: [
message: "Identifier name 'z' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: obj.x } = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = 1'
options: [properties: 'never']
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
class B extends A
'''
errors: [
message: "Identifier name 'B' is too short (< 2).", type: 'Identifier'
]
]
| 84577 | ###*
# @fileoverview Tests for id-length rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/id-length'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'id-length', rule,
valid: [
'xyz'
'xy = 1'
'xyz = ->'
'xyz = (abc, de) ->'
'obj = { abc: 1, de: 2 }'
"obj = { 'a': 1, bc: 2 }"
'''
obj = {}
obj['a'] = 2
'''
'abc = d'
'''
try
blah()
catch err
### pass ###
'''
'handler = ($e) ->'
'_a = 2'
'_ad$$ = new $'
'xyz = new ΣΣ()'
'unrelatedExpressionThatNeedsToBeIgnored()'
'''
obj = { 'a': 1, bc: 2 }
obj.tk = obj.a
'''
"query = location.query.q or ''"
"query = if location.query.q then location.query.q else ''"
,
code: 'x = Foo(42)', options: [min: 1]
,
code: 'x = Foo(42)', options: [min: 0]
,
code: 'foo.$x = Foo(42)', options: [min: 1]
,
code: 'lalala = Foo(42)', options: [max: 6]
,
code: '''
for q, h in list
console.log(h)
'''
options: [exceptions: ['h', 'q']]
,
code: '(num) => num * num'
,
code: 'foo = (num = 0) ->'
,
code: 'class MyClass'
,
code: '''
class Foo
method: ->
'''
,
code: 'foo = (...args) ->'
,
code: '{ prop } = {}'
,
code: '{ a: prop } = {}'
,
code: '{ x: [prop] } = {}'
,
code: "import something from 'y'"
,
code: 'export num = 0'
,
code: '{ prop: obj.x.y.something } = {}'
,
code: '{ prop: obj.longName } = {}'
,
code: 'obj = { a: 1, bc: 2 }', options: [properties: 'never']
,
code: '''
obj = {}
obj.a = 1
obj.bc = 2
'''
options: [properties: 'never']
,
code: '{ a: obj.x.y.z } = {}'
options: [properties: 'never']
,
code: '{ prop: obj.x } = {}'
options: [properties: 'never']
,
code: 'obj = { aaaaa: 1 }', options: [max: 4, properties: 'never']
,
code: '''
obj = {}
obj.aaaaa = 1
'''
options: [max: 4, properties: 'never']
,
code: '{ a: obj.x.y.z } = {}'
options: [max: 4, properties: 'never']
,
code: '{ prop: obj.xxxxx } = {}'
options: [max: 4, properties: 'never']
]
invalid: [
code: 'x = 1'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = null'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'obj.e = document.body'
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'xyz = (a) ->'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: 'obj = { a: 1, bc: 2 }'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: a } = {}'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: [x] } = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
try
blah()
catch e
### pass ###
'''
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'handler = (e) ->'
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'console.log i for i in [0...10]'
errors: [
message: "Identifier name 'i' is too short (< 2).", type: 'Identifier'
]
,
code: '''
j = 0
while j > -10
console.log --j
'''
errors: [
message: "Identifier name 'j' is too short (< 2).", type: 'Identifier'
]
,
code: '_$xt_$ = Foo(42)'
options: [min: 2, max: 4]
errors: [
message: "Identifier name '_$xt_$' is too long (> 4).", type: 'Identifier'
]
,
code: '_$x$_t$ = Foo(42)'
options: [min: 2, max: 4]
errors: [
message: "Identifier name '_$x$_t$' is too long (> 4)."
type: 'Identifier'
]
,
code: '(a) => a * a'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: 'foo = (x = 0) ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'class x'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
class Foo
x: ->
'''
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'foo = (...x) ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ x} = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ x: a} = {}'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ a: [x]} = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: "import x from 'y'"
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'export x = 0'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ a: obj.x.y.z } = {}'
errors: [
message: "Identifier name 'z' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: obj.x } = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = 1'
options: [properties: 'never']
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
class B extends A
'''
errors: [
message: "Identifier name 'B' is too short (< 2).", type: 'Identifier'
]
]
| true | ###*
# @fileoverview Tests for id-length rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/id-length'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'id-length', rule,
valid: [
'xyz'
'xy = 1'
'xyz = ->'
'xyz = (abc, de) ->'
'obj = { abc: 1, de: 2 }'
"obj = { 'a': 1, bc: 2 }"
'''
obj = {}
obj['a'] = 2
'''
'abc = d'
'''
try
blah()
catch err
### pass ###
'''
'handler = ($e) ->'
'_a = 2'
'_ad$$ = new $'
'xyz = new ΣΣ()'
'unrelatedExpressionThatNeedsToBeIgnored()'
'''
obj = { 'a': 1, bc: 2 }
obj.tk = obj.a
'''
"query = location.query.q or ''"
"query = if location.query.q then location.query.q else ''"
,
code: 'x = Foo(42)', options: [min: 1]
,
code: 'x = Foo(42)', options: [min: 0]
,
code: 'foo.$x = Foo(42)', options: [min: 1]
,
code: 'lalala = Foo(42)', options: [max: 6]
,
code: '''
for q, h in list
console.log(h)
'''
options: [exceptions: ['h', 'q']]
,
code: '(num) => num * num'
,
code: 'foo = (num = 0) ->'
,
code: 'class MyClass'
,
code: '''
class Foo
method: ->
'''
,
code: 'foo = (...args) ->'
,
code: '{ prop } = {}'
,
code: '{ a: prop } = {}'
,
code: '{ x: [prop] } = {}'
,
code: "import something from 'y'"
,
code: 'export num = 0'
,
code: '{ prop: obj.x.y.something } = {}'
,
code: '{ prop: obj.longName } = {}'
,
code: 'obj = { a: 1, bc: 2 }', options: [properties: 'never']
,
code: '''
obj = {}
obj.a = 1
obj.bc = 2
'''
options: [properties: 'never']
,
code: '{ a: obj.x.y.z } = {}'
options: [properties: 'never']
,
code: '{ prop: obj.x } = {}'
options: [properties: 'never']
,
code: 'obj = { aaaaa: 1 }', options: [max: 4, properties: 'never']
,
code: '''
obj = {}
obj.aaaaa = 1
'''
options: [max: 4, properties: 'never']
,
code: '{ a: obj.x.y.z } = {}'
options: [max: 4, properties: 'never']
,
code: '{ prop: obj.xxxxx } = {}'
options: [max: 4, properties: 'never']
]
invalid: [
code: 'x = 1'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = null'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'obj.e = document.body'
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'xyz = (a) ->'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: 'obj = { a: 1, bc: 2 }'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: a } = {}'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: [x] } = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
try
blah()
catch e
### pass ###
'''
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'handler = (e) ->'
errors: [
message: "Identifier name 'e' is too short (< 2).", type: 'Identifier'
]
,
code: 'console.log i for i in [0...10]'
errors: [
message: "Identifier name 'i' is too short (< 2).", type: 'Identifier'
]
,
code: '''
j = 0
while j > -10
console.log --j
'''
errors: [
message: "Identifier name 'j' is too short (< 2).", type: 'Identifier'
]
,
code: '_$xt_$ = Foo(42)'
options: [min: 2, max: 4]
errors: [
message: "Identifier name '_$xt_$' is too long (> 4).", type: 'Identifier'
]
,
code: '_$x$_t$ = Foo(42)'
options: [min: 2, max: 4]
errors: [
message: "Identifier name '_$x$_t$' is too long (> 4)."
type: 'Identifier'
]
,
code: '(a) => a * a'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: 'foo = (x = 0) ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'class x'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
class Foo
x: ->
'''
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'foo = (...x) ->'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ x} = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ x: a} = {}'
errors: [
message: "Identifier name 'a' is too short (< 2).", type: 'Identifier'
]
,
code: '{ a: [x]} = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: "import x from 'y'"
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'export x = 0'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '{ a: obj.x.y.z } = {}'
errors: [
message: "Identifier name 'z' is too short (< 2).", type: 'Identifier'
]
,
code: '{ prop: obj.x } = {}'
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: 'x = 1'
options: [properties: 'never']
errors: [
message: "Identifier name 'x' is too short (< 2).", type: 'Identifier'
]
,
code: '''
class B extends A
'''
errors: [
message: "Identifier name 'B' is too short (< 2).", type: 'Identifier'
]
]
|
[
{
"context": "cons/qingcloud@2x.png'\n\n @_fields.push\n key: 'token'\n type: 'text'\n description: util.i18n\n ",
"end": 1637,
"score": 0.6983695030212402,
"start": 1632,
"tag": "KEY",
"value": "token"
},
{
"context": "reating a integration'\n\n @_fields.push\n key:... | src/services/qingcloud.coffee | jianliaoim/talk-services | 40 | _ = require 'lodash'
util = require '../util'
_receiveWebhook = ({integration, body}) ->
payload = body
return integration.token unless payload.resource
title = ''
resource = payload.resource.replace(/(')|(u\')/g, '"')
resource_json = JSON.parse resource
rules = payload.rules.replace(/'/g, '"')
rules_json = JSON.parse rules
if resource_json.resource_name isnt ''
title += "QingCloud: #{resource_json.resource_id} #{resource_json.resource_name} #{resource_json.resource_type}"
else
title += "QingCloud: #{resource_json.resource_id} #{resource_json.resource_type}"
text = []
_.forIn rules_json, (rule) ->
if rule.alarm_policy_rule_name isnt ''
text.push "RULE_ID: #{rule.alarm_policy_rule_id} RULE_NAME: #{rule.alarm_policy_rule_name} STATUS: #{rule.status}"
else
text.push "RULE_ID: #{rule.alarm_policy_rule_id} STATUS: #{rule.status}"
text = text.join '\n'
message =
attachments: [
category: 'quote'
data:
title: title
text: text
]
message
module.exports = ->
@title = '青云'
@template = 'webhook'
@summary = util.i18n
zh: '基础设施即服务(IaaS)云平台'
en: 'IaaS Cloud Platform'
@description = util.i18n
zh: '青云 QingCloud 可在秒级时间内获取计算资源,并通过 SDN 实现虚拟路由器和交换机功能,为您提供按需分配、弹性可伸缩的计算及组网能力。在基础设施层提供完整的云化解决方案。'
en: 'QingCloud can acquire the computing resource within the second time, realize the function of virtual router and switch, and provide the distribution according to demands, the flexible calculation and networking ability.'
@iconUrl = util.static 'images/icons/qingcloud@2x.png'
@_fields.push
key: 'token'
type: 'text'
description: util.i18n
zh: '第一次添加聚合时必填'
en: 'Required for creating a integration'
@_fields.push
key: 'webhookUrl'
type: 'text'
readonly: true
description: util.i18n
zh: '复制 web hook 地址到你的青云中使用。'
en: 'Copy this web hook to your Qing Cloud account to use it.'
@registerEvent 'service.webhook', _receiveWebhook
| 43831 | _ = require 'lodash'
util = require '../util'
_receiveWebhook = ({integration, body}) ->
payload = body
return integration.token unless payload.resource
title = ''
resource = payload.resource.replace(/(')|(u\')/g, '"')
resource_json = JSON.parse resource
rules = payload.rules.replace(/'/g, '"')
rules_json = JSON.parse rules
if resource_json.resource_name isnt ''
title += "QingCloud: #{resource_json.resource_id} #{resource_json.resource_name} #{resource_json.resource_type}"
else
title += "QingCloud: #{resource_json.resource_id} #{resource_json.resource_type}"
text = []
_.forIn rules_json, (rule) ->
if rule.alarm_policy_rule_name isnt ''
text.push "RULE_ID: #{rule.alarm_policy_rule_id} RULE_NAME: #{rule.alarm_policy_rule_name} STATUS: #{rule.status}"
else
text.push "RULE_ID: #{rule.alarm_policy_rule_id} STATUS: #{rule.status}"
text = text.join '\n'
message =
attachments: [
category: 'quote'
data:
title: title
text: text
]
message
module.exports = ->
@title = '青云'
@template = 'webhook'
@summary = util.i18n
zh: '基础设施即服务(IaaS)云平台'
en: 'IaaS Cloud Platform'
@description = util.i18n
zh: '青云 QingCloud 可在秒级时间内获取计算资源,并通过 SDN 实现虚拟路由器和交换机功能,为您提供按需分配、弹性可伸缩的计算及组网能力。在基础设施层提供完整的云化解决方案。'
en: 'QingCloud can acquire the computing resource within the second time, realize the function of virtual router and switch, and provide the distribution according to demands, the flexible calculation and networking ability.'
@iconUrl = util.static 'images/icons/qingcloud@2x.png'
@_fields.push
key: '<KEY>'
type: 'text'
description: util.i18n
zh: '第一次添加聚合时必填'
en: 'Required for creating a integration'
@_fields.push
key: '<KEY>'
type: 'text'
readonly: true
description: util.i18n
zh: '复制 web hook 地址到你的青云中使用。'
en: 'Copy this web hook to your Qing Cloud account to use it.'
@registerEvent 'service.webhook', _receiveWebhook
| true | _ = require 'lodash'
util = require '../util'
_receiveWebhook = ({integration, body}) ->
payload = body
return integration.token unless payload.resource
title = ''
resource = payload.resource.replace(/(')|(u\')/g, '"')
resource_json = JSON.parse resource
rules = payload.rules.replace(/'/g, '"')
rules_json = JSON.parse rules
if resource_json.resource_name isnt ''
title += "QingCloud: #{resource_json.resource_id} #{resource_json.resource_name} #{resource_json.resource_type}"
else
title += "QingCloud: #{resource_json.resource_id} #{resource_json.resource_type}"
text = []
_.forIn rules_json, (rule) ->
if rule.alarm_policy_rule_name isnt ''
text.push "RULE_ID: #{rule.alarm_policy_rule_id} RULE_NAME: #{rule.alarm_policy_rule_name} STATUS: #{rule.status}"
else
text.push "RULE_ID: #{rule.alarm_policy_rule_id} STATUS: #{rule.status}"
text = text.join '\n'
message =
attachments: [
category: 'quote'
data:
title: title
text: text
]
message
module.exports = ->
@title = '青云'
@template = 'webhook'
@summary = util.i18n
zh: '基础设施即服务(IaaS)云平台'
en: 'IaaS Cloud Platform'
@description = util.i18n
zh: '青云 QingCloud 可在秒级时间内获取计算资源,并通过 SDN 实现虚拟路由器和交换机功能,为您提供按需分配、弹性可伸缩的计算及组网能力。在基础设施层提供完整的云化解决方案。'
en: 'QingCloud can acquire the computing resource within the second time, realize the function of virtual router and switch, and provide the distribution according to demands, the flexible calculation and networking ability.'
@iconUrl = util.static 'images/icons/qingcloud@2x.png'
@_fields.push
key: 'PI:KEY:<KEY>END_PI'
type: 'text'
description: util.i18n
zh: '第一次添加聚合时必填'
en: 'Required for creating a integration'
@_fields.push
key: 'PI:KEY:<KEY>END_PI'
type: 'text'
readonly: true
description: util.i18n
zh: '复制 web hook 地址到你的青云中使用。'
en: 'Copy this web hook to your Qing Cloud account to use it.'
@registerEvent 'service.webhook', _receiveWebhook
|
[
{
"context": "###\n* md2conf-watcher\n* https://github.com/Layzie/md2conf-watcher\n*\n* Copyright (c) 2013 HIRAKI Sat",
"end": 49,
"score": 0.9996169805526733,
"start": 43,
"tag": "USERNAME",
"value": "Layzie"
},
{
"context": ".com/Layzie/md2conf-watcher\n*\n* Copyright (c) 2013 HIRA... | index.coffee | Layzie/md2conf-watcher | 1 | ###
* md2conf-watcher
* https://github.com/Layzie/md2conf-watcher
*
* Copyright (c) 2013 HIRAKI Satoru
* Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
exec = require('child_process').exec
watch = require 'node-watch'
argv = require('optimist')
.usage('Usage: $0 -d [directory]')
.demand(['d'])
.options('d',
alias: 'dir'
describe: 'directory want to watch files'
demand: true
)
.argv
colors = require 'colors'
helper = require './src/helper'
filterReg = /\.md$|\.markdown$/
# Judge existance of file/directory refred argv options
fs.exists argv.d, (exists) ->
if exists
watch(argv.d, helper.filter(filterReg, (filename) ->
console.log "#{filename} changed.".green
exec(helper.execCommand(filename), (err, stdout, stderr) ->
throw new Error('Error!'.underline.red) if err
console.log stdout
console.log stderr
console.log "#{helper.splitFilename filename}.wiki is created.".magenta
)
))
else
console.log 'File or directory is not exist.'.underline.red
process.exit 1
| 3291 | ###
* md2conf-watcher
* https://github.com/Layzie/md2conf-watcher
*
* Copyright (c) 2013 <NAME>
* Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
exec = require('child_process').exec
watch = require 'node-watch'
argv = require('optimist')
.usage('Usage: $0 -d [directory]')
.demand(['d'])
.options('d',
alias: 'dir'
describe: 'directory want to watch files'
demand: true
)
.argv
colors = require 'colors'
helper = require './src/helper'
filterReg = /\.md$|\.markdown$/
# Judge existance of file/directory refred argv options
fs.exists argv.d, (exists) ->
if exists
watch(argv.d, helper.filter(filterReg, (filename) ->
console.log "#{filename} changed.".green
exec(helper.execCommand(filename), (err, stdout, stderr) ->
throw new Error('Error!'.underline.red) if err
console.log stdout
console.log stderr
console.log "#{helper.splitFilename filename}.wiki is created.".magenta
)
))
else
console.log 'File or directory is not exist.'.underline.red
process.exit 1
| true | ###
* md2conf-watcher
* https://github.com/Layzie/md2conf-watcher
*
* Copyright (c) 2013 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
exec = require('child_process').exec
watch = require 'node-watch'
argv = require('optimist')
.usage('Usage: $0 -d [directory]')
.demand(['d'])
.options('d',
alias: 'dir'
describe: 'directory want to watch files'
demand: true
)
.argv
colors = require 'colors'
helper = require './src/helper'
filterReg = /\.md$|\.markdown$/
# Judge existance of file/directory refred argv options
fs.exists argv.d, (exists) ->
if exists
watch(argv.d, helper.filter(filterReg, (filename) ->
console.log "#{filename} changed.".green
exec(helper.execCommand(filename), (err, stdout, stderr) ->
throw new Error('Error!'.underline.red) if err
console.log stdout
console.log stderr
console.log "#{helper.splitFilename filename}.wiki is created.".magenta
)
))
else
console.log 'File or directory is not exist.'.underline.red
process.exit 1
|
[
{
"context": "trol.addTo(window.map)\n \n L.tileLayer \"http://160.94.51.184/slides/2340/tile_{z}_{x}_{y}.jpg\", \n attributi",
"end": 830,
"score": 0.9853832721710205,
"start": 817,
"tag": "IP_ADDRESS",
"value": "160.94.51.184"
}
] | client/client.coffee | bdunnette/meteor-virtualscope | 1 | # create marker collection
Meteor.subscribe('markers')
Markers = new Meteor.Collection('markers')
# resize the layout
window.resize = (t) ->
w = window.innerWidth
h = window.innerHeight
top = t.find('#map').offsetTop
c = w - 40
m = (h-top) - 65
t.find('#container').style.width = "#{c}px"
t.find('#map').style.height = "#{m}px"
Template.map.rendered = ->
# resize on load
window.resize(@)
# resize on resize of window
$(window).resize =>
window.resize(@)
# create default image path
L.Icon.Default.imagePath = 'packages/leaflet/images'
# create a map in the map div, set the view to a given place and zoom
window.map = L.map('map')
.setView([0, 0], 5)
if Meteor.userId()
drawControl = new L.Control.Draw()
drawControl.addTo(window.map)
L.tileLayer "http://160.94.51.184/slides/2340/tile_{z}_{x}_{y}.jpg",
attribution: 'Images © University of Minnesota 2013'
.addTo(window.map)
window.map.on 'draw:created', (e) ->
console.log(e)
Markers.insert
latlng: e.layer._latlng
zoom: window.map.getZoom()
created:
by: Meteor.user()._id
on: new Date().toISOString()
# watch the markers collection
query = Markers.find({})
query.observe
# when new marker - then add to map and when on click then remove
added: (mark) ->
console.log(mark)
console.log(Meteor.users.find({_id: mark.created.by}).fetch())
marker = L.marker(mark.latlng)
.addTo(window.map)
.bindPopup(Date(mark.created.on))
.on 'dblclick', (e) ->
if Meteor.userId()
m = Markers.findOne({latlng: @._latlng})
console.log(m)
Markers.remove(m._id)
# when removing marker - loop through all layers on the map and remove the matching layer (marker)
# matching based on matching lat/lon
removed: (mark) ->
console.log(mark)
layers = window.map._layers
for key, val of layers
if !val._latlng
else
if val._latlng.lat is mark.latlng.lat and val._latlng.lng is mark.latlng.lng
window.map.removeLayer(val)
| 106401 | # create marker collection
Meteor.subscribe('markers')
Markers = new Meteor.Collection('markers')
# resize the layout
window.resize = (t) ->
w = window.innerWidth
h = window.innerHeight
top = t.find('#map').offsetTop
c = w - 40
m = (h-top) - 65
t.find('#container').style.width = "#{c}px"
t.find('#map').style.height = "#{m}px"
Template.map.rendered = ->
# resize on load
window.resize(@)
# resize on resize of window
$(window).resize =>
window.resize(@)
# create default image path
L.Icon.Default.imagePath = 'packages/leaflet/images'
# create a map in the map div, set the view to a given place and zoom
window.map = L.map('map')
.setView([0, 0], 5)
if Meteor.userId()
drawControl = new L.Control.Draw()
drawControl.addTo(window.map)
L.tileLayer "http://172.16.58.3/slides/2340/tile_{z}_{x}_{y}.jpg",
attribution: 'Images © University of Minnesota 2013'
.addTo(window.map)
window.map.on 'draw:created', (e) ->
console.log(e)
Markers.insert
latlng: e.layer._latlng
zoom: window.map.getZoom()
created:
by: Meteor.user()._id
on: new Date().toISOString()
# watch the markers collection
query = Markers.find({})
query.observe
# when new marker - then add to map and when on click then remove
added: (mark) ->
console.log(mark)
console.log(Meteor.users.find({_id: mark.created.by}).fetch())
marker = L.marker(mark.latlng)
.addTo(window.map)
.bindPopup(Date(mark.created.on))
.on 'dblclick', (e) ->
if Meteor.userId()
m = Markers.findOne({latlng: @._latlng})
console.log(m)
Markers.remove(m._id)
# when removing marker - loop through all layers on the map and remove the matching layer (marker)
# matching based on matching lat/lon
removed: (mark) ->
console.log(mark)
layers = window.map._layers
for key, val of layers
if !val._latlng
else
if val._latlng.lat is mark.latlng.lat and val._latlng.lng is mark.latlng.lng
window.map.removeLayer(val)
| true | # create marker collection
Meteor.subscribe('markers')
Markers = new Meteor.Collection('markers')
# resize the layout
window.resize = (t) ->
w = window.innerWidth
h = window.innerHeight
top = t.find('#map').offsetTop
c = w - 40
m = (h-top) - 65
t.find('#container').style.width = "#{c}px"
t.find('#map').style.height = "#{m}px"
Template.map.rendered = ->
# resize on load
window.resize(@)
# resize on resize of window
$(window).resize =>
window.resize(@)
# create default image path
L.Icon.Default.imagePath = 'packages/leaflet/images'
# create a map in the map div, set the view to a given place and zoom
window.map = L.map('map')
.setView([0, 0], 5)
if Meteor.userId()
drawControl = new L.Control.Draw()
drawControl.addTo(window.map)
L.tileLayer "http://PI:IP_ADDRESS:172.16.58.3END_PI/slides/2340/tile_{z}_{x}_{y}.jpg",
attribution: 'Images © University of Minnesota 2013'
.addTo(window.map)
window.map.on 'draw:created', (e) ->
console.log(e)
Markers.insert
latlng: e.layer._latlng
zoom: window.map.getZoom()
created:
by: Meteor.user()._id
on: new Date().toISOString()
# watch the markers collection
query = Markers.find({})
query.observe
# when new marker - then add to map and when on click then remove
added: (mark) ->
console.log(mark)
console.log(Meteor.users.find({_id: mark.created.by}).fetch())
marker = L.marker(mark.latlng)
.addTo(window.map)
.bindPopup(Date(mark.created.on))
.on 'dblclick', (e) ->
if Meteor.userId()
m = Markers.findOne({latlng: @._latlng})
console.log(m)
Markers.remove(m._id)
# when removing marker - loop through all layers on the map and remove the matching layer (marker)
# matching based on matching lat/lon
removed: (mark) ->
console.log(mark)
layers = window.map._layers
for key, val of layers
if !val._latlng
else
if val._latlng.lat is mark.latlng.lat and val._latlng.lng is mark.latlng.lng
window.map.removeLayer(val)
|
[
{
"context": "_family:cb', $:'cc'}\n {key:'test_filter|row_3', column:'node_column_family:cc', $:'cc'}\n ",
"end": 3615,
"score": 0.6918073892593384,
"start": 3615,
"tag": "KEY",
"value": ""
},
{
"context": "h.should.eql 3\n cells[0].key.should.eql 'test_filter|r... | test/filter.coffee | LiveTex/node-hbase | 0 |
fs = require 'fs'
should = require 'should'
test = require './test'
hbase = require '..'
Scanner = require '../lib/scanner'
#{"op":"LESS","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"GREATER_OR_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"GREATER","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"testValue((One)|(Two))","type":"RegexStringComparator"}}
#{"op":"LESS","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"GREATER_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"GREATER","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"type":"SkipFilter","filters":[{"op":"NOT_EQUAL","type":"QualifierFilter","comparator":{"value":"dGVzdFF1YWxpZmllck9uZS0y","type":"BinaryComparator"}}]}
#{"op":"MUST_PASS_ALL","type":"FilterList","filters":[{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"QualifierFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"one","type":"SubstringComparator"}}]}
#{"op":"MUST_PASS_ONE","type":"FilterList","filters":[{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+Two.+","type":"RegexStringComparator"}},{"op":"EQUAL","type":"QualifierFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"one","type":"SubstringComparator"}}]}
describe 'filter', ->
it 'Option filter', (next) ->
test.getClient (err, client) ->
time = (new Date).getTime()
client
.getRow('node_table')
.put [
{key:'test_filter|row_1', column:'node_column_family:aa', $:'aa'}
{key:'test_filter|row_1', column:'node_column_family:aa', $:'ab'}
{key:'test_filter|row_1', column:'node_column_family:aa', $:'ac'}
{key:'test_filter|row_2', column:'node_column_family:ab', $:'ba'}
{key:'test_filter|row_2', column:'node_column_family:bb', $:'bb'}
{key:'test_filter|row_2', column:'node_column_family:bc', $:'bc'}
{key:'test_filter|row_3', column:'node_column_family:ca', $:'cc'}
{key:'test_filter|row_3', column:'node_column_family:cb', $:'cc'}
{key:'test_filter|row_3', column:'node_column_family:cc', $:'cc'}
], (err, success) ->
should.not.exist err
next()
it 'FilterList # must_pass_all # +RegexStringComparator', (next) ->
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
maxVersions: 1
filter: {
"op":"MUST_PASS_ALL","type":"FilterList","filters":[
{"op":"EQUAL","type":"RowFilter","comparator":{"value":"test_filter\\|row_.*","type":"RegexStringComparator"}}
{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+2$","type":"RegexStringComparator"}}
]}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 3
cells[0].key.should.eql 'test_filter|row_2'
cells[1].key.should.eql 'test_filter|row_2'
cells[2].key.should.eql 'test_filter|row_2'
this.delete next
it 'FirstKeyOnlyFilter', (next) ->
test.getClient (err, client) ->
# Only return the first KV from each row.
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
filter: {'type':'FirstKeyOnlyFilter'}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.be.above 2
cells[0].key.should.eql 'test_filter|row_1'
cells[1].key.should.eql 'test_filter|row_2'
cells[2].key.should.eql 'test_filter|row_3'
this.delete next
it 'PageFilter # string value', (next) ->
getKeysFromCells = (cells) ->
keys = []
cells.forEach (cell) ->
if keys.indexOf(cell['key']) is -1
keys.push cell['key']
keys
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"type":"PageFilter","value":"2"}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.eql 4
keys = getKeysFromCells(cells)
keys.should.eql ['test_filter|row_1','test_filter|row_2']
this.delete next
it 'PageFilter # int value', (next) ->
getKeysFromCells = (cells) ->
keys = []
cells.forEach (cell) ->
if keys.indexOf(cell['key']) is -1
keys.push cell['key']
keys
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"type":"PageFilter","value":2}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.eql 4
keys = getKeysFromCells(cells)
keys.should.eql ['test_filter|row_1','test_filter|row_2']
this.delete next
it 'RowFilter # equal_with_binary_comparator', (next) ->
test.getClient (err, client) ->
# Based on the key
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
maxVersions: 1
filter: {'op':'EQUAL','type':'RowFilter','comparator':{'value':'test_filter|row_2','type':'BinaryComparator'}}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 3
this.delete next
it 'ValueFilter # op equal', (next) ->
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"op":"EQUAL","type":"ValueFilter","comparator":{"value":"bb","type":"BinaryComparator"}}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 1
cells[0].key.should.eql 'test_filter|row_2'
cells[0].column.should.eql 'node_column_family:bb'
this.delete next
| 92579 |
fs = require 'fs'
should = require 'should'
test = require './test'
hbase = require '..'
Scanner = require '../lib/scanner'
#{"op":"LESS","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"GREATER_OR_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"GREATER","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"testValue((One)|(Two))","type":"RegexStringComparator"}}
#{"op":"LESS","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"GREATER_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"GREATER","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"type":"SkipFilter","filters":[{"op":"NOT_EQUAL","type":"QualifierFilter","comparator":{"value":"dGVzdFF1YWxpZmllck9uZS0y","type":"BinaryComparator"}}]}
#{"op":"MUST_PASS_ALL","type":"FilterList","filters":[{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"QualifierFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"one","type":"SubstringComparator"}}]}
#{"op":"MUST_PASS_ONE","type":"FilterList","filters":[{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+Two.+","type":"RegexStringComparator"}},{"op":"EQUAL","type":"QualifierFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"one","type":"SubstringComparator"}}]}
describe 'filter', ->
it 'Option filter', (next) ->
test.getClient (err, client) ->
time = (new Date).getTime()
client
.getRow('node_table')
.put [
{key:'test_filter|row_1', column:'node_column_family:aa', $:'aa'}
{key:'test_filter|row_1', column:'node_column_family:aa', $:'ab'}
{key:'test_filter|row_1', column:'node_column_family:aa', $:'ac'}
{key:'test_filter|row_2', column:'node_column_family:ab', $:'ba'}
{key:'test_filter|row_2', column:'node_column_family:bb', $:'bb'}
{key:'test_filter|row_2', column:'node_column_family:bc', $:'bc'}
{key:'test_filter|row_3', column:'node_column_family:ca', $:'cc'}
{key:'test_filter|row_3', column:'node_column_family:cb', $:'cc'}
{key:'test_filter|row<KEY>_3', column:'node_column_family:cc', $:'cc'}
], (err, success) ->
should.not.exist err
next()
it 'FilterList # must_pass_all # +RegexStringComparator', (next) ->
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
maxVersions: 1
filter: {
"op":"MUST_PASS_ALL","type":"FilterList","filters":[
{"op":"EQUAL","type":"RowFilter","comparator":{"value":"test_filter\\|row_.*","type":"RegexStringComparator"}}
{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+2$","type":"RegexStringComparator"}}
]}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 3
cells[0].key.should.eql '<KEY>'
cells[1].key.should.eql '<KEY>'
cells[2].key.should.eql '<KEY>'
this.delete next
it 'FirstKeyOnlyFilter', (next) ->
test.getClient (err, client) ->
# Only return the first KV from each row.
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
filter: {'type':'FirstKeyOnlyFilter'}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.be.above 2
cells[0].key.should.eql '<KEY>'
cells[1].key.should.eql '<KEY>|row_2'
cells[2].key.should.eql '<KEY>'
this.delete next
it 'PageFilter # string value', (next) ->
getKeysFromCells = (cells) ->
keys = []
cells.forEach (cell) ->
if keys.indexOf(cell['key']) is -1
keys.push cell['key']
keys
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"type":"PageFilter","value":"2"}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.eql 4
keys = getKeysFromCells(cells)
keys.should.eql ['test_filter|row_1','test_filter|row_2']
this.delete next
it 'PageFilter # int value', (next) ->
getKeysFromCells = (cells) ->
keys = []
cells.forEach (cell) ->
if keys.indexOf(cell['key']) is -1
keys.push cell['key']
keys
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"type":"PageFilter","value":2}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.eql 4
keys = getKeysFromCells(cells)
keys.should.eql ['test_filter|row_1','test_filter|row_2']
this.delete next
it 'RowFilter # equal_with_binary_comparator', (next) ->
test.getClient (err, client) ->
# Based on the key
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
maxVersions: 1
filter: {'op':'EQUAL','type':'RowFilter','comparator':{'value':'test_filter|row_2','type':'BinaryComparator'}}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 3
this.delete next
it 'ValueFilter # op equal', (next) ->
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"op":"EQUAL","type":"ValueFilter","comparator":{"value":"bb","type":"BinaryComparator"}}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 1
cells[0].key.should.eql 'test_filter|row_2'
cells[0].column.should.eql 'node_column_family:bb'
this.delete next
| true |
fs = require 'fs'
should = require 'should'
test = require './test'
hbase = require '..'
Scanner = require '../lib/scanner'
#{"op":"LESS","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"GREATER_OR_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"GREATER","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"RowFilter","comparator":{"value":"dGVzdFJvd09uZS0y","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"testValue((One)|(Two))","type":"RegexStringComparator"}}
#{"op":"LESS","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlVHdv","type":"BinaryComparator"}}
#{"op":"LESS_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"GREATER_OR_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"GREATER","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"op":"NOT_EQUAL","type":"ValueFilter","comparator":{"value":"dGVzdFZhbHVlT25l","type":"BinaryComparator"}}
#{"type":"SkipFilter","filters":[{"op":"NOT_EQUAL","type":"QualifierFilter","comparator":{"value":"dGVzdFF1YWxpZmllck9uZS0y","type":"BinaryComparator"}}]}
#{"op":"MUST_PASS_ALL","type":"FilterList","filters":[{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"QualifierFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"one","type":"SubstringComparator"}}]}
#{"op":"MUST_PASS_ONE","type":"FilterList","filters":[{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+Two.+","type":"RegexStringComparator"}},{"op":"EQUAL","type":"QualifierFilter","comparator":{"value":".+-2","type":"RegexStringComparator"}},{"op":"EQUAL","type":"ValueFilter","comparator":{"value":"one","type":"SubstringComparator"}}]}
describe 'filter', ->
it 'Option filter', (next) ->
test.getClient (err, client) ->
time = (new Date).getTime()
client
.getRow('node_table')
.put [
{key:'test_filter|row_1', column:'node_column_family:aa', $:'aa'}
{key:'test_filter|row_1', column:'node_column_family:aa', $:'ab'}
{key:'test_filter|row_1', column:'node_column_family:aa', $:'ac'}
{key:'test_filter|row_2', column:'node_column_family:ab', $:'ba'}
{key:'test_filter|row_2', column:'node_column_family:bb', $:'bb'}
{key:'test_filter|row_2', column:'node_column_family:bc', $:'bc'}
{key:'test_filter|row_3', column:'node_column_family:ca', $:'cc'}
{key:'test_filter|row_3', column:'node_column_family:cb', $:'cc'}
{key:'test_filter|rowPI:KEY:<KEY>END_PI_3', column:'node_column_family:cc', $:'cc'}
], (err, success) ->
should.not.exist err
next()
it 'FilterList # must_pass_all # +RegexStringComparator', (next) ->
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
maxVersions: 1
filter: {
"op":"MUST_PASS_ALL","type":"FilterList","filters":[
{"op":"EQUAL","type":"RowFilter","comparator":{"value":"test_filter\\|row_.*","type":"RegexStringComparator"}}
{"op":"EQUAL","type":"RowFilter","comparator":{"value":".+2$","type":"RegexStringComparator"}}
]}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 3
cells[0].key.should.eql 'PI:KEY:<KEY>END_PI'
cells[1].key.should.eql 'PI:KEY:<KEY>END_PI'
cells[2].key.should.eql 'PI:KEY:<KEY>END_PI'
this.delete next
it 'FirstKeyOnlyFilter', (next) ->
test.getClient (err, client) ->
# Only return the first KV from each row.
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
filter: {'type':'FirstKeyOnlyFilter'}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.be.above 2
cells[0].key.should.eql 'PI:KEY:<KEY>END_PI'
cells[1].key.should.eql 'PI:KEY:<KEY>END_PI|row_2'
cells[2].key.should.eql 'PI:KEY:<KEY>END_PI'
this.delete next
it 'PageFilter # string value', (next) ->
getKeysFromCells = (cells) ->
keys = []
cells.forEach (cell) ->
if keys.indexOf(cell['key']) is -1
keys.push cell['key']
keys
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"type":"PageFilter","value":"2"}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.eql 4
keys = getKeysFromCells(cells)
keys.should.eql ['test_filter|row_1','test_filter|row_2']
this.delete next
it 'PageFilter # int value', (next) ->
getKeysFromCells = (cells) ->
keys = []
cells.forEach (cell) ->
if keys.indexOf(cell['key']) is -1
keys.push cell['key']
keys
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"type":"PageFilter","value":2}
, (err, id) ->
should.not.exist err
this.get (err, cells) ->
should.not.exist err
cells.length.should.eql 4
keys = getKeysFromCells(cells)
keys.should.eql ['test_filter|row_1','test_filter|row_2']
this.delete next
it 'RowFilter # equal_with_binary_comparator', (next) ->
test.getClient (err, client) ->
# Based on the key
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
maxVersions: 1
filter: {'op':'EQUAL','type':'RowFilter','comparator':{'value':'test_filter|row_2','type':'BinaryComparator'}}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 3
this.delete next
it 'ValueFilter # op equal', (next) ->
test.getClient (err, client) ->
client
.getScanner('node_table')
.create
startRow: 'test_filter|row_1'
endRow: 'test_filter|row_4'
maxVersions: 1
filter: {"op":"EQUAL","type":"ValueFilter","comparator":{"value":"bb","type":"BinaryComparator"}}
, (err, id) ->
should.not.exist err
this.get (err,cells) ->
should.not.exist err
cells.length.should.eql 1
cells[0].key.should.eql 'test_filter|row_2'
cells[0].column.should.eql 'node_column_family:bb'
this.delete next
|
[
{
"context": "###\nCopyright 2017 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 25,
"score": 0.9995467662811279,
"start": 19,
"tag": "NAME",
"value": "Balena"
}
] | lib/actions/local/index.coffee | eternius/otto-cli | 0 | ###
Copyright 2017 Balena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
exports.configure = require('./configure')
exports.flash = require('./flash').flash
| 26522 | ###
Copyright 2017 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
exports.configure = require('./configure')
exports.flash = require('./flash').flash
| true | ###
Copyright 2017 PI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
exports.configure = require('./configure')
exports.flash = require('./flash').flash
|
[
{
"context": " connection:\n host: '127.0.0.1'\n user: 'test'\n ",
"end": 675,
"score": 0.9997093677520752,
"start": 666,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " user: 'test'\n p... | test/init.coffee | bgaeddert/bookshelf-schema | 44 | Knex = require 'knex'
Bookshelf = require 'bookshelf'
Schema = require '../src/'
db = null
initDb = ->
db_variant = process.env.BOOKSHELF_SCHEMA_TESTS_DB_VARIANT
db_variant ?= 'sqlite'
knex = switch db_variant
when 'sqlite'
Knex
client: 'sqlite'
debug: process.env.BOOKSHELF_SCHEMA_TESTS_DEBUG?
connection:
filename: ':memory:'
useNullAsDefault: true
when 'pg', 'postgres'
Knex
client: 'pg'
debug: process.env.BOOKSHELF_SCHEMA_TESTS_DEBUG?
connection:
host: '127.0.0.1'
user: 'test'
password: 'test'
database: 'test'
charset: 'utf8'
useNullAsDefault: true
else throw new Error "Unknown db variant: #{db_variant}"
db = Bookshelf knex
init = (pluginOptions) ->
return db if db?
db = initDb()
db.plugin Schema(pluginOptions)
db
truncate = co (tables...) -> yield (db.knex(table).truncate() for table in tables)
users = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'users'
yield knex.schema.createTable 'users', (table) ->
table.increments('id').primary()
table.string 'username', 255
table.string 'password', 1024
table.string 'email', 255
table.float 'code'
table.boolean 'flag'
table.dateTime 'last_login'
table.date 'birth_date'
table.json 'additional_data'
table.integer 'inviter_id'
photos = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'photos'
yield knex.schema.createTable 'photos', (table) ->
table.increments('id').primary()
table.string 'filename', 255
table.integer 'user_id'
table.string 'user_name', 255
profiles = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'profiles'
yield knex.schema.createTable 'profiles', (table) ->
table.increments('id').primary()
table.string 'greetings', 255
table.integer 'user_id'
groups = co ->
init() unless db
knex = db.knex
yield [
knex.schema.dropTableIfExists 'groups'
knex.schema.dropTableIfExists 'groups_users'
]
yield knex.schema.createTable 'groups', (table) ->
table.increments('id').primary()
table.string 'name', 255
yield knex.schema.createTable 'groups_users', (table) ->
table.integer 'user_id'
table.integer 'group_id'
tags = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'tags'
yield knex.schema.createTable 'tags', (table) ->
table.increments('id').primary()
table.string 'name', 255
table.integer 'tagable_id'
table.string 'tagable_type', 255
inviters = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'inviters'
yield knex.schema.createTable 'inviters', (table) ->
table.increments('id').primary()
table.string 'greeting'
table.integer 'user_id'
module.exports =
initDb: initDb
init: init
truncate: truncate
users: users
photos: photos
profiles: profiles
groups: groups
tags: tags
inviters: inviters
| 6020 | Knex = require 'knex'
Bookshelf = require 'bookshelf'
Schema = require '../src/'
db = null
initDb = ->
db_variant = process.env.BOOKSHELF_SCHEMA_TESTS_DB_VARIANT
db_variant ?= 'sqlite'
knex = switch db_variant
when 'sqlite'
Knex
client: 'sqlite'
debug: process.env.BOOKSHELF_SCHEMA_TESTS_DEBUG?
connection:
filename: ':memory:'
useNullAsDefault: true
when 'pg', 'postgres'
Knex
client: 'pg'
debug: process.env.BOOKSHELF_SCHEMA_TESTS_DEBUG?
connection:
host: '127.0.0.1'
user: 'test'
password: '<PASSWORD>'
database: 'test'
charset: 'utf8'
useNullAsDefault: true
else throw new Error "Unknown db variant: #{db_variant}"
db = Bookshelf knex
init = (pluginOptions) ->
return db if db?
db = initDb()
db.plugin Schema(pluginOptions)
db
truncate = co (tables...) -> yield (db.knex(table).truncate() for table in tables)
users = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'users'
yield knex.schema.createTable 'users', (table) ->
table.increments('id').primary()
table.string 'username', 255
table.string 'password', <PASSWORD>
table.string 'email', 255
table.float 'code'
table.boolean 'flag'
table.dateTime 'last_login'
table.date 'birth_date'
table.json 'additional_data'
table.integer 'inviter_id'
photos = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'photos'
yield knex.schema.createTable 'photos', (table) ->
table.increments('id').primary()
table.string 'filename', 255
table.integer 'user_id'
table.string 'user_name', 255
profiles = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'profiles'
yield knex.schema.createTable 'profiles', (table) ->
table.increments('id').primary()
table.string 'greetings', 255
table.integer 'user_id'
groups = co ->
init() unless db
knex = db.knex
yield [
knex.schema.dropTableIfExists 'groups'
knex.schema.dropTableIfExists 'groups_users'
]
yield knex.schema.createTable 'groups', (table) ->
table.increments('id').primary()
table.string 'name', 255
yield knex.schema.createTable 'groups_users', (table) ->
table.integer 'user_id'
table.integer 'group_id'
tags = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'tags'
yield knex.schema.createTable 'tags', (table) ->
table.increments('id').primary()
table.string 'name', 255
table.integer 'tagable_id'
table.string 'tagable_type', 255
inviters = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'inviters'
yield knex.schema.createTable 'inviters', (table) ->
table.increments('id').primary()
table.string 'greeting'
table.integer 'user_id'
module.exports =
initDb: initDb
init: init
truncate: truncate
users: users
photos: photos
profiles: profiles
groups: groups
tags: tags
inviters: inviters
| true | Knex = require 'knex'
Bookshelf = require 'bookshelf'
Schema = require '../src/'
db = null
initDb = ->
db_variant = process.env.BOOKSHELF_SCHEMA_TESTS_DB_VARIANT
db_variant ?= 'sqlite'
knex = switch db_variant
when 'sqlite'
Knex
client: 'sqlite'
debug: process.env.BOOKSHELF_SCHEMA_TESTS_DEBUG?
connection:
filename: ':memory:'
useNullAsDefault: true
when 'pg', 'postgres'
Knex
client: 'pg'
debug: process.env.BOOKSHELF_SCHEMA_TESTS_DEBUG?
connection:
host: '127.0.0.1'
user: 'test'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
database: 'test'
charset: 'utf8'
useNullAsDefault: true
else throw new Error "Unknown db variant: #{db_variant}"
db = Bookshelf knex
init = (pluginOptions) ->
return db if db?
db = initDb()
db.plugin Schema(pluginOptions)
db
truncate = co (tables...) -> yield (db.knex(table).truncate() for table in tables)
users = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'users'
yield knex.schema.createTable 'users', (table) ->
table.increments('id').primary()
table.string 'username', 255
table.string 'password', PI:PASSWORD:<PASSWORD>END_PI
table.string 'email', 255
table.float 'code'
table.boolean 'flag'
table.dateTime 'last_login'
table.date 'birth_date'
table.json 'additional_data'
table.integer 'inviter_id'
photos = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'photos'
yield knex.schema.createTable 'photos', (table) ->
table.increments('id').primary()
table.string 'filename', 255
table.integer 'user_id'
table.string 'user_name', 255
profiles = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'profiles'
yield knex.schema.createTable 'profiles', (table) ->
table.increments('id').primary()
table.string 'greetings', 255
table.integer 'user_id'
groups = co ->
init() unless db
knex = db.knex
yield [
knex.schema.dropTableIfExists 'groups'
knex.schema.dropTableIfExists 'groups_users'
]
yield knex.schema.createTable 'groups', (table) ->
table.increments('id').primary()
table.string 'name', 255
yield knex.schema.createTable 'groups_users', (table) ->
table.integer 'user_id'
table.integer 'group_id'
tags = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'tags'
yield knex.schema.createTable 'tags', (table) ->
table.increments('id').primary()
table.string 'name', 255
table.integer 'tagable_id'
table.string 'tagable_type', 255
inviters = co ->
init() unless db
knex = db.knex
yield knex.schema.dropTableIfExists 'inviters'
yield knex.schema.createTable 'inviters', (table) ->
table.increments('id').primary()
table.string 'greeting'
table.integer 'user_id'
module.exports =
initDb: initDb
init: init
truncate: truncate
users: users
photos: photos
profiles: profiles
groups: groups
tags: tags
inviters: inviters
|
[
{
"context": ")\n\n suite 'should be invalid:', ->\n test 'foo@@bla.com', ->\n format.value = 'foo@@bla.com'\n ",
"end": 318,
"score": 0.9996626377105713,
"start": 306,
"tag": "EMAIL",
"value": "foo@@bla.com"
},
{
"context": " test 'foo@@bla.com', ->\n for... | este/validators/format_test.coffee | vlkous/este-library | 0 | suite 'este.validators.format', ->
format = null
setup ->
format = este.validators.format(/^\d+$/)()
suite 'validate', ->
suite 'should be valid:', ->
test '123', ->
format.value = '123'
assert.isTrue format.validate()
suite 'should be invalid:', ->
test 'foo@@bla.com', ->
format.value = 'foo@@bla.com'
assert.isFalse format.validate()
suite 'getMsg', ->
test 'should return message', ->
assert.equal format.getMsg(), 'Please enter a value in correct format.'
test 'should return alternative message', ->
getMsg = -> 'This is not format.'
format = este.validators.format(/^\d+$/, getMsg)()
assert.equal format.getMsg(), getMsg() | 128237 | suite 'este.validators.format', ->
format = null
setup ->
format = este.validators.format(/^\d+$/)()
suite 'validate', ->
suite 'should be valid:', ->
test '123', ->
format.value = '123'
assert.isTrue format.validate()
suite 'should be invalid:', ->
test '<EMAIL>', ->
format.value = '<EMAIL>'
assert.isFalse format.validate()
suite 'getMsg', ->
test 'should return message', ->
assert.equal format.getMsg(), 'Please enter a value in correct format.'
test 'should return alternative message', ->
getMsg = -> 'This is not format.'
format = este.validators.format(/^\d+$/, getMsg)()
assert.equal format.getMsg(), getMsg() | true | suite 'este.validators.format', ->
format = null
setup ->
format = este.validators.format(/^\d+$/)()
suite 'validate', ->
suite 'should be valid:', ->
test '123', ->
format.value = '123'
assert.isTrue format.validate()
suite 'should be invalid:', ->
test 'PI:EMAIL:<EMAIL>END_PI', ->
format.value = 'PI:EMAIL:<EMAIL>END_PI'
assert.isFalse format.validate()
suite 'getMsg', ->
test 'should return message', ->
assert.equal format.getMsg(), 'Please enter a value in correct format.'
test 'should return alternative message', ->
getMsg = -> 'This is not format.'
format = este.validators.format(/^\d+$/, getMsg)()
assert.equal format.getMsg(), getMsg() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.