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": "il.port')\n user: config.get('email.user')\n pass: config.get('email.password')\n from: config.get('email.from'",
"end": 938,
"score": 0.9980164170265198,
"start": 928,
"tag": "PASSWORD",
"value": "config.get"
},
{
"context": "ser: config.get('email.user')\n pass: c... | app.coffee | micirclek/cki-portal | 0 | # initial requires (set up coffeescript stuff)
require('./server/lib/bootstrap')
bodyParser = require('body-parser')
config = require('config')
cookieParser = require('cookie-parser')
express = require('express')
favicon = require('serve-favicon')
fs = require('fs')
http = require('http')
https = require('https')
loggly = require('winston-loggly')
morgan = require('morgan')
passport = require('passport')
raven = require('raven')
requireDir = require('require-dir')
winston = require('winston')
Handler = require(App.path('server/api/1/handler'))
LocalStrategy = require('passport-local').Strategy
RavenLogger = App.lib('ravenLogger')
# require and initialize modules
Db = App.module('database').initialize
uri: config.get('db.uri')
Emailer = App.module('emailer').initialize
host: config.get('email.host')
secure: config.get('email.secure')
port: config.get('email.port')
user: config.get('email.user')
pass: config.get('email.password')
from: config.get('email.from')
enable: config.get('email.enable')
Logger.add(winston.transports.Console, level: config.get('logging.consoleLevel'))
if config.get('logging.logglyLevel') != 'silent'
Logger.add loggly.Loggly,
level: config.get('logging.logglyLevel')
subdomain: config.get('logging.logglySubdomain')
inputToken: config.get('logging.logglyToken')
json: true
stripColors: true
if config.get('logging.ravenLevel') != 'silent'
ravenClient = new raven.Client(config.get('logging.sentryDSN'))
Logger.add RavenLogger,
level: config.get('logging.ravenLevel')
raven: ravenClient
Promise.onPossiblyUnhandledRejection (err, promise) ->
Logger.error(err)
Promise.longStackTraces()
app = express()
# do not log url parameters
morgan.token('url', (req, res) -> req.path)
loggerStream =
write: (message) ->
Logger.info(message.trim())
# this is exactly the dev format, minus the colours
loggerFormat = ':method :url :status :response-time ms - :res[content-length]'
app.set('port', Number(process.env.PORT || config.get('server.port')))
app.use(morgan(loggerFormat, stream: loggerStream))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(extended: true))
app.use(cookieParser(config.get('secret')))
app.use(favicon(App.path(config.get('paths.staticPath'), '/favicon.ico')))
app.use(express.static(App.path(config.get('paths.staticPath'))))
passport.use(Db.User.createStrategy())
passport.serializeUser(Db.User.serializeUser())
passport.deserializeUser(Db.User.deserializeUser())
app.use passport.initialize
userProperty: 'me'
app.use(passport.authenticate('token'))
Handler.listenAll(app)
server = http.createServer(app)
server.listen app.get('port'), ->
Logger.debug('Express server listening on port ' + app.get('port'))
| 148280 | # initial requires (set up coffeescript stuff)
require('./server/lib/bootstrap')
bodyParser = require('body-parser')
config = require('config')
cookieParser = require('cookie-parser')
express = require('express')
favicon = require('serve-favicon')
fs = require('fs')
http = require('http')
https = require('https')
loggly = require('winston-loggly')
morgan = require('morgan')
passport = require('passport')
raven = require('raven')
requireDir = require('require-dir')
winston = require('winston')
Handler = require(App.path('server/api/1/handler'))
LocalStrategy = require('passport-local').Strategy
RavenLogger = App.lib('ravenLogger')
# require and initialize modules
Db = App.module('database').initialize
uri: config.get('db.uri')
Emailer = App.module('emailer').initialize
host: config.get('email.host')
secure: config.get('email.secure')
port: config.get('email.port')
user: config.get('email.user')
pass: <PASSWORD>('<PASSWORD>')
from: config.get('email.from')
enable: config.get('email.enable')
Logger.add(winston.transports.Console, level: config.get('logging.consoleLevel'))
if config.get('logging.logglyLevel') != 'silent'
Logger.add loggly.Loggly,
level: config.get('logging.logglyLevel')
subdomain: config.get('logging.logglySubdomain')
inputToken: config.get('logging.logglyToken')
json: true
stripColors: true
if config.get('logging.ravenLevel') != 'silent'
ravenClient = new raven.Client(config.get('logging.sentryDSN'))
Logger.add RavenLogger,
level: config.get('logging.ravenLevel')
raven: ravenClient
Promise.onPossiblyUnhandledRejection (err, promise) ->
Logger.error(err)
Promise.longStackTraces()
app = express()
# do not log url parameters
morgan.token('url', (req, res) -> req.path)
loggerStream =
write: (message) ->
Logger.info(message.trim())
# this is exactly the dev format, minus the colours
loggerFormat = ':method :url :status :response-time ms - :res[content-length]'
app.set('port', Number(process.env.PORT || config.get('server.port')))
app.use(morgan(loggerFormat, stream: loggerStream))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(extended: true))
app.use(cookieParser(config.get('secret')))
app.use(favicon(App.path(config.get('paths.staticPath'), '/favicon.ico')))
app.use(express.static(App.path(config.get('paths.staticPath'))))
passport.use(Db.User.createStrategy())
passport.serializeUser(Db.User.serializeUser())
passport.deserializeUser(Db.User.deserializeUser())
app.use passport.initialize
userProperty: 'me'
app.use(passport.authenticate('token'))
Handler.listenAll(app)
server = http.createServer(app)
server.listen app.get('port'), ->
Logger.debug('Express server listening on port ' + app.get('port'))
| true | # initial requires (set up coffeescript stuff)
require('./server/lib/bootstrap')
bodyParser = require('body-parser')
config = require('config')
cookieParser = require('cookie-parser')
express = require('express')
favicon = require('serve-favicon')
fs = require('fs')
http = require('http')
https = require('https')
loggly = require('winston-loggly')
morgan = require('morgan')
passport = require('passport')
raven = require('raven')
requireDir = require('require-dir')
winston = require('winston')
Handler = require(App.path('server/api/1/handler'))
LocalStrategy = require('passport-local').Strategy
RavenLogger = App.lib('ravenLogger')
# require and initialize modules
Db = App.module('database').initialize
uri: config.get('db.uri')
Emailer = App.module('emailer').initialize
host: config.get('email.host')
secure: config.get('email.secure')
port: config.get('email.port')
user: config.get('email.user')
pass: PI:PASSWORD:<PASSWORD>END_PI('PI:PASSWORD:<PASSWORD>END_PI')
from: config.get('email.from')
enable: config.get('email.enable')
Logger.add(winston.transports.Console, level: config.get('logging.consoleLevel'))
if config.get('logging.logglyLevel') != 'silent'
Logger.add loggly.Loggly,
level: config.get('logging.logglyLevel')
subdomain: config.get('logging.logglySubdomain')
inputToken: config.get('logging.logglyToken')
json: true
stripColors: true
if config.get('logging.ravenLevel') != 'silent'
ravenClient = new raven.Client(config.get('logging.sentryDSN'))
Logger.add RavenLogger,
level: config.get('logging.ravenLevel')
raven: ravenClient
Promise.onPossiblyUnhandledRejection (err, promise) ->
Logger.error(err)
Promise.longStackTraces()
app = express()
# do not log url parameters
morgan.token('url', (req, res) -> req.path)
loggerStream =
write: (message) ->
Logger.info(message.trim())
# this is exactly the dev format, minus the colours
loggerFormat = ':method :url :status :response-time ms - :res[content-length]'
app.set('port', Number(process.env.PORT || config.get('server.port')))
app.use(morgan(loggerFormat, stream: loggerStream))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(extended: true))
app.use(cookieParser(config.get('secret')))
app.use(favicon(App.path(config.get('paths.staticPath'), '/favicon.ico')))
app.use(express.static(App.path(config.get('paths.staticPath'))))
passport.use(Db.User.createStrategy())
passport.serializeUser(Db.User.serializeUser())
passport.deserializeUser(Db.User.deserializeUser())
app.use passport.initialize
userProperty: 'me'
app.use(passport.authenticate('token'))
Handler.listenAll(app)
server = http.createServer(app)
server.listen app.get('port'), ->
Logger.debug('Express server listening on port ' + app.get('port'))
|
[
{
"context": " valid URI\"\n\n###\nCredits\n email check regex:\n by Scott Gonzalez: http://projects.scottsplayground.com/email_addre",
"end": 6970,
"score": 0.9998741149902344,
"start": 6956,
"tag": "NAME",
"value": "Scott Gonzalez"
}
] | src/components/inputs/inputvalidator.coffee | burakcan/kd | 0 | module.exports = class KDInputValidator
@ruleRequired = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = (value.length > 0)
if doesValidate
return null
else
return ruleSet.messages?.required or "Field is required"
@ruleEmail = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)
if doesValidate
return null
else
return ruleSet.messages?.email or "Please enter a valid email address"
@ruleMinLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{minLength} = ruleSet.rules
doesValidate = value.length >= minLength
if doesValidate
return null
else
return ruleSet.messages?.minLength or "Please enter a value that has #{minLength} characters or more"
@ruleMaxLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{maxLength} = ruleSet.rules
doesValidate = value.length <= maxLength
if doesValidate
return null
else
return ruleSet.messages?.maxLength or "Please enter a value that has #{maxLength} characters or less"
@ruleRangeLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{rangeLength} = ruleSet.rules
doesValidate = value.length <= rangeLength[1] and value.length >= rangeLength[0]
if doesValidate
return null
else
return ruleSet.messages?.rangeLength or "Please enter a value that has more than #{rangeLength[0]} and less than #{rangeLength[1]} characters"
@ruleMatch = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
matchView = ruleSet.rules.match
matchViewVal = $.trim matchView.getValue()
doesValidate = value is matchViewVal
if doesValidate
return null
else
return ruleSet.messages?.match or "Values do not match"
@ruleCreditCard = (input, event)->
###
Visa: start with a 4. New cards have 16 digits. Old cards have 13.
MasterCard: start with the numbers 51 through 55. All have 16 digits.
American Express: start with 34 or 37 and have 15 digits.
Diners Club: start with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
Discover: start with 6011 or 65. All have 16 digits.
JCB: start with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.
###
return if event?.which is 9
value = $.trim input.getValue().replace(/-|\s/g,"")
ruleSet = input.getOptions().validate
doesValidate = /(^4[0-9]{12}(?:[0-9]{3})?$)|(^5[1-5][0-9]{14}$)|(^3[47][0-9]{13}$)|(^3(?:0[0-5]|[68][0-9])[0-9]{11}$)|(^6(?:011|5[0-9]{2})[0-9]{12}$)|(^(?:2131|1800|35\d{3})\d{11}$)/.test(value)
if doesValidate
type = if /^4[0-9]{12}(?:[0-9]{3})?$/.test(value) then "Visa"
else if /^5[1-5][0-9]{14}$/.test(value) then "MasterCard"
else if /^3[47][0-9]{13}$/.test(value) then "Amex"
else if /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/.test(value) then "Diners"
else if /^6(?:011|5[0-9]{2})[0-9]{12}$/.test(value) then "Discover"
else if /^(?:2131|1800|35\d{3})\d{11}$/.test(value) then "JCB"
else no
input.emit "CreditCardTypeIdentified", type
return null
else
return ruleSet.messages?.creditCard or "Please enter a valid credit card number"
@ruleJSON = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = yes
try
JSON.parse value if value
catch err
error err,doesValidate
doesValidate = no
if doesValidate
return null
else
return ruleSet.messages?.JSON or "a valid JSON is required"
@ruleRegExp = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{regExp} = ruleSet.rules
doesValidate = regExp.test value
if doesValidate
return null
else
return ruleSet.messages?.regExp or "Validation failed"
@ruleUri = (input, event)->
return if event?.which is 9
regExp = ///
^
([a-z0-9+.-]+): #scheme
(?:
// #it has an authority:
(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)? #userinfo
((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*) #host
(?::(\d*))? #port
(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)? #path
|
#it doesn't have an authority:
(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)? #path
)
(?:
\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*) #query string
)?
(?:
#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*) #fragment
)?
$
///i
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = regExp.test value
if doesValidate
return null
else
return ruleSet.messages?.uri or "Not a valid URI"
###
Credits
email check regex:
by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
###
| 39617 | module.exports = class KDInputValidator
@ruleRequired = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = (value.length > 0)
if doesValidate
return null
else
return ruleSet.messages?.required or "Field is required"
@ruleEmail = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)
if doesValidate
return null
else
return ruleSet.messages?.email or "Please enter a valid email address"
@ruleMinLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{minLength} = ruleSet.rules
doesValidate = value.length >= minLength
if doesValidate
return null
else
return ruleSet.messages?.minLength or "Please enter a value that has #{minLength} characters or more"
@ruleMaxLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{maxLength} = ruleSet.rules
doesValidate = value.length <= maxLength
if doesValidate
return null
else
return ruleSet.messages?.maxLength or "Please enter a value that has #{maxLength} characters or less"
@ruleRangeLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{rangeLength} = ruleSet.rules
doesValidate = value.length <= rangeLength[1] and value.length >= rangeLength[0]
if doesValidate
return null
else
return ruleSet.messages?.rangeLength or "Please enter a value that has more than #{rangeLength[0]} and less than #{rangeLength[1]} characters"
@ruleMatch = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
matchView = ruleSet.rules.match
matchViewVal = $.trim matchView.getValue()
doesValidate = value is matchViewVal
if doesValidate
return null
else
return ruleSet.messages?.match or "Values do not match"
@ruleCreditCard = (input, event)->
###
Visa: start with a 4. New cards have 16 digits. Old cards have 13.
MasterCard: start with the numbers 51 through 55. All have 16 digits.
American Express: start with 34 or 37 and have 15 digits.
Diners Club: start with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
Discover: start with 6011 or 65. All have 16 digits.
JCB: start with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.
###
return if event?.which is 9
value = $.trim input.getValue().replace(/-|\s/g,"")
ruleSet = input.getOptions().validate
doesValidate = /(^4[0-9]{12}(?:[0-9]{3})?$)|(^5[1-5][0-9]{14}$)|(^3[47][0-9]{13}$)|(^3(?:0[0-5]|[68][0-9])[0-9]{11}$)|(^6(?:011|5[0-9]{2})[0-9]{12}$)|(^(?:2131|1800|35\d{3})\d{11}$)/.test(value)
if doesValidate
type = if /^4[0-9]{12}(?:[0-9]{3})?$/.test(value) then "Visa"
else if /^5[1-5][0-9]{14}$/.test(value) then "MasterCard"
else if /^3[47][0-9]{13}$/.test(value) then "Amex"
else if /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/.test(value) then "Diners"
else if /^6(?:011|5[0-9]{2})[0-9]{12}$/.test(value) then "Discover"
else if /^(?:2131|1800|35\d{3})\d{11}$/.test(value) then "JCB"
else no
input.emit "CreditCardTypeIdentified", type
return null
else
return ruleSet.messages?.creditCard or "Please enter a valid credit card number"
@ruleJSON = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = yes
try
JSON.parse value if value
catch err
error err,doesValidate
doesValidate = no
if doesValidate
return null
else
return ruleSet.messages?.JSON or "a valid JSON is required"
@ruleRegExp = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{regExp} = ruleSet.rules
doesValidate = regExp.test value
if doesValidate
return null
else
return ruleSet.messages?.regExp or "Validation failed"
@ruleUri = (input, event)->
return if event?.which is 9
regExp = ///
^
([a-z0-9+.-]+): #scheme
(?:
// #it has an authority:
(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)? #userinfo
((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*) #host
(?::(\d*))? #port
(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)? #path
|
#it doesn't have an authority:
(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)? #path
)
(?:
\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*) #query string
)?
(?:
#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*) #fragment
)?
$
///i
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = regExp.test value
if doesValidate
return null
else
return ruleSet.messages?.uri or "Not a valid URI"
###
Credits
email check regex:
by <NAME>: http://projects.scottsplayground.com/email_address_validation/
###
| true | module.exports = class KDInputValidator
@ruleRequired = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = (value.length > 0)
if doesValidate
return null
else
return ruleSet.messages?.required or "Field is required"
@ruleEmail = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)
if doesValidate
return null
else
return ruleSet.messages?.email or "Please enter a valid email address"
@ruleMinLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{minLength} = ruleSet.rules
doesValidate = value.length >= minLength
if doesValidate
return null
else
return ruleSet.messages?.minLength or "Please enter a value that has #{minLength} characters or more"
@ruleMaxLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{maxLength} = ruleSet.rules
doesValidate = value.length <= maxLength
if doesValidate
return null
else
return ruleSet.messages?.maxLength or "Please enter a value that has #{maxLength} characters or less"
@ruleRangeLength = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{rangeLength} = ruleSet.rules
doesValidate = value.length <= rangeLength[1] and value.length >= rangeLength[0]
if doesValidate
return null
else
return ruleSet.messages?.rangeLength or "Please enter a value that has more than #{rangeLength[0]} and less than #{rangeLength[1]} characters"
@ruleMatch = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
matchView = ruleSet.rules.match
matchViewVal = $.trim matchView.getValue()
doesValidate = value is matchViewVal
if doesValidate
return null
else
return ruleSet.messages?.match or "Values do not match"
@ruleCreditCard = (input, event)->
###
Visa: start with a 4. New cards have 16 digits. Old cards have 13.
MasterCard: start with the numbers 51 through 55. All have 16 digits.
American Express: start with 34 or 37 and have 15 digits.
Diners Club: start with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
Discover: start with 6011 or 65. All have 16 digits.
JCB: start with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.
###
return if event?.which is 9
value = $.trim input.getValue().replace(/-|\s/g,"")
ruleSet = input.getOptions().validate
doesValidate = /(^4[0-9]{12}(?:[0-9]{3})?$)|(^5[1-5][0-9]{14}$)|(^3[47][0-9]{13}$)|(^3(?:0[0-5]|[68][0-9])[0-9]{11}$)|(^6(?:011|5[0-9]{2})[0-9]{12}$)|(^(?:2131|1800|35\d{3})\d{11}$)/.test(value)
if doesValidate
type = if /^4[0-9]{12}(?:[0-9]{3})?$/.test(value) then "Visa"
else if /^5[1-5][0-9]{14}$/.test(value) then "MasterCard"
else if /^3[47][0-9]{13}$/.test(value) then "Amex"
else if /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/.test(value) then "Diners"
else if /^6(?:011|5[0-9]{2})[0-9]{12}$/.test(value) then "Discover"
else if /^(?:2131|1800|35\d{3})\d{11}$/.test(value) then "JCB"
else no
input.emit "CreditCardTypeIdentified", type
return null
else
return ruleSet.messages?.creditCard or "Please enter a valid credit card number"
@ruleJSON = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = yes
try
JSON.parse value if value
catch err
error err,doesValidate
doesValidate = no
if doesValidate
return null
else
return ruleSet.messages?.JSON or "a valid JSON is required"
@ruleRegExp = (input, event)->
return if event?.which is 9
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
{regExp} = ruleSet.rules
doesValidate = regExp.test value
if doesValidate
return null
else
return ruleSet.messages?.regExp or "Validation failed"
@ruleUri = (input, event)->
return if event?.which is 9
regExp = ///
^
([a-z0-9+.-]+): #scheme
(?:
// #it has an authority:
(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)? #userinfo
((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*) #host
(?::(\d*))? #port
(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)? #path
|
#it doesn't have an authority:
(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)? #path
)
(?:
\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*) #query string
)?
(?:
#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*) #fragment
)?
$
///i
value = $.trim input.getValue()
ruleSet = input.getOptions().validate
doesValidate = regExp.test value
if doesValidate
return null
else
return ruleSet.messages?.uri or "Not a valid URI"
###
Credits
email check regex:
by PI:NAME:<NAME>END_PI: http://projects.scottsplayground.com/email_address_validation/
###
|
[
{
"context": "# @preserve\n# (c) 2012 by Cédric Mesnil. All rights reserved.\n# \n# Redistribution and use",
"end": 40,
"score": 0.9998744130134583,
"start": 27,
"tag": "NAME",
"value": "Cédric Mesnil"
},
{
"context": "SSIBILITY OF SUCH DAMAGE.\n# \n# Further forked from Jeff Mott's... | src/ripemd160.iced | CyberFlameGO/triplesec | 274 | # @preserve
# (c) 2012 by Cédric Mesnil. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Further forked from Jeff Mott's CryptoJS: https://code.google.com/p/crypto-js/source/browse/tags/3.1.2/src/ripemd160.js
#
{WordArray,X64Word,X64WordArray} = require './wordarray'
{Hasher} = require './algbase'
#=======================================================================
class Global
#------------------
constructor : ->
@_zl = new WordArray [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]
@_zr = new WordArray [
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]
@_sl = new WordArray [
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]
@_sr = new WordArray [
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]
@_hl = new WordArray [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
@_hr = new WordArray [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
#=======================================================================
G = new Global()
#=======================================================================
class RIPEMD160 extends Hasher
# XXX I'm not sure what the block size, so there are just random guesses
@blockSize : 512/32
blockSize : RIPEMD160.blockSize
#------------------
@output_size : 160/8
output_size : RIPEMD160.output_size
#------------------
_doReset : () ->
@_hash = new WordArray [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
get_output_size : () -> @output_size
#------------------
_doProcessBlock: (M, offset) ->
# Swap endian
for i in [0...16]
# Shortcuts
offset_i = offset + i
M_offset_i = M[offset_i]
# Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
)
# Shortcut
H = @_hash.words
hl = G._hl.words
hr = G._hr.words
zl = G._zl.words
zr = G._zr.words
sl = G._sl.words
sr = G._sr.words
ar = al = H[0]
br = bl = H[1]
cr = cl = H[2]
dr = dl = H[3]
er = el = H[4]
# Computation
for i in [0...80]
t = (al + M[offset+zl[i]])|0
if (i<16)
t += f1(bl,cl,dl) + hl[0]
else if (i<32)
t += f2(bl,cl,dl) + hl[1]
else if (i<48)
t += f3(bl,cl,dl) + hl[2]
else if (i<64)
t += f4(bl,cl,dl) + hl[3]
else # if (i<80)
t += f5(bl,cl,dl) + hl[4]
t = t|0
t = rotl(t,sl[i])
t = (t+el)|0
al = el
el = dl
dl = rotl(cl, 10)
cl = bl
bl = t
t = (ar + M[offset+zr[i]])|0
if (i<16)
t += f5(br,cr,dr) + hr[0]
else if (i<32)
t += f4(br,cr,dr) + hr[1]
else if (i<48)
t += f3(br,cr,dr) + hr[2]
else if (i<64)
t += f2(br,cr,dr) + hr[3]
else # if (i<80)
t += f1(br,cr,dr) + hr[4]
t = t|0
t = rotl(t,sr[i])
t = (t+er)|0
ar = er
er = dr
dr = rotl(cr, 10)
cr = br
br = t
# Intermediate hash value
t = (H[1] + cl + dr)|0
H[1] = (H[2] + dl + er)|0
H[2] = (H[3] + el + ar)|0
H[3] = (H[4] + al + br)|0
H[4] = (H[0] + bl + cr)|0
H[0] = t
#------------------
_doFinalize: () ->
# Shortcuts
data = @_data
dataWords = data.words
nBitsTotal = @_nDataBytes * 8
nBitsLeft = data.sigBytes * 8
# Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32)
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
)
data.sigBytes = (dataWords.length + 1) * 4
# Hash final blocks
@_process()
# Shortcuts
hash = @_hash
H = hash.words
# Swap endian
for i in [0...5]
# Shortcut
H_i = H[i]
# Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
# Return final computed hash
return hash
#------------------
scrub : () ->
@_hash.scrub()
#------------------
copy_to : (obj) ->
super obj
obj._hash = @_hash.clone()
#------------------
clone : () ->
out = new RIPEMD160()
@copy_to out
return out
#======================================================================
f1 = (x, y, z) -> ((x) ^ (y) ^ (z))
f2 = (x, y, z) -> (((x)&(y)) | ((~x)&(z)))
f3 = (x, y, z) -> (((x) | (~(y))) ^ (z))
f4 = (x, y, z) -> (((x) & (z)) | ((y)&(~(z))))
f5 = (x, y, z) -> ((x) ^ ((y) |(~(z))));
rotl = (x,n) -> (x<<n) | (x>>>(32-n))
#======================================================================
transform = (x) ->
out = (new RIPEMD160).finalize x
x.scrub()
out
#================================================================
exports.RIPEMD160 = RIPEMD160
exports.transform = transform
#================================================================
| 74986 | # @preserve
# (c) 2012 by <NAME>. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Further forked from <NAME>'s CryptoJS: https://code.google.com/p/crypto-js/source/browse/tags/3.1.2/src/ripemd160.js
#
{WordArray,X64Word,X64WordArray} = require './wordarray'
{Hasher} = require './algbase'
#=======================================================================
class Global
#------------------
constructor : ->
@_zl = new WordArray [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]
@_zr = new WordArray [
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]
@_sl = new WordArray [
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]
@_sr = new WordArray [
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]
@_hl = new WordArray [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
@_hr = new WordArray [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
#=======================================================================
G = new Global()
#=======================================================================
class RIPEMD160 extends Hasher
# XXX I'm not sure what the block size, so there are just random guesses
@blockSize : 512/32
blockSize : RIPEMD160.blockSize
#------------------
@output_size : 160/8
output_size : RIPEMD160.output_size
#------------------
_doReset : () ->
@_hash = new WordArray [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
get_output_size : () -> @output_size
#------------------
_doProcessBlock: (M, offset) ->
# Swap endian
for i in [0...16]
# Shortcuts
offset_i = offset + i
M_offset_i = M[offset_i]
# Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
)
# Shortcut
H = @_hash.words
hl = G._hl.words
hr = G._hr.words
zl = G._zl.words
zr = G._zr.words
sl = G._sl.words
sr = G._sr.words
ar = al = H[0]
br = bl = H[1]
cr = cl = H[2]
dr = dl = H[3]
er = el = H[4]
# Computation
for i in [0...80]
t = (al + M[offset+zl[i]])|0
if (i<16)
t += f1(bl,cl,dl) + hl[0]
else if (i<32)
t += f2(bl,cl,dl) + hl[1]
else if (i<48)
t += f3(bl,cl,dl) + hl[2]
else if (i<64)
t += f4(bl,cl,dl) + hl[3]
else # if (i<80)
t += f5(bl,cl,dl) + hl[4]
t = t|0
t = rotl(t,sl[i])
t = (t+el)|0
al = el
el = dl
dl = rotl(cl, 10)
cl = bl
bl = t
t = (ar + M[offset+zr[i]])|0
if (i<16)
t += f5(br,cr,dr) + hr[0]
else if (i<32)
t += f4(br,cr,dr) + hr[1]
else if (i<48)
t += f3(br,cr,dr) + hr[2]
else if (i<64)
t += f2(br,cr,dr) + hr[3]
else # if (i<80)
t += f1(br,cr,dr) + hr[4]
t = t|0
t = rotl(t,sr[i])
t = (t+er)|0
ar = er
er = dr
dr = rotl(cr, 10)
cr = br
br = t
# Intermediate hash value
t = (H[1] + cl + dr)|0
H[1] = (H[2] + dl + er)|0
H[2] = (H[3] + el + ar)|0
H[3] = (H[4] + al + br)|0
H[4] = (H[0] + bl + cr)|0
H[0] = t
#------------------
_doFinalize: () ->
# Shortcuts
data = @_data
dataWords = data.words
nBitsTotal = @_nDataBytes * 8
nBitsLeft = data.sigBytes * 8
# Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32)
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
)
data.sigBytes = (dataWords.length + 1) * 4
# Hash final blocks
@_process()
# Shortcuts
hash = @_hash
H = hash.words
# Swap endian
for i in [0...5]
# Shortcut
H_i = H[i]
# Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
# Return final computed hash
return hash
#------------------
scrub : () ->
@_hash.scrub()
#------------------
copy_to : (obj) ->
super obj
obj._hash = @_hash.clone()
#------------------
clone : () ->
out = new RIPEMD160()
@copy_to out
return out
#======================================================================
f1 = (x, y, z) -> ((x) ^ (y) ^ (z))
f2 = (x, y, z) -> (((x)&(y)) | ((~x)&(z)))
f3 = (x, y, z) -> (((x) | (~(y))) ^ (z))
f4 = (x, y, z) -> (((x) & (z)) | ((y)&(~(z))))
f5 = (x, y, z) -> ((x) ^ ((y) |(~(z))));
rotl = (x,n) -> (x<<n) | (x>>>(32-n))
#======================================================================
transform = (x) ->
out = (new RIPEMD160).finalize x
x.scrub()
out
#================================================================
exports.RIPEMD160 = RIPEMD160
exports.transform = transform
#================================================================
| true | # @preserve
# (c) 2012 by PI:NAME:<NAME>END_PI. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Further forked from PI:NAME:<NAME>END_PI's CryptoJS: https://code.google.com/p/crypto-js/source/browse/tags/3.1.2/src/ripemd160.js
#
{WordArray,X64Word,X64WordArray} = require './wordarray'
{Hasher} = require './algbase'
#=======================================================================
class Global
#------------------
constructor : ->
@_zl = new WordArray [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]
@_zr = new WordArray [
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]
@_sl = new WordArray [
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]
@_sr = new WordArray [
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]
@_hl = new WordArray [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
@_hr = new WordArray [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
#=======================================================================
G = new Global()
#=======================================================================
class RIPEMD160 extends Hasher
# XXX I'm not sure what the block size, so there are just random guesses
@blockSize : 512/32
blockSize : RIPEMD160.blockSize
#------------------
@output_size : 160/8
output_size : RIPEMD160.output_size
#------------------
_doReset : () ->
@_hash = new WordArray [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
get_output_size : () -> @output_size
#------------------
_doProcessBlock: (M, offset) ->
# Swap endian
for i in [0...16]
# Shortcuts
offset_i = offset + i
M_offset_i = M[offset_i]
# Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
)
# Shortcut
H = @_hash.words
hl = G._hl.words
hr = G._hr.words
zl = G._zl.words
zr = G._zr.words
sl = G._sl.words
sr = G._sr.words
ar = al = H[0]
br = bl = H[1]
cr = cl = H[2]
dr = dl = H[3]
er = el = H[4]
# Computation
for i in [0...80]
t = (al + M[offset+zl[i]])|0
if (i<16)
t += f1(bl,cl,dl) + hl[0]
else if (i<32)
t += f2(bl,cl,dl) + hl[1]
else if (i<48)
t += f3(bl,cl,dl) + hl[2]
else if (i<64)
t += f4(bl,cl,dl) + hl[3]
else # if (i<80)
t += f5(bl,cl,dl) + hl[4]
t = t|0
t = rotl(t,sl[i])
t = (t+el)|0
al = el
el = dl
dl = rotl(cl, 10)
cl = bl
bl = t
t = (ar + M[offset+zr[i]])|0
if (i<16)
t += f5(br,cr,dr) + hr[0]
else if (i<32)
t += f4(br,cr,dr) + hr[1]
else if (i<48)
t += f3(br,cr,dr) + hr[2]
else if (i<64)
t += f2(br,cr,dr) + hr[3]
else # if (i<80)
t += f1(br,cr,dr) + hr[4]
t = t|0
t = rotl(t,sr[i])
t = (t+er)|0
ar = er
er = dr
dr = rotl(cr, 10)
cr = br
br = t
# Intermediate hash value
t = (H[1] + cl + dr)|0
H[1] = (H[2] + dl + er)|0
H[2] = (H[3] + el + ar)|0
H[3] = (H[4] + al + br)|0
H[4] = (H[0] + bl + cr)|0
H[0] = t
#------------------
_doFinalize: () ->
# Shortcuts
data = @_data
dataWords = data.words
nBitsTotal = @_nDataBytes * 8
nBitsLeft = data.sigBytes * 8
# Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32)
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
)
data.sigBytes = (dataWords.length + 1) * 4
# Hash final blocks
@_process()
# Shortcuts
hash = @_hash
H = hash.words
# Swap endian
for i in [0...5]
# Shortcut
H_i = H[i]
# Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
# Return final computed hash
return hash
#------------------
scrub : () ->
@_hash.scrub()
#------------------
copy_to : (obj) ->
super obj
obj._hash = @_hash.clone()
#------------------
clone : () ->
out = new RIPEMD160()
@copy_to out
return out
#======================================================================
f1 = (x, y, z) -> ((x) ^ (y) ^ (z))
f2 = (x, y, z) -> (((x)&(y)) | ((~x)&(z)))
f3 = (x, y, z) -> (((x) | (~(y))) ^ (z))
f4 = (x, y, z) -> (((x) & (z)) | ((y)&(~(z))))
f5 = (x, y, z) -> ((x) ^ ((y) |(~(z))));
rotl = (x,n) -> (x<<n) | (x>>>(32-n))
#======================================================================
transform = (x) ->
out = (new RIPEMD160).finalize x
x.scrub()
out
#================================================================
exports.RIPEMD160 = RIPEMD160
exports.transform = transform
#================================================================
|
[
{
"context": "<input type=\"password\" name=\"hunter_password\" id=\"hunter-password\">\n <input type=\"badtype\" name=\"hunter_",
"end": 4917,
"score": 0.7681074738502502,
"start": 4902,
"tag": "PASSWORD",
"value": "hunter-password"
},
{
"context": " ->\n before ->\n... | test/forms_test.coffee | gabrielpconceicao/zombie | 2 | { assert, brains, Browser } = require("./helpers")
File = require("fs")
Crypto = require("crypto")
describe "Forms", ->
browser = null
before (done)->
browser = Browser.create()
brains.ready(done)
before ->
brains.get "/forms/form", (req, res)->
res.send """
<html>
<body>
<form action="/forms/submit" method="post">
<label>Name <input type="text" name="name" id="field-name" /></label>
<label for="field-email">Email</label>
<input type="text" name="email" id="field-email"></label>
<textarea name="likes" id="field-likes">Warm brains</textarea>
<input type="password" name="password" id="field-password">
<input type="badtype" name="invalidtype" id="field-invalidtype">
<input type="text" name="email2" id="field-email2">
<input type="text" name="email3" id="field-email3">
<input type="text" name="disabled" disabled>
<input type="text" name="readonly" readonly>
<input type="text" name="empty_text" id="empty-text">
<label>Hungry</label>
<label>You bet<input type="checkbox" name="hungry[]" value="you bet" id="field-hungry"></label>
<label>Certainly<input type="checkbox" name="hungry[]" value="certainly" id="field-hungry-certainly"></label>
<label for="field-brains">Brains?</label>
<input type="checkbox" name="brains" value="yes" id="field-brains">
<input type="checkbox" name="green" id="field-green" value="Super green!" checked="checked">
<input type="checkbox" name="check" id="field-check" value="Huh?" checked="checked">
<input type="checkbox" name="uncheck" id="field-uncheck" value="Yeah!">
<input type="checkbox" name="empty_checkbox" id="empty-checkbox" checked="checked">
<label>Looks
<select name="looks" id="field-looks">
<option value="blood" label="Bloody"></option>
<option value="clean" label="Clean"></option>
<option value="" label="Choose one"></option>
</select>
</label>
<label>Scary <input name="scary" type="radio" value="yes" id="field-scary"></label>
<label>Not scary <input name="scary" type="radio" value="no" id="field-notscary" checked="checked"></label>
<select name="state" id="field-state">
<option>alive</option>
<option>dead</option>
<option>neither</option>
</select>
<span>First address</span>
<label for='address1_street'>Street</label>
<input type="text" name="addresses[][street]" value="" id="address1_street">
<label for='address1_city'>City</label>
<input type="text" name="addresses[][city]" value="" id="address1_city">
<span>Second address</span>
<label for='address2_street'>Street</label>
<input type="text" name="addresses[][street]" value="" id="address2_street">
<label for='address2_city'>City</label>
<input type="text" name="addresses[][city]" value="" id="address2_city">
<select name="kills" id="field-kills">
<option>Five</option>
<option>Seventeen</option>
<option id="option-killed-thousands">Thousands</option>
</select>
<select name="unselected_state" id="field-unselected-state">
<option>alive</option>
<option>dead</option>
</select>
<select name="hobbies[]" id="field-hobbies" multiple="multiple">
<option>Eat Brains</option>
<option id="hobbies-messy">Make Messy</option>
<option>Sleep</option>
</select>
<select name="months" id="field-months">
<option value=""></option>
<option value="jan_2011"> Jan 2011 </option>
<option value="feb_2011"> Feb 2011 </option>
<option value="mar_2011"> Mar 2011 </option>
</select>
<input type="unknown" name="unknown" value="yes">
<input type="reset" value="Reset">
<input type="submit" name="button" value="Submit">
<input type="image" name="image" id="image_submit" value="Image Submit">
<button name="button" value="hit-me">Hit Me</button>
<input type="checkbox" id="field-prevent-check">
<input type="radio" id="field-prevent-radio">
</form>
<div id="formless_inputs">
<label>Hunter <input type="text" name="hunter_name" id="hunter-name"></label>
<textarea name="hunter_hobbies">Killing zombies.</textarea>
<input type="password" name="hunter_password" id="hunter-password">
<input type="badtype" name="hunter_invalidtype" id="hunter-invalidtype" />
<label>Weapons</label>
<label>Chainsaw<input type="checkbox" name="hunter_weapon[]" value="chainsaw"></label>
<label>Shotgun<input type="checkbox" name="hunter_weapon[]" value="shotgun"></label>
<label>Type
<select name="hunter_type">
<option value="regular" label="Regular"></option>
<option value="evil" label="Evil"></option>
<option value="tiny" label="tiny"></option>
</select>
</label>
<label>Powerglove <input name="hunter_powerglove" type="radio" value="glove"></label>
<label>No powerglove <input name="hunter_powerglove" type="radio" value="noglove" checked="checked"></label>
</div>
</body>
</html>
"""
brains.post "/forms/submit", (req, res)->
res.send """
<html>
<title>Results</title>
<body>
<div id="name">#{req.body.name}</div>
<div id="likes">#{req.body.likes}</div>
<div id="green">#{req.body.green}</div>
<div id="brains">#{req.body.brains}</div>
<div id="looks">#{req.body.looks}</div>
<div id="hungry">#{JSON.stringify(req.body.hungry)}</div>
<div id="scary">#{req.body.scary}</div>
<div id="state">#{req.body.state}</div>
<div id="empty-text">#{req.body.empty_text}</div>
<div id="empty-checkbox">#{req.body.empty_checkbox || "nothing"}</div>
<div id="unselected_state">#{req.body.unselected_state}</div>
<div id="hobbies">#{JSON.stringify(req.body.hobbies)}</div>
<div id="addresses">#{JSON.stringify(req.body.addresses)}</div>
<div id="unknown">#{req.body.unknown}</div>
<div id="clicked">#{req.body.button}</div>
<div id="image_clicked">#{req.body.image}</div>
</body>
</html>
"""
describe "fill field", ->
before (done)->
browser.visit "/forms/form", =>
fill_events = ["input", "change"]
count = fill_events.length
browser.on "event", (event, target)=>
if event.type in fill_events
count -= 1
if count == 0
@changed = target
count = fill_events.length
done()
describe "fill input with same the same value", ->
before ->
browser.fill("Name", "")
it "should not fire input *and* change events", ->
assert.equal @change, undefined
describe "text input enclosed in label", ->
before ->
browser.fill("Name", "ArmBiter")
it "should set text field", ->
browser.assert.input "#field-name", "ArmBiter"
it "should fire input and changed event", ->
assert.equal @changed.id, "field-name"
describe "email input referenced from label", ->
before ->
browser.fill("Email", "armbiter@example.com")
it "should set email field", ->
browser.assert.input "#field-email", "armbiter@example.com"
it "should fire input and change events", ->
assert.equal @changed.id, "field-email"
describe "textarea by field name", ->
before ->
browser.fill("likes", "Arm Biting")
it "should set textarea", ->
browser.assert.input "#field-likes", "Arm Biting"
it "should fire input and change events", ->
assert.equal @changed.id, "field-likes"
describe "password input by selector", ->
before ->
browser.fill("input[name=password]", "b100d")
it "should set password", ->
browser.assert.input "#field-password", "b100d"
it "should fire input and change events", ->
assert.equal @changed.id, "field-password"
describe "input without a valid type", ->
before ->
browser.fill("input[name=invalidtype]", "some value")
it "should set value", ->
browser.assert.input "#field-invalidtype", "some value"
it "should fire input and change events", ->
assert.equal @changed.id, "field-invalidtype"
describe "email2 input by node", ->
before ->
browser.fill("#field-email2", "headchomper@example.com")
it "should set email2 field", ->
browser.assert.input "#field-email2", "headchomper@example.com"
it "should fire input and change events", ->
assert.equal @changed.id, "field-email2"
describe "disabled input can not be modified", ->
it "should raise error", ->
assert.throws ->
browser.fill("#disabled_input_field", "yeahh")
describe "readonly input can not be modified", ->
it "should raise error", ->
assert.throws ->
browser.fill("#readonly_input_field", "yeahh")
describe "focus field (1)", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
browser.fill(field1, "something")
field2.addEventListener "focus", ->
done()
browser.fill(field2, "else")
it "should fire focus event on selected field", ->
assert true
describe "focus field (2)", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
browser.fill field1, "something"
field1.addEventListener "blur", ->
done()
browser.fill field2, "else"
it "should fire blur event on previous field", ->
assert true
describe "keep value and switch focus", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
field1.addEventListener "change", ->
done(new Error("Should not fire"))
browser.focus(field1)
browser.focus(field2)
setImmediate(done)
it "should fire change event on previous field", ->
assert true
describe "change value and switch focus", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
field1.addEventListener "change", ->
done()
browser.focus(field1)
field1.value = "something"
browser.focus(field2)
it "should fire change event on previous field", ->
assert true
describe "check box", ->
changed = null
clicked = null
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
switch event._type
when "change"
changed = target
when "click"
clicked = target
done()
describe "checkbox enclosed in label", ->
before ->
browser.check("You bet")
it "should check checkbox", ->
browser.assert.element "#field-hungry:checked"
it "should fire change event", ->
assert.equal changed.id, "field-hungry"
it "should fire clicked event", ->
assert.equal clicked.id, "field-hungry"
describe "with callback", ->
before ->
browser.check("Brains?")
it "should callback", ->
browser.assert.element "#field-brains:checked"
describe "checkbox referenced from label", ->
before ->
browser.uncheck("Brains?")
changed = null
clicked = null
browser.check("Brains?")
it "should check checkbox", ->
browser.assert.element "#field-brains:checked"
it "should fire change event", ->
assert.equal changed.id, "field-brains"
describe "uncheck with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser
.check("Brains?")
.uncheck("Brains?")
done()
it "should callback", ->
browser.assert.elements "#field-brains:checked", 0
describe "checkbox by name", ->
before ->
browser.check("green")
changed = null
clicked = null
browser.uncheck("green")
it "should uncheck checkbox", ->
browser.assert.elements "#field-green:checked", 0
it "should fire change event", ->
assert.equal changed.id, "field-green"
describe "check callback", ->
before ->
browser.check("uncheck")
it "should callback", ->
browser.assert.elements "#field-uncheck:checked", 1
describe "uncheck callback", ->
before ->
browser.uncheck("check")
it "should callback", ->
browser.assert.elements "#field-uncheck:checked", 1
describe "prevent default", ->
values = []
before ->
checkBox = browser.$$("#field-prevent-check")
values.push(checkBox.checked)
checkBox.addEventListener "click", (event)->
values.push(checkBox.checked)
event.preventDefault()
browser.check(checkBox)
values.push(checkBox.checked)
it "should turn checkbox on then off", ->
assert.deepEqual values, [false, true, false]
describe "any checkbox (1)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-check")
field2 = browser.querySelector("#field-uncheck")
browser.uncheck(field1)
browser.check(field1)
field2.addEventListener "focus", ->
done()
browser.check(field2)
it "should fire focus event on selected field", ->
assert true
describe "any checkbox (2)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-check")
field2 = browser.querySelector("#field-uncheck")
browser.uncheck(field1)
browser.check(field1)
field1.addEventListener "blur", ->
done()
browser.check(field2)
it "should fire blur event on previous field", ->
assert true
describe "radio buttons", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
switch event.type
when "change"
@changed = target
when "click"
@clicked = target
done()
describe "radio button enclosed in label", ->
before ->
browser.choose("Scary")
it "should check radio", ->
browser.assert.element "#field-scary:checked"
it "should fire click event", ->
assert.equal @clicked.id, "field-scary"
it "should fire change event", ->
assert.equal @changed.id, "field-scary"
describe "with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.choose("Scary")
done()
it "should callback", ->
browser.assert.element "#field-scary:checked"
describe "radio button by value", ->
before (done)->
browser.visit "/forms/form", ->
browser.choose("no")
done()
it "should check radio", ->
browser.assert.element "#field-notscary:checked"
it "should uncheck other radio", ->
browser.assert.elements "#field-scary:checked", 0
describe "prevent default", ->
values = []
before ->
radio = browser.$$("#field-prevent-radio")
values.push(radio.checked)
radio.addEventListener "click", (event)->
values.push(radio.checked)
event.preventDefault()
browser.choose(radio)
values.push(radio.checked)
it "should turn radio on then off", ->
assert.deepEqual values, [false, true, false]
describe "any radio button (1) ", ->
before ->
field1 = browser.querySelector("#field-scary")
field2 = browser.querySelector("#field-notscary")
browser.choose(field1)
field2.addEventListener "focus", ->
done()
browser.choose(field2)
it "should fire focus event on selected field", ->
assert true
describe "any radio button (1) ", ->
before ->
field1 = browser.querySelector("#field-scary")
field2 = browser.querySelector("#field-notscary")
browser.choose(field1)
field1.addEventListener "blur", ->
done()
browser.choose(field2)
it "should fire blur event on previous field", ->
assert true
describe "select option", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
if event.type == "change"
@changed = target
done()
describe "enclosed in label using option label", ->
before ->
browser.select("Looks", "Bloody")
it "should set value", ->
browser.assert.input "#field-looks", "blood"
it "should select first option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-looks").options)
assert.deepEqual selected, [true, false, false]
it "should fire change event", ->
assert.equal @changed.id, "field-looks"
describe "select name using option value", ->
before ->
browser.select("state", "dead")
it "should set value", ->
browser.assert.input "#field-state", "dead"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-state").options)
assert.deepEqual selected, [false, true, false]
it "should fire change event", ->
assert.equal @changed.id, "field-state"
describe "select name using option text", ->
before ->
browser.select("months", "Jan 2011")
it "should set value", ->
browser.assert.input "#field-months", "jan_2011"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-months").options)
assert.deepEqual selected, [false, true, false, false]
it "should fire change event", ->
assert.equal @changed.id, "field-months"
describe "select option value directly", ->
before ->
browser.selectOption("#option-killed-thousands")
it "should set value", ->
browser.assert.input "#field-kills", "Thousands"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-kills").options)
assert.deepEqual selected, [false, false, true]
it "should fire change event", ->
assert.equal @changed.id, "field-kills"
describe "select callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.select("unselected_state", "dead")
done()
it "should callback", ->
browser.assert.input "#field-unselected-state", "dead"
describe "select option callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.selectOption("#option-killed-thousands")
done()
it "should callback", ->
browser.assert.input "#field-kills", "Thousands"
describe "any selection (1)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-kills")
browser.fill(field1, "something")
field2.addEventListener "focus", ->
done()
browser.select(field2, "Five")
it "should fire focus event on selected field", ->
assert true
describe "any selection (2)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-kills")
browser.fill(field1, "something")
field1.addEventListener "blur", ->
done()
browser.select(field2, "Five")
it "should fire blur event on previous field", ->
assert true
describe "multiple select option", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
if event.type == "change"
@changed = target
done()
describe "select name using option value", ->
before ->
browser.select("#field-hobbies", "Eat Brains")
browser.select("#field-hobbies", "Sleep")
it "should select first and second options", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, true]
it "should fire change event", ->
assert.equal @changed.id, "field-hobbies"
it "should not fire change event if nothing changed", ->
assert @changed
@changed = null
browser.select("#field-hobbies", "Eat Brains")
assert !@changed
describe "unselect name using option value", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.select("#field-hobbies", "Eat Brains")
browser.select("#field-hobbies", "Sleep")
browser.unselect("#field-hobbies", "Sleep")
return
.then(done, done)
it "should unselect items", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, false]
describe "unselect name using option selector", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.selectOption("#hobbies-messy")
browser.unselectOption("#hobbies-messy")
return
.then(done, done)
it "should unselect items", ->
assert !browser.query("#hobbies-messy").selected
describe "with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.unselect("#field-hobbies", "Eat Brains")
browser.unselect("#field-hobbies", "Sleep")
browser.select("#field-hobbies", "Eat Brains")
done()
it "should unselect callback", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, false]
describe "fields not contained in a form", ->
before (done)->
browser.visit("/forms/form", done)
it "should not fail", ->
browser
.fill("Hunter", "Bruce")
.fill("hunter_hobbies", "Trying to get home")
.fill("#hunter-password", "klaatubarada")
.fill("input[name=hunter_invalidtype]", "necktie?")
.check("Chainsaw")
.choose("Powerglove")
.select("Type", "Evil")
describe "reset form", ->
describe "by calling reset", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "ArmBiter")
.fill("likes", "Arm Biting")
.check("You bet")
.choose("Scary")
.select("state", "dead")
browser.querySelector("form").reset()
return
.then(done, done)
it "should reset input field to original value", ->
browser.assert.input "#field-name", ""
it "should reset textarea to original value", ->
browser.assert.input "#field-likes", "Warm brains"
it "should reset checkbox to original value", ->
browser.assert.elements "#field-hungry:checked", 0
it "should reset radio to original value", ->
browser.assert.elements "#field-scary:checked", 0
browser.assert.elements "#field-notscary:checked", 1
it "should reset select to original option", ->
browser.assert.input "#field-state", "alive"
describe "with event handler", ->
eventType = null
before (done)->
browser.visit("/forms/form")
.then ->
browser.querySelector("form [type=reset]").addEventListener "click", (event)->
eventType = event.type
done()
.then ->
browser.querySelector("form [type=reset]").click()
it "should fire click event", ->
assert.equal eventType, "click"
describe "with preventDefault", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.fill("Name", "ArmBiter")
browser.querySelector("form [type=reset]").addEventListener "click", (event)->
event.preventDefault()
.then ->
browser.querySelector("form [type=reset]").click()
.then(done, done)
it "should not reset input field", ->
browser.assert.input "#field-name", "ArmBiter"
describe "by clicking reset input", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.fill("Name", "ArmBiter")
browser.querySelector("form [type=reset]").click()
.then(done, done)
it "should reset input field to original value", ->
browser.assert.input "#field-name", ""
# Submitting form
describe "submit form", ->
describe "by calling submit", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "ArmBiter")
.fill("likes", "Arm Biting")
.check("You bet")
.check("Certainly")
.choose("Scary")
.select("state", "dead")
.select("looks", "Choose one")
.select("#field-hobbies", "Eat Brains")
.select("#field-hobbies", "Sleep")
.check("Brains?")
.fill('#address1_city', 'Paris')
.fill('#address1_street', 'CDG')
.fill('#address2_city', 'Mikolaiv')
.fill('#address2_street', 'PGS')
browser.querySelector("form").submit()
browser.wait()
.then(done, done)
it "should open new page", ->
browser.assert.url "/forms/submit"
browser.assert.text "title", "Results"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send text input values to server", ->
browser.assert.text "#name", "ArmBiter"
it "should send textarea values to server", ->
browser.assert.text "#likes", "Arm Biting"
it "should send radio button to server", ->
browser.assert.text "#scary", "yes"
it "should send unknown types to server", ->
browser.assert.text "#unknown", "yes"
it "should send checkbox with default value to server (brains)", ->
browser.assert.text "#brains", "yes"
it "should send checkbox with default value to server (green)", ->
browser.assert.text "#green", "Super green!"
it "should send multiple checkbox values to server", ->
browser.assert.text "#hungry", '["you bet","certainly"]'
it "should send selected option to server", ->
browser.assert.text "#state", "dead"
it "should send first selected option if none was chosen to server", ->
browser.assert.text "#unselected_state", "alive"
browser.assert.text "#looks", ""
it "should send multiple selected options to server", ->
browser.assert.text "#hobbies", '["Eat Brains","Sleep"]'
it "should send empty text fields", ->
browser.assert.text "#empty-text", ""
it "should send checked field with no value", ->
browser.assert.text "#empty-checkbox", "1"
describe "by clicking button", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "ArmBiter")
.fill("likes", "Arm Biting")
return browser.pressButton("Hit Me")
.then(done, done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send button value to server", ->
browser.assert.text "#clicked", "hit-me"
it "should send input values to server", ->
browser.assert.text "#name", "ArmBiter"
browser.assert.text "#likes", "Arm Biting"
it "should not send other button values to server", ->
browser.assert.text "#image_clicked", "undefined"
describe "pressButton(1)", ->
before (done)->
browser.visit "/forms/form", ->
field = browser.querySelector("#field-email2")
browser.fill(field, "something")
browser.button("Hit Me").addEventListener "focus", ->
done()
browser.pressButton("Hit Me")
it "should fire focus event on button", ->
assert true
describe "pressButton(2)", ->
before (done)->
browser.visit "/forms/form", ->
field = browser.querySelector("#field-email2")
browser.fill(field, "something")
field.addEventListener "blur", ->
done()
browser.pressButton("Hit Me")
it "should fire blur event on previous field", ->
assert true
describe "by clicking image button", ->
before (done)->
browser.visit "/forms/form", ->
browser
.fill("Name", "ArmBiter")
.fill("likes", "Arm Biting")
.pressButton("#image_submit", done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send image value to server", ->
browser.assert.text "#image_clicked", "Image Submit"
it "should send input values to server", ->
browser.assert.text "#name", "ArmBiter"
browser.assert.text "#likes", "Arm Biting"
it "should not send other button values to server", ->
browser.assert.text "#clicked", "undefined"
describe "by clicking input", ->
before (done)->
browser.visit "/forms/form", ->
browser
.fill("Name", "ArmBiter")
.fill("likes", "Arm Biting")
.pressButton("Submit", done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send submit value to server", ->
browser.assert.text "#clicked", "Submit"
it "should send input values to server", ->
browser.assert.text "#name", "ArmBiter"
browser.assert.text "#likes", "Arm Biting"
describe "cancel event", ->
before (done)->
brains.get "/forms/cancel", (req, res)->
res.send """
<html>
<head>
<script src="/jquery.js"></script>
<script>
$(function() {
$("form").submit(function() {
return false;
})
})
</script>
</head>
<body>
<form action="/forms/submit" method="post">
<button>Submit</button>
</form>
</body>
</html>
"""
browser.visit "/forms/cancel", ->
browser.pressButton("Submit", done)
it "should not change page", ->
browser.assert.url "/forms/cancel"
# File upload
describe "file upload", ->
before ->
brains.get "/forms/upload", (req, res)->
res.send """
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input name="text" type="file">
<input name="image" type="file">
<button>Upload</button>
</form>
</body>
</html>
"""
brains.post "/forms/upload", (req, res)->
if req.files
[text, image] = [req.files.text, req.files.image]
if text || image
file = (text || image)[0]
data = File.readFileSync(file.path)
if image
digest = Crypto.createHash("md5").update(data).digest("hex")
res.send """
<html>
<head><title>#{file.originalFilename}</title></head>
<body>#{digest || data}</body>
</html>
"""
return
res.send "<html><body>nothing</body></html>"
describe "text", ->
before (done)->
browser.visit "/forms/upload", ->
filename = __dirname + "/data/random.txt"
browser
.attach("text", filename)
.pressButton("Upload", done)
it "should upload file", ->
browser.assert.text "body", "Random text"
it "should upload include name", ->
browser.assert.text "title", "random.txt"
describe "binary", ->
filename = __dirname + "/data/zombie.jpg"
before (done)->
browser.visit "/forms/upload", ->
browser
.attach("image", filename)
.pressButton("Upload", done)
it "should upload include name", ->
browser.assert.text "title", "zombie.jpg"
it "should upload file", ->
digest = Crypto.createHash("md5").update(File.readFileSync(filename)).digest("hex")
browser.assert.text "body", digest
describe "mixed", ->
before (done)->
brains.get "/forms/mixed", (req, res)->
res.send """
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input name="username" type="text">
<input name="logfile" type="file">
<button>Save</button>
</form>
</body>
</html>
"""
brains.post "/forms/mixed", (req, res)->
file = req.files.logfile[0]
data = File.readFileSync(file.path)
res.send """
<html>
<head><title>#{file.originalFilename}</title></head>
<body>#{data}</body>
</html>
"""
browser.visit "/forms/mixed", ->
browser
.fill("username", "hello")
.attach("logfile", "#{__dirname}/data/random.txt")
.pressButton("Save", done)
it "should upload file", ->
browser.assert.text "body", "Random text"
it "should upload include name", ->
browser.assert.text "title", "random.txt"
describe "empty", ->
before (done)->
browser.visit "/forms/upload", ->
browser
.attach("text", "")
.pressButton("Upload", done)
it "should not upload any file", ->
browser.assert.text "body", "nothing"
describe "not set", ->
before (done)->
browser.visit "/forms/upload", ->
browser.pressButton("Upload", done)
it "should not send inputs without names", ->
browser.assert.text "body", "nothing"
describe "file upload with JS", ->
before ->
brains.get "/forms/upload-js", (req, res)->
res.send """
<html>
<head>
<title>Upload a file</title>
<script>
function handleFile() {
document.title = "Upload done";
var file = document.getElementById("my_file").files[0];
document.getElementById("filename").innerHTML = file.name;
document.getElementById("type").innerHTML = file.type;
document.getElementById("size").innerHTML = file.size;
document.getElementById("is_file").innerHTML = (file instanceof File);
}
</script>
</head>
<body>
<form>
<input name="my_file" id="my_file" type="file" onchange="handleFile()">
</form>
<div id="filename"></div>
<div id="type"></div>
<div id="size"></div>
<div id="is_file"></div>
</body>
</html>
"""
before (done)->
browser.visit("/forms/upload-js")
.then ->
filename = "#{__dirname}/data/random.txt"
return browser.attach("my_file", filename)
.then(done, done)
it "should call callback", ->
browser.assert.text "title", "Upload done"
it "should have filename", ->
browser.assert.text "#filename", "random.txt"
it "should know file type", ->
browser.assert.text "#type", "text/plain"
it "should know file size", ->
browser.assert.text "#size", "12"
it "should be of type File", ->
browser.assert.text "#is_file", "true"
describe "content length", ->
describe "post form urlencoded having content", ->
before (done)->
brains.get "/forms/urlencoded", (req, res)->
res.send """
<html>
<body>
<form method="post">
<input name="text" type="text">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.post "/forms/urlencoded", (req, res)->
res.send "#{req.body.text};#{req.headers["content-length"]}"
browser.visit "/forms/urlencoded", ->
browser
.fill("text", "bite")
.pressButton("submit", done)
it "should send content-length header", ->
[body, length] = browser.source.split(";")
assert.equal length, "9" # text=bite
it "should have body with content of input field", ->
[body, length] = browser.source.split(";")
assert.equal body, "bite"
describe "post form urlencoded being empty", ->
before (done)->
brains.get "/forms/urlencoded/empty", (req, res)->
res.send """
<html>
<body>
<form method="post">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.post "/forms/urlencoded/empty", (req, res)->
res.send req.headers["content-length"]
browser.visit "/forms/urlencoded/empty", ->
browser.pressButton("submit", done)
it "should send content-length header 0", ->
assert.equal browser.source, "0"
describe "GET form submission", ->
before (done)->
brains.get "/forms/get", (req, res)->
res.send """
<html>
<body>
<form method="get" action="/forms/get/echo">
<input type="text" name="my_param" value="my_value">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.get "/forms/get/echo", (req, res) ->
res.send """
<html>
<body>#{req.query.my_param}</body>
</html>
"""
browser.visit "/forms/get", ->
browser.pressButton("submit", done)
it "should echo the correct query string", ->
assert.equal browser.text("body"), "my_value"
# DOM specifies that getAttribute returns empty string if no value, but in
# practice it always returns `null`. However, the `name` and `value`
# properties must return empty string.
describe "inputs", ->
before (done)->
brains.get "/forms/inputs", (req, res)->
res.send """
<html>
<body>
<form>
<input type="text">
<textarea></textarea>
<select></select>
<button></button>
</form>
</body>
</html>
"""
browser.visit("/forms/inputs", done)
it "should return empty string if name attribute not set", ->
for tagName in ["form", "input", "textarea", "select", "button"]
browser.assert.attribute tagName, "name", null
it "should return empty string if value attribute not set", ->
for tagName in ["input", "textarea", "select", "button"]
assert.equal browser.query(tagName).getAttribute("value"), null
assert.equal browser.query(tagName).value, ""
it "should return empty string if id attribute not set", ->
for tagName in ["form", "input", "textarea", "select", "button"]
assert.equal browser.query(tagName).getAttribute("id"), null
assert.equal browser.query(tagName).id, ""
after ->
browser.destroy()
| 209354 | { assert, brains, Browser } = require("./helpers")
File = require("fs")
Crypto = require("crypto")
describe "Forms", ->
browser = null
before (done)->
browser = Browser.create()
brains.ready(done)
before ->
brains.get "/forms/form", (req, res)->
res.send """
<html>
<body>
<form action="/forms/submit" method="post">
<label>Name <input type="text" name="name" id="field-name" /></label>
<label for="field-email">Email</label>
<input type="text" name="email" id="field-email"></label>
<textarea name="likes" id="field-likes">Warm brains</textarea>
<input type="password" name="password" id="field-password">
<input type="badtype" name="invalidtype" id="field-invalidtype">
<input type="text" name="email2" id="field-email2">
<input type="text" name="email3" id="field-email3">
<input type="text" name="disabled" disabled>
<input type="text" name="readonly" readonly>
<input type="text" name="empty_text" id="empty-text">
<label>Hungry</label>
<label>You bet<input type="checkbox" name="hungry[]" value="you bet" id="field-hungry"></label>
<label>Certainly<input type="checkbox" name="hungry[]" value="certainly" id="field-hungry-certainly"></label>
<label for="field-brains">Brains?</label>
<input type="checkbox" name="brains" value="yes" id="field-brains">
<input type="checkbox" name="green" id="field-green" value="Super green!" checked="checked">
<input type="checkbox" name="check" id="field-check" value="Huh?" checked="checked">
<input type="checkbox" name="uncheck" id="field-uncheck" value="Yeah!">
<input type="checkbox" name="empty_checkbox" id="empty-checkbox" checked="checked">
<label>Looks
<select name="looks" id="field-looks">
<option value="blood" label="Bloody"></option>
<option value="clean" label="Clean"></option>
<option value="" label="Choose one"></option>
</select>
</label>
<label>Scary <input name="scary" type="radio" value="yes" id="field-scary"></label>
<label>Not scary <input name="scary" type="radio" value="no" id="field-notscary" checked="checked"></label>
<select name="state" id="field-state">
<option>alive</option>
<option>dead</option>
<option>neither</option>
</select>
<span>First address</span>
<label for='address1_street'>Street</label>
<input type="text" name="addresses[][street]" value="" id="address1_street">
<label for='address1_city'>City</label>
<input type="text" name="addresses[][city]" value="" id="address1_city">
<span>Second address</span>
<label for='address2_street'>Street</label>
<input type="text" name="addresses[][street]" value="" id="address2_street">
<label for='address2_city'>City</label>
<input type="text" name="addresses[][city]" value="" id="address2_city">
<select name="kills" id="field-kills">
<option>Five</option>
<option>Seventeen</option>
<option id="option-killed-thousands">Thousands</option>
</select>
<select name="unselected_state" id="field-unselected-state">
<option>alive</option>
<option>dead</option>
</select>
<select name="hobbies[]" id="field-hobbies" multiple="multiple">
<option>Eat Brains</option>
<option id="hobbies-messy">Make Messy</option>
<option>Sleep</option>
</select>
<select name="months" id="field-months">
<option value=""></option>
<option value="jan_2011"> Jan 2011 </option>
<option value="feb_2011"> Feb 2011 </option>
<option value="mar_2011"> Mar 2011 </option>
</select>
<input type="unknown" name="unknown" value="yes">
<input type="reset" value="Reset">
<input type="submit" name="button" value="Submit">
<input type="image" name="image" id="image_submit" value="Image Submit">
<button name="button" value="hit-me">Hit Me</button>
<input type="checkbox" id="field-prevent-check">
<input type="radio" id="field-prevent-radio">
</form>
<div id="formless_inputs">
<label>Hunter <input type="text" name="hunter_name" id="hunter-name"></label>
<textarea name="hunter_hobbies">Killing zombies.</textarea>
<input type="password" name="hunter_password" id="<PASSWORD>">
<input type="badtype" name="hunter_invalidtype" id="hunter-invalidtype" />
<label>Weapons</label>
<label>Chainsaw<input type="checkbox" name="hunter_weapon[]" value="chainsaw"></label>
<label>Shotgun<input type="checkbox" name="hunter_weapon[]" value="shotgun"></label>
<label>Type
<select name="hunter_type">
<option value="regular" label="Regular"></option>
<option value="evil" label="Evil"></option>
<option value="tiny" label="tiny"></option>
</select>
</label>
<label>Powerglove <input name="hunter_powerglove" type="radio" value="glove"></label>
<label>No powerglove <input name="hunter_powerglove" type="radio" value="noglove" checked="checked"></label>
</div>
</body>
</html>
"""
brains.post "/forms/submit", (req, res)->
res.send """
<html>
<title>Results</title>
<body>
<div id="name">#{req.body.name}</div>
<div id="likes">#{req.body.likes}</div>
<div id="green">#{req.body.green}</div>
<div id="brains">#{req.body.brains}</div>
<div id="looks">#{req.body.looks}</div>
<div id="hungry">#{JSON.stringify(req.body.hungry)}</div>
<div id="scary">#{req.body.scary}</div>
<div id="state">#{req.body.state}</div>
<div id="empty-text">#{req.body.empty_text}</div>
<div id="empty-checkbox">#{req.body.empty_checkbox || "nothing"}</div>
<div id="unselected_state">#{req.body.unselected_state}</div>
<div id="hobbies">#{JSON.stringify(req.body.hobbies)}</div>
<div id="addresses">#{JSON.stringify(req.body.addresses)}</div>
<div id="unknown">#{req.body.unknown}</div>
<div id="clicked">#{req.body.button}</div>
<div id="image_clicked">#{req.body.image}</div>
</body>
</html>
"""
describe "fill field", ->
before (done)->
browser.visit "/forms/form", =>
fill_events = ["input", "change"]
count = fill_events.length
browser.on "event", (event, target)=>
if event.type in fill_events
count -= 1
if count == 0
@changed = target
count = fill_events.length
done()
describe "fill input with same the same value", ->
before ->
browser.fill("Name", "")
it "should not fire input *and* change events", ->
assert.equal @change, undefined
describe "text input enclosed in label", ->
before ->
browser.fill("Name", "<NAME>")
it "should set text field", ->
browser.assert.input "#field-name", "ArmB<NAME>"
it "should fire input and changed event", ->
assert.equal @changed.id, "field-name"
describe "email input referenced from label", ->
before ->
browser.fill("Email", "<EMAIL>")
it "should set email field", ->
browser.assert.input "#field-email", "<EMAIL>"
it "should fire input and change events", ->
assert.equal @changed.id, "field-email"
describe "textarea by field name", ->
before ->
browser.fill("likes", "Arm Biting")
it "should set textarea", ->
browser.assert.input "#field-likes", "Arm Biting"
it "should fire input and change events", ->
assert.equal @changed.id, "field-likes"
describe "password input by selector", ->
before ->
browser.fill("input[name=password]", "<PASSWORD>")
it "should set password", ->
browser.assert.input "#field-password", "<PASSWORD>"
it "should fire input and change events", ->
assert.equal @changed.id, "field-password"
describe "input without a valid type", ->
before ->
browser.fill("input[name=invalidtype]", "some value")
it "should set value", ->
browser.assert.input "#field-invalidtype", "some value"
it "should fire input and change events", ->
assert.equal @changed.id, "field-invalidtype"
describe "email2 input by node", ->
before ->
browser.fill("#field-email2", "<EMAIL>")
it "should set email2 field", ->
browser.assert.input "#field-email2", "<EMAIL>"
it "should fire input and change events", ->
assert.equal @changed.id, "field-email2"
describe "disabled input can not be modified", ->
it "should raise error", ->
assert.throws ->
browser.fill("#disabled_input_field", "yeahh")
describe "readonly input can not be modified", ->
it "should raise error", ->
assert.throws ->
browser.fill("#readonly_input_field", "yeahh")
describe "focus field (1)", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
browser.fill(field1, "something")
field2.addEventListener "focus", ->
done()
browser.fill(field2, "else")
it "should fire focus event on selected field", ->
assert true
describe "focus field (2)", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
browser.fill field1, "something"
field1.addEventListener "blur", ->
done()
browser.fill field2, "else"
it "should fire blur event on previous field", ->
assert true
describe "keep value and switch focus", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
field1.addEventListener "change", ->
done(new Error("Should not fire"))
browser.focus(field1)
browser.focus(field2)
setImmediate(done)
it "should fire change event on previous field", ->
assert true
describe "change value and switch focus", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
field1.addEventListener "change", ->
done()
browser.focus(field1)
field1.value = "something"
browser.focus(field2)
it "should fire change event on previous field", ->
assert true
describe "check box", ->
changed = null
clicked = null
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
switch event._type
when "change"
changed = target
when "click"
clicked = target
done()
describe "checkbox enclosed in label", ->
before ->
browser.check("You bet")
it "should check checkbox", ->
browser.assert.element "#field-hungry:checked"
it "should fire change event", ->
assert.equal changed.id, "field-hungry"
it "should fire clicked event", ->
assert.equal clicked.id, "field-hungry"
describe "with callback", ->
before ->
browser.check("Brains?")
it "should callback", ->
browser.assert.element "#field-brains:checked"
describe "checkbox referenced from label", ->
before ->
browser.uncheck("Brains?")
changed = null
clicked = null
browser.check("Brains?")
it "should check checkbox", ->
browser.assert.element "#field-brains:checked"
it "should fire change event", ->
assert.equal changed.id, "field-brains"
describe "uncheck with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser
.check("Brains?")
.uncheck("Brains?")
done()
it "should callback", ->
browser.assert.elements "#field-brains:checked", 0
describe "checkbox by name", ->
before ->
browser.check("green")
changed = null
clicked = null
browser.uncheck("green")
it "should uncheck checkbox", ->
browser.assert.elements "#field-green:checked", 0
it "should fire change event", ->
assert.equal changed.id, "field-green"
describe "check callback", ->
before ->
browser.check("uncheck")
it "should callback", ->
browser.assert.elements "#field-uncheck:checked", 1
describe "uncheck callback", ->
before ->
browser.uncheck("check")
it "should callback", ->
browser.assert.elements "#field-uncheck:checked", 1
describe "prevent default", ->
values = []
before ->
checkBox = browser.$$("#field-prevent-check")
values.push(checkBox.checked)
checkBox.addEventListener "click", (event)->
values.push(checkBox.checked)
event.preventDefault()
browser.check(checkBox)
values.push(checkBox.checked)
it "should turn checkbox on then off", ->
assert.deepEqual values, [false, true, false]
describe "any checkbox (1)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-check")
field2 = browser.querySelector("#field-uncheck")
browser.uncheck(field1)
browser.check(field1)
field2.addEventListener "focus", ->
done()
browser.check(field2)
it "should fire focus event on selected field", ->
assert true
describe "any checkbox (2)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-check")
field2 = browser.querySelector("#field-uncheck")
browser.uncheck(field1)
browser.check(field1)
field1.addEventListener "blur", ->
done()
browser.check(field2)
it "should fire blur event on previous field", ->
assert true
describe "radio buttons", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
switch event.type
when "change"
@changed = target
when "click"
@clicked = target
done()
describe "radio button enclosed in label", ->
before ->
browser.choose("Scary")
it "should check radio", ->
browser.assert.element "#field-scary:checked"
it "should fire click event", ->
assert.equal @clicked.id, "field-scary"
it "should fire change event", ->
assert.equal @changed.id, "field-scary"
describe "with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.choose("Scary")
done()
it "should callback", ->
browser.assert.element "#field-scary:checked"
describe "radio button by value", ->
before (done)->
browser.visit "/forms/form", ->
browser.choose("no")
done()
it "should check radio", ->
browser.assert.element "#field-notscary:checked"
it "should uncheck other radio", ->
browser.assert.elements "#field-scary:checked", 0
describe "prevent default", ->
values = []
before ->
radio = browser.$$("#field-prevent-radio")
values.push(radio.checked)
radio.addEventListener "click", (event)->
values.push(radio.checked)
event.preventDefault()
browser.choose(radio)
values.push(radio.checked)
it "should turn radio on then off", ->
assert.deepEqual values, [false, true, false]
describe "any radio button (1) ", ->
before ->
field1 = browser.querySelector("#field-scary")
field2 = browser.querySelector("#field-notscary")
browser.choose(field1)
field2.addEventListener "focus", ->
done()
browser.choose(field2)
it "should fire focus event on selected field", ->
assert true
describe "any radio button (1) ", ->
before ->
field1 = browser.querySelector("#field-scary")
field2 = browser.querySelector("#field-notscary")
browser.choose(field1)
field1.addEventListener "blur", ->
done()
browser.choose(field2)
it "should fire blur event on previous field", ->
assert true
describe "select option", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
if event.type == "change"
@changed = target
done()
describe "enclosed in label using option label", ->
before ->
browser.select("Looks", "Bloody")
it "should set value", ->
browser.assert.input "#field-looks", "blood"
it "should select first option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-looks").options)
assert.deepEqual selected, [true, false, false]
it "should fire change event", ->
assert.equal @changed.id, "field-looks"
describe "select name using option value", ->
before ->
browser.select("state", "dead")
it "should set value", ->
browser.assert.input "#field-state", "dead"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-state").options)
assert.deepEqual selected, [false, true, false]
it "should fire change event", ->
assert.equal @changed.id, "field-state"
describe "select name using option text", ->
before ->
browser.select("months", "Jan 2011")
it "should set value", ->
browser.assert.input "#field-months", "jan_2011"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-months").options)
assert.deepEqual selected, [false, true, false, false]
it "should fire change event", ->
assert.equal @changed.id, "field-months"
describe "select option value directly", ->
before ->
browser.selectOption("#option-killed-thousands")
it "should set value", ->
browser.assert.input "#field-kills", "Thousands"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-kills").options)
assert.deepEqual selected, [false, false, true]
it "should fire change event", ->
assert.equal @changed.id, "field-kills"
describe "select callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.select("unselected_state", "dead")
done()
it "should callback", ->
browser.assert.input "#field-unselected-state", "dead"
describe "select option callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.selectOption("#option-killed-thousands")
done()
it "should callback", ->
browser.assert.input "#field-kills", "Thousands"
describe "any selection (1)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-kills")
browser.fill(field1, "something")
field2.addEventListener "focus", ->
done()
browser.select(field2, "Five")
it "should fire focus event on selected field", ->
assert true
describe "any selection (2)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-kills")
browser.fill(field1, "something")
field1.addEventListener "blur", ->
done()
browser.select(field2, "Five")
it "should fire blur event on previous field", ->
assert true
describe "multiple select option", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
if event.type == "change"
@changed = target
done()
describe "select name using option value", ->
before ->
browser.select("#field-hobbies", "Eat Brains")
browser.select("#field-hobbies", "Sleep")
it "should select first and second options", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, true]
it "should fire change event", ->
assert.equal @changed.id, "field-hobbies"
it "should not fire change event if nothing changed", ->
assert @changed
@changed = null
browser.select("#field-hobbies", "Eat Brains")
assert !@changed
describe "unselect name using option value", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.select("#field-hobbies", "Eat Brains")
browser.select("#field-hobbies", "Sleep")
browser.unselect("#field-hobbies", "Sleep")
return
.then(done, done)
it "should unselect items", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, false]
describe "unselect name using option selector", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.selectOption("#hobbies-messy")
browser.unselectOption("#hobbies-messy")
return
.then(done, done)
it "should unselect items", ->
assert !browser.query("#hobbies-messy").selected
describe "with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.unselect("#field-hobbies", "Eat Brains")
browser.unselect("#field-hobbies", "Sleep")
browser.select("#field-hobbies", "Eat Brains")
done()
it "should unselect callback", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, false]
describe "fields not contained in a form", ->
before (done)->
browser.visit("/forms/form", done)
it "should not fail", ->
browser
.fill("<NAME>", "<NAME>")
.fill("hunter_hobbies", "Trying to get home")
.fill("#hunter-password", "<PASSWORD>")
.fill("input[name=hunter_invalidtype]", "necktie?")
.check("Chainsaw")
.choose("Powerglove")
.select("Type", "Evil")
describe "reset form", ->
describe "by calling reset", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "<NAME>")
.fill("likes", "Arm Biting")
.check("You bet")
.choose("Scary")
.select("state", "dead")
browser.querySelector("form").reset()
return
.then(done, done)
it "should reset input field to original value", ->
browser.assert.input "#field-name", ""
it "should reset textarea to original value", ->
browser.assert.input "#field-likes", "Warm brains"
it "should reset checkbox to original value", ->
browser.assert.elements "#field-hungry:checked", 0
it "should reset radio to original value", ->
browser.assert.elements "#field-scary:checked", 0
browser.assert.elements "#field-notscary:checked", 1
it "should reset select to original option", ->
browser.assert.input "#field-state", "alive"
describe "with event handler", ->
eventType = null
before (done)->
browser.visit("/forms/form")
.then ->
browser.querySelector("form [type=reset]").addEventListener "click", (event)->
eventType = event.type
done()
.then ->
browser.querySelector("form [type=reset]").click()
it "should fire click event", ->
assert.equal eventType, "click"
describe "with preventDefault", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.fill("Name", "<NAME>")
browser.querySelector("form [type=reset]").addEventListener "click", (event)->
event.preventDefault()
.then ->
browser.querySelector("form [type=reset]").click()
.then(done, done)
it "should not reset input field", ->
browser.assert.input "#field-name", "<NAME>"
describe "by clicking reset input", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.fill("Name", "<NAME>")
browser.querySelector("form [type=reset]").click()
.then(done, done)
it "should reset input field to original value", ->
browser.assert.input "#field-name", ""
# Submitting form
describe "submit form", ->
describe "by calling submit", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "<NAME>")
.fill("likes", "<NAME>")
.check("You bet")
.check("Certainly")
.choose("Scary")
.select("state", "dead")
.select("looks", "Choose one")
.select("#field-hobbies", "Eat Brains")
.select("#field-hobbies", "Sleep")
.check("Brains?")
.fill('#address1_city', 'Paris')
.fill('#address1_street', 'CDG')
.fill('#address2_city', 'Mikolaiv')
.fill('#address2_street', 'PGS')
browser.querySelector("form").submit()
browser.wait()
.then(done, done)
it "should open new page", ->
browser.assert.url "/forms/submit"
browser.assert.text "title", "Results"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send text input values to server", ->
browser.assert.text "#name", "<NAME>"
it "should send textarea values to server", ->
browser.assert.text "#likes", "<NAME>"
it "should send radio button to server", ->
browser.assert.text "#scary", "yes"
it "should send unknown types to server", ->
browser.assert.text "#unknown", "yes"
it "should send checkbox with default value to server (brains)", ->
browser.assert.text "#brains", "yes"
it "should send checkbox with default value to server (green)", ->
browser.assert.text "#green", "Super green!"
it "should send multiple checkbox values to server", ->
browser.assert.text "#hungry", '["you bet","certainly"]'
it "should send selected option to server", ->
browser.assert.text "#state", "dead"
it "should send first selected option if none was chosen to server", ->
browser.assert.text "#unselected_state", "alive"
browser.assert.text "#looks", ""
it "should send multiple selected options to server", ->
browser.assert.text "#hobbies", '["Eat Brains","Sleep"]'
it "should send empty text fields", ->
browser.assert.text "#empty-text", ""
it "should send checked field with no value", ->
browser.assert.text "#empty-checkbox", "1"
describe "by clicking button", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "<NAME>")
.fill("likes", "<NAME>")
return browser.pressButton("Hit Me")
.then(done, done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send button value to server", ->
browser.assert.text "#clicked", "hit-me"
it "should send input values to server", ->
browser.assert.text "#name", "ArmBiter"
browser.assert.text "#likes", "Arm Biting"
it "should not send other button values to server", ->
browser.assert.text "#image_clicked", "undefined"
describe "pressButton(1)", ->
before (done)->
browser.visit "/forms/form", ->
field = browser.querySelector("#field-email2")
browser.fill(field, "something")
browser.button("Hit Me").addEventListener "focus", ->
done()
browser.pressButton("Hit Me")
it "should fire focus event on button", ->
assert true
describe "pressButton(2)", ->
before (done)->
browser.visit "/forms/form", ->
field = browser.querySelector("#field-email2")
browser.fill(field, "something")
field.addEventListener "blur", ->
done()
browser.pressButton("Hit Me")
it "should fire blur event on previous field", ->
assert true
describe "by clicking image button", ->
before (done)->
browser.visit "/forms/form", ->
browser
.fill("Name", "<NAME>")
.fill("likes", "<NAME>")
.pressButton("#image_submit", done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send image value to server", ->
browser.assert.text "#image_clicked", "Image Submit"
it "should send input values to server", ->
browser.assert.text "#name", "<NAME>"
browser.assert.text "#likes", "Arm Biting"
it "should not send other button values to server", ->
browser.assert.text "#clicked", "undefined"
describe "by clicking input", ->
before (done)->
browser.visit "/forms/form", ->
browser
.fill("Name", "<NAME>")
.fill("likes", "<NAME>")
.pressButton("Submit", done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send submit value to server", ->
browser.assert.text "#clicked", "Submit"
it "should send input values to server", ->
browser.assert.text "#name", "<NAME>"
browser.assert.text "#likes", "Arm Biting"
describe "cancel event", ->
before (done)->
brains.get "/forms/cancel", (req, res)->
res.send """
<html>
<head>
<script src="/jquery.js"></script>
<script>
$(function() {
$("form").submit(function() {
return false;
})
})
</script>
</head>
<body>
<form action="/forms/submit" method="post">
<button>Submit</button>
</form>
</body>
</html>
"""
browser.visit "/forms/cancel", ->
browser.pressButton("Submit", done)
it "should not change page", ->
browser.assert.url "/forms/cancel"
# File upload
describe "file upload", ->
before ->
brains.get "/forms/upload", (req, res)->
res.send """
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input name="text" type="file">
<input name="image" type="file">
<button>Upload</button>
</form>
</body>
</html>
"""
brains.post "/forms/upload", (req, res)->
if req.files
[text, image] = [req.files.text, req.files.image]
if text || image
file = (text || image)[0]
data = File.readFileSync(file.path)
if image
digest = Crypto.createHash("md5").update(data).digest("hex")
res.send """
<html>
<head><title>#{file.originalFilename}</title></head>
<body>#{digest || data}</body>
</html>
"""
return
res.send "<html><body>nothing</body></html>"
describe "text", ->
before (done)->
browser.visit "/forms/upload", ->
filename = __dirname + "/data/random.txt"
browser
.attach("text", filename)
.pressButton("Upload", done)
it "should upload file", ->
browser.assert.text "body", "Random text"
it "should upload include name", ->
browser.assert.text "title", "random.txt"
describe "binary", ->
filename = __dirname + "/data/zombie.jpg"
before (done)->
browser.visit "/forms/upload", ->
browser
.attach("image", filename)
.pressButton("Upload", done)
it "should upload include name", ->
browser.assert.text "title", "zombie.jpg"
it "should upload file", ->
digest = Crypto.createHash("md5").update(File.readFileSync(filename)).digest("hex")
browser.assert.text "body", digest
describe "mixed", ->
before (done)->
brains.get "/forms/mixed", (req, res)->
res.send """
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input name="username" type="text">
<input name="logfile" type="file">
<button>Save</button>
</form>
</body>
</html>
"""
brains.post "/forms/mixed", (req, res)->
file = req.files.logfile[0]
data = File.readFileSync(file.path)
res.send """
<html>
<head><title>#{file.originalFilename}</title></head>
<body>#{data}</body>
</html>
"""
browser.visit "/forms/mixed", ->
browser
.fill("username", "hello")
.attach("logfile", "#{__dirname}/data/random.txt")
.pressButton("Save", done)
it "should upload file", ->
browser.assert.text "body", "Random text"
it "should upload include name", ->
browser.assert.text "title", "random.txt"
describe "empty", ->
before (done)->
browser.visit "/forms/upload", ->
browser
.attach("text", "")
.pressButton("Upload", done)
it "should not upload any file", ->
browser.assert.text "body", "nothing"
describe "not set", ->
before (done)->
browser.visit "/forms/upload", ->
browser.pressButton("Upload", done)
it "should not send inputs without names", ->
browser.assert.text "body", "nothing"
describe "file upload with JS", ->
before ->
brains.get "/forms/upload-js", (req, res)->
res.send """
<html>
<head>
<title>Upload a file</title>
<script>
function handleFile() {
document.title = "Upload done";
var file = document.getElementById("my_file").files[0];
document.getElementById("filename").innerHTML = file.name;
document.getElementById("type").innerHTML = file.type;
document.getElementById("size").innerHTML = file.size;
document.getElementById("is_file").innerHTML = (file instanceof File);
}
</script>
</head>
<body>
<form>
<input name="my_file" id="my_file" type="file" onchange="handleFile()">
</form>
<div id="filename"></div>
<div id="type"></div>
<div id="size"></div>
<div id="is_file"></div>
</body>
</html>
"""
before (done)->
browser.visit("/forms/upload-js")
.then ->
filename = "#{__dirname}/data/random.txt"
return browser.attach("my_file", filename)
.then(done, done)
it "should call callback", ->
browser.assert.text "title", "Upload done"
it "should have filename", ->
browser.assert.text "#filename", "random.txt"
it "should know file type", ->
browser.assert.text "#type", "text/plain"
it "should know file size", ->
browser.assert.text "#size", "12"
it "should be of type File", ->
browser.assert.text "#is_file", "true"
describe "content length", ->
describe "post form urlencoded having content", ->
before (done)->
brains.get "/forms/urlencoded", (req, res)->
res.send """
<html>
<body>
<form method="post">
<input name="text" type="text">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.post "/forms/urlencoded", (req, res)->
res.send "#{req.body.text};#{req.headers["content-length"]}"
browser.visit "/forms/urlencoded", ->
browser
.fill("text", "bite")
.pressButton("submit", done)
it "should send content-length header", ->
[body, length] = browser.source.split(";")
assert.equal length, "9" # text=bite
it "should have body with content of input field", ->
[body, length] = browser.source.split(";")
assert.equal body, "bite"
describe "post form urlencoded being empty", ->
before (done)->
brains.get "/forms/urlencoded/empty", (req, res)->
res.send """
<html>
<body>
<form method="post">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.post "/forms/urlencoded/empty", (req, res)->
res.send req.headers["content-length"]
browser.visit "/forms/urlencoded/empty", ->
browser.pressButton("submit", done)
it "should send content-length header 0", ->
assert.equal browser.source, "0"
describe "GET form submission", ->
before (done)->
brains.get "/forms/get", (req, res)->
res.send """
<html>
<body>
<form method="get" action="/forms/get/echo">
<input type="text" name="my_param" value="my_value">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.get "/forms/get/echo", (req, res) ->
res.send """
<html>
<body>#{req.query.my_param}</body>
</html>
"""
browser.visit "/forms/get", ->
browser.pressButton("submit", done)
it "should echo the correct query string", ->
assert.equal browser.text("body"), "my_value"
# DOM specifies that getAttribute returns empty string if no value, but in
# practice it always returns `null`. However, the `name` and `value`
# properties must return empty string.
describe "inputs", ->
before (done)->
brains.get "/forms/inputs", (req, res)->
res.send """
<html>
<body>
<form>
<input type="text">
<textarea></textarea>
<select></select>
<button></button>
</form>
</body>
</html>
"""
browser.visit("/forms/inputs", done)
it "should return empty string if name attribute not set", ->
for tagName in ["form", "input", "textarea", "select", "button"]
browser.assert.attribute tagName, "name", null
it "should return empty string if value attribute not set", ->
for tagName in ["input", "textarea", "select", "button"]
assert.equal browser.query(tagName).getAttribute("value"), null
assert.equal browser.query(tagName).value, ""
it "should return empty string if id attribute not set", ->
for tagName in ["form", "input", "textarea", "select", "button"]
assert.equal browser.query(tagName).getAttribute("id"), null
assert.equal browser.query(tagName).id, ""
after ->
browser.destroy()
| true | { assert, brains, Browser } = require("./helpers")
File = require("fs")
Crypto = require("crypto")
describe "Forms", ->
browser = null
before (done)->
browser = Browser.create()
brains.ready(done)
before ->
brains.get "/forms/form", (req, res)->
res.send """
<html>
<body>
<form action="/forms/submit" method="post">
<label>Name <input type="text" name="name" id="field-name" /></label>
<label for="field-email">Email</label>
<input type="text" name="email" id="field-email"></label>
<textarea name="likes" id="field-likes">Warm brains</textarea>
<input type="password" name="password" id="field-password">
<input type="badtype" name="invalidtype" id="field-invalidtype">
<input type="text" name="email2" id="field-email2">
<input type="text" name="email3" id="field-email3">
<input type="text" name="disabled" disabled>
<input type="text" name="readonly" readonly>
<input type="text" name="empty_text" id="empty-text">
<label>Hungry</label>
<label>You bet<input type="checkbox" name="hungry[]" value="you bet" id="field-hungry"></label>
<label>Certainly<input type="checkbox" name="hungry[]" value="certainly" id="field-hungry-certainly"></label>
<label for="field-brains">Brains?</label>
<input type="checkbox" name="brains" value="yes" id="field-brains">
<input type="checkbox" name="green" id="field-green" value="Super green!" checked="checked">
<input type="checkbox" name="check" id="field-check" value="Huh?" checked="checked">
<input type="checkbox" name="uncheck" id="field-uncheck" value="Yeah!">
<input type="checkbox" name="empty_checkbox" id="empty-checkbox" checked="checked">
<label>Looks
<select name="looks" id="field-looks">
<option value="blood" label="Bloody"></option>
<option value="clean" label="Clean"></option>
<option value="" label="Choose one"></option>
</select>
</label>
<label>Scary <input name="scary" type="radio" value="yes" id="field-scary"></label>
<label>Not scary <input name="scary" type="radio" value="no" id="field-notscary" checked="checked"></label>
<select name="state" id="field-state">
<option>alive</option>
<option>dead</option>
<option>neither</option>
</select>
<span>First address</span>
<label for='address1_street'>Street</label>
<input type="text" name="addresses[][street]" value="" id="address1_street">
<label for='address1_city'>City</label>
<input type="text" name="addresses[][city]" value="" id="address1_city">
<span>Second address</span>
<label for='address2_street'>Street</label>
<input type="text" name="addresses[][street]" value="" id="address2_street">
<label for='address2_city'>City</label>
<input type="text" name="addresses[][city]" value="" id="address2_city">
<select name="kills" id="field-kills">
<option>Five</option>
<option>Seventeen</option>
<option id="option-killed-thousands">Thousands</option>
</select>
<select name="unselected_state" id="field-unselected-state">
<option>alive</option>
<option>dead</option>
</select>
<select name="hobbies[]" id="field-hobbies" multiple="multiple">
<option>Eat Brains</option>
<option id="hobbies-messy">Make Messy</option>
<option>Sleep</option>
</select>
<select name="months" id="field-months">
<option value=""></option>
<option value="jan_2011"> Jan 2011 </option>
<option value="feb_2011"> Feb 2011 </option>
<option value="mar_2011"> Mar 2011 </option>
</select>
<input type="unknown" name="unknown" value="yes">
<input type="reset" value="Reset">
<input type="submit" name="button" value="Submit">
<input type="image" name="image" id="image_submit" value="Image Submit">
<button name="button" value="hit-me">Hit Me</button>
<input type="checkbox" id="field-prevent-check">
<input type="radio" id="field-prevent-radio">
</form>
<div id="formless_inputs">
<label>Hunter <input type="text" name="hunter_name" id="hunter-name"></label>
<textarea name="hunter_hobbies">Killing zombies.</textarea>
<input type="password" name="hunter_password" id="PI:PASSWORD:<PASSWORD>END_PI">
<input type="badtype" name="hunter_invalidtype" id="hunter-invalidtype" />
<label>Weapons</label>
<label>Chainsaw<input type="checkbox" name="hunter_weapon[]" value="chainsaw"></label>
<label>Shotgun<input type="checkbox" name="hunter_weapon[]" value="shotgun"></label>
<label>Type
<select name="hunter_type">
<option value="regular" label="Regular"></option>
<option value="evil" label="Evil"></option>
<option value="tiny" label="tiny"></option>
</select>
</label>
<label>Powerglove <input name="hunter_powerglove" type="radio" value="glove"></label>
<label>No powerglove <input name="hunter_powerglove" type="radio" value="noglove" checked="checked"></label>
</div>
</body>
</html>
"""
brains.post "/forms/submit", (req, res)->
res.send """
<html>
<title>Results</title>
<body>
<div id="name">#{req.body.name}</div>
<div id="likes">#{req.body.likes}</div>
<div id="green">#{req.body.green}</div>
<div id="brains">#{req.body.brains}</div>
<div id="looks">#{req.body.looks}</div>
<div id="hungry">#{JSON.stringify(req.body.hungry)}</div>
<div id="scary">#{req.body.scary}</div>
<div id="state">#{req.body.state}</div>
<div id="empty-text">#{req.body.empty_text}</div>
<div id="empty-checkbox">#{req.body.empty_checkbox || "nothing"}</div>
<div id="unselected_state">#{req.body.unselected_state}</div>
<div id="hobbies">#{JSON.stringify(req.body.hobbies)}</div>
<div id="addresses">#{JSON.stringify(req.body.addresses)}</div>
<div id="unknown">#{req.body.unknown}</div>
<div id="clicked">#{req.body.button}</div>
<div id="image_clicked">#{req.body.image}</div>
</body>
</html>
"""
describe "fill field", ->
before (done)->
browser.visit "/forms/form", =>
fill_events = ["input", "change"]
count = fill_events.length
browser.on "event", (event, target)=>
if event.type in fill_events
count -= 1
if count == 0
@changed = target
count = fill_events.length
done()
describe "fill input with same the same value", ->
before ->
browser.fill("Name", "")
it "should not fire input *and* change events", ->
assert.equal @change, undefined
describe "text input enclosed in label", ->
before ->
browser.fill("Name", "PI:NAME:<NAME>END_PI")
it "should set text field", ->
browser.assert.input "#field-name", "ArmBPI:NAME:<NAME>END_PI"
it "should fire input and changed event", ->
assert.equal @changed.id, "field-name"
describe "email input referenced from label", ->
before ->
browser.fill("Email", "PI:EMAIL:<EMAIL>END_PI")
it "should set email field", ->
browser.assert.input "#field-email", "PI:EMAIL:<EMAIL>END_PI"
it "should fire input and change events", ->
assert.equal @changed.id, "field-email"
describe "textarea by field name", ->
before ->
browser.fill("likes", "Arm Biting")
it "should set textarea", ->
browser.assert.input "#field-likes", "Arm Biting"
it "should fire input and change events", ->
assert.equal @changed.id, "field-likes"
describe "password input by selector", ->
before ->
browser.fill("input[name=password]", "PI:PASSWORD:<PASSWORD>END_PI")
it "should set password", ->
browser.assert.input "#field-password", "PI:PASSWORD:<PASSWORD>END_PI"
it "should fire input and change events", ->
assert.equal @changed.id, "field-password"
describe "input without a valid type", ->
before ->
browser.fill("input[name=invalidtype]", "some value")
it "should set value", ->
browser.assert.input "#field-invalidtype", "some value"
it "should fire input and change events", ->
assert.equal @changed.id, "field-invalidtype"
describe "email2 input by node", ->
before ->
browser.fill("#field-email2", "PI:EMAIL:<EMAIL>END_PI")
it "should set email2 field", ->
browser.assert.input "#field-email2", "PI:EMAIL:<EMAIL>END_PI"
it "should fire input and change events", ->
assert.equal @changed.id, "field-email2"
describe "disabled input can not be modified", ->
it "should raise error", ->
assert.throws ->
browser.fill("#disabled_input_field", "yeahh")
describe "readonly input can not be modified", ->
it "should raise error", ->
assert.throws ->
browser.fill("#readonly_input_field", "yeahh")
describe "focus field (1)", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
browser.fill(field1, "something")
field2.addEventListener "focus", ->
done()
browser.fill(field2, "else")
it "should fire focus event on selected field", ->
assert true
describe "focus field (2)", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
browser.fill field1, "something"
field1.addEventListener "blur", ->
done()
browser.fill field2, "else"
it "should fire blur event on previous field", ->
assert true
describe "keep value and switch focus", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
field1.addEventListener "change", ->
done(new Error("Should not fire"))
browser.focus(field1)
browser.focus(field2)
setImmediate(done)
it "should fire change event on previous field", ->
assert true
describe "change value and switch focus", ->
before (done)->
browser.visit("/forms/form")
.then ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-email3")
field1.addEventListener "change", ->
done()
browser.focus(field1)
field1.value = "something"
browser.focus(field2)
it "should fire change event on previous field", ->
assert true
describe "check box", ->
changed = null
clicked = null
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
switch event._type
when "change"
changed = target
when "click"
clicked = target
done()
describe "checkbox enclosed in label", ->
before ->
browser.check("You bet")
it "should check checkbox", ->
browser.assert.element "#field-hungry:checked"
it "should fire change event", ->
assert.equal changed.id, "field-hungry"
it "should fire clicked event", ->
assert.equal clicked.id, "field-hungry"
describe "with callback", ->
before ->
browser.check("Brains?")
it "should callback", ->
browser.assert.element "#field-brains:checked"
describe "checkbox referenced from label", ->
before ->
browser.uncheck("Brains?")
changed = null
clicked = null
browser.check("Brains?")
it "should check checkbox", ->
browser.assert.element "#field-brains:checked"
it "should fire change event", ->
assert.equal changed.id, "field-brains"
describe "uncheck with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser
.check("Brains?")
.uncheck("Brains?")
done()
it "should callback", ->
browser.assert.elements "#field-brains:checked", 0
describe "checkbox by name", ->
before ->
browser.check("green")
changed = null
clicked = null
browser.uncheck("green")
it "should uncheck checkbox", ->
browser.assert.elements "#field-green:checked", 0
it "should fire change event", ->
assert.equal changed.id, "field-green"
describe "check callback", ->
before ->
browser.check("uncheck")
it "should callback", ->
browser.assert.elements "#field-uncheck:checked", 1
describe "uncheck callback", ->
before ->
browser.uncheck("check")
it "should callback", ->
browser.assert.elements "#field-uncheck:checked", 1
describe "prevent default", ->
values = []
before ->
checkBox = browser.$$("#field-prevent-check")
values.push(checkBox.checked)
checkBox.addEventListener "click", (event)->
values.push(checkBox.checked)
event.preventDefault()
browser.check(checkBox)
values.push(checkBox.checked)
it "should turn checkbox on then off", ->
assert.deepEqual values, [false, true, false]
describe "any checkbox (1)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-check")
field2 = browser.querySelector("#field-uncheck")
browser.uncheck(field1)
browser.check(field1)
field2.addEventListener "focus", ->
done()
browser.check(field2)
it "should fire focus event on selected field", ->
assert true
describe "any checkbox (2)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-check")
field2 = browser.querySelector("#field-uncheck")
browser.uncheck(field1)
browser.check(field1)
field1.addEventListener "blur", ->
done()
browser.check(field2)
it "should fire blur event on previous field", ->
assert true
describe "radio buttons", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
switch event.type
when "change"
@changed = target
when "click"
@clicked = target
done()
describe "radio button enclosed in label", ->
before ->
browser.choose("Scary")
it "should check radio", ->
browser.assert.element "#field-scary:checked"
it "should fire click event", ->
assert.equal @clicked.id, "field-scary"
it "should fire change event", ->
assert.equal @changed.id, "field-scary"
describe "with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.choose("Scary")
done()
it "should callback", ->
browser.assert.element "#field-scary:checked"
describe "radio button by value", ->
before (done)->
browser.visit "/forms/form", ->
browser.choose("no")
done()
it "should check radio", ->
browser.assert.element "#field-notscary:checked"
it "should uncheck other radio", ->
browser.assert.elements "#field-scary:checked", 0
describe "prevent default", ->
values = []
before ->
radio = browser.$$("#field-prevent-radio")
values.push(radio.checked)
radio.addEventListener "click", (event)->
values.push(radio.checked)
event.preventDefault()
browser.choose(radio)
values.push(radio.checked)
it "should turn radio on then off", ->
assert.deepEqual values, [false, true, false]
describe "any radio button (1) ", ->
before ->
field1 = browser.querySelector("#field-scary")
field2 = browser.querySelector("#field-notscary")
browser.choose(field1)
field2.addEventListener "focus", ->
done()
browser.choose(field2)
it "should fire focus event on selected field", ->
assert true
describe "any radio button (1) ", ->
before ->
field1 = browser.querySelector("#field-scary")
field2 = browser.querySelector("#field-notscary")
browser.choose(field1)
field1.addEventListener "blur", ->
done()
browser.choose(field2)
it "should fire blur event on previous field", ->
assert true
describe "select option", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
if event.type == "change"
@changed = target
done()
describe "enclosed in label using option label", ->
before ->
browser.select("Looks", "Bloody")
it "should set value", ->
browser.assert.input "#field-looks", "blood"
it "should select first option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-looks").options)
assert.deepEqual selected, [true, false, false]
it "should fire change event", ->
assert.equal @changed.id, "field-looks"
describe "select name using option value", ->
before ->
browser.select("state", "dead")
it "should set value", ->
browser.assert.input "#field-state", "dead"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-state").options)
assert.deepEqual selected, [false, true, false]
it "should fire change event", ->
assert.equal @changed.id, "field-state"
describe "select name using option text", ->
before ->
browser.select("months", "Jan 2011")
it "should set value", ->
browser.assert.input "#field-months", "jan_2011"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-months").options)
assert.deepEqual selected, [false, true, false, false]
it "should fire change event", ->
assert.equal @changed.id, "field-months"
describe "select option value directly", ->
before ->
browser.selectOption("#option-killed-thousands")
it "should set value", ->
browser.assert.input "#field-kills", "Thousands"
it "should select second option", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-kills").options)
assert.deepEqual selected, [false, false, true]
it "should fire change event", ->
assert.equal @changed.id, "field-kills"
describe "select callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.select("unselected_state", "dead")
done()
it "should callback", ->
browser.assert.input "#field-unselected-state", "dead"
describe "select option callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.selectOption("#option-killed-thousands")
done()
it "should callback", ->
browser.assert.input "#field-kills", "Thousands"
describe "any selection (1)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-kills")
browser.fill(field1, "something")
field2.addEventListener "focus", ->
done()
browser.select(field2, "Five")
it "should fire focus event on selected field", ->
assert true
describe "any selection (2)", ->
before (done)->
browser.visit "/forms/form", ->
field1 = browser.querySelector("#field-email2")
field2 = browser.querySelector("#field-kills")
browser.fill(field1, "something")
field1.addEventListener "blur", ->
done()
browser.select(field2, "Five")
it "should fire blur event on previous field", ->
assert true
describe "multiple select option", ->
before (done)->
browser.visit "/forms/form", =>
browser.on "event", (event, target)=>
if event.type == "change"
@changed = target
done()
describe "select name using option value", ->
before ->
browser.select("#field-hobbies", "Eat Brains")
browser.select("#field-hobbies", "Sleep")
it "should select first and second options", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, true]
it "should fire change event", ->
assert.equal @changed.id, "field-hobbies"
it "should not fire change event if nothing changed", ->
assert @changed
@changed = null
browser.select("#field-hobbies", "Eat Brains")
assert !@changed
describe "unselect name using option value", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.select("#field-hobbies", "Eat Brains")
browser.select("#field-hobbies", "Sleep")
browser.unselect("#field-hobbies", "Sleep")
return
.then(done, done)
it "should unselect items", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, false]
describe "unselect name using option selector", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.selectOption("#hobbies-messy")
browser.unselectOption("#hobbies-messy")
return
.then(done, done)
it "should unselect items", ->
assert !browser.query("#hobbies-messy").selected
describe "with callback", ->
before (done)->
browser.visit "/forms/form", ->
browser.unselect("#field-hobbies", "Eat Brains")
browser.unselect("#field-hobbies", "Sleep")
browser.select("#field-hobbies", "Eat Brains")
done()
it "should unselect callback", ->
selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options)
assert.deepEqual selected, [true, false, false]
describe "fields not contained in a form", ->
before (done)->
browser.visit("/forms/form", done)
it "should not fail", ->
browser
.fill("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI")
.fill("hunter_hobbies", "Trying to get home")
.fill("#hunter-password", "PI:PASSWORD:<PASSWORD>END_PI")
.fill("input[name=hunter_invalidtype]", "necktie?")
.check("Chainsaw")
.choose("Powerglove")
.select("Type", "Evil")
describe "reset form", ->
describe "by calling reset", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "PI:NAME:<NAME>END_PI")
.fill("likes", "Arm Biting")
.check("You bet")
.choose("Scary")
.select("state", "dead")
browser.querySelector("form").reset()
return
.then(done, done)
it "should reset input field to original value", ->
browser.assert.input "#field-name", ""
it "should reset textarea to original value", ->
browser.assert.input "#field-likes", "Warm brains"
it "should reset checkbox to original value", ->
browser.assert.elements "#field-hungry:checked", 0
it "should reset radio to original value", ->
browser.assert.elements "#field-scary:checked", 0
browser.assert.elements "#field-notscary:checked", 1
it "should reset select to original option", ->
browser.assert.input "#field-state", "alive"
describe "with event handler", ->
eventType = null
before (done)->
browser.visit("/forms/form")
.then ->
browser.querySelector("form [type=reset]").addEventListener "click", (event)->
eventType = event.type
done()
.then ->
browser.querySelector("form [type=reset]").click()
it "should fire click event", ->
assert.equal eventType, "click"
describe "with preventDefault", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.fill("Name", "PI:NAME:<NAME>END_PI")
browser.querySelector("form [type=reset]").addEventListener "click", (event)->
event.preventDefault()
.then ->
browser.querySelector("form [type=reset]").click()
.then(done, done)
it "should not reset input field", ->
browser.assert.input "#field-name", "PI:NAME:<NAME>END_PI"
describe "by clicking reset input", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser.fill("Name", "PI:NAME:<NAME>END_PI")
browser.querySelector("form [type=reset]").click()
.then(done, done)
it "should reset input field to original value", ->
browser.assert.input "#field-name", ""
# Submitting form
describe "submit form", ->
describe "by calling submit", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "PI:NAME:<NAME>END_PI")
.fill("likes", "PI:NAME:<NAME>END_PI")
.check("You bet")
.check("Certainly")
.choose("Scary")
.select("state", "dead")
.select("looks", "Choose one")
.select("#field-hobbies", "Eat Brains")
.select("#field-hobbies", "Sleep")
.check("Brains?")
.fill('#address1_city', 'Paris')
.fill('#address1_street', 'CDG')
.fill('#address2_city', 'Mikolaiv')
.fill('#address2_street', 'PGS')
browser.querySelector("form").submit()
browser.wait()
.then(done, done)
it "should open new page", ->
browser.assert.url "/forms/submit"
browser.assert.text "title", "Results"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send text input values to server", ->
browser.assert.text "#name", "PI:NAME:<NAME>END_PI"
it "should send textarea values to server", ->
browser.assert.text "#likes", "PI:NAME:<NAME>END_PI"
it "should send radio button to server", ->
browser.assert.text "#scary", "yes"
it "should send unknown types to server", ->
browser.assert.text "#unknown", "yes"
it "should send checkbox with default value to server (brains)", ->
browser.assert.text "#brains", "yes"
it "should send checkbox with default value to server (green)", ->
browser.assert.text "#green", "Super green!"
it "should send multiple checkbox values to server", ->
browser.assert.text "#hungry", '["you bet","certainly"]'
it "should send selected option to server", ->
browser.assert.text "#state", "dead"
it "should send first selected option if none was chosen to server", ->
browser.assert.text "#unselected_state", "alive"
browser.assert.text "#looks", ""
it "should send multiple selected options to server", ->
browser.assert.text "#hobbies", '["Eat Brains","Sleep"]'
it "should send empty text fields", ->
browser.assert.text "#empty-text", ""
it "should send checked field with no value", ->
browser.assert.text "#empty-checkbox", "1"
describe "by clicking button", ->
before (done)->
browser.visit("/forms/form")
.then ->
browser
.fill("Name", "PI:NAME:<NAME>END_PI")
.fill("likes", "PI:NAME:<NAME>END_PI")
return browser.pressButton("Hit Me")
.then(done, done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send button value to server", ->
browser.assert.text "#clicked", "hit-me"
it "should send input values to server", ->
browser.assert.text "#name", "ArmBiter"
browser.assert.text "#likes", "Arm Biting"
it "should not send other button values to server", ->
browser.assert.text "#image_clicked", "undefined"
describe "pressButton(1)", ->
before (done)->
browser.visit "/forms/form", ->
field = browser.querySelector("#field-email2")
browser.fill(field, "something")
browser.button("Hit Me").addEventListener "focus", ->
done()
browser.pressButton("Hit Me")
it "should fire focus event on button", ->
assert true
describe "pressButton(2)", ->
before (done)->
browser.visit "/forms/form", ->
field = browser.querySelector("#field-email2")
browser.fill(field, "something")
field.addEventListener "blur", ->
done()
browser.pressButton("Hit Me")
it "should fire blur event on previous field", ->
assert true
describe "by clicking image button", ->
before (done)->
browser.visit "/forms/form", ->
browser
.fill("Name", "PI:NAME:<NAME>END_PI")
.fill("likes", "PI:NAME:<NAME>END_PI")
.pressButton("#image_submit", done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send image value to server", ->
browser.assert.text "#image_clicked", "Image Submit"
it "should send input values to server", ->
browser.assert.text "#name", "PI:NAME:<NAME>END_PI"
browser.assert.text "#likes", "Arm Biting"
it "should not send other button values to server", ->
browser.assert.text "#clicked", "undefined"
describe "by clicking input", ->
before (done)->
browser.visit "/forms/form", ->
browser
.fill("Name", "PI:NAME:<NAME>END_PI")
.fill("likes", "PI:NAME:<NAME>END_PI")
.pressButton("Submit", done)
it "should open new page", ->
browser.assert.url "/forms/submit"
it "should add location to history", ->
assert.equal browser.window.history.length, 2
it "should send submit value to server", ->
browser.assert.text "#clicked", "Submit"
it "should send input values to server", ->
browser.assert.text "#name", "PI:NAME:<NAME>END_PI"
browser.assert.text "#likes", "Arm Biting"
describe "cancel event", ->
before (done)->
brains.get "/forms/cancel", (req, res)->
res.send """
<html>
<head>
<script src="/jquery.js"></script>
<script>
$(function() {
$("form").submit(function() {
return false;
})
})
</script>
</head>
<body>
<form action="/forms/submit" method="post">
<button>Submit</button>
</form>
</body>
</html>
"""
browser.visit "/forms/cancel", ->
browser.pressButton("Submit", done)
it "should not change page", ->
browser.assert.url "/forms/cancel"
# File upload
describe "file upload", ->
before ->
brains.get "/forms/upload", (req, res)->
res.send """
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input name="text" type="file">
<input name="image" type="file">
<button>Upload</button>
</form>
</body>
</html>
"""
brains.post "/forms/upload", (req, res)->
if req.files
[text, image] = [req.files.text, req.files.image]
if text || image
file = (text || image)[0]
data = File.readFileSync(file.path)
if image
digest = Crypto.createHash("md5").update(data).digest("hex")
res.send """
<html>
<head><title>#{file.originalFilename}</title></head>
<body>#{digest || data}</body>
</html>
"""
return
res.send "<html><body>nothing</body></html>"
describe "text", ->
before (done)->
browser.visit "/forms/upload", ->
filename = __dirname + "/data/random.txt"
browser
.attach("text", filename)
.pressButton("Upload", done)
it "should upload file", ->
browser.assert.text "body", "Random text"
it "should upload include name", ->
browser.assert.text "title", "random.txt"
describe "binary", ->
filename = __dirname + "/data/zombie.jpg"
before (done)->
browser.visit "/forms/upload", ->
browser
.attach("image", filename)
.pressButton("Upload", done)
it "should upload include name", ->
browser.assert.text "title", "zombie.jpg"
it "should upload file", ->
digest = Crypto.createHash("md5").update(File.readFileSync(filename)).digest("hex")
browser.assert.text "body", digest
describe "mixed", ->
before (done)->
brains.get "/forms/mixed", (req, res)->
res.send """
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input name="username" type="text">
<input name="logfile" type="file">
<button>Save</button>
</form>
</body>
</html>
"""
brains.post "/forms/mixed", (req, res)->
file = req.files.logfile[0]
data = File.readFileSync(file.path)
res.send """
<html>
<head><title>#{file.originalFilename}</title></head>
<body>#{data}</body>
</html>
"""
browser.visit "/forms/mixed", ->
browser
.fill("username", "hello")
.attach("logfile", "#{__dirname}/data/random.txt")
.pressButton("Save", done)
it "should upload file", ->
browser.assert.text "body", "Random text"
it "should upload include name", ->
browser.assert.text "title", "random.txt"
describe "empty", ->
before (done)->
browser.visit "/forms/upload", ->
browser
.attach("text", "")
.pressButton("Upload", done)
it "should not upload any file", ->
browser.assert.text "body", "nothing"
describe "not set", ->
before (done)->
browser.visit "/forms/upload", ->
browser.pressButton("Upload", done)
it "should not send inputs without names", ->
browser.assert.text "body", "nothing"
describe "file upload with JS", ->
before ->
brains.get "/forms/upload-js", (req, res)->
res.send """
<html>
<head>
<title>Upload a file</title>
<script>
function handleFile() {
document.title = "Upload done";
var file = document.getElementById("my_file").files[0];
document.getElementById("filename").innerHTML = file.name;
document.getElementById("type").innerHTML = file.type;
document.getElementById("size").innerHTML = file.size;
document.getElementById("is_file").innerHTML = (file instanceof File);
}
</script>
</head>
<body>
<form>
<input name="my_file" id="my_file" type="file" onchange="handleFile()">
</form>
<div id="filename"></div>
<div id="type"></div>
<div id="size"></div>
<div id="is_file"></div>
</body>
</html>
"""
before (done)->
browser.visit("/forms/upload-js")
.then ->
filename = "#{__dirname}/data/random.txt"
return browser.attach("my_file", filename)
.then(done, done)
it "should call callback", ->
browser.assert.text "title", "Upload done"
it "should have filename", ->
browser.assert.text "#filename", "random.txt"
it "should know file type", ->
browser.assert.text "#type", "text/plain"
it "should know file size", ->
browser.assert.text "#size", "12"
it "should be of type File", ->
browser.assert.text "#is_file", "true"
describe "content length", ->
describe "post form urlencoded having content", ->
before (done)->
brains.get "/forms/urlencoded", (req, res)->
res.send """
<html>
<body>
<form method="post">
<input name="text" type="text">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.post "/forms/urlencoded", (req, res)->
res.send "#{req.body.text};#{req.headers["content-length"]}"
browser.visit "/forms/urlencoded", ->
browser
.fill("text", "bite")
.pressButton("submit", done)
it "should send content-length header", ->
[body, length] = browser.source.split(";")
assert.equal length, "9" # text=bite
it "should have body with content of input field", ->
[body, length] = browser.source.split(";")
assert.equal body, "bite"
describe "post form urlencoded being empty", ->
before (done)->
brains.get "/forms/urlencoded/empty", (req, res)->
res.send """
<html>
<body>
<form method="post">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.post "/forms/urlencoded/empty", (req, res)->
res.send req.headers["content-length"]
browser.visit "/forms/urlencoded/empty", ->
browser.pressButton("submit", done)
it "should send content-length header 0", ->
assert.equal browser.source, "0"
describe "GET form submission", ->
before (done)->
brains.get "/forms/get", (req, res)->
res.send """
<html>
<body>
<form method="get" action="/forms/get/echo">
<input type="text" name="my_param" value="my_value">
<input type="submit" value="submit">
</form>
</body>
</html>
"""
brains.get "/forms/get/echo", (req, res) ->
res.send """
<html>
<body>#{req.query.my_param}</body>
</html>
"""
browser.visit "/forms/get", ->
browser.pressButton("submit", done)
it "should echo the correct query string", ->
assert.equal browser.text("body"), "my_value"
# DOM specifies that getAttribute returns empty string if no value, but in
# practice it always returns `null`. However, the `name` and `value`
# properties must return empty string.
describe "inputs", ->
before (done)->
brains.get "/forms/inputs", (req, res)->
res.send """
<html>
<body>
<form>
<input type="text">
<textarea></textarea>
<select></select>
<button></button>
</form>
</body>
</html>
"""
browser.visit("/forms/inputs", done)
it "should return empty string if name attribute not set", ->
for tagName in ["form", "input", "textarea", "select", "button"]
browser.assert.attribute tagName, "name", null
it "should return empty string if value attribute not set", ->
for tagName in ["input", "textarea", "select", "button"]
assert.equal browser.query(tagName).getAttribute("value"), null
assert.equal browser.query(tagName).value, ""
it "should return empty string if id attribute not set", ->
for tagName in ["form", "input", "textarea", "select", "button"]
assert.equal browser.query(tagName).getAttribute("id"), null
assert.equal browser.query(tagName).id, ""
after ->
browser.destroy()
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999151229858398,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/contest-voting/base-entry-list.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.
export class BaseEntryList extends React.Component
constructor: (props) ->
super props
@state =
waitingForResponse: false
contest: @props.contest
selected: @props.selected
options:
showPreview: @props.options.showPreview ? false
showLink: @props.options.showLink ? false
linkIcon: @props.options.linkIcon ? false
handleVoteClick: (_e, {contest_id, entry_id, callback}) =>
return unless contest_id == @state.contest.id
selected = _.clone @state.selected
if _.includes(selected, entry_id)
_.pull selected, entry_id
else
selected.push entry_id
@setState
selected: selected
waitingForResponse: true
callback
handleUpdate: (_e, {response, callback}) =>
return unless response.contest.id == @state.contest.id
@setState
contest: response.contest
selected: response.userVotes
waitingForResponse: false
callback
componentDidMount: ->
$.subscribe 'contest:vote:click.contest', @handleVoteClick
$.subscribe 'contest:vote:done.contest', @handleUpdate
componentWillUnmount: ->
$.unsubscribe '.contest'
| 133166 | # 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.
export class BaseEntryList extends React.Component
constructor: (props) ->
super props
@state =
waitingForResponse: false
contest: @props.contest
selected: @props.selected
options:
showPreview: @props.options.showPreview ? false
showLink: @props.options.showLink ? false
linkIcon: @props.options.linkIcon ? false
handleVoteClick: (_e, {contest_id, entry_id, callback}) =>
return unless contest_id == @state.contest.id
selected = _.clone @state.selected
if _.includes(selected, entry_id)
_.pull selected, entry_id
else
selected.push entry_id
@setState
selected: selected
waitingForResponse: true
callback
handleUpdate: (_e, {response, callback}) =>
return unless response.contest.id == @state.contest.id
@setState
contest: response.contest
selected: response.userVotes
waitingForResponse: false
callback
componentDidMount: ->
$.subscribe 'contest:vote:click.contest', @handleVoteClick
$.subscribe 'contest:vote:done.contest', @handleUpdate
componentWillUnmount: ->
$.unsubscribe '.contest'
| 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.
export class BaseEntryList extends React.Component
constructor: (props) ->
super props
@state =
waitingForResponse: false
contest: @props.contest
selected: @props.selected
options:
showPreview: @props.options.showPreview ? false
showLink: @props.options.showLink ? false
linkIcon: @props.options.linkIcon ? false
handleVoteClick: (_e, {contest_id, entry_id, callback}) =>
return unless contest_id == @state.contest.id
selected = _.clone @state.selected
if _.includes(selected, entry_id)
_.pull selected, entry_id
else
selected.push entry_id
@setState
selected: selected
waitingForResponse: true
callback
handleUpdate: (_e, {response, callback}) =>
return unless response.contest.id == @state.contest.id
@setState
contest: response.contest
selected: response.userVotes
waitingForResponse: false
callback
componentDidMount: ->
$.subscribe 'contest:vote:click.contest', @handleVoteClick
$.subscribe 'contest:vote:done.contest', @handleUpdate
componentWillUnmount: ->
$.unsubscribe '.contest'
|
[
{
"context": "der.\n#\n# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,\n# and released und",
"end": 728,
"score": 0.9991399645805359,
"start": 719,
"tag": "USERNAME",
"value": "jashkenas"
},
{
"context": "# from [its Mercurial repo](https://bitbuck... | node_modules/swagger-node-express/node_modules/docco/src/docco.coffee | revnode/todo | 1 | # **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
# documentation generator. It produces HTML
# that displays your comments alongside your code. Comments are passed through
# [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
# passed through [Pygments](http://pygments.org/) syntax highlighting.
# This page is the result of running Docco against its own source file.
#
# If you install Docco, you can run it from the command-line:
#
# docco src/*.coffee
#
# ...will generate an HTML documentation page for each of the named source files,
# with a menu linking to the other pages, saving it into a `docs` folder.
#
# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
# and released under the MIT license.
#
# To install Docco, first make sure you have [Node.js](http://nodejs.org/),
# [Pygments](http://pygments.org/) (install the latest dev version of Pygments
# from [its Mercurial repo](https://bitbucket.org/birkenfeld/pygments-main)), and
# [CoffeeScript](http://coffeescript.org/). Then, with NPM:
#
# sudo npm install -g docco
#
# Docco can be used to process CoffeeScript, JavaScript, Ruby, Python, or TeX files.
# Only single-line comments are processed -- block comments are ignored.
#
#### Partners in Crime:
#
# * If **Node.js** doesn't run on your platform, or you'd prefer a more
# convenient package, get [Ryan Tomayko](http://github.com/rtomayko)'s
# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
# available as a gem.
#
# * If you're writing shell scripts, try
# [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
# also by Mr. Tomayko.
#
# * If Python's more your speed, take a look at
# [Nick Fitzgerald](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).
#
# * For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
# [Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
# "quick-and-dirty", but it'll get the job done.
#
# * **Lua** enthusiasts can get their fix with
# [Robert Gieseke](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).
#
# * And if you happen to be a **.NET**
# aficionado, check out [Don Wilson](https://github.com/dontangg)'s
# [Nocco](http://dontangg.github.com/nocco/).
#### Main Documentation Generation Functions
# Generate the documentation for a source file by reading it in, splitting it
# up into comment/code sections, highlighting them for the appropriate language,
# and merging them into an HTML template.
generateDocumentation = (source, config, callback) ->
fs.readFile source, (error, buffer) ->
throw error if error
code = buffer.toString()
sections = parse source, code
highlight source, sections, ->
generateHtml source, sections, config
callback()
# Given a string of source code, parse out each comment and the code that
# follows it, and create an individual **section** for it.
# Sections take the form:
#
# {
# docsText: ...
# docsHtml: ...
# codeText: ...
# codeHtml: ...
# }
#
parse = (source, code) ->
lines = code.split '\n'
sections = []
language = getLanguage source
hasCode = docsText = codeText = ''
save = (docsText, codeText) ->
sections.push {docsText, codeText}
for line in lines
if line.match(language.commentMatcher) and not line.match(language.commentFilter)
if hasCode
save docsText, codeText
hasCode = docsText = codeText = ''
docsText += line.replace(language.commentMatcher, '') + '\n'
else
hasCode = yes
codeText += line + '\n'
save docsText, codeText
sections
# Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio,
# and runs the text of its corresponding comment through **Markdown**, using
# [Showdown.js](http://attacklab.net/showdown/).
#
# We process the entire file in a single call to Pygments by inserting little
# marker comments between each section and then splitting the result string
# wherever our markers occur.
highlight = (source, sections, callback) ->
language = getLanguage source
pygments = spawn 'pygmentize', [
'-l', language.name,
'-f', 'html',
'-O', 'encoding=utf-8,tabsize=2'
]
output = ''
pygments.stderr.on 'data', (error) ->
console.error error.toString() if error
pygments.stdin.on 'error', (error) ->
console.error 'Could not use Pygments to highlight the source.'
process.exit 1
pygments.stdout.on 'data', (result) ->
output += result if result
pygments.on 'exit', ->
output = output.replace(highlightStart, '').replace(highlightEnd, '')
fragments = output.split language.dividerHtml
for section, i in sections
section.codeHtml = highlightStart + fragments[i] + highlightEnd
section.docsHtml = showdown.makeHtml section.docsText
callback()
if pygments.stdin.writable
text = (section.codeText for section in sections)
pygments.stdin.write text.join language.dividerText
pygments.stdin.end()
# Once all of the code is finished highlighting, we can generate the HTML file by
# passing the completed sections into the template, and then writing the file to
# the specified output path.
generateHtml = (source, sections, config) ->
destination = (filepath) ->
path.join(config.output, path.basename(filepath, path.extname(filepath)) + '.html')
title = path.basename source
dest = destination source
html = config.doccoTemplate {
title : title,
sections : sections,
sources : config.sources,
path : path,
destination: destination
css : path.basename(config.css)
}
console.log "docco: #{source} -> #{dest}"
fs.writeFileSync dest, html
#### Helpers & Setup
# Require our external dependencies, including **Showdown.js**
# (the JavaScript implementation of Markdown).
fs = require 'fs'
path = require 'path'
showdown = require('./../vendor/showdown').Showdown
{spawn, exec} = require 'child_process'
commander = require 'commander'
# Read resource file and return its content.
getResource = (name) ->
fullPath = path.join __dirname, '..', 'resources', name
fs.readFileSync(fullPath).toString()
# Languages are stored in JSON format in the file `resources/languages.json`
# Each item maps the file extension to the name of the Pygments lexer and the
# symbol that indicates a comment. To add a new language, modify the file.
languages = JSON.parse getResource 'languages.json'
# Build out the appropriate matchers and delimiters for each language.
for ext, l of languages
# Does the line begin with a comment?
l.commentMatcher = ///^\s*#{l.symbol}\s?///
# Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix\))
# and interpolations...
l.commentFilter = /(^#![/]|^\s*#\{)/
# The dividing token we feed into Pygments, to delimit the boundaries between
# sections.
l.dividerText = "\n#{l.symbol}DIVIDER\n"
# The mirror of `dividerText` that we expect Pygments to return. We can split
# on this to recover the original sections.
# Note: the class is "c" for Python and "c1" for the other languages
l.dividerHtml = ///\n*<span\sclass="c1?">#{l.symbol}DIVIDER<\/span>\n*///
# Get the current language we're documenting, based on the extension.
getLanguage = (source) -> languages[path.extname(source)]
# Ensure that the destination directory exists.
ensureDirectory = (dir, callback) ->
exec "mkdir -p #{dir}", -> callback()
# Micro-templating, originally by John Resig, borrowed by way of
# [Underscore.js](http://documentcloud.github.com/underscore/).
template = (str) ->
new Function 'obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj){p.push(\'' +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^<]*%>)/g,"\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
.split('<%').join("');")
.split('%>').join("p.push('") +
"');}return p.join('');"
# The start of each Pygments highlight block.
highlightStart = '<div class="highlight"><pre>'
# The end of each Pygments highlight block.
highlightEnd = '</pre></div>'
# Extract the docco version from `package.json`
version = JSON.parse(fs.readFileSync("#{__dirname}/../package.json")).version
# Default configuration options.
defaults =
template: "#{__dirname}/../resources/docco.jst"
css : "#{__dirname}/../resources/docco.css"
output : "docs/"
# ### Run from Commandline
# Run Docco from a set of command line arguments.
#
# 1. Parse command line using [Commander JS](https://github.com/visionmedia/commander.js).
# 2. Document sources, or print the usage help if none are specified.
run = (args=process.argv) ->
commander.version(version)
.usage("[options] <filePattern ...>")
.option("-c, --css [file]","use a custom css file",defaults.css)
.option("-o, --output [path]","use a custom output path",defaults.output)
.option("-t, --template [file]","use a custom .jst template",defaults.template)
.parse(args)
.name = "docco"
if commander.args.length
document(commander.args.slice(),commander)
else
console.log commander.helpInformation()
# ### Document Sources
# Run Docco over a list of `sources` with the given `options`.
#
# 1. Construct config to use by taking `defaults` first, then merging in `options`
# 2. Generate the resolved source list, filtering out unknown types.
# 3. Load the specified template and css files.
# 4. Ensure the output path is created, write out the CSS file,
# document each source, and invoke the completion callback if it is specified.
document = (sources, options = {}, callback = null) ->
config = {}
config[key] = defaults[key] for key,value of defaults
config[key] = value for key,value of options if key of defaults
resolved = []
resolved = resolved.concat(resolveSource(src)) for src in sources
config.sources = resolved.filter((source) -> getLanguage source).sort()
console.log "docco: skipped unknown type (#{m})" for m in resolved when m not in config.sources
config.doccoTemplate = template fs.readFileSync(config.template).toString()
doccoStyles = fs.readFileSync(config.css).toString()
ensureDirectory config.output, ->
fs.writeFileSync path.join(config.output,path.basename(config.css)), doccoStyles
files = config.sources.slice()
nextFile = ->
callback() if callback? and not files.length
generateDocumentation files.shift(), config, nextFile if files.length
nextFile()
# ### Resolve Wildcard Source Inputs
# Resolve a wildcard `source` input to the files it matches.
#
# 1. If the input contains no wildcard characters, just return it.
# 2. Convert the wildcard match to a regular expression, and return
# an array of files in the path that match it.
resolveSource = (source) ->
return source if not source.match(/([\*\?])/)
regex_str = path.basename(source)
.replace(/\./g, "\\$&")
.replace(/\*/,".*")
.replace(/\?/,".")
regex = new RegExp('^(' + regex_str + ')$')
file_path = path.dirname(source)
files = fs.readdirSync file_path
return (path.join(file_path,file) for file in files when file.match regex)
# ### Exports
# Information about docco, and functions for programatic usage.
exports[key] = value for key, value of {
run : run
document : document
parse : parse
resolveSource : resolveSource
version : version
defaults : defaults
languages : languages
}
| 85192 | # **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
# documentation generator. It produces HTML
# that displays your comments alongside your code. Comments are passed through
# [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
# passed through [Pygments](http://pygments.org/) syntax highlighting.
# This page is the result of running Docco against its own source file.
#
# If you install Docco, you can run it from the command-line:
#
# docco src/*.coffee
#
# ...will generate an HTML documentation page for each of the named source files,
# with a menu linking to the other pages, saving it into a `docs` folder.
#
# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
# and released under the MIT license.
#
# To install Docco, first make sure you have [Node.js](http://nodejs.org/),
# [Pygments](http://pygments.org/) (install the latest dev version of Pygments
# from [its Mercurial repo](https://bitbucket.org/birkenfeld/pygments-main)), and
# [CoffeeScript](http://coffeescript.org/). Then, with NPM:
#
# sudo npm install -g docco
#
# Docco can be used to process CoffeeScript, JavaScript, Ruby, Python, or TeX files.
# Only single-line comments are processed -- block comments are ignored.
#
#### Partners in Crime:
#
# * If **Node.js** doesn't run on your platform, or you'd prefer a more
# convenient package, get [<NAME>ko](http://github.com/rtomayko)'s
# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
# available as a gem.
#
# * If you're writing shell scripts, try
# [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
# also by Mr. <NAME>.
#
# * If Python's more your speed, take a look at
# [<NAME>](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).
#
# * For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
# [Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
# "quick-and-dirty", but it'll get the job done.
#
# * **Lua** enthusiasts can get their fix with
# [<NAME>](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).
#
# * And if you happen to be a **.NET**
# aficionado, check out [<NAME>](https://github.com/dontangg)'s
# [Nocco](http://dontangg.github.com/nocco/).
#### Main Documentation Generation Functions
# Generate the documentation for a source file by reading it in, splitting it
# up into comment/code sections, highlighting them for the appropriate language,
# and merging them into an HTML template.
generateDocumentation = (source, config, callback) ->
fs.readFile source, (error, buffer) ->
throw error if error
code = buffer.toString()
sections = parse source, code
highlight source, sections, ->
generateHtml source, sections, config
callback()
# Given a string of source code, parse out each comment and the code that
# follows it, and create an individual **section** for it.
# Sections take the form:
#
# {
# docsText: ...
# docsHtml: ...
# codeText: ...
# codeHtml: ...
# }
#
parse = (source, code) ->
lines = code.split '\n'
sections = []
language = getLanguage source
hasCode = docsText = codeText = ''
save = (docsText, codeText) ->
sections.push {docsText, codeText}
for line in lines
if line.match(language.commentMatcher) and not line.match(language.commentFilter)
if hasCode
save docsText, codeText
hasCode = docsText = codeText = ''
docsText += line.replace(language.commentMatcher, '') + '\n'
else
hasCode = yes
codeText += line + '\n'
save docsText, codeText
sections
# Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio,
# and runs the text of its corresponding comment through **Markdown**, using
# [Showdown.js](http://attacklab.net/showdown/).
#
# We process the entire file in a single call to Pygments by inserting little
# marker comments between each section and then splitting the result string
# wherever our markers occur.
highlight = (source, sections, callback) ->
language = getLanguage source
pygments = spawn 'pygmentize', [
'-l', language.name,
'-f', 'html',
'-O', 'encoding=utf-8,tabsize=2'
]
output = ''
pygments.stderr.on 'data', (error) ->
console.error error.toString() if error
pygments.stdin.on 'error', (error) ->
console.error 'Could not use Pygments to highlight the source.'
process.exit 1
pygments.stdout.on 'data', (result) ->
output += result if result
pygments.on 'exit', ->
output = output.replace(highlightStart, '').replace(highlightEnd, '')
fragments = output.split language.dividerHtml
for section, i in sections
section.codeHtml = highlightStart + fragments[i] + highlightEnd
section.docsHtml = showdown.makeHtml section.docsText
callback()
if pygments.stdin.writable
text = (section.codeText for section in sections)
pygments.stdin.write text.join language.dividerText
pygments.stdin.end()
# Once all of the code is finished highlighting, we can generate the HTML file by
# passing the completed sections into the template, and then writing the file to
# the specified output path.
generateHtml = (source, sections, config) ->
destination = (filepath) ->
path.join(config.output, path.basename(filepath, path.extname(filepath)) + '.html')
title = path.basename source
dest = destination source
html = config.doccoTemplate {
title : title,
sections : sections,
sources : config.sources,
path : path,
destination: destination
css : path.basename(config.css)
}
console.log "docco: #{source} -> #{dest}"
fs.writeFileSync dest, html
#### Helpers & Setup
# Require our external dependencies, including **Showdown.js**
# (the JavaScript implementation of Markdown).
fs = require 'fs'
path = require 'path'
showdown = require('./../vendor/showdown').Showdown
{spawn, exec} = require 'child_process'
commander = require 'commander'
# Read resource file and return its content.
getResource = (name) ->
fullPath = path.join __dirname, '..', 'resources', name
fs.readFileSync(fullPath).toString()
# Languages are stored in JSON format in the file `resources/languages.json`
# Each item maps the file extension to the name of the Pygments lexer and the
# symbol that indicates a comment. To add a new language, modify the file.
languages = JSON.parse getResource 'languages.json'
# Build out the appropriate matchers and delimiters for each language.
for ext, l of languages
# Does the line begin with a comment?
l.commentMatcher = ///^\s*#{l.symbol}\s?///
# Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix\))
# and interpolations...
l.commentFilter = /(^#![/]|^\s*#\{)/
# The dividing token we feed into Pygments, to delimit the boundaries between
# sections.
l.dividerText = "\n#{l.symbol}DIVIDER\n"
# The mirror of `dividerText` that we expect Pygments to return. We can split
# on this to recover the original sections.
# Note: the class is "c" for Python and "c1" for the other languages
l.dividerHtml = ///\n*<span\sclass="c1?">#{l.symbol}DIVIDER<\/span>\n*///
# Get the current language we're documenting, based on the extension.
getLanguage = (source) -> languages[path.extname(source)]
# Ensure that the destination directory exists.
ensureDirectory = (dir, callback) ->
exec "mkdir -p #{dir}", -> callback()
# Micro-templating, originally by <NAME>, borrowed by way of
# [Underscore.js](http://documentcloud.github.com/underscore/).
template = (str) ->
new Function 'obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj){p.push(\'' +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^<]*%>)/g,"\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
.split('<%').join("');")
.split('%>').join("p.push('") +
"');}return p.join('');"
# The start of each Pygments highlight block.
highlightStart = '<div class="highlight"><pre>'
# The end of each Pygments highlight block.
highlightEnd = '</pre></div>'
# Extract the docco version from `package.json`
version = JSON.parse(fs.readFileSync("#{__dirname}/../package.json")).version
# Default configuration options.
defaults =
template: "#{__dirname}/../resources/docco.jst"
css : "#{__dirname}/../resources/docco.css"
output : "docs/"
# ### Run from Commandline
# Run Docco from a set of command line arguments.
#
# 1. Parse command line using [Commander JS](https://github.com/visionmedia/commander.js).
# 2. Document sources, or print the usage help if none are specified.
run = (args=process.argv) ->
commander.version(version)
.usage("[options] <filePattern ...>")
.option("-c, --css [file]","use a custom css file",defaults.css)
.option("-o, --output [path]","use a custom output path",defaults.output)
.option("-t, --template [file]","use a custom .jst template",defaults.template)
.parse(args)
.name = "docco"
if commander.args.length
document(commander.args.slice(),commander)
else
console.log commander.helpInformation()
# ### Document Sources
# Run Docco over a list of `sources` with the given `options`.
#
# 1. Construct config to use by taking `defaults` first, then merging in `options`
# 2. Generate the resolved source list, filtering out unknown types.
# 3. Load the specified template and css files.
# 4. Ensure the output path is created, write out the CSS file,
# document each source, and invoke the completion callback if it is specified.
document = (sources, options = {}, callback = null) ->
config = {}
config[key] = defaults[key] for key,value of defaults
config[key] = value for key,value of options if key of defaults
resolved = []
resolved = resolved.concat(resolveSource(src)) for src in sources
config.sources = resolved.filter((source) -> getLanguage source).sort()
console.log "docco: skipped unknown type (#{m})" for m in resolved when m not in config.sources
config.doccoTemplate = template fs.readFileSync(config.template).toString()
doccoStyles = fs.readFileSync(config.css).toString()
ensureDirectory config.output, ->
fs.writeFileSync path.join(config.output,path.basename(config.css)), doccoStyles
files = config.sources.slice()
nextFile = ->
callback() if callback? and not files.length
generateDocumentation files.shift(), config, nextFile if files.length
nextFile()
# ### Resolve Wildcard Source Inputs
# Resolve a wildcard `source` input to the files it matches.
#
# 1. If the input contains no wildcard characters, just return it.
# 2. Convert the wildcard match to a regular expression, and return
# an array of files in the path that match it.
resolveSource = (source) ->
return source if not source.match(/([\*\?])/)
regex_str = path.basename(source)
.replace(/\./g, "\\$&")
.replace(/\*/,".*")
.replace(/\?/,".")
regex = new RegExp('^(' + regex_str + ')$')
file_path = path.dirname(source)
files = fs.readdirSync file_path
return (path.join(file_path,file) for file in files when file.match regex)
# ### Exports
# Information about docco, and functions for programatic usage.
exports[key] = value for key, value of {
run : run
document : document
parse : parse
resolveSource : resolveSource
version : version
defaults : defaults
languages : languages
}
| true | # **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style
# documentation generator. It produces HTML
# that displays your comments alongside your code. Comments are passed through
# [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is
# passed through [Pygments](http://pygments.org/) syntax highlighting.
# This page is the result of running Docco against its own source file.
#
# If you install Docco, you can run it from the command-line:
#
# docco src/*.coffee
#
# ...will generate an HTML documentation page for each of the named source files,
# with a menu linking to the other pages, saving it into a `docs` folder.
#
# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,
# and released under the MIT license.
#
# To install Docco, first make sure you have [Node.js](http://nodejs.org/),
# [Pygments](http://pygments.org/) (install the latest dev version of Pygments
# from [its Mercurial repo](https://bitbucket.org/birkenfeld/pygments-main)), and
# [CoffeeScript](http://coffeescript.org/). Then, with NPM:
#
# sudo npm install -g docco
#
# Docco can be used to process CoffeeScript, JavaScript, Ruby, Python, or TeX files.
# Only single-line comments are processed -- block comments are ignored.
#
#### Partners in Crime:
#
# * If **Node.js** doesn't run on your platform, or you'd prefer a more
# convenient package, get [PI:NAME:<NAME>END_PIko](http://github.com/rtomayko)'s
# [Rocco](http://rtomayko.github.com/rocco/rocco.html), the Ruby port that's
# available as a gem.
#
# * If you're writing shell scripts, try
# [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**,
# also by Mr. PI:NAME:<NAME>END_PI.
#
# * If Python's more your speed, take a look at
# [PI:NAME:<NAME>END_PI](http://github.com/fitzgen)'s [Pycco](http://fitzgen.github.com/pycco/).
#
# * For **Clojure** fans, [Fogus](http://blog.fogus.me/)'s
# [Marginalia](http://fogus.me/fun/marginalia/) is a bit of a departure from
# "quick-and-dirty", but it'll get the job done.
#
# * **Lua** enthusiasts can get their fix with
# [PI:NAME:<NAME>END_PI](https://github.com/rgieseke)'s [Locco](http://rgieseke.github.com/locco/).
#
# * And if you happen to be a **.NET**
# aficionado, check out [PI:NAME:<NAME>END_PI](https://github.com/dontangg)'s
# [Nocco](http://dontangg.github.com/nocco/).
#### Main Documentation Generation Functions
# Generate the documentation for a source file by reading it in, splitting it
# up into comment/code sections, highlighting them for the appropriate language,
# and merging them into an HTML template.
generateDocumentation = (source, config, callback) ->
fs.readFile source, (error, buffer) ->
throw error if error
code = buffer.toString()
sections = parse source, code
highlight source, sections, ->
generateHtml source, sections, config
callback()
# Given a string of source code, parse out each comment and the code that
# follows it, and create an individual **section** for it.
# Sections take the form:
#
# {
# docsText: ...
# docsHtml: ...
# codeText: ...
# codeHtml: ...
# }
#
parse = (source, code) ->
lines = code.split '\n'
sections = []
language = getLanguage source
hasCode = docsText = codeText = ''
save = (docsText, codeText) ->
sections.push {docsText, codeText}
for line in lines
if line.match(language.commentMatcher) and not line.match(language.commentFilter)
if hasCode
save docsText, codeText
hasCode = docsText = codeText = ''
docsText += line.replace(language.commentMatcher, '') + '\n'
else
hasCode = yes
codeText += line + '\n'
save docsText, codeText
sections
# Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio,
# and runs the text of its corresponding comment through **Markdown**, using
# [Showdown.js](http://attacklab.net/showdown/).
#
# We process the entire file in a single call to Pygments by inserting little
# marker comments between each section and then splitting the result string
# wherever our markers occur.
highlight = (source, sections, callback) ->
language = getLanguage source
pygments = spawn 'pygmentize', [
'-l', language.name,
'-f', 'html',
'-O', 'encoding=utf-8,tabsize=2'
]
output = ''
pygments.stderr.on 'data', (error) ->
console.error error.toString() if error
pygments.stdin.on 'error', (error) ->
console.error 'Could not use Pygments to highlight the source.'
process.exit 1
pygments.stdout.on 'data', (result) ->
output += result if result
pygments.on 'exit', ->
output = output.replace(highlightStart, '').replace(highlightEnd, '')
fragments = output.split language.dividerHtml
for section, i in sections
section.codeHtml = highlightStart + fragments[i] + highlightEnd
section.docsHtml = showdown.makeHtml section.docsText
callback()
if pygments.stdin.writable
text = (section.codeText for section in sections)
pygments.stdin.write text.join language.dividerText
pygments.stdin.end()
# Once all of the code is finished highlighting, we can generate the HTML file by
# passing the completed sections into the template, and then writing the file to
# the specified output path.
generateHtml = (source, sections, config) ->
destination = (filepath) ->
path.join(config.output, path.basename(filepath, path.extname(filepath)) + '.html')
title = path.basename source
dest = destination source
html = config.doccoTemplate {
title : title,
sections : sections,
sources : config.sources,
path : path,
destination: destination
css : path.basename(config.css)
}
console.log "docco: #{source} -> #{dest}"
fs.writeFileSync dest, html
#### Helpers & Setup
# Require our external dependencies, including **Showdown.js**
# (the JavaScript implementation of Markdown).
fs = require 'fs'
path = require 'path'
showdown = require('./../vendor/showdown').Showdown
{spawn, exec} = require 'child_process'
commander = require 'commander'
# Read resource file and return its content.
getResource = (name) ->
fullPath = path.join __dirname, '..', 'resources', name
fs.readFileSync(fullPath).toString()
# Languages are stored in JSON format in the file `resources/languages.json`
# Each item maps the file extension to the name of the Pygments lexer and the
# symbol that indicates a comment. To add a new language, modify the file.
languages = JSON.parse getResource 'languages.json'
# Build out the appropriate matchers and delimiters for each language.
for ext, l of languages
# Does the line begin with a comment?
l.commentMatcher = ///^\s*#{l.symbol}\s?///
# Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix\))
# and interpolations...
l.commentFilter = /(^#![/]|^\s*#\{)/
# The dividing token we feed into Pygments, to delimit the boundaries between
# sections.
l.dividerText = "\n#{l.symbol}DIVIDER\n"
# The mirror of `dividerText` that we expect Pygments to return. We can split
# on this to recover the original sections.
# Note: the class is "c" for Python and "c1" for the other languages
l.dividerHtml = ///\n*<span\sclass="c1?">#{l.symbol}DIVIDER<\/span>\n*///
# Get the current language we're documenting, based on the extension.
getLanguage = (source) -> languages[path.extname(source)]
# Ensure that the destination directory exists.
ensureDirectory = (dir, callback) ->
exec "mkdir -p #{dir}", -> callback()
# Micro-templating, originally by PI:NAME:<NAME>END_PI, borrowed by way of
# [Underscore.js](http://documentcloud.github.com/underscore/).
template = (str) ->
new Function 'obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj){p.push(\'' +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^<]*%>)/g,"\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
.split('<%').join("');")
.split('%>').join("p.push('") +
"');}return p.join('');"
# The start of each Pygments highlight block.
highlightStart = '<div class="highlight"><pre>'
# The end of each Pygments highlight block.
highlightEnd = '</pre></div>'
# Extract the docco version from `package.json`
version = JSON.parse(fs.readFileSync("#{__dirname}/../package.json")).version
# Default configuration options.
defaults =
template: "#{__dirname}/../resources/docco.jst"
css : "#{__dirname}/../resources/docco.css"
output : "docs/"
# ### Run from Commandline
# Run Docco from a set of command line arguments.
#
# 1. Parse command line using [Commander JS](https://github.com/visionmedia/commander.js).
# 2. Document sources, or print the usage help if none are specified.
run = (args=process.argv) ->
commander.version(version)
.usage("[options] <filePattern ...>")
.option("-c, --css [file]","use a custom css file",defaults.css)
.option("-o, --output [path]","use a custom output path",defaults.output)
.option("-t, --template [file]","use a custom .jst template",defaults.template)
.parse(args)
.name = "docco"
if commander.args.length
document(commander.args.slice(),commander)
else
console.log commander.helpInformation()
# ### Document Sources
# Run Docco over a list of `sources` with the given `options`.
#
# 1. Construct config to use by taking `defaults` first, then merging in `options`
# 2. Generate the resolved source list, filtering out unknown types.
# 3. Load the specified template and css files.
# 4. Ensure the output path is created, write out the CSS file,
# document each source, and invoke the completion callback if it is specified.
document = (sources, options = {}, callback = null) ->
config = {}
config[key] = defaults[key] for key,value of defaults
config[key] = value for key,value of options if key of defaults
resolved = []
resolved = resolved.concat(resolveSource(src)) for src in sources
config.sources = resolved.filter((source) -> getLanguage source).sort()
console.log "docco: skipped unknown type (#{m})" for m in resolved when m not in config.sources
config.doccoTemplate = template fs.readFileSync(config.template).toString()
doccoStyles = fs.readFileSync(config.css).toString()
ensureDirectory config.output, ->
fs.writeFileSync path.join(config.output,path.basename(config.css)), doccoStyles
files = config.sources.slice()
nextFile = ->
callback() if callback? and not files.length
generateDocumentation files.shift(), config, nextFile if files.length
nextFile()
# ### Resolve Wildcard Source Inputs
# Resolve a wildcard `source` input to the files it matches.
#
# 1. If the input contains no wildcard characters, just return it.
# 2. Convert the wildcard match to a regular expression, and return
# an array of files in the path that match it.
resolveSource = (source) ->
return source if not source.match(/([\*\?])/)
regex_str = path.basename(source)
.replace(/\./g, "\\$&")
.replace(/\*/,".*")
.replace(/\?/,".")
regex = new RegExp('^(' + regex_str + ')$')
file_path = path.dirname(source)
files = fs.readdirSync file_path
return (path.join(file_path,file) for file in files when file.match regex)
# ### Exports
# Information about docco, and functions for programatic usage.
exports[key] = value for key, value of {
run : run
document : document
parse : parse
resolveSource : resolveSource
version : version
defaults : defaults
languages : languages
}
|
[
{
"context": " message: \"buildKiteMessage\"\n authorName: \"buildKiteBuildCreator\"\n authorEmail: \"buildKiteCreatorEmail\"\n ",
"end": 5830,
"score": 0.9967344999313354,
"start": 5809,
"tag": "USERNAME",
"value": "buildKiteBuildCreator"
},
{
"context": "PrReponame\... | packages/server/test/unit/ci_provider_spec.coffee | Everworks/cypress | 1 | R = require("ramda")
require("../spec_helper")
ciProvider = require("#{root}lib/util/ci_provider")
expectsName = (name) ->
expect(ciProvider.provider(), "CI providers detected name").to.eq(name)
expectsCiParams = (params) ->
expect(ciProvider.ciParams(), "CI providers detected CI params").to.deep.eq(params)
expectsCommitParams = (params) ->
expect(ciProvider.commitParams(), "CI providers detected commit params").to.deep.eq(params)
expectsCommitDefaults = (existing, expected) ->
expect(ciProvider.commitDefaults(existing), "CI providers default git params").to.deep.eq(expected)
resetEnv = ->
process.env = {}
describe "lib/util/ci_provider", ->
beforeEach ->
resetEnv()
it "null when unknown", ->
resetEnv()
expectsName(null)
expectsCiParams(null)
expectsCommitParams(null)
it "appveyor", ->
process.env.APPVEYOR = true
process.env.APPVEYOR_JOB_ID = "appveyorJobId2"
process.env.APPVEYOR_ACCOUNT_NAME = "appveyorAccountName"
process.env.APPVEYOR_PROJECT_SLUG = "appveyorProjectSlug"
process.env.APPVEYOR_BUILD_VERSION = "appveyorBuildVersion"
process.env.APPVEYOR_BUILD_NUMBER = "appveyorBuildNumber"
process.env.APPVEYOR_PULL_REQUEST_NUMBER = "appveyorPullRequestNumber"
process.env.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH = "appveyorPullRequestHeadRepoBranch"
process.env.APPVEYOR_REPO_COMMIT = "repoCommit"
process.env.APPVEYOR_REPO_COMMIT_MESSAGE = "repoCommitMessage"
process.env.APPVEYOR_REPO_BRANCH = "repoBranch"
process.env.APPVEYOR_REPO_COMMIT_AUTHOR = "repoCommitAuthor"
process.env.APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL = "repoCommitAuthorEmail"
expectsName("appveyor")
expectsCiParams({
appveyorJobId: "appveyorJobId2"
appveyorAccountName: "appveyorAccountName"
appveyorProjectSlug: "appveyorProjectSlug"
appveyorBuildNumber: "appveyorBuildNumber"
appveyorBuildVersion: "appveyorBuildVersion"
appveyorPullRequestNumber: "appveyorPullRequestNumber"
appveyorPullRequestHeadRepoBranch: "appveyorPullRequestHeadRepoBranch"
})
expectsCommitParams({
sha: "repoCommit"
branch: "repoBranch"
message: "repoCommitMessage"
authorName: "repoCommitAuthor"
authorEmail: "repoCommitAuthorEmail"
})
resetEnv()
process.env.APPVEYOR = true
process.env.APPVEYOR_REPO_COMMIT_MESSAGE = "repoCommitMessage"
process.env.APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED = "repoCommitMessageExtended"
expectsCommitParams({
message: "repoCommitMessage\nrepoCommitMessageExtended"
})
it "bamboo", ->
process.env["bamboo.buildNumber"] = "123"
process.env["bamboo.resultsUrl"] = "bamboo.resultsUrl"
process.env["bamboo.buildResultsUrl"] = "bamboo.buildResultsUrl"
process.env["bamboo.planRepository.repositoryUrl"] = "bamboo.planRepository.repositoryUrl"
process.env["bamboo.planRepository.branch"] = "bamboo.planRepository.branch"
expectsName("bamboo")
expectsCiParams({
bambooResultsUrl: "bamboo.resultsUrl"
bambooBuildNumber: "123"
bambooBuildResultsUrl: "bamboo.buildResultsUrl"
bambooPlanRepositoryRepositoryUrl: "bamboo.planRepository.repositoryUrl"
})
expectsCommitParams({
branch: "bamboo.planRepository.branch"
})
it "bitbucket", ->
process.env.CI = "1"
# build information
process.env.BITBUCKET_BUILD_NUMBER = "bitbucketBuildNumber"
process.env.BITBUCKET_REPO_OWNER = "bitbucketRepoOwner"
process.env.BITBUCKET_REPO_SLUG = "bitbucketRepoSlug"
# git information
process.env.BITBUCKET_COMMIT = "bitbucketCommit"
process.env.BITBUCKET_BRANCH = "bitbucketBranch"
expectsName("bitbucket")
expectsCiParams({
bitbucketBuildNumber: "bitbucketBuildNumber"
bitbucketRepoOwner: "bitbucketRepoOwner"
bitbucketRepoSlug: "bitbucketRepoSlug"
})
expectsCommitParams({
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
expectsCommitDefaults({
sha: null
branch: "gitFoundBranch"
}, {
sha: "bitbucketCommit"
branch: "gitFoundBranch"
})
it "buildkite", ->
process.env.BUILDKITE = true
process.env.BUILDKITE_REPO = "buildkiteRepo"
process.env.BUILDKITE_JOB_ID = "buildkiteJobId"
process.env.BUILDKITE_SOURCE = "buildkiteSource"
process.env.BUILDKITE_BUILD_ID = "buildkiteBuildId"
process.env.BUILDKITE_BUILD_URL = "buildkiteBuildUrl"
process.env.BUILDKITE_BUILD_NUMBER = "buildkiteBuildNumber"
process.env.BUILDKITE_PULL_REQUEST = "buildkitePullRequest"
process.env.BUILDKITE_PULL_REQUEST_REPO = "buildkitePullRequestRepo"
process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH = "buildkitePullRequestBaseBranch"
process.env.BUILDKITE_COMMIT = "buildKiteCommit"
process.env.BUILDKITE_BRANCH = "buildKiteBranch"
process.env.BUILDKITE_MESSAGE = "buildKiteMessage"
process.env.BUILDKITE_BUILD_CREATOR = "buildKiteBuildCreator"
process.env.BUILDKITE_BUILD_CREATOR_EMAIL = "buildKiteCreatorEmail"
process.env.BUILDKITE_REPO = "buildkiteRepo"
process.env.BUILDKITE_PIPELINE_DEFAULT_BRANCH = "buildkitePipelineDefaultBranch"
expectsName("buildkite")
expectsCiParams({
buildkiteRepo: "buildkiteRepo"
buildkiteJobId: "buildkiteJobId"
buildkiteSource: "buildkiteSource"
buildkiteBuildId: "buildkiteBuildId"
buildkiteBuildUrl: "buildkiteBuildUrl"
buildkiteBuildNumber: "buildkiteBuildNumber"
buildkitePullRequest: "buildkitePullRequest"
buildkitePullRequestRepo: "buildkitePullRequestRepo"
buildkitePullRequestBaseBranch: "buildkitePullRequestBaseBranch"
})
expectsCommitParams({
sha: "buildKiteCommit"
branch: "buildKiteBranch"
message: "buildKiteMessage"
authorName: "buildKiteBuildCreator"
authorEmail: "buildKiteCreatorEmail"
remoteOrigin: "buildkiteRepo"
defaultBranch: "buildkitePipelineDefaultBranch"
})
it "circle", ->
process.env.CIRCLECI = true
process.env.CIRCLE_JOB = "circleJob"
process.env.CIRCLE_BUILD_NUM = "circleBuildNum"
process.env.CIRCLE_BUILD_URL = "circleBuildUrl"
process.env.CIRCLE_PR_NUMBER = "circlePrNumber"
process.env.CIRCLE_PR_REPONAME = "circlePrReponame"
process.env.CIRCLE_PR_USERNAME = "circlePrUsername"
process.env.CIRCLE_COMPARE_URL = "circleCompareUrl"
process.env.CIRCLE_WORKFLOW_ID = "circleWorkflowId"
process.env.CIRCLE_PULL_REQUEST = "circlePullRequest"
process.env.CIRCLE_REPOSITORY_URL = "circleRepositoryUrl"
process.env.CI_PULL_REQUEST = "ciPullRequest"
process.env.CIRCLE_SHA1 = "circleSha"
process.env.CIRCLE_BRANCH = "circleBranch"
process.env.CIRCLE_USERNAME = "circleUsername"
expectsName("circle")
expectsCiParams({
circleJob: "circleJob"
circleBuildNum: "circleBuildNum"
circleBuildUrl: "circleBuildUrl"
circlePrNumber: "circlePrNumber"
circlePrReponame: "circlePrReponame"
circlePrUsername: "circlePrUsername"
circleCompareUrl: "circleCompareUrl"
circleWorkflowId: "circleWorkflowId"
circlePullRequest: "circlePullRequest"
circleRepositoryUrl: "circleRepositoryUrl"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "circleSha"
branch: "circleBranch"
authorName: "circleUsername"
})
it "codeshipBasic", ->
process.env.CODESHIP = "TRUE"
process.env.CI_NAME = "codeship"
process.env.CI_BUILD_ID = "ciBuildId"
process.env.CI_REPO_NAME = "ciRepoName"
process.env.CI_BUILD_URL = "ciBuildUrl"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_BUILD_NUMBER = "ciBuildNumber"
process.env.CI_PULL_REQUEST = "ciPullRequest"
process.env.CI_COMMIT_ID = "ciCommitId"
process.env.CI_BRANCH = "ciBranch"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.CI_COMMITTER_NAME = "ciCommitterName"
process.env.CI_COMMITTER_EMAIL = "ciCommitterEmail"
expectsName("codeshipBasic")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciBuildUrl: "ciBuildUrl"
ciProjectId: "ciProjectId"
ciBuildNumber: "ciBuildNumber"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "codeshipPro", ->
process.env.CI_NAME = "codeship"
process.env.CI_BUILD_ID = "ciBuildId"
process.env.CI_REPO_NAME = "ciRepoName"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_COMMIT_ID = "ciCommitId"
process.env.CI_BRANCH = "ciBranch"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.CI_COMMITTER_NAME = "ciCommitterName"
process.env.CI_COMMITTER_EMAIL = "ciCommitterEmail"
expectsName("codeshipPro")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciProjectId: "ciProjectId"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "drone", ->
process.env.DRONE = true
process.env.DRONE_JOB_NUMBER = "droneJobNumber"
process.env.DRONE_BUILD_LINK = "droneBuildLink"
process.env.DRONE_BUILD_NUMBER = "droneBuildNumber"
process.env.DRONE_PULL_REQUEST = "dronePullRequest"
process.env.DRONE_COMMIT_SHA = "droneCommitSha"
process.env.DRONE_COMMIT_BRANCH = "droneCommitBranch"
process.env.DRONE_COMMIT_MESSAGE = "droneCommitMessage"
process.env.DRONE_COMMIT_AUTHOR = "droneCommitAuthor"
process.env.DRONE_COMMIT_AUTHOR_EMAIL = "droneCommitAuthorEmail"
process.env.DRONE_REPO_BRANCH = "droneRepoBranch"
expectsName("drone")
expectsCiParams({
droneJobNumber: "droneJobNumber"
droneBuildLink: "droneBuildLink"
droneBuildNumber: "droneBuildNumber"
dronePullRequest: "dronePullRequest"
})
expectsCommitParams({
sha: "droneCommitSha"
branch: "droneCommitBranch"
message: "droneCommitMessage"
authorName: "droneCommitAuthor"
authorEmail: "droneCommitAuthorEmail"
defaultBranch: "droneRepoBranch"
})
it "gitlab", ->
process.env.GITLAB_CI = true
# Gitlab has job id and build id as synonyms
process.env.CI_BUILD_ID = "ciJobId"
process.env.CI_JOB_ID = "ciJobId"
process.env.CI_JOB_URL = "ciJobUrl"
process.env.CI_PIPELINE_ID = "ciPipelineId"
process.env.CI_PIPELINE_URL = "ciPipelineUrl"
process.env.GITLAB_HOST = "gitlabHost"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_PROJECT_URL = "ciProjectUrl"
process.env.CI_REPOSITORY_URL = "ciRepositoryUrl"
process.env.CI_ENVIRONMENT_URL = "ciEnvironmentUrl"
process.env.CI_COMMIT_SHA = "ciCommitSha"
process.env.CI_COMMIT_REF_NAME = "ciCommitRefName"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.GITLAB_USER_NAME = "gitlabUserName"
process.env.GITLAB_USER_EMAIL = "gitlabUserEmail"
expectsName("gitlab")
expectsCiParams({
ciJobId: "ciJobId"
ciJobUrl: "ciJobUrl"
ciBuildId: "ciJobId"
ciPipelineId: "ciPipelineId"
ciPipelineUrl: "ciPipelineUrl"
gitlabHost: "gitlabHost"
ciProjectId: "ciProjectId"
ciProjectUrl: "ciProjectUrl"
ciRepositoryUrl: "ciRepositoryUrl"
ciEnvironmentUrl: "ciEnvironmentUrl"
})
expectsCommitParams({
sha: "ciCommitSha"
branch: "ciCommitRefName"
message: "ciCommitMessage"
authorName: "gitlabUserName"
authorEmail: "gitlabUserEmail"
})
resetEnv()
process.env.CI_SERVER_NAME = "GitLab CI"
expectsName("gitlab")
resetEnv()
process.env.CI_SERVER_NAME = "GitLab"
expectsName("gitlab")
it "jenkins", ->
process.env.JENKINS_URL = true
process.env.BUILD_ID = "buildId"
process.env.BUILD_URL = "buildUrl"
process.env.BUILD_NUMBER = "buildNumber"
process.env.ghprbPullId = "gbprbPullId"
process.env.GIT_COMMIT = "gitCommit"
process.env.GIT_BRANCH = "gitBranch"
expectsName("jenkins")
expectsCiParams({
buildId: "buildId"
buildUrl: "buildUrl"
buildNumber: "buildNumber"
ghprbPullId: "gbprbPullId"
})
expectsCommitParams({
sha: "gitCommit"
branch: "gitBranch"
})
resetEnv()
process.env.JENKINS_HOME = "/path/to/jenkins"
expectsName("jenkins")
resetEnv()
process.env.JENKINS_VERSION = "1.2.3"
expectsName("jenkins")
resetEnv()
process.env.HUDSON_HOME = "/path/to/jenkins"
expectsName("jenkins")
resetEnv()
process.env.HUDSON_URL = true
expectsName("jenkins")
it "semaphore", ->
process.env.SEMAPHORE = true
process.env.SEMAPHORE_BRANCH_ID = "semaphoreBranchId"
process.env.SEMAPHORE_BUILD_NUMBER = "semaphoreBuildNumber"
process.env.SEMAPHORE_CURRENT_JOB = "semaphoreCurrentJob"
process.env.SEMAPHORE_CURRENT_THREAD = "semaphoreCurrentThread"
process.env.SEMAPHORE_EXECUTABLE_UUID = "semaphoreExecutableUuid"
process.env.SEMAPHORE_JOB_COUNT = "semaphoreJobCount"
process.env.SEMAPHORE_JOB_UUID = "semaphoreJobUuid"
process.env.SEMAPHORE_PLATFORM = "semaphorePlatform"
process.env.SEMAPHORE_PROJECT_DIR = "semaphoreProjectDir"
process.env.SEMAPHORE_PROJECT_HASH_ID = "semaphoreProjectHashId"
process.env.SEMAPHORE_PROJECT_NAME = "semaphoreProjectName"
process.env.SEMAPHORE_PROJECT_UUID = "semaphoreProjectUuid"
process.env.SEMAPHORE_REPO_SLUG = "semaphoreRepoSlug"
process.env.SEMAPHORE_TRIGGER_SOURCE = "semaphoreTriggerSource"
process.env.PULL_REQUEST_NUMBER = "pullRequestNumber"
process.env.REVISION = "revision"
process.env.BRANCH_NAME = "branchName"
expectsName("semaphore")
expectsCiParams({
pullRequestNumber: "pullRequestNumber"
semaphoreBranchId: "semaphoreBranchId"
semaphoreBuildNumber: "semaphoreBuildNumber"
semaphoreCurrentJob: "semaphoreCurrentJob"
semaphoreCurrentThread: "semaphoreCurrentThread"
semaphoreExecutableUuid: "semaphoreExecutableUuid"
semaphoreJobCount: "semaphoreJobCount"
semaphoreJobUuid: "semaphoreJobUuid"
semaphorePlatform: "semaphorePlatform"
semaphoreProjectDir: "semaphoreProjectDir"
semaphoreProjectHashId: "semaphoreProjectHashId"
semaphoreProjectName: "semaphoreProjectName"
semaphoreProjectUuid: "semaphoreProjectUuid"
semaphoreRepoSlug: "semaphoreRepoSlug"
semaphoreTriggerSource: "semaphoreTriggerSource"
})
expectsCommitParams({
sha: "revision"
branch: "branchName"
})
it "shippable", ->
process.env.SHIPPABLE = "true"
# build environment variables
process.env.SHIPPABLE_BUILD_ID = "buildId"
process.env.SHIPPABLE_BUILD_NUMBER = "buildNumber"
process.env.SHIPPABLE_COMMIT_RANGE = "commitRange"
process.env.SHIPPABLE_CONTAINER_NAME = "containerName"
process.env.SHIPPABLE_JOB_ID = "jobId"
process.env.SHIPPABLE_JOB_NUMBER = "jobNumber"
process.env.SHIPPABLE_REPO_SLUG = "repoSlug"
# additional information
process.env.IS_FORK = "isFork"
process.env.IS_GIT_TAG = "isGitTag"
process.env.IS_PRERELEASE = "isPrerelease"
process.env.IS_RELEASE = "isRelease"
process.env.REPOSITORY_URL = "repositoryUrl"
process.env.REPO_FULL_NAME = "repoFullName"
process.env.REPO_NAME = "repoName"
process.env.BUILD_URL = "buildUrl"
# pull request variables
process.env.BASE_BRANCH = "baseBranch"
process.env.HEAD_BRANCH = "headBranch"
process.env.IS_PULL_REQUEST = "isPullRequest"
process.env.PULL_REQUEST = "pullRequest"
process.env.PULL_REQUEST_BASE_BRANCH = "pullRequestBaseBranch"
process.env.PULL_REQUEST_REPO_FULL_NAME = "pullRequestRepoFullName"
# git information
process.env.COMMIT = "commit"
process.env.BRANCH = "branch"
process.env.COMMITTER = "committer"
process.env.COMMIT_MESSAGE = "commitMessage"
expectsName("shippable")
expectsCiParams({
# build information
shippableBuildId: "buildId"
shippableBuildNumber: "buildNumber"
shippableCommitRange: "commitRange"
shippableContainerName: "containerName"
shippableJobId: "jobId"
shippableJobNumber: "jobNumber"
shippableRepoSlug: "repoSlug"
# additional information
isFork: "isFork"
isGitTag: "isGitTag"
isPrerelease: "isPrerelease"
isRelease: "isRelease"
repositoryUrl: "repositoryUrl"
repoFullName: "repoFullName"
repoName: "repoName"
buildUrl: "buildUrl"
# pull request information
baseBranch: "baseBranch"
headBranch: "headBranch"
isPullRequest: "isPullRequest"
pullRequest: "pullRequest"
pullRequestBaseBranch: "pullRequestBaseBranch"
pullRequestRepoFullName: "pullRequestRepoFullName"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "commitMessage"
authorName: "committer"
})
it "snap", ->
process.env.SNAP_CI = true
expectsName("snap")
expectsCiParams(null)
expectsCommitParams(null)
it "teamcity", ->
process.env.TEAMCITY_VERSION = true
expectsName("teamcity")
expectsCiParams(null)
expectsCommitParams(null)
it "teamfoundation", ->
process.env.TF_BUILD = true
process.env.BUILD_BUILDID = "buildId"
process.env.BUILD_BUILDNUMBER = "buildNumber"
process.env.BUILD_CONTAINERID = "containerId"
process.env.BUILD_SOURCEVERSION = "commit"
process.env.BUILD_SOURCEBRANCHNAME = "branch"
process.env.BUILD_SOURCEVERSIONMESSAGE = "message"
process.env.BUILD_SOURCEVERSIONAUTHOR = "name"
expectsName("teamfoundation")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
})
it "travis", ->
process.env.TRAVIS = true
process.env.TRAVIS_JOB_ID = "travisJobId"
process.env.TRAVIS_BUILD_ID = "travisBuildId"
process.env.TRAVIS_REPO_SLUG = "travisRepoSlug"
process.env.TRAVIS_JOB_NUMBER = "travisJobNumber"
process.env.TRAVIS_EVENT_TYPE = "travisEventType"
process.env.TRAVIS_COMMIT_RANGE = "travisCommitRange"
process.env.TRAVIS_BUILD_NUMBER = "travisBuildNumber"
process.env.TRAVIS_PULL_REQUEST = "travisPullRequest"
process.env.TRAVIS_PULL_REQUEST_BRANCH = "travisPullRequestBranch"
process.env.TRAVIS_COMMIT = "travisCommit"
process.env.TRAVIS_BRANCH = "travisBranch"
process.env.TRAVIS_COMMIT_MESSAGE = "travisCommitMessage"
expectsName("travis")
expectsCiParams({
travisJobId: "travisJobId"
travisBuildId: "travisBuildId"
travisRepoSlug: "travisRepoSlug"
travisJobNumber: "travisJobNumber"
travisEventType: "travisEventType"
travisCommitRange: "travisCommitRange"
travisBuildNumber: "travisBuildNumber"
travisPullRequest: "travisPullRequest"
travisPullRequestBranch: "travisPullRequestBranch"
})
expectsCommitParams({
sha: "travisCommit"
branch: "travisPullRequestBranch"
message: "travisCommitMessage"
})
resetEnv()
process.env.TRAVIS = true
process.env.TRAVIS_BRANCH = "travisBranch"
expectsCommitParams({
branch: "travisBranch"
})
it "wercker", ->
process.env.WERCKER = true
expectsName("wercker")
expectsCiParams(null)
expectsCommitParams(null)
resetEnv()
process.env.WERCKER_MAIN_PIPELINE_STARTED = true
expectsName("wercker")
| 223071 | R = require("ramda")
require("../spec_helper")
ciProvider = require("#{root}lib/util/ci_provider")
expectsName = (name) ->
expect(ciProvider.provider(), "CI providers detected name").to.eq(name)
expectsCiParams = (params) ->
expect(ciProvider.ciParams(), "CI providers detected CI params").to.deep.eq(params)
expectsCommitParams = (params) ->
expect(ciProvider.commitParams(), "CI providers detected commit params").to.deep.eq(params)
expectsCommitDefaults = (existing, expected) ->
expect(ciProvider.commitDefaults(existing), "CI providers default git params").to.deep.eq(expected)
resetEnv = ->
process.env = {}
describe "lib/util/ci_provider", ->
beforeEach ->
resetEnv()
it "null when unknown", ->
resetEnv()
expectsName(null)
expectsCiParams(null)
expectsCommitParams(null)
it "appveyor", ->
process.env.APPVEYOR = true
process.env.APPVEYOR_JOB_ID = "appveyorJobId2"
process.env.APPVEYOR_ACCOUNT_NAME = "appveyorAccountName"
process.env.APPVEYOR_PROJECT_SLUG = "appveyorProjectSlug"
process.env.APPVEYOR_BUILD_VERSION = "appveyorBuildVersion"
process.env.APPVEYOR_BUILD_NUMBER = "appveyorBuildNumber"
process.env.APPVEYOR_PULL_REQUEST_NUMBER = "appveyorPullRequestNumber"
process.env.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH = "appveyorPullRequestHeadRepoBranch"
process.env.APPVEYOR_REPO_COMMIT = "repoCommit"
process.env.APPVEYOR_REPO_COMMIT_MESSAGE = "repoCommitMessage"
process.env.APPVEYOR_REPO_BRANCH = "repoBranch"
process.env.APPVEYOR_REPO_COMMIT_AUTHOR = "repoCommitAuthor"
process.env.APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL = "repoCommitAuthorEmail"
expectsName("appveyor")
expectsCiParams({
appveyorJobId: "appveyorJobId2"
appveyorAccountName: "appveyorAccountName"
appveyorProjectSlug: "appveyorProjectSlug"
appveyorBuildNumber: "appveyorBuildNumber"
appveyorBuildVersion: "appveyorBuildVersion"
appveyorPullRequestNumber: "appveyorPullRequestNumber"
appveyorPullRequestHeadRepoBranch: "appveyorPullRequestHeadRepoBranch"
})
expectsCommitParams({
sha: "repoCommit"
branch: "repoBranch"
message: "repoCommitMessage"
authorName: "repoCommitAuthor"
authorEmail: "repoCommitAuthorEmail"
})
resetEnv()
process.env.APPVEYOR = true
process.env.APPVEYOR_REPO_COMMIT_MESSAGE = "repoCommitMessage"
process.env.APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED = "repoCommitMessageExtended"
expectsCommitParams({
message: "repoCommitMessage\nrepoCommitMessageExtended"
})
it "bamboo", ->
process.env["bamboo.buildNumber"] = "123"
process.env["bamboo.resultsUrl"] = "bamboo.resultsUrl"
process.env["bamboo.buildResultsUrl"] = "bamboo.buildResultsUrl"
process.env["bamboo.planRepository.repositoryUrl"] = "bamboo.planRepository.repositoryUrl"
process.env["bamboo.planRepository.branch"] = "bamboo.planRepository.branch"
expectsName("bamboo")
expectsCiParams({
bambooResultsUrl: "bamboo.resultsUrl"
bambooBuildNumber: "123"
bambooBuildResultsUrl: "bamboo.buildResultsUrl"
bambooPlanRepositoryRepositoryUrl: "bamboo.planRepository.repositoryUrl"
})
expectsCommitParams({
branch: "bamboo.planRepository.branch"
})
it "bitbucket", ->
process.env.CI = "1"
# build information
process.env.BITBUCKET_BUILD_NUMBER = "bitbucketBuildNumber"
process.env.BITBUCKET_REPO_OWNER = "bitbucketRepoOwner"
process.env.BITBUCKET_REPO_SLUG = "bitbucketRepoSlug"
# git information
process.env.BITBUCKET_COMMIT = "bitbucketCommit"
process.env.BITBUCKET_BRANCH = "bitbucketBranch"
expectsName("bitbucket")
expectsCiParams({
bitbucketBuildNumber: "bitbucketBuildNumber"
bitbucketRepoOwner: "bitbucketRepoOwner"
bitbucketRepoSlug: "bitbucketRepoSlug"
})
expectsCommitParams({
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
expectsCommitDefaults({
sha: null
branch: "gitFoundBranch"
}, {
sha: "bitbucketCommit"
branch: "gitFoundBranch"
})
it "buildkite", ->
process.env.BUILDKITE = true
process.env.BUILDKITE_REPO = "buildkiteRepo"
process.env.BUILDKITE_JOB_ID = "buildkiteJobId"
process.env.BUILDKITE_SOURCE = "buildkiteSource"
process.env.BUILDKITE_BUILD_ID = "buildkiteBuildId"
process.env.BUILDKITE_BUILD_URL = "buildkiteBuildUrl"
process.env.BUILDKITE_BUILD_NUMBER = "buildkiteBuildNumber"
process.env.BUILDKITE_PULL_REQUEST = "buildkitePullRequest"
process.env.BUILDKITE_PULL_REQUEST_REPO = "buildkitePullRequestRepo"
process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH = "buildkitePullRequestBaseBranch"
process.env.BUILDKITE_COMMIT = "buildKiteCommit"
process.env.BUILDKITE_BRANCH = "buildKiteBranch"
process.env.BUILDKITE_MESSAGE = "buildKiteMessage"
process.env.BUILDKITE_BUILD_CREATOR = "buildKiteBuildCreator"
process.env.BUILDKITE_BUILD_CREATOR_EMAIL = "buildKiteCreatorEmail"
process.env.BUILDKITE_REPO = "buildkiteRepo"
process.env.BUILDKITE_PIPELINE_DEFAULT_BRANCH = "buildkitePipelineDefaultBranch"
expectsName("buildkite")
expectsCiParams({
buildkiteRepo: "buildkiteRepo"
buildkiteJobId: "buildkiteJobId"
buildkiteSource: "buildkiteSource"
buildkiteBuildId: "buildkiteBuildId"
buildkiteBuildUrl: "buildkiteBuildUrl"
buildkiteBuildNumber: "buildkiteBuildNumber"
buildkitePullRequest: "buildkitePullRequest"
buildkitePullRequestRepo: "buildkitePullRequestRepo"
buildkitePullRequestBaseBranch: "buildkitePullRequestBaseBranch"
})
expectsCommitParams({
sha: "buildKiteCommit"
branch: "buildKiteBranch"
message: "buildKiteMessage"
authorName: "buildKiteBuildCreator"
authorEmail: "buildKiteCreatorEmail"
remoteOrigin: "buildkiteRepo"
defaultBranch: "buildkitePipelineDefaultBranch"
})
it "circle", ->
process.env.CIRCLECI = true
process.env.CIRCLE_JOB = "circleJob"
process.env.CIRCLE_BUILD_NUM = "circleBuildNum"
process.env.CIRCLE_BUILD_URL = "circleBuildUrl"
process.env.CIRCLE_PR_NUMBER = "circlePrNumber"
process.env.CIRCLE_PR_REPONAME = "circlePrReponame"
process.env.CIRCLE_PR_USERNAME = "circlePrUsername"
process.env.CIRCLE_COMPARE_URL = "circleCompareUrl"
process.env.CIRCLE_WORKFLOW_ID = "circleWorkflowId"
process.env.CIRCLE_PULL_REQUEST = "circlePullRequest"
process.env.CIRCLE_REPOSITORY_URL = "circleRepositoryUrl"
process.env.CI_PULL_REQUEST = "ciPullRequest"
process.env.CIRCLE_SHA1 = "circleSha"
process.env.CIRCLE_BRANCH = "circleBranch"
process.env.CIRCLE_USERNAME = "circleUsername"
expectsName("circle")
expectsCiParams({
circleJob: "circleJob"
circleBuildNum: "circleBuildNum"
circleBuildUrl: "circleBuildUrl"
circlePrNumber: "circlePrNumber"
circlePrReponame: "circlePrReponame"
circlePrUsername: "circlePrUsername"
circleCompareUrl: "circleCompareUrl"
circleWorkflowId: "circleWorkflowId"
circlePullRequest: "circlePullRequest"
circleRepositoryUrl: "circleRepositoryUrl"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "circleSha"
branch: "circleBranch"
authorName: "circleUsername"
})
it "codeshipBasic", ->
process.env.CODESHIP = "TRUE"
process.env.CI_NAME = "codeship"
process.env.CI_BUILD_ID = "ciBuildId"
process.env.CI_REPO_NAME = "ciRepoName"
process.env.CI_BUILD_URL = "ciBuildUrl"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_BUILD_NUMBER = "ciBuildNumber"
process.env.CI_PULL_REQUEST = "ciPullRequest"
process.env.CI_COMMIT_ID = "ciCommitId"
process.env.CI_BRANCH = "ciBranch"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.CI_COMMITTER_NAME = "ciCommitterName"
process.env.CI_COMMITTER_EMAIL = "ciCommitterEmail"
expectsName("codeshipBasic")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciBuildUrl: "ciBuildUrl"
ciProjectId: "ciProjectId"
ciBuildNumber: "ciBuildNumber"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "codeshipPro", ->
process.env.CI_NAME = "codeship"
process.env.CI_BUILD_ID = "ciBuildId"
process.env.CI_REPO_NAME = "ciRepoName"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_COMMIT_ID = "ciCommitId"
process.env.CI_BRANCH = "ciBranch"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.CI_COMMITTER_NAME = "ciCommitterName"
process.env.CI_COMMITTER_EMAIL = "ciCommitterEmail"
expectsName("codeshipPro")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciProjectId: "ciProjectId"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "drone", ->
process.env.DRONE = true
process.env.DRONE_JOB_NUMBER = "droneJobNumber"
process.env.DRONE_BUILD_LINK = "droneBuildLink"
process.env.DRONE_BUILD_NUMBER = "droneBuildNumber"
process.env.DRONE_PULL_REQUEST = "dronePullRequest"
process.env.DRONE_COMMIT_SHA = "droneCommitSha"
process.env.DRONE_COMMIT_BRANCH = "droneCommitBranch"
process.env.DRONE_COMMIT_MESSAGE = "droneCommitMessage"
process.env.DRONE_COMMIT_AUTHOR = "droneCommitAuthor"
process.env.DRONE_COMMIT_AUTHOR_EMAIL = "droneCommitAuthorEmail"
process.env.DRONE_REPO_BRANCH = "droneRepoBranch"
expectsName("drone")
expectsCiParams({
droneJobNumber: "droneJobNumber"
droneBuildLink: "droneBuildLink"
droneBuildNumber: "droneBuildNumber"
dronePullRequest: "dronePullRequest"
})
expectsCommitParams({
sha: "droneCommitSha"
branch: "droneCommitBranch"
message: "droneCommitMessage"
authorName: "droneCommitAuthor"
authorEmail: "droneCommitAuthorEmail"
defaultBranch: "droneRepoBranch"
})
it "gitlab", ->
process.env.GITLAB_CI = true
# Gitlab has job id and build id as synonyms
process.env.CI_BUILD_ID = "ciJobId"
process.env.CI_JOB_ID = "ciJobId"
process.env.CI_JOB_URL = "ciJobUrl"
process.env.CI_PIPELINE_ID = "ciPipelineId"
process.env.CI_PIPELINE_URL = "ciPipelineUrl"
process.env.GITLAB_HOST = "gitlabHost"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_PROJECT_URL = "ciProjectUrl"
process.env.CI_REPOSITORY_URL = "ciRepositoryUrl"
process.env.CI_ENVIRONMENT_URL = "ciEnvironmentUrl"
process.env.CI_COMMIT_SHA = "ciCommitSha"
process.env.CI_COMMIT_REF_NAME = "ciCommitRefName"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.GITLAB_USER_NAME = "gitlabUserName"
process.env.GITLAB_USER_EMAIL = "gitlabUserEmail"
expectsName("gitlab")
expectsCiParams({
ciJobId: "ciJobId"
ciJobUrl: "ciJobUrl"
ciBuildId: "ciJobId"
ciPipelineId: "ciPipelineId"
ciPipelineUrl: "ciPipelineUrl"
gitlabHost: "gitlabHost"
ciProjectId: "ciProjectId"
ciProjectUrl: "ciProjectUrl"
ciRepositoryUrl: "ciRepositoryUrl"
ciEnvironmentUrl: "ciEnvironmentUrl"
})
expectsCommitParams({
sha: "ciCommitSha"
branch: "ciCommitRefName"
message: "ciCommitMessage"
authorName: "gitlabUserName"
authorEmail: "gitlabUserEmail"
})
resetEnv()
process.env.CI_SERVER_NAME = "GitLab CI"
expectsName("gitlab")
resetEnv()
process.env.CI_SERVER_NAME = "GitLab"
expectsName("gitlab")
it "jenkins", ->
process.env.JENKINS_URL = true
process.env.BUILD_ID = "buildId"
process.env.BUILD_URL = "buildUrl"
process.env.BUILD_NUMBER = "buildNumber"
process.env.ghprbPullId = "gbprbPullId"
process.env.GIT_COMMIT = "gitCommit"
process.env.GIT_BRANCH = "gitBranch"
expectsName("jenkins")
expectsCiParams({
buildId: "buildId"
buildUrl: "buildUrl"
buildNumber: "buildNumber"
ghprbPullId: "gbprbPullId"
})
expectsCommitParams({
sha: "gitCommit"
branch: "gitBranch"
})
resetEnv()
process.env.JENKINS_HOME = "/path/to/jenkins"
expectsName("jenkins")
resetEnv()
process.env.JENKINS_VERSION = "1.2.3"
expectsName("jenkins")
resetEnv()
process.env.HUDSON_HOME = "/path/to/jenkins"
expectsName("jenkins")
resetEnv()
process.env.HUDSON_URL = true
expectsName("jenkins")
it "semaphore", ->
process.env.SEMAPHORE = true
process.env.SEMAPHORE_BRANCH_ID = "semaphoreBranchId"
process.env.SEMAPHORE_BUILD_NUMBER = "semaphoreBuildNumber"
process.env.SEMAPHORE_CURRENT_JOB = "semaphoreCurrentJob"
process.env.SEMAPHORE_CURRENT_THREAD = "semaphoreCurrentThread"
process.env.SEMAPHORE_EXECUTABLE_UUID = "semaphoreExecutableUuid"
process.env.SEMAPHORE_JOB_COUNT = "semaphoreJobCount"
process.env.SEMAPHORE_JOB_UUID = "semaphoreJobUuid"
process.env.SEMAPHORE_PLATFORM = "semaphorePlatform"
process.env.SEMAPHORE_PROJECT_DIR = "semaphoreProjectDir"
process.env.SEMAPHORE_PROJECT_HASH_ID = "semaphoreProjectHashId"
process.env.SEMAPHORE_PROJECT_NAME = "semaphoreProjectName"
process.env.SEMAPHORE_PROJECT_UUID = "semaphoreProjectUuid"
process.env.SEMAPHORE_REPO_SLUG = "semaphoreRepoSlug"
process.env.SEMAPHORE_TRIGGER_SOURCE = "semaphoreTriggerSource"
process.env.PULL_REQUEST_NUMBER = "pullRequestNumber"
process.env.REVISION = "revision"
process.env.BRANCH_NAME = "branchName"
expectsName("semaphore")
expectsCiParams({
pullRequestNumber: "pullRequestNumber"
semaphoreBranchId: "semaphoreBranchId"
semaphoreBuildNumber: "semaphoreBuildNumber"
semaphoreCurrentJob: "semaphoreCurrentJob"
semaphoreCurrentThread: "semaphoreCurrentThread"
semaphoreExecutableUuid: "semaphoreExecutableUuid"
semaphoreJobCount: "semaphoreJobCount"
semaphoreJobUuid: "semaphoreJobUuid"
semaphorePlatform: "semaphorePlatform"
semaphoreProjectDir: "semaphoreProjectDir"
semaphoreProjectHashId: "semaphoreProjectHashId"
semaphoreProjectName: "semaphoreProjectName"
semaphoreProjectUuid: "semaphoreProjectUuid"
semaphoreRepoSlug: "semaphoreRepoSlug"
semaphoreTriggerSource: "semaphoreTriggerSource"
})
expectsCommitParams({
sha: "revision"
branch: "branchName"
})
it "shippable", ->
process.env.SHIPPABLE = "true"
# build environment variables
process.env.SHIPPABLE_BUILD_ID = "buildId"
process.env.SHIPPABLE_BUILD_NUMBER = "buildNumber"
process.env.SHIPPABLE_COMMIT_RANGE = "commitRange"
process.env.SHIPPABLE_CONTAINER_NAME = "containerName"
process.env.SHIPPABLE_JOB_ID = "jobId"
process.env.SHIPPABLE_JOB_NUMBER = "jobNumber"
process.env.SHIPPABLE_REPO_SLUG = "repoSlug"
# additional information
process.env.IS_FORK = "isFork"
process.env.IS_GIT_TAG = "isGitTag"
process.env.IS_PRERELEASE = "isPrerelease"
process.env.IS_RELEASE = "isRelease"
process.env.REPOSITORY_URL = "repositoryUrl"
process.env.REPO_FULL_NAME = "repoFullName"
process.env.REPO_NAME = "repoName"
process.env.BUILD_URL = "buildUrl"
# pull request variables
process.env.BASE_BRANCH = "baseBranch"
process.env.HEAD_BRANCH = "headBranch"
process.env.IS_PULL_REQUEST = "isPullRequest"
process.env.PULL_REQUEST = "pullRequest"
process.env.PULL_REQUEST_BASE_BRANCH = "pullRequestBaseBranch"
process.env.PULL_REQUEST_REPO_FULL_NAME = "pullRequestRepoFullName"
# git information
process.env.COMMIT = "commit"
process.env.BRANCH = "branch"
process.env.COMMITTER = "committer"
process.env.COMMIT_MESSAGE = "commitMessage"
expectsName("shippable")
expectsCiParams({
# build information
shippableBuildId: "buildId"
shippableBuildNumber: "buildNumber"
shippableCommitRange: "commitRange"
shippableContainerName: "containerName"
shippableJobId: "jobId"
shippableJobNumber: "jobNumber"
shippableRepoSlug: "repoSlug"
# additional information
isFork: "isFork"
isGitTag: "isGitTag"
isPrerelease: "isPrerelease"
isRelease: "isRelease"
repositoryUrl: "repositoryUrl"
repoFullName: "repoFullName"
repoName: "repoName"
buildUrl: "buildUrl"
# pull request information
baseBranch: "baseBranch"
headBranch: "headBranch"
isPullRequest: "isPullRequest"
pullRequest: "pullRequest"
pullRequestBaseBranch: "pullRequestBaseBranch"
pullRequestRepoFullName: "pullRequestRepoFullName"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "commitMessage"
authorName: "<NAME>"
})
it "snap", ->
process.env.SNAP_CI = true
expectsName("snap")
expectsCiParams(null)
expectsCommitParams(null)
it "teamcity", ->
process.env.TEAMCITY_VERSION = true
expectsName("teamcity")
expectsCiParams(null)
expectsCommitParams(null)
it "teamfoundation", ->
process.env.TF_BUILD = true
process.env.BUILD_BUILDID = "buildId"
process.env.BUILD_BUILDNUMBER = "buildNumber"
process.env.BUILD_CONTAINERID = "containerId"
process.env.BUILD_SOURCEVERSION = "commit"
process.env.BUILD_SOURCEBRANCHNAME = "branch"
process.env.BUILD_SOURCEVERSIONMESSAGE = "message"
process.env.BUILD_SOURCEVERSIONAUTHOR = "name"
expectsName("teamfoundation")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
})
it "travis", ->
process.env.TRAVIS = true
process.env.TRAVIS_JOB_ID = "travisJobId"
process.env.TRAVIS_BUILD_ID = "travisBuildId"
process.env.TRAVIS_REPO_SLUG = "travisRepoSlug"
process.env.TRAVIS_JOB_NUMBER = "travisJobNumber"
process.env.TRAVIS_EVENT_TYPE = "travisEventType"
process.env.TRAVIS_COMMIT_RANGE = "travisCommitRange"
process.env.TRAVIS_BUILD_NUMBER = "travisBuildNumber"
process.env.TRAVIS_PULL_REQUEST = "travisPullRequest"
process.env.TRAVIS_PULL_REQUEST_BRANCH = "travisPullRequestBranch"
process.env.TRAVIS_COMMIT = "travisCommit"
process.env.TRAVIS_BRANCH = "travisBranch"
process.env.TRAVIS_COMMIT_MESSAGE = "travisCommitMessage"
expectsName("travis")
expectsCiParams({
travisJobId: "travisJobId"
travisBuildId: "travisBuildId"
travisRepoSlug: "travisRepoSlug"
travisJobNumber: "travisJobNumber"
travisEventType: "travisEventType"
travisCommitRange: "travisCommitRange"
travisBuildNumber: "travisBuildNumber"
travisPullRequest: "travisPullRequest"
travisPullRequestBranch: "travisPullRequestBranch"
})
expectsCommitParams({
sha: "travisCommit"
branch: "travisPullRequestBranch"
message: "travisCommitMessage"
})
resetEnv()
process.env.TRAVIS = true
process.env.TRAVIS_BRANCH = "travisBranch"
expectsCommitParams({
branch: "travisBranch"
})
it "wercker", ->
process.env.WERCKER = true
expectsName("wercker")
expectsCiParams(null)
expectsCommitParams(null)
resetEnv()
process.env.WERCKER_MAIN_PIPELINE_STARTED = true
expectsName("wercker")
| true | R = require("ramda")
require("../spec_helper")
ciProvider = require("#{root}lib/util/ci_provider")
expectsName = (name) ->
expect(ciProvider.provider(), "CI providers detected name").to.eq(name)
expectsCiParams = (params) ->
expect(ciProvider.ciParams(), "CI providers detected CI params").to.deep.eq(params)
expectsCommitParams = (params) ->
expect(ciProvider.commitParams(), "CI providers detected commit params").to.deep.eq(params)
expectsCommitDefaults = (existing, expected) ->
expect(ciProvider.commitDefaults(existing), "CI providers default git params").to.deep.eq(expected)
resetEnv = ->
process.env = {}
describe "lib/util/ci_provider", ->
beforeEach ->
resetEnv()
it "null when unknown", ->
resetEnv()
expectsName(null)
expectsCiParams(null)
expectsCommitParams(null)
it "appveyor", ->
process.env.APPVEYOR = true
process.env.APPVEYOR_JOB_ID = "appveyorJobId2"
process.env.APPVEYOR_ACCOUNT_NAME = "appveyorAccountName"
process.env.APPVEYOR_PROJECT_SLUG = "appveyorProjectSlug"
process.env.APPVEYOR_BUILD_VERSION = "appveyorBuildVersion"
process.env.APPVEYOR_BUILD_NUMBER = "appveyorBuildNumber"
process.env.APPVEYOR_PULL_REQUEST_NUMBER = "appveyorPullRequestNumber"
process.env.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH = "appveyorPullRequestHeadRepoBranch"
process.env.APPVEYOR_REPO_COMMIT = "repoCommit"
process.env.APPVEYOR_REPO_COMMIT_MESSAGE = "repoCommitMessage"
process.env.APPVEYOR_REPO_BRANCH = "repoBranch"
process.env.APPVEYOR_REPO_COMMIT_AUTHOR = "repoCommitAuthor"
process.env.APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL = "repoCommitAuthorEmail"
expectsName("appveyor")
expectsCiParams({
appveyorJobId: "appveyorJobId2"
appveyorAccountName: "appveyorAccountName"
appveyorProjectSlug: "appveyorProjectSlug"
appveyorBuildNumber: "appveyorBuildNumber"
appveyorBuildVersion: "appveyorBuildVersion"
appveyorPullRequestNumber: "appveyorPullRequestNumber"
appveyorPullRequestHeadRepoBranch: "appveyorPullRequestHeadRepoBranch"
})
expectsCommitParams({
sha: "repoCommit"
branch: "repoBranch"
message: "repoCommitMessage"
authorName: "repoCommitAuthor"
authorEmail: "repoCommitAuthorEmail"
})
resetEnv()
process.env.APPVEYOR = true
process.env.APPVEYOR_REPO_COMMIT_MESSAGE = "repoCommitMessage"
process.env.APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED = "repoCommitMessageExtended"
expectsCommitParams({
message: "repoCommitMessage\nrepoCommitMessageExtended"
})
it "bamboo", ->
process.env["bamboo.buildNumber"] = "123"
process.env["bamboo.resultsUrl"] = "bamboo.resultsUrl"
process.env["bamboo.buildResultsUrl"] = "bamboo.buildResultsUrl"
process.env["bamboo.planRepository.repositoryUrl"] = "bamboo.planRepository.repositoryUrl"
process.env["bamboo.planRepository.branch"] = "bamboo.planRepository.branch"
expectsName("bamboo")
expectsCiParams({
bambooResultsUrl: "bamboo.resultsUrl"
bambooBuildNumber: "123"
bambooBuildResultsUrl: "bamboo.buildResultsUrl"
bambooPlanRepositoryRepositoryUrl: "bamboo.planRepository.repositoryUrl"
})
expectsCommitParams({
branch: "bamboo.planRepository.branch"
})
it "bitbucket", ->
process.env.CI = "1"
# build information
process.env.BITBUCKET_BUILD_NUMBER = "bitbucketBuildNumber"
process.env.BITBUCKET_REPO_OWNER = "bitbucketRepoOwner"
process.env.BITBUCKET_REPO_SLUG = "bitbucketRepoSlug"
# git information
process.env.BITBUCKET_COMMIT = "bitbucketCommit"
process.env.BITBUCKET_BRANCH = "bitbucketBranch"
expectsName("bitbucket")
expectsCiParams({
bitbucketBuildNumber: "bitbucketBuildNumber"
bitbucketRepoOwner: "bitbucketRepoOwner"
bitbucketRepoSlug: "bitbucketRepoSlug"
})
expectsCommitParams({
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
expectsCommitDefaults({
sha: null
branch: "gitFoundBranch"
}, {
sha: "bitbucketCommit"
branch: "gitFoundBranch"
})
it "buildkite", ->
process.env.BUILDKITE = true
process.env.BUILDKITE_REPO = "buildkiteRepo"
process.env.BUILDKITE_JOB_ID = "buildkiteJobId"
process.env.BUILDKITE_SOURCE = "buildkiteSource"
process.env.BUILDKITE_BUILD_ID = "buildkiteBuildId"
process.env.BUILDKITE_BUILD_URL = "buildkiteBuildUrl"
process.env.BUILDKITE_BUILD_NUMBER = "buildkiteBuildNumber"
process.env.BUILDKITE_PULL_REQUEST = "buildkitePullRequest"
process.env.BUILDKITE_PULL_REQUEST_REPO = "buildkitePullRequestRepo"
process.env.BUILDKITE_PULL_REQUEST_BASE_BRANCH = "buildkitePullRequestBaseBranch"
process.env.BUILDKITE_COMMIT = "buildKiteCommit"
process.env.BUILDKITE_BRANCH = "buildKiteBranch"
process.env.BUILDKITE_MESSAGE = "buildKiteMessage"
process.env.BUILDKITE_BUILD_CREATOR = "buildKiteBuildCreator"
process.env.BUILDKITE_BUILD_CREATOR_EMAIL = "buildKiteCreatorEmail"
process.env.BUILDKITE_REPO = "buildkiteRepo"
process.env.BUILDKITE_PIPELINE_DEFAULT_BRANCH = "buildkitePipelineDefaultBranch"
expectsName("buildkite")
expectsCiParams({
buildkiteRepo: "buildkiteRepo"
buildkiteJobId: "buildkiteJobId"
buildkiteSource: "buildkiteSource"
buildkiteBuildId: "buildkiteBuildId"
buildkiteBuildUrl: "buildkiteBuildUrl"
buildkiteBuildNumber: "buildkiteBuildNumber"
buildkitePullRequest: "buildkitePullRequest"
buildkitePullRequestRepo: "buildkitePullRequestRepo"
buildkitePullRequestBaseBranch: "buildkitePullRequestBaseBranch"
})
expectsCommitParams({
sha: "buildKiteCommit"
branch: "buildKiteBranch"
message: "buildKiteMessage"
authorName: "buildKiteBuildCreator"
authorEmail: "buildKiteCreatorEmail"
remoteOrigin: "buildkiteRepo"
defaultBranch: "buildkitePipelineDefaultBranch"
})
it "circle", ->
process.env.CIRCLECI = true
process.env.CIRCLE_JOB = "circleJob"
process.env.CIRCLE_BUILD_NUM = "circleBuildNum"
process.env.CIRCLE_BUILD_URL = "circleBuildUrl"
process.env.CIRCLE_PR_NUMBER = "circlePrNumber"
process.env.CIRCLE_PR_REPONAME = "circlePrReponame"
process.env.CIRCLE_PR_USERNAME = "circlePrUsername"
process.env.CIRCLE_COMPARE_URL = "circleCompareUrl"
process.env.CIRCLE_WORKFLOW_ID = "circleWorkflowId"
process.env.CIRCLE_PULL_REQUEST = "circlePullRequest"
process.env.CIRCLE_REPOSITORY_URL = "circleRepositoryUrl"
process.env.CI_PULL_REQUEST = "ciPullRequest"
process.env.CIRCLE_SHA1 = "circleSha"
process.env.CIRCLE_BRANCH = "circleBranch"
process.env.CIRCLE_USERNAME = "circleUsername"
expectsName("circle")
expectsCiParams({
circleJob: "circleJob"
circleBuildNum: "circleBuildNum"
circleBuildUrl: "circleBuildUrl"
circlePrNumber: "circlePrNumber"
circlePrReponame: "circlePrReponame"
circlePrUsername: "circlePrUsername"
circleCompareUrl: "circleCompareUrl"
circleWorkflowId: "circleWorkflowId"
circlePullRequest: "circlePullRequest"
circleRepositoryUrl: "circleRepositoryUrl"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "circleSha"
branch: "circleBranch"
authorName: "circleUsername"
})
it "codeshipBasic", ->
process.env.CODESHIP = "TRUE"
process.env.CI_NAME = "codeship"
process.env.CI_BUILD_ID = "ciBuildId"
process.env.CI_REPO_NAME = "ciRepoName"
process.env.CI_BUILD_URL = "ciBuildUrl"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_BUILD_NUMBER = "ciBuildNumber"
process.env.CI_PULL_REQUEST = "ciPullRequest"
process.env.CI_COMMIT_ID = "ciCommitId"
process.env.CI_BRANCH = "ciBranch"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.CI_COMMITTER_NAME = "ciCommitterName"
process.env.CI_COMMITTER_EMAIL = "ciCommitterEmail"
expectsName("codeshipBasic")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciBuildUrl: "ciBuildUrl"
ciProjectId: "ciProjectId"
ciBuildNumber: "ciBuildNumber"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "codeshipPro", ->
process.env.CI_NAME = "codeship"
process.env.CI_BUILD_ID = "ciBuildId"
process.env.CI_REPO_NAME = "ciRepoName"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_COMMIT_ID = "ciCommitId"
process.env.CI_BRANCH = "ciBranch"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.CI_COMMITTER_NAME = "ciCommitterName"
process.env.CI_COMMITTER_EMAIL = "ciCommitterEmail"
expectsName("codeshipPro")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciProjectId: "ciProjectId"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "drone", ->
process.env.DRONE = true
process.env.DRONE_JOB_NUMBER = "droneJobNumber"
process.env.DRONE_BUILD_LINK = "droneBuildLink"
process.env.DRONE_BUILD_NUMBER = "droneBuildNumber"
process.env.DRONE_PULL_REQUEST = "dronePullRequest"
process.env.DRONE_COMMIT_SHA = "droneCommitSha"
process.env.DRONE_COMMIT_BRANCH = "droneCommitBranch"
process.env.DRONE_COMMIT_MESSAGE = "droneCommitMessage"
process.env.DRONE_COMMIT_AUTHOR = "droneCommitAuthor"
process.env.DRONE_COMMIT_AUTHOR_EMAIL = "droneCommitAuthorEmail"
process.env.DRONE_REPO_BRANCH = "droneRepoBranch"
expectsName("drone")
expectsCiParams({
droneJobNumber: "droneJobNumber"
droneBuildLink: "droneBuildLink"
droneBuildNumber: "droneBuildNumber"
dronePullRequest: "dronePullRequest"
})
expectsCommitParams({
sha: "droneCommitSha"
branch: "droneCommitBranch"
message: "droneCommitMessage"
authorName: "droneCommitAuthor"
authorEmail: "droneCommitAuthorEmail"
defaultBranch: "droneRepoBranch"
})
it "gitlab", ->
process.env.GITLAB_CI = true
# Gitlab has job id and build id as synonyms
process.env.CI_BUILD_ID = "ciJobId"
process.env.CI_JOB_ID = "ciJobId"
process.env.CI_JOB_URL = "ciJobUrl"
process.env.CI_PIPELINE_ID = "ciPipelineId"
process.env.CI_PIPELINE_URL = "ciPipelineUrl"
process.env.GITLAB_HOST = "gitlabHost"
process.env.CI_PROJECT_ID = "ciProjectId"
process.env.CI_PROJECT_URL = "ciProjectUrl"
process.env.CI_REPOSITORY_URL = "ciRepositoryUrl"
process.env.CI_ENVIRONMENT_URL = "ciEnvironmentUrl"
process.env.CI_COMMIT_SHA = "ciCommitSha"
process.env.CI_COMMIT_REF_NAME = "ciCommitRefName"
process.env.CI_COMMIT_MESSAGE = "ciCommitMessage"
process.env.GITLAB_USER_NAME = "gitlabUserName"
process.env.GITLAB_USER_EMAIL = "gitlabUserEmail"
expectsName("gitlab")
expectsCiParams({
ciJobId: "ciJobId"
ciJobUrl: "ciJobUrl"
ciBuildId: "ciJobId"
ciPipelineId: "ciPipelineId"
ciPipelineUrl: "ciPipelineUrl"
gitlabHost: "gitlabHost"
ciProjectId: "ciProjectId"
ciProjectUrl: "ciProjectUrl"
ciRepositoryUrl: "ciRepositoryUrl"
ciEnvironmentUrl: "ciEnvironmentUrl"
})
expectsCommitParams({
sha: "ciCommitSha"
branch: "ciCommitRefName"
message: "ciCommitMessage"
authorName: "gitlabUserName"
authorEmail: "gitlabUserEmail"
})
resetEnv()
process.env.CI_SERVER_NAME = "GitLab CI"
expectsName("gitlab")
resetEnv()
process.env.CI_SERVER_NAME = "GitLab"
expectsName("gitlab")
it "jenkins", ->
process.env.JENKINS_URL = true
process.env.BUILD_ID = "buildId"
process.env.BUILD_URL = "buildUrl"
process.env.BUILD_NUMBER = "buildNumber"
process.env.ghprbPullId = "gbprbPullId"
process.env.GIT_COMMIT = "gitCommit"
process.env.GIT_BRANCH = "gitBranch"
expectsName("jenkins")
expectsCiParams({
buildId: "buildId"
buildUrl: "buildUrl"
buildNumber: "buildNumber"
ghprbPullId: "gbprbPullId"
})
expectsCommitParams({
sha: "gitCommit"
branch: "gitBranch"
})
resetEnv()
process.env.JENKINS_HOME = "/path/to/jenkins"
expectsName("jenkins")
resetEnv()
process.env.JENKINS_VERSION = "1.2.3"
expectsName("jenkins")
resetEnv()
process.env.HUDSON_HOME = "/path/to/jenkins"
expectsName("jenkins")
resetEnv()
process.env.HUDSON_URL = true
expectsName("jenkins")
it "semaphore", ->
process.env.SEMAPHORE = true
process.env.SEMAPHORE_BRANCH_ID = "semaphoreBranchId"
process.env.SEMAPHORE_BUILD_NUMBER = "semaphoreBuildNumber"
process.env.SEMAPHORE_CURRENT_JOB = "semaphoreCurrentJob"
process.env.SEMAPHORE_CURRENT_THREAD = "semaphoreCurrentThread"
process.env.SEMAPHORE_EXECUTABLE_UUID = "semaphoreExecutableUuid"
process.env.SEMAPHORE_JOB_COUNT = "semaphoreJobCount"
process.env.SEMAPHORE_JOB_UUID = "semaphoreJobUuid"
process.env.SEMAPHORE_PLATFORM = "semaphorePlatform"
process.env.SEMAPHORE_PROJECT_DIR = "semaphoreProjectDir"
process.env.SEMAPHORE_PROJECT_HASH_ID = "semaphoreProjectHashId"
process.env.SEMAPHORE_PROJECT_NAME = "semaphoreProjectName"
process.env.SEMAPHORE_PROJECT_UUID = "semaphoreProjectUuid"
process.env.SEMAPHORE_REPO_SLUG = "semaphoreRepoSlug"
process.env.SEMAPHORE_TRIGGER_SOURCE = "semaphoreTriggerSource"
process.env.PULL_REQUEST_NUMBER = "pullRequestNumber"
process.env.REVISION = "revision"
process.env.BRANCH_NAME = "branchName"
expectsName("semaphore")
expectsCiParams({
pullRequestNumber: "pullRequestNumber"
semaphoreBranchId: "semaphoreBranchId"
semaphoreBuildNumber: "semaphoreBuildNumber"
semaphoreCurrentJob: "semaphoreCurrentJob"
semaphoreCurrentThread: "semaphoreCurrentThread"
semaphoreExecutableUuid: "semaphoreExecutableUuid"
semaphoreJobCount: "semaphoreJobCount"
semaphoreJobUuid: "semaphoreJobUuid"
semaphorePlatform: "semaphorePlatform"
semaphoreProjectDir: "semaphoreProjectDir"
semaphoreProjectHashId: "semaphoreProjectHashId"
semaphoreProjectName: "semaphoreProjectName"
semaphoreProjectUuid: "semaphoreProjectUuid"
semaphoreRepoSlug: "semaphoreRepoSlug"
semaphoreTriggerSource: "semaphoreTriggerSource"
})
expectsCommitParams({
sha: "revision"
branch: "branchName"
})
it "shippable", ->
process.env.SHIPPABLE = "true"
# build environment variables
process.env.SHIPPABLE_BUILD_ID = "buildId"
process.env.SHIPPABLE_BUILD_NUMBER = "buildNumber"
process.env.SHIPPABLE_COMMIT_RANGE = "commitRange"
process.env.SHIPPABLE_CONTAINER_NAME = "containerName"
process.env.SHIPPABLE_JOB_ID = "jobId"
process.env.SHIPPABLE_JOB_NUMBER = "jobNumber"
process.env.SHIPPABLE_REPO_SLUG = "repoSlug"
# additional information
process.env.IS_FORK = "isFork"
process.env.IS_GIT_TAG = "isGitTag"
process.env.IS_PRERELEASE = "isPrerelease"
process.env.IS_RELEASE = "isRelease"
process.env.REPOSITORY_URL = "repositoryUrl"
process.env.REPO_FULL_NAME = "repoFullName"
process.env.REPO_NAME = "repoName"
process.env.BUILD_URL = "buildUrl"
# pull request variables
process.env.BASE_BRANCH = "baseBranch"
process.env.HEAD_BRANCH = "headBranch"
process.env.IS_PULL_REQUEST = "isPullRequest"
process.env.PULL_REQUEST = "pullRequest"
process.env.PULL_REQUEST_BASE_BRANCH = "pullRequestBaseBranch"
process.env.PULL_REQUEST_REPO_FULL_NAME = "pullRequestRepoFullName"
# git information
process.env.COMMIT = "commit"
process.env.BRANCH = "branch"
process.env.COMMITTER = "committer"
process.env.COMMIT_MESSAGE = "commitMessage"
expectsName("shippable")
expectsCiParams({
# build information
shippableBuildId: "buildId"
shippableBuildNumber: "buildNumber"
shippableCommitRange: "commitRange"
shippableContainerName: "containerName"
shippableJobId: "jobId"
shippableJobNumber: "jobNumber"
shippableRepoSlug: "repoSlug"
# additional information
isFork: "isFork"
isGitTag: "isGitTag"
isPrerelease: "isPrerelease"
isRelease: "isRelease"
repositoryUrl: "repositoryUrl"
repoFullName: "repoFullName"
repoName: "repoName"
buildUrl: "buildUrl"
# pull request information
baseBranch: "baseBranch"
headBranch: "headBranch"
isPullRequest: "isPullRequest"
pullRequest: "pullRequest"
pullRequestBaseBranch: "pullRequestBaseBranch"
pullRequestRepoFullName: "pullRequestRepoFullName"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "commitMessage"
authorName: "PI:NAME:<NAME>END_PI"
})
it "snap", ->
process.env.SNAP_CI = true
expectsName("snap")
expectsCiParams(null)
expectsCommitParams(null)
it "teamcity", ->
process.env.TEAMCITY_VERSION = true
expectsName("teamcity")
expectsCiParams(null)
expectsCommitParams(null)
it "teamfoundation", ->
process.env.TF_BUILD = true
process.env.BUILD_BUILDID = "buildId"
process.env.BUILD_BUILDNUMBER = "buildNumber"
process.env.BUILD_CONTAINERID = "containerId"
process.env.BUILD_SOURCEVERSION = "commit"
process.env.BUILD_SOURCEBRANCHNAME = "branch"
process.env.BUILD_SOURCEVERSIONMESSAGE = "message"
process.env.BUILD_SOURCEVERSIONAUTHOR = "name"
expectsName("teamfoundation")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
})
it "travis", ->
process.env.TRAVIS = true
process.env.TRAVIS_JOB_ID = "travisJobId"
process.env.TRAVIS_BUILD_ID = "travisBuildId"
process.env.TRAVIS_REPO_SLUG = "travisRepoSlug"
process.env.TRAVIS_JOB_NUMBER = "travisJobNumber"
process.env.TRAVIS_EVENT_TYPE = "travisEventType"
process.env.TRAVIS_COMMIT_RANGE = "travisCommitRange"
process.env.TRAVIS_BUILD_NUMBER = "travisBuildNumber"
process.env.TRAVIS_PULL_REQUEST = "travisPullRequest"
process.env.TRAVIS_PULL_REQUEST_BRANCH = "travisPullRequestBranch"
process.env.TRAVIS_COMMIT = "travisCommit"
process.env.TRAVIS_BRANCH = "travisBranch"
process.env.TRAVIS_COMMIT_MESSAGE = "travisCommitMessage"
expectsName("travis")
expectsCiParams({
travisJobId: "travisJobId"
travisBuildId: "travisBuildId"
travisRepoSlug: "travisRepoSlug"
travisJobNumber: "travisJobNumber"
travisEventType: "travisEventType"
travisCommitRange: "travisCommitRange"
travisBuildNumber: "travisBuildNumber"
travisPullRequest: "travisPullRequest"
travisPullRequestBranch: "travisPullRequestBranch"
})
expectsCommitParams({
sha: "travisCommit"
branch: "travisPullRequestBranch"
message: "travisCommitMessage"
})
resetEnv()
process.env.TRAVIS = true
process.env.TRAVIS_BRANCH = "travisBranch"
expectsCommitParams({
branch: "travisBranch"
})
it "wercker", ->
process.env.WERCKER = true
expectsName("wercker")
expectsCiParams(null)
expectsCommitParams(null)
resetEnv()
process.env.WERCKER_MAIN_PIPELINE_STARTED = true
expectsName("wercker")
|
[
{
"context": "ate\n) ->\n baseUrl = '/radio/'\n tracksSrc =\n 'Alex Beroza':\n 'Art Now': 'AlexBeroza_-_Art_Now.ogg'\n ",
"end": 132,
"score": 0.999891996383667,
"start": 121,
"tag": "NAME",
"value": "Alex Beroza"
},
{
"context": " 'In Peace': 'AlexBeroza_-_In_Peace.o... | server/public/scripts/views/music.coffee | triggerrally/triggerrally.github.io | 1 | define [
'cs!views/view'
'jade!templates/music'
], (
View
template
) ->
baseUrl = '/radio/'
tracksSrc =
'Alex Beroza':
'Art Now': 'AlexBeroza_-_Art_Now.ogg'
'Brake Dance': 'AlexBeroza_-_Brake_Dance.ogg'
'Could Be': 'AlexBeroza_-_Could_Be.ogg'
'Emerge In Love': 'AlexBeroza_-_Emerge_In_Love.ogg' # 5
'In Peace': 'AlexBeroza_-_In_Peace.ogg'
'Carl and the Saganauts':
# 'Trigger Theme 1': 'saganauts-tr1.ogg'
# 'Theme 2': 'saganauts-tr2.ogg'
'Trigger Rally Theme': 'saganauts-tr4.ogg'
'Citizen X0':
'Art is Born': 'Citizen_X0_-_Art_is_Born.ogg'
'DoKashiteru':
'2025': 'DoKashiteru_-_2025.ogg'
'Dubslate':
'Nervous Refix': 'dubslate_-_nervous_refix.ogg'
'J.Lang':
'Love Will Open Your Heart Dance Mix': 'djlang59_-_Love_Will_Open_Your_Heart_Dance_Mix.ogg'
'Sawtooth':
'Carcinogens': 'Sawtooth_-_Carcinogens.ogg'
'SpinningMerkaba':
'260809 Funky Nurykabe': 'jlbrock44_-_260809_Funky_Nurykabe.ogg'
'Super Sigil':
'Thunderlizard at the Art War': 'Super_Sigil_-_Thunderlizard_at_the_Art_War.ogg'
'Travis Morgan':
'pROgraM vs. Us3R': 'morgantj_-_pROgraM_vs._Us3R.ogg'
tracks = []
for artist, val of tracksSrc
for title, src of val
tracks.push { artist, title, src }
class MusicView extends View
tagName: 'span'
className: 'dropdownmenu'
template: template
constructor: (@app) -> super()
afterRender: ->
prefs = @app.root.prefs
$audio = @$ 'audio'
$title = @$ '.title'
$artist = @$ '.artist'
$status = @$ '.status'
$volume = @$ 'input.volume'
$playpause = @$ '.musiccontrol.playpause'
$next = @$ '.musiccontrol.next'
$audio.on 'all'
track = null
updateStatus = ->
if prefs.musicplay
$status.text "(#{track.title} by #{track.artist})"
else
$status.text "(paused)"
idx = -1
recent = []
playNext = ->
prefs.musicplay = yes
pickRandom = -> Math.floor Math.random() * tracks.length
while true
idx = pickRandom()
break if idx not in recent
recent = recent.slice(-5)
recent.push idx
track = tracks[idx]
$audio.attr 'src', baseUrl + track.src
$artist.text track.artist
$title.text track.title
updateStatus()
# $audio.prop 'autoplay', yes # Done in template.
$audio[0].volume = 0.5
$audio.on 'ended', playNext
$next.on 'click', playNext
do updatePlay = ->
$playpause.toggleClass 'play', not prefs.musicplay
$playpause.toggleClass 'pause', prefs.musicplay
if prefs.musicplay
if track
updateStatus()
$audio[0].play()
else
playNext()
else
updateStatus()
$audio[0].pause()
$playpause.on 'click', -> prefs.musicplay = not prefs.musicplay
prefs.on 'change:musicplay', updatePlay
do updateVolume = ->
$volume.val prefs.musicvolume
$audio[0].volume = prefs.musicvolume
$volume.on 'change', -> prefs.musicvolume = $volume.val()
prefs.on 'change:musicvolume', updateVolume
| 218734 | define [
'cs!views/view'
'jade!templates/music'
], (
View
template
) ->
baseUrl = '/radio/'
tracksSrc =
'<NAME>':
'Art Now': 'AlexBeroza_-_Art_Now.ogg'
'Brake Dance': 'AlexBeroza_-_Brake_Dance.ogg'
'Could Be': 'AlexBeroza_-_Could_Be.ogg'
'Emerge In Love': 'AlexBeroza_-_Emerge_In_Love.ogg' # 5
'In Peace': 'AlexBeroza_-_In_Peace.ogg'
'<NAME> and the S<NAME>anaut<NAME>':
# 'Trigger Theme 1': 'saganauts-tr1.ogg'
# 'Theme 2': 'saganauts-tr2.ogg'
'Trigger Rally Theme': 'saganauts-tr4.ogg'
'Citizen X0':
'Art is Born': 'Citizen_X0_-_Art_is_Born.ogg'
'DoKashiteru':
'2025': 'DoKashiteru_-_2025.ogg'
'Dubslate':
'Nervous Refix': 'dubslate_-_nervous_refix.ogg'
'J.Lang':
'Love Will Open Your Heart Dance Mix': 'djlang59_-_Love_Will_Open_Your_Heart_Dance_Mix.ogg'
'Sawtooth':
'Carcinogens': 'Sawtooth_-_Carcinogens.ogg'
'SpinningMerkaba':
'260809 Funky Nurykabe': 'jlbrock44_-_260809_Funky_Nurykabe.ogg'
'Super Sigil':
'Thunderlizard at the Art War': 'Super_Sigil_-_Thunderlizard_at_the_Art_War.ogg'
'<NAME>':
'pROgraM vs. Us3R': 'morgantj_-_pROgraM_vs._Us3R.ogg'
tracks = []
for artist, val of tracksSrc
for title, src of val
tracks.push { artist, title, src }
class MusicView extends View
tagName: 'span'
className: 'dropdownmenu'
template: template
constructor: (@app) -> super()
afterRender: ->
prefs = @app.root.prefs
$audio = @$ 'audio'
$title = @$ '.title'
$artist = @$ '.artist'
$status = @$ '.status'
$volume = @$ 'input.volume'
$playpause = @$ '.musiccontrol.playpause'
$next = @$ '.musiccontrol.next'
$audio.on 'all'
track = null
updateStatus = ->
if prefs.musicplay
$status.text "(#{track.title} by #{track.artist})"
else
$status.text "(paused)"
idx = -1
recent = []
playNext = ->
prefs.musicplay = yes
pickRandom = -> Math.floor Math.random() * tracks.length
while true
idx = pickRandom()
break if idx not in recent
recent = recent.slice(-5)
recent.push idx
track = tracks[idx]
$audio.attr 'src', baseUrl + track.src
$artist.text track.artist
$title.text track.title
updateStatus()
# $audio.prop 'autoplay', yes # Done in template.
$audio[0].volume = 0.5
$audio.on 'ended', playNext
$next.on 'click', playNext
do updatePlay = ->
$playpause.toggleClass 'play', not prefs.musicplay
$playpause.toggleClass 'pause', prefs.musicplay
if prefs.musicplay
if track
updateStatus()
$audio[0].play()
else
playNext()
else
updateStatus()
$audio[0].pause()
$playpause.on 'click', -> prefs.musicplay = not prefs.musicplay
prefs.on 'change:musicplay', updatePlay
do updateVolume = ->
$volume.val prefs.musicvolume
$audio[0].volume = prefs.musicvolume
$volume.on 'change', -> prefs.musicvolume = $volume.val()
prefs.on 'change:musicvolume', updateVolume
| true | define [
'cs!views/view'
'jade!templates/music'
], (
View
template
) ->
baseUrl = '/radio/'
tracksSrc =
'PI:NAME:<NAME>END_PI':
'Art Now': 'AlexBeroza_-_Art_Now.ogg'
'Brake Dance': 'AlexBeroza_-_Brake_Dance.ogg'
'Could Be': 'AlexBeroza_-_Could_Be.ogg'
'Emerge In Love': 'AlexBeroza_-_Emerge_In_Love.ogg' # 5
'In Peace': 'AlexBeroza_-_In_Peace.ogg'
'PI:NAME:<NAME>END_PI and the SPI:NAME:<NAME>END_PIanautPI:NAME:<NAME>END_PI':
# 'Trigger Theme 1': 'saganauts-tr1.ogg'
# 'Theme 2': 'saganauts-tr2.ogg'
'Trigger Rally Theme': 'saganauts-tr4.ogg'
'Citizen X0':
'Art is Born': 'Citizen_X0_-_Art_is_Born.ogg'
'DoKashiteru':
'2025': 'DoKashiteru_-_2025.ogg'
'Dubslate':
'Nervous Refix': 'dubslate_-_nervous_refix.ogg'
'J.Lang':
'Love Will Open Your Heart Dance Mix': 'djlang59_-_Love_Will_Open_Your_Heart_Dance_Mix.ogg'
'Sawtooth':
'Carcinogens': 'Sawtooth_-_Carcinogens.ogg'
'SpinningMerkaba':
'260809 Funky Nurykabe': 'jlbrock44_-_260809_Funky_Nurykabe.ogg'
'Super Sigil':
'Thunderlizard at the Art War': 'Super_Sigil_-_Thunderlizard_at_the_Art_War.ogg'
'PI:NAME:<NAME>END_PI':
'pROgraM vs. Us3R': 'morgantj_-_pROgraM_vs._Us3R.ogg'
tracks = []
for artist, val of tracksSrc
for title, src of val
tracks.push { artist, title, src }
class MusicView extends View
tagName: 'span'
className: 'dropdownmenu'
template: template
constructor: (@app) -> super()
afterRender: ->
prefs = @app.root.prefs
$audio = @$ 'audio'
$title = @$ '.title'
$artist = @$ '.artist'
$status = @$ '.status'
$volume = @$ 'input.volume'
$playpause = @$ '.musiccontrol.playpause'
$next = @$ '.musiccontrol.next'
$audio.on 'all'
track = null
updateStatus = ->
if prefs.musicplay
$status.text "(#{track.title} by #{track.artist})"
else
$status.text "(paused)"
idx = -1
recent = []
playNext = ->
prefs.musicplay = yes
pickRandom = -> Math.floor Math.random() * tracks.length
while true
idx = pickRandom()
break if idx not in recent
recent = recent.slice(-5)
recent.push idx
track = tracks[idx]
$audio.attr 'src', baseUrl + track.src
$artist.text track.artist
$title.text track.title
updateStatus()
# $audio.prop 'autoplay', yes # Done in template.
$audio[0].volume = 0.5
$audio.on 'ended', playNext
$next.on 'click', playNext
do updatePlay = ->
$playpause.toggleClass 'play', not prefs.musicplay
$playpause.toggleClass 'pause', prefs.musicplay
if prefs.musicplay
if track
updateStatus()
$audio[0].play()
else
playNext()
else
updateStatus()
$audio[0].pause()
$playpause.on 'click', -> prefs.musicplay = not prefs.musicplay
prefs.on 'change:musicplay', updatePlay
do updateVolume = ->
$volume.val prefs.musicvolume
$audio[0].volume = prefs.musicvolume
$volume.on 'change', -> prefs.musicvolume = $volume.val()
prefs.on 'change:musicvolume', updateVolume
|
[
{
"context": "e defined because this is nested document.\n@author Nathan Klick\n@copyright QRef 2012\n@abstract\n###\nclass Aircraft",
"end": 455,
"score": 0.999880313873291,
"start": 443,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/schema/AircraftChecklistCategorySchema.coffee | qrefdev/qref | 0 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
AircraftChecklistItemSchema = require('./AircraftChecklistItemSchema')
AircraftChecklistSectionSchema = require('./AircraftChecklistSectionSchema')
###
Nested Schema representing a specific checklist section.
@note This is a nested document and does not have a separate Mongo collection.
@note No indexes are defined because this is nested document.
@author Nathan Klick
@copyright QRef 2012
@abstract
###
class AircraftChecklistCategorySchemaInternal
###
@property [String] (Required) An enum value indicating the section type. Valid values are ['standard', 'emergency'].
###
sectionType:
type: String
required: true
enum: ['standard', 'emergency']
###
@property [Number] (Required) A numeric value indicating the position of this section relative to other sections.
###
index:
type: Number
required: true
###
@property [String] (Required) The name of this checklist section as displayed in the application.
###
name:
type: String
required: true
###
@property [Array<AircraftChecklistItemSchemaInternal>] (Optional) An array of ordered checklist items.
###
items:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [String] (Optional) A path to the sections icon relative to the root of the server.
###
sectionIcon:
type: String
required: false
AircraftChecklistCategorySchema = new Schema(new AircraftChecklistCategorySchemaInternal())
module.exports = AircraftChecklistCategorySchema | 55715 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
AircraftChecklistItemSchema = require('./AircraftChecklistItemSchema')
AircraftChecklistSectionSchema = require('./AircraftChecklistSectionSchema')
###
Nested Schema representing a specific checklist section.
@note This is a nested document and does not have a separate Mongo collection.
@note No indexes are defined because this is nested document.
@author <NAME>
@copyright QRef 2012
@abstract
###
class AircraftChecklistCategorySchemaInternal
###
@property [String] (Required) An enum value indicating the section type. Valid values are ['standard', 'emergency'].
###
sectionType:
type: String
required: true
enum: ['standard', 'emergency']
###
@property [Number] (Required) A numeric value indicating the position of this section relative to other sections.
###
index:
type: Number
required: true
###
@property [String] (Required) The name of this checklist section as displayed in the application.
###
name:
type: String
required: true
###
@property [Array<AircraftChecklistItemSchemaInternal>] (Optional) An array of ordered checklist items.
###
items:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [String] (Optional) A path to the sections icon relative to the root of the server.
###
sectionIcon:
type: String
required: false
AircraftChecklistCategorySchema = new Schema(new AircraftChecklistCategorySchemaInternal())
module.exports = AircraftChecklistCategorySchema | true | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
AircraftChecklistItemSchema = require('./AircraftChecklistItemSchema')
AircraftChecklistSectionSchema = require('./AircraftChecklistSectionSchema')
###
Nested Schema representing a specific checklist section.
@note This is a nested document and does not have a separate Mongo collection.
@note No indexes are defined because this is nested document.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
@abstract
###
class AircraftChecklistCategorySchemaInternal
###
@property [String] (Required) An enum value indicating the section type. Valid values are ['standard', 'emergency'].
###
sectionType:
type: String
required: true
enum: ['standard', 'emergency']
###
@property [Number] (Required) A numeric value indicating the position of this section relative to other sections.
###
index:
type: Number
required: true
###
@property [String] (Required) The name of this checklist section as displayed in the application.
###
name:
type: String
required: true
###
@property [Array<AircraftChecklistItemSchemaInternal>] (Optional) An array of ordered checklist items.
###
items:
type: [AircraftChecklistSectionSchema]
required: false
###
@property [String] (Optional) A path to the sections icon relative to the root of the server.
###
sectionIcon:
type: String
required: false
AircraftChecklistCategorySchema = new Schema(new AircraftChecklistCategorySchemaInternal())
module.exports = AircraftChecklistCategorySchema |
[
{
"context": "scopeName: 'text.tex.biber.log'\nname: 'Biber Log'\nfileTypes: [\n 'blg'\n]\nfirstLineMatch: '^[\\\\d+]\\",
"end": 48,
"score": 0.937166154384613,
"start": 39,
"tag": "NAME",
"value": "Biber Log"
}
] | grammars/biber_log.cson | Aerijo/language-latex2e | 12 | scopeName: 'text.tex.biber.log'
name: 'Biber Log'
fileTypes: [
'blg'
]
firstLineMatch: '^[\\d+]\\sConfig\\.pm\\:\\d+>\\sINFO\\s\\-\\sThis is Biber [\\d\\.]+$'
limitLineLength: false
patterns: [
{ include: '#error' }
{ include: '#warning' }
{ include: '#info' }
{ include: '#debug' }
]
repository:
error:
match: '(ERROR)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.error'
warning:
match: '(WARN)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.warn'
info:
match: '(INFO)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.info'
debug:
match: '(DEBUG)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.debug'
| 211154 | scopeName: 'text.tex.biber.log'
name: '<NAME>'
fileTypes: [
'blg'
]
firstLineMatch: '^[\\d+]\\sConfig\\.pm\\:\\d+>\\sINFO\\s\\-\\sThis is Biber [\\d\\.]+$'
limitLineLength: false
patterns: [
{ include: '#error' }
{ include: '#warning' }
{ include: '#info' }
{ include: '#debug' }
]
repository:
error:
match: '(ERROR)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.error'
warning:
match: '(WARN)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.warn'
info:
match: '(INFO)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.info'
debug:
match: '(DEBUG)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.debug'
| true | scopeName: 'text.tex.biber.log'
name: 'PI:NAME:<NAME>END_PI'
fileTypes: [
'blg'
]
firstLineMatch: '^[\\d+]\\sConfig\\.pm\\:\\d+>\\sINFO\\s\\-\\sThis is Biber [\\d\\.]+$'
limitLineLength: false
patterns: [
{ include: '#error' }
{ include: '#warning' }
{ include: '#info' }
{ include: '#debug' }
]
repository:
error:
match: '(ERROR)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.error'
warning:
match: '(WARN)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.warn'
info:
match: '(INFO)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.info'
debug:
match: '(DEBUG)\\s*(?=\\-)'
captures: 1: name: 'markup.other.log.debug'
|
[
{
"context": " <account> - list the ELB statuses\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\n{Promise} = require 'es6-promis",
"end": 296,
"score": 0.99969482421875,
"start": 289,
"tag": "USERNAME",
"value": "bouzuya"
},
{
"context": " - list the ELB statuses\n#\n# Author:\n# bo... | src/scripts/elb.coffee | bouzuya/hubot-elb | 3 | # Description
# A Hubot script to manage the Elastic Load Balancing
#
# Configuration:
# HUBOT_ELB_ACCOUNTS
# HUBOT_ELB_<xxx>_ACCESS_KEY_ID
# HUBOT_ELB_<xxx>_SECRET_ACCESS_KEY
# HUBOT_ELB_<xxx>_REGION
#
# Commands:
# hubot elb <account> - list the ELB statuses
#
# Author:
# bouzuya <m@bouzuya.net>
#
{Promise} = require 'es6-promise'
AWS = require 'aws-sdk'
Case = require 'case'
module.exports = (robot) ->
accounts = (process.env.HUBOT_ELB_ACCOUNTS || '')
.split ','
.filter (i) -> i.length > 0
.reduce (as, i) ->
as[i] = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'REGION'].reduce (a, j) ->
a[Case.camel(j)] = process.env['HUBOT_ELB_' + i.toUpperCase() + '_' + j]
a
, {}
as
, {}
formatELBs = (elbs) ->
loadBalancers = elbs.map (i) ->
instances = i.Instances.map (j) ->
" #{j.InstanceId}: #{j.State} (#{j.ReasonCode})"
"""
#{i.LoadBalancerName}:
#{instances.join('\n')}
"""
"""
ELBs:
#{loadBalancers.join('\n')}
"""
newClient = (account) ->
new AWS.ELB
apiVersion: '2012-06-01'
accessKeyId: account.accessKeyId
secretAccessKey: account.secretAccessKey
region: account.region ? 'ap-northeast-1'
listLoadBalancers = (client) ->
# promised describeLoadBalancers
new Promise (resolve, reject) ->
client.describeLoadBalancers {}, (err, data) ->
return reject(err) if err
resolve data.LoadBalancerDescriptions
listInstances = (client, elb) ->
# promised describeInstanceHealth
new Promise (resolve, reject) ->
params =
LoadBalancerName: elb.LoadBalancerName
Instances: elb.Instances.map (i) -> { InstanceId: i.InstanceId }
client.describeInstanceHealth params, (err, data) ->
return reject(err) if err
resolve(data.InstanceStates)
listELBs = (account) ->
# describeLoadBalancers & describeInstanceHealth
client = newClient account
listLoadBalancers client
.then (elbs) ->
# add instance statuses to elb.Instances
elbs.reduce(((promise, elb) ->
promise.then ->
listInstances client, elb
.then (result) ->
elb.Instances = elb.Instances.map (i) ->
result.filter((j) -> i.InstanceId is j.InstanceId)[0]
.then ->
elbs
), Promise.resolve())
deregisterInstances = (client, loadBalancerName, instances) ->
# promised deregisterInstancesFromLoadBalancer
new Promise (resolve, reject) ->
params =
Instances: instances.map (i) -> { InstanceId: i.InstanceId }
LoadBalancerName: loadBalancerName
client.deregisterInstancesFromLoadBalancer params, (err, data) ->
return reject(err) if err
resolve(data.Instances)
registerInstances = (client, loadBalancerName, instances) ->
# promised registerInstancesToLoadBalancer
new Promise (resolve, reject) ->
params =
Instances: instances.map (i) -> { InstanceId: i.InstanceId }
LoadBalancerName: loadBalancerName
client.registerInstancesWithLoadBalancer params, (err, data) ->
return reject(err) if err
resolve(data.Instances)
error = (res, e) ->
res.robot.logger.error 'hubot-elb: error'
res.robot.logger.error e
res.send 'hubot-elb: error'
status = (res, account) ->
listELBs account
.then formatELBs
.then (message) ->
res.send message
.catch (e) ->
error res, e
robot.respond /elb\s+([-\w]+)$/i, (res) ->
accountId = res.match[1]
account = accounts[accountId]
return res.send("account #{accountId} is not found") unless account?
res.send 'elb status ' + accountId
status res, account
| 151043 | # Description
# A Hubot script to manage the Elastic Load Balancing
#
# Configuration:
# HUBOT_ELB_ACCOUNTS
# HUBOT_ELB_<xxx>_ACCESS_KEY_ID
# HUBOT_ELB_<xxx>_SECRET_ACCESS_KEY
# HUBOT_ELB_<xxx>_REGION
#
# Commands:
# hubot elb <account> - list the ELB statuses
#
# Author:
# bouzuya <<EMAIL>>
#
{Promise} = require 'es6-promise'
AWS = require 'aws-sdk'
Case = require 'case'
module.exports = (robot) ->
accounts = (process.env.HUBOT_ELB_ACCOUNTS || '')
.split ','
.filter (i) -> i.length > 0
.reduce (as, i) ->
as[i] = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'REGION'].reduce (a, j) ->
a[Case.camel(j)] = process.env['HUBOT_ELB_' + i.toUpperCase() + '_' + j]
a
, {}
as
, {}
formatELBs = (elbs) ->
loadBalancers = elbs.map (i) ->
instances = i.Instances.map (j) ->
" #{j.InstanceId}: #{j.State} (#{j.ReasonCode})"
"""
#{i.LoadBalancerName}:
#{instances.join('\n')}
"""
"""
ELBs:
#{loadBalancers.join('\n')}
"""
newClient = (account) ->
new AWS.ELB
apiVersion: '2012-06-01'
accessKeyId: account.accessKeyId
secretAccessKey: account.secretAccessKey
region: account.region ? 'ap-northeast-1'
listLoadBalancers = (client) ->
# promised describeLoadBalancers
new Promise (resolve, reject) ->
client.describeLoadBalancers {}, (err, data) ->
return reject(err) if err
resolve data.LoadBalancerDescriptions
listInstances = (client, elb) ->
# promised describeInstanceHealth
new Promise (resolve, reject) ->
params =
LoadBalancerName: elb.LoadBalancerName
Instances: elb.Instances.map (i) -> { InstanceId: i.InstanceId }
client.describeInstanceHealth params, (err, data) ->
return reject(err) if err
resolve(data.InstanceStates)
listELBs = (account) ->
# describeLoadBalancers & describeInstanceHealth
client = newClient account
listLoadBalancers client
.then (elbs) ->
# add instance statuses to elb.Instances
elbs.reduce(((promise, elb) ->
promise.then ->
listInstances client, elb
.then (result) ->
elb.Instances = elb.Instances.map (i) ->
result.filter((j) -> i.InstanceId is j.InstanceId)[0]
.then ->
elbs
), Promise.resolve())
deregisterInstances = (client, loadBalancerName, instances) ->
# promised deregisterInstancesFromLoadBalancer
new Promise (resolve, reject) ->
params =
Instances: instances.map (i) -> { InstanceId: i.InstanceId }
LoadBalancerName: loadBalancerName
client.deregisterInstancesFromLoadBalancer params, (err, data) ->
return reject(err) if err
resolve(data.Instances)
registerInstances = (client, loadBalancerName, instances) ->
# promised registerInstancesToLoadBalancer
new Promise (resolve, reject) ->
params =
Instances: instances.map (i) -> { InstanceId: i.InstanceId }
LoadBalancerName: loadBalancerName
client.registerInstancesWithLoadBalancer params, (err, data) ->
return reject(err) if err
resolve(data.Instances)
error = (res, e) ->
res.robot.logger.error 'hubot-elb: error'
res.robot.logger.error e
res.send 'hubot-elb: error'
status = (res, account) ->
listELBs account
.then formatELBs
.then (message) ->
res.send message
.catch (e) ->
error res, e
robot.respond /elb\s+([-\w]+)$/i, (res) ->
accountId = res.match[1]
account = accounts[accountId]
return res.send("account #{accountId} is not found") unless account?
res.send 'elb status ' + accountId
status res, account
| true | # Description
# A Hubot script to manage the Elastic Load Balancing
#
# Configuration:
# HUBOT_ELB_ACCOUNTS
# HUBOT_ELB_<xxx>_ACCESS_KEY_ID
# HUBOT_ELB_<xxx>_SECRET_ACCESS_KEY
# HUBOT_ELB_<xxx>_REGION
#
# Commands:
# hubot elb <account> - list the ELB statuses
#
# Author:
# bouzuya <PI:EMAIL:<EMAIL>END_PI>
#
{Promise} = require 'es6-promise'
AWS = require 'aws-sdk'
Case = require 'case'
module.exports = (robot) ->
accounts = (process.env.HUBOT_ELB_ACCOUNTS || '')
.split ','
.filter (i) -> i.length > 0
.reduce (as, i) ->
as[i] = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'REGION'].reduce (a, j) ->
a[Case.camel(j)] = process.env['HUBOT_ELB_' + i.toUpperCase() + '_' + j]
a
, {}
as
, {}
formatELBs = (elbs) ->
loadBalancers = elbs.map (i) ->
instances = i.Instances.map (j) ->
" #{j.InstanceId}: #{j.State} (#{j.ReasonCode})"
"""
#{i.LoadBalancerName}:
#{instances.join('\n')}
"""
"""
ELBs:
#{loadBalancers.join('\n')}
"""
newClient = (account) ->
new AWS.ELB
apiVersion: '2012-06-01'
accessKeyId: account.accessKeyId
secretAccessKey: account.secretAccessKey
region: account.region ? 'ap-northeast-1'
listLoadBalancers = (client) ->
# promised describeLoadBalancers
new Promise (resolve, reject) ->
client.describeLoadBalancers {}, (err, data) ->
return reject(err) if err
resolve data.LoadBalancerDescriptions
listInstances = (client, elb) ->
# promised describeInstanceHealth
new Promise (resolve, reject) ->
params =
LoadBalancerName: elb.LoadBalancerName
Instances: elb.Instances.map (i) -> { InstanceId: i.InstanceId }
client.describeInstanceHealth params, (err, data) ->
return reject(err) if err
resolve(data.InstanceStates)
listELBs = (account) ->
# describeLoadBalancers & describeInstanceHealth
client = newClient account
listLoadBalancers client
.then (elbs) ->
# add instance statuses to elb.Instances
elbs.reduce(((promise, elb) ->
promise.then ->
listInstances client, elb
.then (result) ->
elb.Instances = elb.Instances.map (i) ->
result.filter((j) -> i.InstanceId is j.InstanceId)[0]
.then ->
elbs
), Promise.resolve())
deregisterInstances = (client, loadBalancerName, instances) ->
# promised deregisterInstancesFromLoadBalancer
new Promise (resolve, reject) ->
params =
Instances: instances.map (i) -> { InstanceId: i.InstanceId }
LoadBalancerName: loadBalancerName
client.deregisterInstancesFromLoadBalancer params, (err, data) ->
return reject(err) if err
resolve(data.Instances)
registerInstances = (client, loadBalancerName, instances) ->
# promised registerInstancesToLoadBalancer
new Promise (resolve, reject) ->
params =
Instances: instances.map (i) -> { InstanceId: i.InstanceId }
LoadBalancerName: loadBalancerName
client.registerInstancesWithLoadBalancer params, (err, data) ->
return reject(err) if err
resolve(data.Instances)
error = (res, e) ->
res.robot.logger.error 'hubot-elb: error'
res.robot.logger.error e
res.send 'hubot-elb: error'
status = (res, account) ->
listELBs account
.then formatELBs
.then (message) ->
res.send message
.catch (e) ->
error res, e
robot.respond /elb\s+([-\w]+)$/i, (res) ->
accountId = res.match[1]
account = accounts[accountId]
return res.send("account #{accountId} is not found") unless account?
res.send 'elb status ' + accountId
status res, account
|
[
{
"context": "chie[characterName]\n resourceKey = \"#{characterName}-#{tachieAlter}\"\n\n @newTachieResource = @app.resou",
"end": 675,
"score": 0.8278405666351318,
"start": 667,
"tag": "KEY",
"value": "Name}-#{"
},
{
"context": "\n resourceKey = \"#{characterName}-#{tachieA... | app/$elements/aurora-tachie/aurora-tachie.coffee | namiheike/aozora | 0 | Polymer
is: 'aurora-tachie'
behaviors: [
Aurora.behaviors.base
Polymer.NeonAnimationRunnerBehavior
]
properties:
tachie:
type: Object
observer: '_tachieChanged'
currentTachieResource:
type: Object
animationConfig:
value: ->
entry:
name: 'fade-in-animation'
node: @
exit:
name: 'fade-out-animation'
node: @
listeners:
'neon-animation-finish': '_onNeonAnimationFinish'
_tachieChanged: (newTachie, oldTachie) ->
# build resource name
characterName = Object.keys(@tachie)[0]
tachieAlter = @tachie[characterName]
resourceKey = "#{characterName}-#{tachieAlter}"
@newTachieResource = @app.resources.getResource('tachies', resourceKey)
if @newTachieResource isnt @currentTachieResource
if not @currentTachieResource?
@_setImageSrcAndfadeIn()
else
@_fadeOut()
_onNeonAnimationFinish: (e) ->
switch @_animationState
when 'fading_in'
@_animationState = undefined
# TODO notify other elements that animation is finished
when 'fading_out'
@_setImageSrcAndfadeIn()
_fadeOut: () ->
@_animationState = 'fading_out'
@playAnimation 'exit'
_fadeIn: () ->
@_animationState = 'fading_in'
@playAnimation 'entry'
_setImageSrcAndfadeIn: () ->
@currentTachieResource = @newTachieResource
@_fadeIn()
| 6320 | Polymer
is: 'aurora-tachie'
behaviors: [
Aurora.behaviors.base
Polymer.NeonAnimationRunnerBehavior
]
properties:
tachie:
type: Object
observer: '_tachieChanged'
currentTachieResource:
type: Object
animationConfig:
value: ->
entry:
name: 'fade-in-animation'
node: @
exit:
name: 'fade-out-animation'
node: @
listeners:
'neon-animation-finish': '_onNeonAnimationFinish'
_tachieChanged: (newTachie, oldTachie) ->
# build resource name
characterName = Object.keys(@tachie)[0]
tachieAlter = @tachie[characterName]
resourceKey = "#{character<KEY>tachieAlter<KEY>}"
@newTachieResource = @app.resources.getResource('tachies', resourceKey)
if @newTachieResource isnt @currentTachieResource
if not @currentTachieResource?
@_setImageSrcAndfadeIn()
else
@_fadeOut()
_onNeonAnimationFinish: (e) ->
switch @_animationState
when 'fading_in'
@_animationState = undefined
# TODO notify other elements that animation is finished
when 'fading_out'
@_setImageSrcAndfadeIn()
_fadeOut: () ->
@_animationState = 'fading_out'
@playAnimation 'exit'
_fadeIn: () ->
@_animationState = 'fading_in'
@playAnimation 'entry'
_setImageSrcAndfadeIn: () ->
@currentTachieResource = @newTachieResource
@_fadeIn()
| true | Polymer
is: 'aurora-tachie'
behaviors: [
Aurora.behaviors.base
Polymer.NeonAnimationRunnerBehavior
]
properties:
tachie:
type: Object
observer: '_tachieChanged'
currentTachieResource:
type: Object
animationConfig:
value: ->
entry:
name: 'fade-in-animation'
node: @
exit:
name: 'fade-out-animation'
node: @
listeners:
'neon-animation-finish': '_onNeonAnimationFinish'
_tachieChanged: (newTachie, oldTachie) ->
# build resource name
characterName = Object.keys(@tachie)[0]
tachieAlter = @tachie[characterName]
resourceKey = "#{characterPI:KEY:<KEY>END_PItachieAlterPI:KEY:<KEY>END_PI}"
@newTachieResource = @app.resources.getResource('tachies', resourceKey)
if @newTachieResource isnt @currentTachieResource
if not @currentTachieResource?
@_setImageSrcAndfadeIn()
else
@_fadeOut()
_onNeonAnimationFinish: (e) ->
switch @_animationState
when 'fading_in'
@_animationState = undefined
# TODO notify other elements that animation is finished
when 'fading_out'
@_setImageSrcAndfadeIn()
_fadeOut: () ->
@_animationState = 'fading_out'
@playAnimation 'exit'
_fadeIn: () ->
@_animationState = 'fading_in'
@playAnimation 'entry'
_setImageSrcAndfadeIn: () ->
@currentTachieResource = @newTachieResource
@_fadeIn()
|
[
{
"context": "& Debt\"\nlocation: \"Stockport\"\nphase: \"beta\"\nsro: \"Charu Gorasia\"\nservice_man: \"Gary Wainwright\"\nphase_history:\n ",
"end": 296,
"score": 0.9999008774757385,
"start": 283,
"tag": "NAME",
"value": "Charu Gorasia"
},
{
"context": "\nphase: \"beta\"\nsro: \"C... | app/data/projects/fraud-error-service-work-management.cson | tsmorgan/dwp-ux-work | 0 | id: 36
name: "Fraud and Error Service Work Management"
description: "Looking at how the Fraud and Error Service manage fraud, error and risk referrals, by improving business processes and the quality of interventions."
theme: "Fraud & Debt"
location: "Stockport"
phase: "beta"
sro: "Charu Gorasia"
service_man: "Gary Wainwright"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2016"
}
]
alpha: [
{
label: "Completed"
date: "July2016"
}
]
beta: [
{
label: "Started"
date: "August 2016"
}
]
priority: "Medium" | 20104 | id: 36
name: "Fraud and Error Service Work Management"
description: "Looking at how the Fraud and Error Service manage fraud, error and risk referrals, by improving business processes and the quality of interventions."
theme: "Fraud & Debt"
location: "Stockport"
phase: "beta"
sro: "<NAME>"
service_man: "<NAME>"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2016"
}
]
alpha: [
{
label: "Completed"
date: "July2016"
}
]
beta: [
{
label: "Started"
date: "August 2016"
}
]
priority: "Medium" | true | id: 36
name: "Fraud and Error Service Work Management"
description: "Looking at how the Fraud and Error Service manage fraud, error and risk referrals, by improving business processes and the quality of interventions."
theme: "Fraud & Debt"
location: "Stockport"
phase: "beta"
sro: "PI:NAME:<NAME>END_PI"
service_man: "PI:NAME:<NAME>END_PI"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2016"
}
]
alpha: [
{
label: "Completed"
date: "July2016"
}
]
beta: [
{
label: "Started"
date: "August 2016"
}
]
priority: "Medium" |
[
{
"context": "*\n * This personality does nothing.\n *\n * @name Overkiller\n * @prerequisite Deal 5000 damage in one hit\n ",
"end": 108,
"score": 0.6964206695556641,
"start": 100,
"tag": "NAME",
"value": "Overkill"
},
{
"context": "s personality does nothing.\n *\n * @name Ov... | src/character/personalities/Overkiller.coffee | sadbear-/IdleLands | 3 |
Personality = require "../base/Personality"
`/**
* This personality does nothing.
*
* @name Overkiller
* @prerequisite Deal 5000 damage in one hit
* @category Personalities
* @package Player
*/`
class Overkiller extends Personality
constructor: ->
@canUse = (player) ->
player.statistics["calculated max damage given"] > 5000
@desc = "Deal 5000 damage in one hit"
module.exports = exports = Overkiller
| 78047 |
Personality = require "../base/Personality"
`/**
* This personality does nothing.
*
* @name <NAME> <NAME>
* @prerequisite Deal 5000 damage in one hit
* @category Personalities
* @package Player
*/`
class Overkiller extends Personality
constructor: ->
@canUse = (player) ->
player.statistics["calculated max damage given"] > 5000
@desc = "Deal 5000 damage in one hit"
module.exports = exports = Overkiller
| true |
Personality = require "../base/Personality"
`/**
* This personality does nothing.
*
* @name PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
* @prerequisite Deal 5000 damage in one hit
* @category Personalities
* @package Player
*/`
class Overkiller extends Personality
constructor: ->
@canUse = (player) ->
player.statistics["calculated max damage given"] > 5000
@desc = "Deal 5000 damage in one hit"
module.exports = exports = Overkiller
|
[
{
"context": "tor mode, changing the MAC address, etc.\n# Author: Robbie Saunders http://eibbors.com/[/p/reavetard]\n# =============",
"end": 234,
"score": 0.9998723268508911,
"start": 219,
"tag": "NAME",
"value": "Robbie Saunders"
},
{
"context": " else if attcat?.length is 3... | src/wifi.coffee | eibbors/reavetard | 1 | # Reavetard - Reaver WPS (+Wash) extension scripts
# wifi.coffee :: Overly complicated module to automate various wifi adapter tasks
# such as enabling/disabling monitor mode, changing the MAC address, etc.
# Author: Robbie Saunders http://eibbors.com/[/p/reavetard]
# ==============================================================================
# Module dependencies
# -------------------------
{exec} = require 'child_process'
cli = require './cli'
# airmon-ng commands to start, stop, and check wlan adapter monitor mode
# ----------------------------------------------------------------------
airmon = exports.airmon =
# Execute airmon-ng + args and call back fancy parsed output
run: (args, cb) ->
if Array.isArray(args) then args = args.join ' '
if args then cmd = "airmon-ng #{args}" else cmd = "airmon-ng"
exec cmd, {}, (err, stdout, stderr) =>
isIfaces = false
results = {}
if err then throw(err)
else if stdout
for section in stdout.split('\n\n')
lines = section.split('\n')
# Possible problem processes included in output
if lines[0] is 'PID\tName'
results.processes = {}
for line in lines[1..]
proc = /(\d+)\t(\w+)/.exec line
if proc then results.processes[proc[1]] = { pid: proc[1], name: proc[2] }
else
oniface = /Process with PID (\d+) \((.*)\) is running on interface (.*)/.exec line
if oniface then results.processes[oniface[1]].runningOn = oniface[3]
# Grab interfaces, should there be any (these columns are always one section before)
if /Interface\tChipset\t\tDriver/g.test section
isIfaces = true
else if isIfaces
isIfaces = false
results.interfaces = []
for line in lines
# This regex was hard on my eyes for some reason, so I split it up into parts
ifrow = ///
([^\t]+)\t+
([^\t]+)\t+
(\w+)\s-\s
\[(\w+)\]
(\s+\(removed\))?///.exec line
if ifrow then results.interfaces.push
interface: ifrow[1]
chipset: ifrow[2]
driver: ifrow[3]
phyid: ifrow[4]
removed: ifrow[5] is ' (removed)'
else
monok = /\s+\(monitor mode enabled on (\w+)\)/.exec line
if monok then results.enabledOn = monok[1]
cb results, stdout, stderr
# Run with no arguments, used to search for all compatible ifaces
getInterfaces: (cb) ->
@run undefined, (res) ->
cb res.interfaces
# Return results of above, categorized by phyical name ie:
# { phy0: [{mon0}, {wlan2}], phy1: [{wlan1}] }
# Useful for determining which cards aren't yet in monitor mode
getPhysicalInterfaces: (cb) ->
@getInterfaces (ifaces) ->
phys = {}
for iface in ifaces
phys[iface.phyid] ?= []
phys[iface.phyid].push iface
cb phys
# Start monitor mode on an interface, return parsed results via callback
# Optionally, restrict monitor mode to a single channel with channel arg
start: (iface, cb, channel=false) ->
cmd = ['start', iface]
if channel then cmd.push channel
@run cmd, (res) ->
if res.enabledOn?.length > 0
res.success = true
else
res.success = false
cb res
# Stop monitor mode
stop: (iface, cb) ->
@run ['stop', iface], (res) ->
res.success = false
for iface in res.interfaces
if iface.removed then res.success = true
cb res
# Check for possible `problem processes`
check: (cb) ->
@run ['check'], cb
# Try to kill the processes returned by check/start
kill: (cb) ->
@run ['check', 'kill'], cb
# iwconfig command - view/edit wireless adapter settings,
# ----------------------------------------------------------------------
iwconfig = exports.iwconfig =
# Execute iwconfig and call your cb function with its parsed output
run: (args, cb) =>
if Array.isArray(args) then args = args.join ' '
if args then cmd = "iwconfig #{args}" else cmd = 'iwconfig'
exec cmd, {}, (err, stdout, stderr) =>
if err then return cb err, false
interfaces = []
# Split by 2 newlines (with(out) spaces too) in a row
sections = stdout.split /\n\s*\n/
for section in sections
# Parse the iface & supported 802.11 standards / "field-like" strings
iwname = /(\w+)\s+IEEE 802\.11(\w+)/.exec section
iwflds = section.match /\s\s+((\S+\s?)+)(:|=)\s?((\S+\s?)+)/g
if iwname # Once we know its name we need to rename and trim our fields
iwtmp = { name: iwname[1], supports: iwname[2].split('') }
for flds in iwflds
fld = flds.split(/(:|=)/)
if fld.length > 3 # Fixes Access Point Bssid, which contains :'s
fld[2] = fld[2..].join('')
fld[0] = fld[0].replace('-', ' ').trim()
fld[0] = fld[0].toLowerCase().replace(/(\s+\w)/g, (m) -> m.trim().toUpperCase())
fld[2] = fld[2].trim()
iwtmp[fld[0]] = fld[2]
interfaces.push iwtmp
cb err, interfaces
# Same as running with no args, but can be used to check for the existence of
# or simply to filter out a single interface
checkWifiSetup: (iface, cb) ->
if iface
@run '', (err, interfaces) ->
for i in interfaces
if i.name is iface
return cb err, i
cb "Error: Interface #{iface} not found!", false
else
@run '', cb
# ifconfig - commands for configuring network interfaces
# ----------------------------------------------------------------------
ifconfig = exports.ifconfig =
# Execute ifconfig and parse the output... the output that seems horribly
# inconsistently formatted. If I'm missing a pattern or trick to handling
# all the different possibilities besides hardcoding them one by one as
# I'm currently doing, please enlighten me!
run: (args, cb) =>
if Array.isArray(args) then args = args.join ' '
if args then cmd = "ifconfig #{args}" else cmd = 'ifconfig'
exec cmd, {}, (err, stdout, stderr) =>
if err then return cb err, false
interfaces = []
# Split by 2 newlines (with(out) spaces too) in a row
sections = stdout.split /\n\s*\n/
for section in sections
lines = section.split '\n'
for line in lines
decl = /^(\w+)\s+Link encap:((\s?\w+)+) (HWaddr (\S+) )?/i.exec line
if decl # Fairly straightforward
if lastiface? then interfaces.push lastiface
lastiface = { name: decl[1], type: decl[2], mac: decl[5] }
decl = false
else # I have to be missing a trick... Please clean me up!
pieces = line.split(/\s\s+/)
for piece in pieces[1..]
attrs = piece.match(/(RX |TX |inet |inet6 )?((\S+):\s?(\S+))+/g)
if attrs?.length? >= 1
attcat = attrs[0].split(' ')
if attcat?.length is 1 # RX ...\n {child:val} || {Normal:val}
ischild = /^([a-z]+):(.*)/g.exec attcat[0]
if ischild and lastcat
lastiface[lastcat][ischild[1]] = ischild[2]
ismore = attrs[1].split ':'
if ismore.length > 1
lastiface[lastcat][ismore[0]] = ismore[1]
else
attr = attcat[0].split(':')
lastiface[attr[0]] = attr[1]
else if attcat?.length is 2 # RX/TX/inet(6) a:1 b:2 ...
lastcat = attcat[0]
attr = attcat[1].split(':')
lastiface[lastcat] ?= {}
lastiface[lastcat][attr[0]] = attr[attr.length - 1]
for attr in attrs[1..]
attr = attr.split(':')
lastiface[lastcat][attr[0]] = attr[attr.length - 1]
else if attcat?.length is 3 # inet6 addr: 121:14:14:...
lastcat = attcat[0]
lastiface[lastcat] ?= {}
lastiface[lastcat][attcat[1].replace(':','')] = attcat[2]
else
if /([A-Z]+ ?)+/g.test piece
lastiface.flags = piece.split(' ')
interfaces.push lastiface # push the final interface
cb err, interfaces
all: (cb) ->
@run '-a', cb
up: (iface, cb) ->
@run "#{iface} up", (err) ->
if err then cb err, false
else cb null, true
down: (iface, cb) ->
@run "#{iface} down", (err) ->
if err then cb err, false
else cb null, true
| 30198 | # Reavetard - Reaver WPS (+Wash) extension scripts
# wifi.coffee :: Overly complicated module to automate various wifi adapter tasks
# such as enabling/disabling monitor mode, changing the MAC address, etc.
# Author: <NAME> http://eibbors.com/[/p/reavetard]
# ==============================================================================
# Module dependencies
# -------------------------
{exec} = require 'child_process'
cli = require './cli'
# airmon-ng commands to start, stop, and check wlan adapter monitor mode
# ----------------------------------------------------------------------
airmon = exports.airmon =
# Execute airmon-ng + args and call back fancy parsed output
run: (args, cb) ->
if Array.isArray(args) then args = args.join ' '
if args then cmd = "airmon-ng #{args}" else cmd = "airmon-ng"
exec cmd, {}, (err, stdout, stderr) =>
isIfaces = false
results = {}
if err then throw(err)
else if stdout
for section in stdout.split('\n\n')
lines = section.split('\n')
# Possible problem processes included in output
if lines[0] is 'PID\tName'
results.processes = {}
for line in lines[1..]
proc = /(\d+)\t(\w+)/.exec line
if proc then results.processes[proc[1]] = { pid: proc[1], name: proc[2] }
else
oniface = /Process with PID (\d+) \((.*)\) is running on interface (.*)/.exec line
if oniface then results.processes[oniface[1]].runningOn = oniface[3]
# Grab interfaces, should there be any (these columns are always one section before)
if /Interface\tChipset\t\tDriver/g.test section
isIfaces = true
else if isIfaces
isIfaces = false
results.interfaces = []
for line in lines
# This regex was hard on my eyes for some reason, so I split it up into parts
ifrow = ///
([^\t]+)\t+
([^\t]+)\t+
(\w+)\s-\s
\[(\w+)\]
(\s+\(removed\))?///.exec line
if ifrow then results.interfaces.push
interface: ifrow[1]
chipset: ifrow[2]
driver: ifrow[3]
phyid: ifrow[4]
removed: ifrow[5] is ' (removed)'
else
monok = /\s+\(monitor mode enabled on (\w+)\)/.exec line
if monok then results.enabledOn = monok[1]
cb results, stdout, stderr
# Run with no arguments, used to search for all compatible ifaces
getInterfaces: (cb) ->
@run undefined, (res) ->
cb res.interfaces
# Return results of above, categorized by phyical name ie:
# { phy0: [{mon0}, {wlan2}], phy1: [{wlan1}] }
# Useful for determining which cards aren't yet in monitor mode
getPhysicalInterfaces: (cb) ->
@getInterfaces (ifaces) ->
phys = {}
for iface in ifaces
phys[iface.phyid] ?= []
phys[iface.phyid].push iface
cb phys
# Start monitor mode on an interface, return parsed results via callback
# Optionally, restrict monitor mode to a single channel with channel arg
start: (iface, cb, channel=false) ->
cmd = ['start', iface]
if channel then cmd.push channel
@run cmd, (res) ->
if res.enabledOn?.length > 0
res.success = true
else
res.success = false
cb res
# Stop monitor mode
stop: (iface, cb) ->
@run ['stop', iface], (res) ->
res.success = false
for iface in res.interfaces
if iface.removed then res.success = true
cb res
# Check for possible `problem processes`
check: (cb) ->
@run ['check'], cb
# Try to kill the processes returned by check/start
kill: (cb) ->
@run ['check', 'kill'], cb
# iwconfig command - view/edit wireless adapter settings,
# ----------------------------------------------------------------------
iwconfig = exports.iwconfig =
# Execute iwconfig and call your cb function with its parsed output
run: (args, cb) =>
if Array.isArray(args) then args = args.join ' '
if args then cmd = "iwconfig #{args}" else cmd = 'iwconfig'
exec cmd, {}, (err, stdout, stderr) =>
if err then return cb err, false
interfaces = []
# Split by 2 newlines (with(out) spaces too) in a row
sections = stdout.split /\n\s*\n/
for section in sections
# Parse the iface & supported 802.11 standards / "field-like" strings
iwname = /(\w+)\s+IEEE 802\.11(\w+)/.exec section
iwflds = section.match /\s\s+((\S+\s?)+)(:|=)\s?((\S+\s?)+)/g
if iwname # Once we know its name we need to rename and trim our fields
iwtmp = { name: iwname[1], supports: iwname[2].split('') }
for flds in iwflds
fld = flds.split(/(:|=)/)
if fld.length > 3 # Fixes Access Point Bssid, which contains :'s
fld[2] = fld[2..].join('')
fld[0] = fld[0].replace('-', ' ').trim()
fld[0] = fld[0].toLowerCase().replace(/(\s+\w)/g, (m) -> m.trim().toUpperCase())
fld[2] = fld[2].trim()
iwtmp[fld[0]] = fld[2]
interfaces.push iwtmp
cb err, interfaces
# Same as running with no args, but can be used to check for the existence of
# or simply to filter out a single interface
checkWifiSetup: (iface, cb) ->
if iface
@run '', (err, interfaces) ->
for i in interfaces
if i.name is iface
return cb err, i
cb "Error: Interface #{iface} not found!", false
else
@run '', cb
# ifconfig - commands for configuring network interfaces
# ----------------------------------------------------------------------
ifconfig = exports.ifconfig =
# Execute ifconfig and parse the output... the output that seems horribly
# inconsistently formatted. If I'm missing a pattern or trick to handling
# all the different possibilities besides hardcoding them one by one as
# I'm currently doing, please enlighten me!
run: (args, cb) =>
if Array.isArray(args) then args = args.join ' '
if args then cmd = "ifconfig #{args}" else cmd = 'ifconfig'
exec cmd, {}, (err, stdout, stderr) =>
if err then return cb err, false
interfaces = []
# Split by 2 newlines (with(out) spaces too) in a row
sections = stdout.split /\n\s*\n/
for section in sections
lines = section.split '\n'
for line in lines
decl = /^(\w+)\s+Link encap:((\s?\w+)+) (HWaddr (\S+) )?/i.exec line
if decl # Fairly straightforward
if lastiface? then interfaces.push lastiface
lastiface = { name: decl[1], type: decl[2], mac: decl[5] }
decl = false
else # I have to be missing a trick... Please clean me up!
pieces = line.split(/\s\s+/)
for piece in pieces[1..]
attrs = piece.match(/(RX |TX |inet |inet6 )?((\S+):\s?(\S+))+/g)
if attrs?.length? >= 1
attcat = attrs[0].split(' ')
if attcat?.length is 1 # RX ...\n {child:val} || {Normal:val}
ischild = /^([a-z]+):(.*)/g.exec attcat[0]
if ischild and lastcat
lastiface[lastcat][ischild[1]] = ischild[2]
ismore = attrs[1].split ':'
if ismore.length > 1
lastiface[lastcat][ismore[0]] = ismore[1]
else
attr = attcat[0].split(':')
lastiface[attr[0]] = attr[1]
else if attcat?.length is 2 # RX/TX/inet(6) a:1 b:2 ...
lastcat = attcat[0]
attr = attcat[1].split(':')
lastiface[lastcat] ?= {}
lastiface[lastcat][attr[0]] = attr[attr.length - 1]
for attr in attrs[1..]
attr = attr.split(':')
lastiface[lastcat][attr[0]] = attr[attr.length - 1]
else if attcat?.length is 3 # inet6 addr: 121:14:14:...
lastcat = attcat[0]
lastiface[lastcat] ?= {}
lastiface[lastcat][attcat[1].replace(':','')] = attcat[2]
else
if /([A-Z]+ ?)+/g.test piece
lastiface.flags = piece.split(' ')
interfaces.push lastiface # push the final interface
cb err, interfaces
all: (cb) ->
@run '-a', cb
up: (iface, cb) ->
@run "#{iface} up", (err) ->
if err then cb err, false
else cb null, true
down: (iface, cb) ->
@run "#{iface} down", (err) ->
if err then cb err, false
else cb null, true
| true | # Reavetard - Reaver WPS (+Wash) extension scripts
# wifi.coffee :: Overly complicated module to automate various wifi adapter tasks
# such as enabling/disabling monitor mode, changing the MAC address, etc.
# Author: PI:NAME:<NAME>END_PI http://eibbors.com/[/p/reavetard]
# ==============================================================================
# Module dependencies
# -------------------------
{exec} = require 'child_process'
cli = require './cli'
# airmon-ng commands to start, stop, and check wlan adapter monitor mode
# ----------------------------------------------------------------------
airmon = exports.airmon =
# Execute airmon-ng + args and call back fancy parsed output
run: (args, cb) ->
if Array.isArray(args) then args = args.join ' '
if args then cmd = "airmon-ng #{args}" else cmd = "airmon-ng"
exec cmd, {}, (err, stdout, stderr) =>
isIfaces = false
results = {}
if err then throw(err)
else if stdout
for section in stdout.split('\n\n')
lines = section.split('\n')
# Possible problem processes included in output
if lines[0] is 'PID\tName'
results.processes = {}
for line in lines[1..]
proc = /(\d+)\t(\w+)/.exec line
if proc then results.processes[proc[1]] = { pid: proc[1], name: proc[2] }
else
oniface = /Process with PID (\d+) \((.*)\) is running on interface (.*)/.exec line
if oniface then results.processes[oniface[1]].runningOn = oniface[3]
# Grab interfaces, should there be any (these columns are always one section before)
if /Interface\tChipset\t\tDriver/g.test section
isIfaces = true
else if isIfaces
isIfaces = false
results.interfaces = []
for line in lines
# This regex was hard on my eyes for some reason, so I split it up into parts
ifrow = ///
([^\t]+)\t+
([^\t]+)\t+
(\w+)\s-\s
\[(\w+)\]
(\s+\(removed\))?///.exec line
if ifrow then results.interfaces.push
interface: ifrow[1]
chipset: ifrow[2]
driver: ifrow[3]
phyid: ifrow[4]
removed: ifrow[5] is ' (removed)'
else
monok = /\s+\(monitor mode enabled on (\w+)\)/.exec line
if monok then results.enabledOn = monok[1]
cb results, stdout, stderr
# Run with no arguments, used to search for all compatible ifaces
getInterfaces: (cb) ->
@run undefined, (res) ->
cb res.interfaces
# Return results of above, categorized by phyical name ie:
# { phy0: [{mon0}, {wlan2}], phy1: [{wlan1}] }
# Useful for determining which cards aren't yet in monitor mode
getPhysicalInterfaces: (cb) ->
@getInterfaces (ifaces) ->
phys = {}
for iface in ifaces
phys[iface.phyid] ?= []
phys[iface.phyid].push iface
cb phys
# Start monitor mode on an interface, return parsed results via callback
# Optionally, restrict monitor mode to a single channel with channel arg
start: (iface, cb, channel=false) ->
cmd = ['start', iface]
if channel then cmd.push channel
@run cmd, (res) ->
if res.enabledOn?.length > 0
res.success = true
else
res.success = false
cb res
# Stop monitor mode
stop: (iface, cb) ->
@run ['stop', iface], (res) ->
res.success = false
for iface in res.interfaces
if iface.removed then res.success = true
cb res
# Check for possible `problem processes`
check: (cb) ->
@run ['check'], cb
# Try to kill the processes returned by check/start
kill: (cb) ->
@run ['check', 'kill'], cb
# iwconfig command - view/edit wireless adapter settings,
# ----------------------------------------------------------------------
iwconfig = exports.iwconfig =
# Execute iwconfig and call your cb function with its parsed output
run: (args, cb) =>
if Array.isArray(args) then args = args.join ' '
if args then cmd = "iwconfig #{args}" else cmd = 'iwconfig'
exec cmd, {}, (err, stdout, stderr) =>
if err then return cb err, false
interfaces = []
# Split by 2 newlines (with(out) spaces too) in a row
sections = stdout.split /\n\s*\n/
for section in sections
# Parse the iface & supported 802.11 standards / "field-like" strings
iwname = /(\w+)\s+IEEE 802\.11(\w+)/.exec section
iwflds = section.match /\s\s+((\S+\s?)+)(:|=)\s?((\S+\s?)+)/g
if iwname # Once we know its name we need to rename and trim our fields
iwtmp = { name: iwname[1], supports: iwname[2].split('') }
for flds in iwflds
fld = flds.split(/(:|=)/)
if fld.length > 3 # Fixes Access Point Bssid, which contains :'s
fld[2] = fld[2..].join('')
fld[0] = fld[0].replace('-', ' ').trim()
fld[0] = fld[0].toLowerCase().replace(/(\s+\w)/g, (m) -> m.trim().toUpperCase())
fld[2] = fld[2].trim()
iwtmp[fld[0]] = fld[2]
interfaces.push iwtmp
cb err, interfaces
# Same as running with no args, but can be used to check for the existence of
# or simply to filter out a single interface
checkWifiSetup: (iface, cb) ->
if iface
@run '', (err, interfaces) ->
for i in interfaces
if i.name is iface
return cb err, i
cb "Error: Interface #{iface} not found!", false
else
@run '', cb
# ifconfig - commands for configuring network interfaces
# ----------------------------------------------------------------------
ifconfig = exports.ifconfig =
# Execute ifconfig and parse the output... the output that seems horribly
# inconsistently formatted. If I'm missing a pattern or trick to handling
# all the different possibilities besides hardcoding them one by one as
# I'm currently doing, please enlighten me!
run: (args, cb) =>
if Array.isArray(args) then args = args.join ' '
if args then cmd = "ifconfig #{args}" else cmd = 'ifconfig'
exec cmd, {}, (err, stdout, stderr) =>
if err then return cb err, false
interfaces = []
# Split by 2 newlines (with(out) spaces too) in a row
sections = stdout.split /\n\s*\n/
for section in sections
lines = section.split '\n'
for line in lines
decl = /^(\w+)\s+Link encap:((\s?\w+)+) (HWaddr (\S+) )?/i.exec line
if decl # Fairly straightforward
if lastiface? then interfaces.push lastiface
lastiface = { name: decl[1], type: decl[2], mac: decl[5] }
decl = false
else # I have to be missing a trick... Please clean me up!
pieces = line.split(/\s\s+/)
for piece in pieces[1..]
attrs = piece.match(/(RX |TX |inet |inet6 )?((\S+):\s?(\S+))+/g)
if attrs?.length? >= 1
attcat = attrs[0].split(' ')
if attcat?.length is 1 # RX ...\n {child:val} || {Normal:val}
ischild = /^([a-z]+):(.*)/g.exec attcat[0]
if ischild and lastcat
lastiface[lastcat][ischild[1]] = ischild[2]
ismore = attrs[1].split ':'
if ismore.length > 1
lastiface[lastcat][ismore[0]] = ismore[1]
else
attr = attcat[0].split(':')
lastiface[attr[0]] = attr[1]
else if attcat?.length is 2 # RX/TX/inet(6) a:1 b:2 ...
lastcat = attcat[0]
attr = attcat[1].split(':')
lastiface[lastcat] ?= {}
lastiface[lastcat][attr[0]] = attr[attr.length - 1]
for attr in attrs[1..]
attr = attr.split(':')
lastiface[lastcat][attr[0]] = attr[attr.length - 1]
else if attcat?.length is 3 # inet6 addr: 121:14:14:...
lastcat = attcat[0]
lastiface[lastcat] ?= {}
lastiface[lastcat][attcat[1].replace(':','')] = attcat[2]
else
if /([A-Z]+ ?)+/g.test piece
lastiface.flags = piece.split(' ')
interfaces.push lastiface # push the final interface
cb err, interfaces
all: (cb) ->
@run '-a', cb
up: (iface, cb) ->
@run "#{iface} up", (err) ->
if err then cb err, false
else cb null, true
down: (iface, cb) ->
@run "#{iface} down", (err) ->
if err then cb err, false
else cb null, true
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9922372102737427,
"start": 16,
"tag": "NAME",
"value": "Konode"
},
{
"context": "\t\t\t\t\t\tR.br(), R.br(),\n\t\t\t\t\t\tR.input({\n\t\t\t\t\t\t\tid: \"username\",\n\t\t\t... | src/loginPage.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Window for user login -> account validation, with detection for setup/migrations
Async = require 'async'
Fs = require 'fs'
Path = require 'path'
Semver = require 'semver'
Config = require './config'
Persist = require './persist'
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
Window = nw.Window.get(win)
CrashHandler = require('./crashHandler').load(win)
Spinner = require('./spinner').load(win)
{openWindow} = require('./utils').load(win)
LoginPage = React.createFactory React.createClass
displayName: 'LoginPage'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
isSetUp: null
isLoading: false
}
init: ->
if Config.logoSubtitle
@props.setWindowTitle("#{Config.logoSubtitle} - #{Config.productName}")
@_checkSetUp()
deinit: (cb=(->)) ->
@setState {isLoading: false}, cb
suggestClose: ->
@props.closeWindow()
render: ->
unless @state.isSetUp
return null
LoginPageUi({
ref: 'ui'
isLoading: @state.isLoading
loadingMessage: @state.loadingMessage
checkVersionsMatch: @_checkVersionsMatch
login: @_login
})
_checkSetUp: ->
# Check to make sure the dataDir exists and has an account system
Persist.Users.isAccountSystemSetUp Config.backend, (err, isSetUp) =>
if err
if err instanceof Persist.IOError
Bootbox.alert """
Sorry, we're unable to reach the database.
Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
if isSetUp
# Already set up, no need to continue here
@setState {
isSetUp: true
}
return
# Falsy isSetUp triggers NewInstallationPage
@setState {isSetUp: false}
@props.navigateTo {page:'newInstallation'}
_checkVersionsMatch: ->
dataDir = Config.backend.dataDirectory
appVersion = nw.App.manifest.version
# Read DB's version file, compare against app version
Fs.readFile Path.join(dataDir, 'version.json'), (err, result) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
dbVersion = JSON.parse(result).dataVersion
# Launch migration dialog if mismatched versions
if Semver.lt(dbVersion, appVersion)
console.log "data version less than app version. Migration required"
@_showMigrationDialog(dbVersion, appVersion)
else if Semver.gt(dbVersion, appVersion)
console.log "Warning! Data version newer than app version"
$ =>
Bootbox.dialog {
title: "Database Error"
message: R.div({},
"The application cannot start because your database appears to be from a newer version of #{Config.productName}.",
R.br(), R.br(),
"You must upgrade #{Config.productName} from v#{appVersion} to v#{dbVersion} or greater to continue."
)
closeButton: false
buttons: {
cancel: {
label: "OK"
className: 'btn-primary'
callback: =>
@props.closeWindow()
}
}
}
_showMigrationDialog: (dbVersion, appVersion) ->
$ =>
Bootbox.dialog {
title: "Database Migration Required"
message: R.div({},
"Your database is from an earlier version of #{Config.productName} (v#{dbVersion}), so a migration is required.",
"To update the database to v#{appVersion}, please log in with an administrator account:",
R.br(), R.br(),
R.input({
id: "username",
name: "username",
type: "text",
placeholder: "username",
className: "form-control input-md",
}),
R.br(),
R.input({
id: "password"
name: "password"
type: "password"
placeholder: "password"
className: "form-control input-md"
}),
R.br()
)
closeButton: false
buttons: {
cancel: {
label: "Cancel"
className: 'btn-default'
callback: =>
@props.closeWindow()
}
continue: {
label: "Continue"
className: 'btn-primary'
callback: =>
# passing a string to the migrate function if the fields are left empty
# this lets the existing error conditions handle empty fields.
username = $('#username').val() or ' '
password = $('#password').val() or ' '
@_migrateToLatestVersion(username, password, dbVersion)
}
}
}
# Focus first field
# bootbox focuses primary button by default
setTimeout(->
$('#username').focus()
, 500)
_migrateToLatestVersion: (username, password, currentVersion) ->
Migration = require './migrations'
dataDir = Config.backend.dataDirectory
destinationVersion = nw.App.manifest.version
Async.series [
(cb) =>
@setState {isLoading: true, loadingMessage: "Migrating Database..."}, cb
(cb) =>
Migration.atomicMigration dataDir, currentVersion, destinationVersion, username, password, cb
], (err) =>
@setState {isLoading: false, loadingMessage: ""}
# ToDo: handle case where migration file is not found
if err
if err instanceof Persist.Session.AccountTypeError
@refs.ui.onLoginError('AccountTypeError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.UnknownUserNameError
@refs.ui.onLoginError('UnknownUserNameError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.InvalidUserNameError
@refs.ui.onLoginError('InvalidUserNameError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.IncorrectPasswordError
@refs.ui.onLoginError('IncorrectPasswordError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.DeactivatedAccountError
@refs.ui.onLoginError('DeactivatedAccountError', @_checkVersionsMatch)
return
if err instanceof Persist.IOError
@refs.ui.onLoginError('IOError', @_checkVersionsMatch)
return
CrashHandler.handle err
return
# Migrations were successful!
Bootbox.alert "The data file has been successfully migrated to the app version. Please log in to continue."
_login: (userName, password) ->
Async.series [
(cb) =>
@setState {isLoading: true, loadingMessage: "Authenticating..."}, cb
(cb) =>
# Create session
Persist.Session.login userName, password, Config.backend, (err, session) =>
if err
cb err
return
# Store the session globally
global.ActiveSession = session
cb()
(cb) =>
openWindow {page: 'clientSelection'}, (newWindow) =>
clientSelectionPageWindow = newWindow
Window.hide()
clientSelectionPageWindow.on 'closed', =>
@props.closeWindow()
Window.quit()
# Finish series and hide loginPage once loaded event fires
global.ActiveSession.persist.eventBus.once 'clientSelectionPage:loaded', cb
], (err) =>
@setState {isLoading: false, loadingMessage: ""}
if err
if err instanceof Persist.Session.UnknownUserNameError
@refs.ui.onLoginError('UnknownUserNameError')
return
if err instanceof Persist.Session.InvalidUserNameError
@refs.ui.onLoginError('InvalidUserNameError')
return
if err instanceof Persist.Session.IncorrectPasswordError
@refs.ui.onLoginError('IncorrectPasswordError')
return
if err instanceof Persist.Session.DeactivatedAccountError
@refs.ui.onLoginError('DeactivatedAccountError')
return
if err instanceof Persist.IOError
@refs.ui.onLoginError('IOError')
return
CrashHandler.handle err
return
LoginPageUi = React.createFactory React.createClass
displayName: 'LoginPageUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
userName: ''
password: ''
}
componentDidMount: ->
@props.checkVersionsMatch()
Persist.initializeCrypto()
onLoginError: (type, cb=(->)) ->
switch type
when 'AccountTypeError'
Bootbox.alert "This user is not an Admin. Please try again.", =>
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'UnknownUserNameError'
Bootbox.alert "Unknown user name. Please try again.", =>
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'InvalidUserNameError'
Bootbox.alert "Invalid user name. Please try again.", =>
@refs.userNameField.focus()
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'IncorrectPasswordError'
Bootbox.alert "Incorrect password. Please try again.", =>
@setState {password: ''}
setTimeout(=>
@refs.passwordField.focus()
, 100)
cb()
when 'DeactivatedAccountError'
Bootbox.alert "This user account has been deactivated.", =>
@refs.userNameField.focus()
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'IOError'
Bootbox.alert "Please check your network connection and try again.", cb
else
throw new Error "Invalid Login Error"
render: ->
return R.div({className: 'loginPage'},
Spinner({
isVisible: @props.isLoading
isOverlay: true
message: @props.loadingMessage
})
R.div({id: "loginForm"},
R.div({
id: 'logoContainer'
className: 'animated fadeInDown'
},
R.img({
className: 'animated rotateIn'
src: 'img/konode-kn.svg'
})
)
R.div({className: 'subtitleContainer'},
R.div({
className: 'subtitleText'
style: {color: Config.logoSubtitleColor}
},
Config.logoSubtitle
)
(if not Config.logoSubtitle
R.div({className: 'versionNumber'},
"v" + nw.App.manifest.version
)
)
)
R.div({
id: 'formContainer'
className: 'animated fadeInUp'
},
R.div({className: 'form-group'},
R.input({
className: 'form-control'
autoFocus: true
ref: 'userNameField'
onChange: @_updateUserName
onKeyDown: @_onEnterKeyDown
value: @state.userName
type: 'text'
placeholder: 'Username'
autoComplete: 'off'
})
)
R.div({className: 'form-group'},
R.input({
className: 'form-control'
type: 'password'
ref: 'passwordField'
onChange: @_updatePassword
onKeyDown: @_onEnterKeyDown
value: @state.password
placeholder: 'Password'
autoComplete: 'off'
})
)
R.div({className: 'btn-toolbar'},
## TODO: Password reminder
# R.button({
# className: 'btn btn-link'
# onClick: @_forgotPassword
# }, "Forgot Password?")
R.button({
className: [
'btn'
if @_formIsInvalid() then 'btn-primary' else 'btn-success animated pulse'
].join ' '
type: 'submit'
disabled: @_formIsInvalid()
onClick: @_login
}, "Sign in")
)
)
)
)
_quit: ->
win.close(true)
_updateUserName: (event) ->
@setState {userName: event.target.value}
_updatePassword: (event) ->
@setState {password: event.target.value}
_onEnterKeyDown: (event) ->
@_login() if event.which is 13 and not @_formIsInvalid()
_formIsInvalid: ->
not @state.userName or not @state.password
_login: (event) ->
@props.login(@state.userName.split('@')[0], @state.password)
return LoginPage
module.exports = {load}
| 94256 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Window for user login -> account validation, with detection for setup/migrations
Async = require 'async'
Fs = require 'fs'
Path = require 'path'
Semver = require 'semver'
Config = require './config'
Persist = require './persist'
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
Window = nw.Window.get(win)
CrashHandler = require('./crashHandler').load(win)
Spinner = require('./spinner').load(win)
{openWindow} = require('./utils').load(win)
LoginPage = React.createFactory React.createClass
displayName: 'LoginPage'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
isSetUp: null
isLoading: false
}
init: ->
if Config.logoSubtitle
@props.setWindowTitle("#{Config.logoSubtitle} - #{Config.productName}")
@_checkSetUp()
deinit: (cb=(->)) ->
@setState {isLoading: false}, cb
suggestClose: ->
@props.closeWindow()
render: ->
unless @state.isSetUp
return null
LoginPageUi({
ref: 'ui'
isLoading: @state.isLoading
loadingMessage: @state.loadingMessage
checkVersionsMatch: @_checkVersionsMatch
login: @_login
})
_checkSetUp: ->
# Check to make sure the dataDir exists and has an account system
Persist.Users.isAccountSystemSetUp Config.backend, (err, isSetUp) =>
if err
if err instanceof Persist.IOError
Bootbox.alert """
Sorry, we're unable to reach the database.
Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
if isSetUp
# Already set up, no need to continue here
@setState {
isSetUp: true
}
return
# Falsy isSetUp triggers NewInstallationPage
@setState {isSetUp: false}
@props.navigateTo {page:'newInstallation'}
_checkVersionsMatch: ->
dataDir = Config.backend.dataDirectory
appVersion = nw.App.manifest.version
# Read DB's version file, compare against app version
Fs.readFile Path.join(dataDir, 'version.json'), (err, result) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
dbVersion = JSON.parse(result).dataVersion
# Launch migration dialog if mismatched versions
if Semver.lt(dbVersion, appVersion)
console.log "data version less than app version. Migration required"
@_showMigrationDialog(dbVersion, appVersion)
else if Semver.gt(dbVersion, appVersion)
console.log "Warning! Data version newer than app version"
$ =>
Bootbox.dialog {
title: "Database Error"
message: R.div({},
"The application cannot start because your database appears to be from a newer version of #{Config.productName}.",
R.br(), R.br(),
"You must upgrade #{Config.productName} from v#{appVersion} to v#{dbVersion} or greater to continue."
)
closeButton: false
buttons: {
cancel: {
label: "OK"
className: 'btn-primary'
callback: =>
@props.closeWindow()
}
}
}
_showMigrationDialog: (dbVersion, appVersion) ->
$ =>
Bootbox.dialog {
title: "Database Migration Required"
message: R.div({},
"Your database is from an earlier version of #{Config.productName} (v#{dbVersion}), so a migration is required.",
"To update the database to v#{appVersion}, please log in with an administrator account:",
R.br(), R.br(),
R.input({
id: "username",
name: "username",
type: "text",
placeholder: "username",
className: "form-control input-md",
}),
R.br(),
R.input({
id: "password"
name: "password"
type: "<PASSWORD>"
placeholder: "<PASSWORD>"
className: "form-control input-md"
}),
R.br()
)
closeButton: false
buttons: {
cancel: {
label: "Cancel"
className: 'btn-default'
callback: =>
@props.closeWindow()
}
continue: {
label: "Continue"
className: 'btn-primary'
callback: =>
# passing a string to the migrate function if the fields are left empty
# this lets the existing error conditions handle empty fields.
username = $('#username').val() or ' '
password = $('#password').val() or ' '
@_migrateToLatestVersion(username, password, dbVersion)
}
}
}
# Focus first field
# bootbox focuses primary button by default
setTimeout(->
$('#username').focus()
, 500)
_migrateToLatestVersion: (username, password, currentVersion) ->
Migration = require './migrations'
dataDir = Config.backend.dataDirectory
destinationVersion = nw.App.manifest.version
Async.series [
(cb) =>
@setState {isLoading: true, loadingMessage: "Migrating Database..."}, cb
(cb) =>
Migration.atomicMigration dataDir, currentVersion, destinationVersion, username, password, cb
], (err) =>
@setState {isLoading: false, loadingMessage: ""}
# ToDo: handle case where migration file is not found
if err
if err instanceof Persist.Session.AccountTypeError
@refs.ui.onLoginError('AccountTypeError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.UnknownUserNameError
@refs.ui.onLoginError('UnknownUserNameError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.InvalidUserNameError
@refs.ui.onLoginError('InvalidUserNameError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.IncorrectPasswordError
@refs.ui.onLoginError('IncorrectPasswordError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.DeactivatedAccountError
@refs.ui.onLoginError('DeactivatedAccountError', @_checkVersionsMatch)
return
if err instanceof Persist.IOError
@refs.ui.onLoginError('IOError', @_checkVersionsMatch)
return
CrashHandler.handle err
return
# Migrations were successful!
Bootbox.alert "The data file has been successfully migrated to the app version. Please log in to continue."
_login: (userName, password) ->
Async.series [
(cb) =>
@setState {isLoading: true, loadingMessage: "Authenticating..."}, cb
(cb) =>
# Create session
Persist.Session.login userName, password, Config.backend, (err, session) =>
if err
cb err
return
# Store the session globally
global.ActiveSession = session
cb()
(cb) =>
openWindow {page: 'clientSelection'}, (newWindow) =>
clientSelectionPageWindow = newWindow
Window.hide()
clientSelectionPageWindow.on 'closed', =>
@props.closeWindow()
Window.quit()
# Finish series and hide loginPage once loaded event fires
global.ActiveSession.persist.eventBus.once 'clientSelectionPage:loaded', cb
], (err) =>
@setState {isLoading: false, loadingMessage: ""}
if err
if err instanceof Persist.Session.UnknownUserNameError
@refs.ui.onLoginError('UnknownUserNameError')
return
if err instanceof Persist.Session.InvalidUserNameError
@refs.ui.onLoginError('InvalidUserNameError')
return
if err instanceof Persist.Session.IncorrectPasswordError
@refs.ui.onLoginError('IncorrectPasswordError')
return
if err instanceof Persist.Session.DeactivatedAccountError
@refs.ui.onLoginError('DeactivatedAccountError')
return
if err instanceof Persist.IOError
@refs.ui.onLoginError('IOError')
return
CrashHandler.handle err
return
LoginPageUi = React.createFactory React.createClass
displayName: 'LoginPageUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
userName: ''
password: ''
}
componentDidMount: ->
@props.checkVersionsMatch()
Persist.initializeCrypto()
onLoginError: (type, cb=(->)) ->
switch type
when 'AccountTypeError'
Bootbox.alert "This user is not an Admin. Please try again.", =>
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'UnknownUserNameError'
Bootbox.alert "Unknown user name. Please try again.", =>
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'InvalidUserNameError'
Bootbox.alert "Invalid user name. Please try again.", =>
@refs.userNameField.focus()
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'IncorrectPasswordError'
Bootbox.alert "Incorrect password. Please try again.", =>
@setState {password: ''}
setTimeout(=>
@refs.passwordField.focus()
, 100)
cb()
when 'DeactivatedAccountError'
Bootbox.alert "This user account has been deactivated.", =>
@refs.userNameField.focus()
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'IOError'
Bootbox.alert "Please check your network connection and try again.", cb
else
throw new Error "Invalid Login Error"
render: ->
return R.div({className: 'loginPage'},
Spinner({
isVisible: @props.isLoading
isOverlay: true
message: @props.loadingMessage
})
R.div({id: "loginForm"},
R.div({
id: 'logoContainer'
className: 'animated fadeInDown'
},
R.img({
className: 'animated rotateIn'
src: 'img/konode-kn.svg'
})
)
R.div({className: 'subtitleContainer'},
R.div({
className: 'subtitleText'
style: {color: Config.logoSubtitleColor}
},
Config.logoSubtitle
)
(if not Config.logoSubtitle
R.div({className: 'versionNumber'},
"v" + nw.App.manifest.version
)
)
)
R.div({
id: 'formContainer'
className: 'animated fadeInUp'
},
R.div({className: 'form-group'},
R.input({
className: 'form-control'
autoFocus: true
ref: 'userNameField'
onChange: @_updateUserName
onKeyDown: @_onEnterKeyDown
value: @state.userName
type: 'text'
placeholder: 'Username'
autoComplete: 'off'
})
)
R.div({className: 'form-group'},
R.input({
className: 'form-control'
type: 'password'
ref: 'passwordField'
onChange: @_updatePassword
onKeyDown: @_onEnterKeyDown
value: @state.password
placeholder: '<PASSWORD>'
autoComplete: 'off'
})
)
R.div({className: 'btn-toolbar'},
## TODO: Password reminder
# R.button({
# className: 'btn btn-link'
# onClick: @_forgotPassword
# }, "Forgot Password?")
R.button({
className: [
'btn'
if @_formIsInvalid() then 'btn-primary' else 'btn-success animated pulse'
].join ' '
type: 'submit'
disabled: @_formIsInvalid()
onClick: @_login
}, "Sign in")
)
)
)
)
_quit: ->
win.close(true)
_updateUserName: (event) ->
@setState {userName: event.target.value}
_updatePassword: (event) ->
@setState {password: event.target.value}
_onEnterKeyDown: (event) ->
@_login() if event.which is 13 and not @_formIsInvalid()
_formIsInvalid: ->
not @state.userName or not @state.password
_login: (event) ->
@props.login(@state.userName.split('@')[0], @state.password)
return LoginPage
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Window for user login -> account validation, with detection for setup/migrations
Async = require 'async'
Fs = require 'fs'
Path = require 'path'
Semver = require 'semver'
Config = require './config'
Persist = require './persist'
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
Window = nw.Window.get(win)
CrashHandler = require('./crashHandler').load(win)
Spinner = require('./spinner').load(win)
{openWindow} = require('./utils').load(win)
LoginPage = React.createFactory React.createClass
displayName: 'LoginPage'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
isSetUp: null
isLoading: false
}
init: ->
if Config.logoSubtitle
@props.setWindowTitle("#{Config.logoSubtitle} - #{Config.productName}")
@_checkSetUp()
deinit: (cb=(->)) ->
@setState {isLoading: false}, cb
suggestClose: ->
@props.closeWindow()
render: ->
unless @state.isSetUp
return null
LoginPageUi({
ref: 'ui'
isLoading: @state.isLoading
loadingMessage: @state.loadingMessage
checkVersionsMatch: @_checkVersionsMatch
login: @_login
})
_checkSetUp: ->
# Check to make sure the dataDir exists and has an account system
Persist.Users.isAccountSystemSetUp Config.backend, (err, isSetUp) =>
if err
if err instanceof Persist.IOError
Bootbox.alert """
Sorry, we're unable to reach the database.
Please check your network connection and try again.
"""
return
CrashHandler.handle err
return
if isSetUp
# Already set up, no need to continue here
@setState {
isSetUp: true
}
return
# Falsy isSetUp triggers NewInstallationPage
@setState {isSetUp: false}
@props.navigateTo {page:'newInstallation'}
_checkVersionsMatch: ->
dataDir = Config.backend.dataDirectory
appVersion = nw.App.manifest.version
# Read DB's version file, compare against app version
Fs.readFile Path.join(dataDir, 'version.json'), (err, result) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
dbVersion = JSON.parse(result).dataVersion
# Launch migration dialog if mismatched versions
if Semver.lt(dbVersion, appVersion)
console.log "data version less than app version. Migration required"
@_showMigrationDialog(dbVersion, appVersion)
else if Semver.gt(dbVersion, appVersion)
console.log "Warning! Data version newer than app version"
$ =>
Bootbox.dialog {
title: "Database Error"
message: R.div({},
"The application cannot start because your database appears to be from a newer version of #{Config.productName}.",
R.br(), R.br(),
"You must upgrade #{Config.productName} from v#{appVersion} to v#{dbVersion} or greater to continue."
)
closeButton: false
buttons: {
cancel: {
label: "OK"
className: 'btn-primary'
callback: =>
@props.closeWindow()
}
}
}
_showMigrationDialog: (dbVersion, appVersion) ->
$ =>
Bootbox.dialog {
title: "Database Migration Required"
message: R.div({},
"Your database is from an earlier version of #{Config.productName} (v#{dbVersion}), so a migration is required.",
"To update the database to v#{appVersion}, please log in with an administrator account:",
R.br(), R.br(),
R.input({
id: "username",
name: "username",
type: "text",
placeholder: "username",
className: "form-control input-md",
}),
R.br(),
R.input({
id: "password"
name: "password"
type: "PI:PASSWORD:<PASSWORD>END_PI"
placeholder: "PI:PASSWORD:<PASSWORD>END_PI"
className: "form-control input-md"
}),
R.br()
)
closeButton: false
buttons: {
cancel: {
label: "Cancel"
className: 'btn-default'
callback: =>
@props.closeWindow()
}
continue: {
label: "Continue"
className: 'btn-primary'
callback: =>
# passing a string to the migrate function if the fields are left empty
# this lets the existing error conditions handle empty fields.
username = $('#username').val() or ' '
password = $('#password').val() or ' '
@_migrateToLatestVersion(username, password, dbVersion)
}
}
}
# Focus first field
# bootbox focuses primary button by default
setTimeout(->
$('#username').focus()
, 500)
_migrateToLatestVersion: (username, password, currentVersion) ->
Migration = require './migrations'
dataDir = Config.backend.dataDirectory
destinationVersion = nw.App.manifest.version
Async.series [
(cb) =>
@setState {isLoading: true, loadingMessage: "Migrating Database..."}, cb
(cb) =>
Migration.atomicMigration dataDir, currentVersion, destinationVersion, username, password, cb
], (err) =>
@setState {isLoading: false, loadingMessage: ""}
# ToDo: handle case where migration file is not found
if err
if err instanceof Persist.Session.AccountTypeError
@refs.ui.onLoginError('AccountTypeError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.UnknownUserNameError
@refs.ui.onLoginError('UnknownUserNameError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.InvalidUserNameError
@refs.ui.onLoginError('InvalidUserNameError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.IncorrectPasswordError
@refs.ui.onLoginError('IncorrectPasswordError', @_checkVersionsMatch)
return
if err instanceof Persist.Session.DeactivatedAccountError
@refs.ui.onLoginError('DeactivatedAccountError', @_checkVersionsMatch)
return
if err instanceof Persist.IOError
@refs.ui.onLoginError('IOError', @_checkVersionsMatch)
return
CrashHandler.handle err
return
# Migrations were successful!
Bootbox.alert "The data file has been successfully migrated to the app version. Please log in to continue."
_login: (userName, password) ->
Async.series [
(cb) =>
@setState {isLoading: true, loadingMessage: "Authenticating..."}, cb
(cb) =>
# Create session
Persist.Session.login userName, password, Config.backend, (err, session) =>
if err
cb err
return
# Store the session globally
global.ActiveSession = session
cb()
(cb) =>
openWindow {page: 'clientSelection'}, (newWindow) =>
clientSelectionPageWindow = newWindow
Window.hide()
clientSelectionPageWindow.on 'closed', =>
@props.closeWindow()
Window.quit()
# Finish series and hide loginPage once loaded event fires
global.ActiveSession.persist.eventBus.once 'clientSelectionPage:loaded', cb
], (err) =>
@setState {isLoading: false, loadingMessage: ""}
if err
if err instanceof Persist.Session.UnknownUserNameError
@refs.ui.onLoginError('UnknownUserNameError')
return
if err instanceof Persist.Session.InvalidUserNameError
@refs.ui.onLoginError('InvalidUserNameError')
return
if err instanceof Persist.Session.IncorrectPasswordError
@refs.ui.onLoginError('IncorrectPasswordError')
return
if err instanceof Persist.Session.DeactivatedAccountError
@refs.ui.onLoginError('DeactivatedAccountError')
return
if err instanceof Persist.IOError
@refs.ui.onLoginError('IOError')
return
CrashHandler.handle err
return
LoginPageUi = React.createFactory React.createClass
displayName: 'LoginPageUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
userName: ''
password: ''
}
componentDidMount: ->
@props.checkVersionsMatch()
Persist.initializeCrypto()
onLoginError: (type, cb=(->)) ->
switch type
when 'AccountTypeError'
Bootbox.alert "This user is not an Admin. Please try again.", =>
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'UnknownUserNameError'
Bootbox.alert "Unknown user name. Please try again.", =>
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'InvalidUserNameError'
Bootbox.alert "Invalid user name. Please try again.", =>
@refs.userNameField.focus()
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'IncorrectPasswordError'
Bootbox.alert "Incorrect password. Please try again.", =>
@setState {password: ''}
setTimeout(=>
@refs.passwordField.focus()
, 100)
cb()
when 'DeactivatedAccountError'
Bootbox.alert "This user account has been deactivated.", =>
@refs.userNameField.focus()
setTimeout(=>
@refs.userNameField.focus()
, 100)
cb()
when 'IOError'
Bootbox.alert "Please check your network connection and try again.", cb
else
throw new Error "Invalid Login Error"
render: ->
return R.div({className: 'loginPage'},
Spinner({
isVisible: @props.isLoading
isOverlay: true
message: @props.loadingMessage
})
R.div({id: "loginForm"},
R.div({
id: 'logoContainer'
className: 'animated fadeInDown'
},
R.img({
className: 'animated rotateIn'
src: 'img/konode-kn.svg'
})
)
R.div({className: 'subtitleContainer'},
R.div({
className: 'subtitleText'
style: {color: Config.logoSubtitleColor}
},
Config.logoSubtitle
)
(if not Config.logoSubtitle
R.div({className: 'versionNumber'},
"v" + nw.App.manifest.version
)
)
)
R.div({
id: 'formContainer'
className: 'animated fadeInUp'
},
R.div({className: 'form-group'},
R.input({
className: 'form-control'
autoFocus: true
ref: 'userNameField'
onChange: @_updateUserName
onKeyDown: @_onEnterKeyDown
value: @state.userName
type: 'text'
placeholder: 'Username'
autoComplete: 'off'
})
)
R.div({className: 'form-group'},
R.input({
className: 'form-control'
type: 'password'
ref: 'passwordField'
onChange: @_updatePassword
onKeyDown: @_onEnterKeyDown
value: @state.password
placeholder: 'PI:PASSWORD:<PASSWORD>END_PI'
autoComplete: 'off'
})
)
R.div({className: 'btn-toolbar'},
## TODO: Password reminder
# R.button({
# className: 'btn btn-link'
# onClick: @_forgotPassword
# }, "Forgot Password?")
R.button({
className: [
'btn'
if @_formIsInvalid() then 'btn-primary' else 'btn-success animated pulse'
].join ' '
type: 'submit'
disabled: @_formIsInvalid()
onClick: @_login
}, "Sign in")
)
)
)
)
_quit: ->
win.close(true)
_updateUserName: (event) ->
@setState {userName: event.target.value}
_updatePassword: (event) ->
@setState {password: event.target.value}
_onEnterKeyDown: (event) ->
@_login() if event.which is 13 and not @_formIsInvalid()
_formIsInvalid: ->
not @state.userName or not @state.password
_login: (event) ->
@props.login(@state.userName.split('@')[0], @state.password)
return LoginPage
module.exports = {load}
|
[
{
"context": "given a diceware-formatted\n# wordlist.\n#\n# Author: Brad Osgood\n# Date: 12/22/2013\n# Copyright: MIT\n\n# Wordlist f",
"end": 155,
"score": 0.9998574256896973,
"start": 144,
"tag": "NAME",
"value": "Brad Osgood"
}
] | dice2pw.coffee | bosgood/dice2pw | 0 | #!/usr/bin/env coffee
#
# dice2pw
#
# Convert a set of dice rolls into a diceware password, given a diceware-formatted
# wordlist.
#
# Author: Brad Osgood
# Date: 12/22/2013
# Copyright: MIT
# Wordlist format:
# 11111 aword
# 11112 anotherword
# ...
# 66666 zlastword
fs = require 'fs'
prompt = require 'prompt'
PasswordLookup = require './dicelib'
usage = (msg) ->
msg = msg or 'convert a set of dice rolls into a diceware password'
console.log """
dice2pw: #{msg}
usage: diceware_list_file dice_roll [dice_roll, ...]
where dice_roll is 6 digits from 1-6 like `123456'
"""
readDiceRolls = (argv, startIndex) ->
rolls = []
for i in [startIndex..argv.length - 1]
roll = argv[i]
if not roll?
break
rolls.push roll
rolls
dicewareFile = process.argv[2]
unless dicewareFile?
usage('missing diceware file')
process.exit(1)
wordlist = fs.readFileSync dicewareFile, 'utf8'
unless wordlist
usage("unable to load file: #{dicewareFile}")
process.exit(1)
db = new PasswordLookup(wordlist.split('\n'))
# Get the input in a prompt so their password
# isn't in the shell history
prompt.start()
prompt.get ['rolls'], (err, result) ->
diceRolls = result.rolls?.split(' ')
unless diceRolls?.length > 0
usage('unable to read dice rolls')
process.exit(1)
pw = db.getPasswordFromDiceRolls(diceRolls)
console.log(pw)
| 17954 | #!/usr/bin/env coffee
#
# dice2pw
#
# Convert a set of dice rolls into a diceware password, given a diceware-formatted
# wordlist.
#
# Author: <NAME>
# Date: 12/22/2013
# Copyright: MIT
# Wordlist format:
# 11111 aword
# 11112 anotherword
# ...
# 66666 zlastword
fs = require 'fs'
prompt = require 'prompt'
PasswordLookup = require './dicelib'
usage = (msg) ->
msg = msg or 'convert a set of dice rolls into a diceware password'
console.log """
dice2pw: #{msg}
usage: diceware_list_file dice_roll [dice_roll, ...]
where dice_roll is 6 digits from 1-6 like `123456'
"""
readDiceRolls = (argv, startIndex) ->
rolls = []
for i in [startIndex..argv.length - 1]
roll = argv[i]
if not roll?
break
rolls.push roll
rolls
dicewareFile = process.argv[2]
unless dicewareFile?
usage('missing diceware file')
process.exit(1)
wordlist = fs.readFileSync dicewareFile, 'utf8'
unless wordlist
usage("unable to load file: #{dicewareFile}")
process.exit(1)
db = new PasswordLookup(wordlist.split('\n'))
# Get the input in a prompt so their password
# isn't in the shell history
prompt.start()
prompt.get ['rolls'], (err, result) ->
diceRolls = result.rolls?.split(' ')
unless diceRolls?.length > 0
usage('unable to read dice rolls')
process.exit(1)
pw = db.getPasswordFromDiceRolls(diceRolls)
console.log(pw)
| true | #!/usr/bin/env coffee
#
# dice2pw
#
# Convert a set of dice rolls into a diceware password, given a diceware-formatted
# wordlist.
#
# Author: PI:NAME:<NAME>END_PI
# Date: 12/22/2013
# Copyright: MIT
# Wordlist format:
# 11111 aword
# 11112 anotherword
# ...
# 66666 zlastword
fs = require 'fs'
prompt = require 'prompt'
PasswordLookup = require './dicelib'
usage = (msg) ->
msg = msg or 'convert a set of dice rolls into a diceware password'
console.log """
dice2pw: #{msg}
usage: diceware_list_file dice_roll [dice_roll, ...]
where dice_roll is 6 digits from 1-6 like `123456'
"""
readDiceRolls = (argv, startIndex) ->
rolls = []
for i in [startIndex..argv.length - 1]
roll = argv[i]
if not roll?
break
rolls.push roll
rolls
dicewareFile = process.argv[2]
unless dicewareFile?
usage('missing diceware file')
process.exit(1)
wordlist = fs.readFileSync dicewareFile, 'utf8'
unless wordlist
usage("unable to load file: #{dicewareFile}")
process.exit(1)
db = new PasswordLookup(wordlist.split('\n'))
# Get the input in a prompt so their password
# isn't in the shell history
prompt.start()
prompt.get ['rolls'], (err, result) ->
diceRolls = result.rolls?.split(' ')
unless diceRolls?.length > 0
usage('unable to read dice rolls')
process.exit(1)
pw = db.getPasswordFromDiceRolls(diceRolls)
console.log(pw)
|
[
{
"context": "d the convex shape of an array of points\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nclass ConvexHullPo",
"end": 103,
"score": 0.9998400807380676,
"start": 92,
"tag": "NAME",
"value": "David Ronai"
},
{
"context": "hape of an array of points\n# @author Davi... | src/coffee/makio/math/ConvexHull.coffee | Makio64/pizzaparty_vj | 1 | #
# ConvexHullPoint
#
# Algorythme to find the convex shape of an array of points
# @author David Ronai / Makiopolis.com / @Makio64
#
class ConvexHullPoint
constructor:(@index, @angle, @distance)->
return
compare:(p)=>
if(@angle < p.angle)
return -1
else if(@angle > p.angle)
return 1
else
if(@distance < p.distance)
return -1
else if(@distance > p.distance)
return 1
return 0
class ConvexHull
@ccw = (p1, p2, p3)->
return (@points[p2][@x]-@points[p1][@x])*(@points[p3][@y]-@points[p1][@y])-(@points[p2][@y]-@points[p1][@y])*(@points[p3][@x]-@points[p1][@x])
@angle = (o, a)->
return Math.atan((@points[a][@y]-@points[o][@y])/(@points[a][@x]-@points[o][@x]))
@distance = (a, b)->
return (@points[b][@x]-@points[a][@x])*(@points[b][@x]-@points[a][@x])+(@points[b][@y]-@points[a][@y])*(@points[b][@y]-@points[a][@y])
@compute = (@points,@x="x",@y="y")->
if @points.length < 3
throw new Error('the array should have at the minimum 3 points')
return
min = 0
for i in [1...@points.length] by 1
if(@points[i][@y] == @points[min][@y])
if(@points[i][@x] < @points[min][@x])
min = i
else if(@points[i][@y] < @points[min][@y])
min = i
al = new Array()
ang = 0.0
dist = 0
for i in [0...@points.length] by 1
if(i == min)
continue
ang = @angle(min, i)
if(ang < 0)
ang += Math.PI
dist = @distance(min, i)
al.push(new ConvexHullPoint(i, ang, dist))
al.sort((a, b)->
return a.compare(b)
)
stack = new Array(@points.length + 1)
j = 2
for i in [0...@points.length] by 1
if(i == min)
continue
stack[j] = al[j-2].index
j++
stack[0] = stack[@points.length]
stack[1] = min
M = 2
for i in [3..@points.length] by 1
while(@ccw(stack[M-1], stack[M], stack[i]) <= 0)
M--
M++
tmp = stack[i]
stack[i] = stack[M]
stack[M] = tmp
@indices = new Array(M)
for i in [0...M] by 1
@indices[i] = stack[i + 1]
return @indices
module.exports = ConvexHull
| 89477 | #
# ConvexHullPoint
#
# Algorythme to find the convex shape of an array of points
# @author <NAME> / <EMAIL> / @Makio64
#
class ConvexHullPoint
constructor:(@index, @angle, @distance)->
return
compare:(p)=>
if(@angle < p.angle)
return -1
else if(@angle > p.angle)
return 1
else
if(@distance < p.distance)
return -1
else if(@distance > p.distance)
return 1
return 0
class ConvexHull
@ccw = (p1, p2, p3)->
return (@points[p2][@x]-@points[p1][@x])*(@points[p3][@y]-@points[p1][@y])-(@points[p2][@y]-@points[p1][@y])*(@points[p3][@x]-@points[p1][@x])
@angle = (o, a)->
return Math.atan((@points[a][@y]-@points[o][@y])/(@points[a][@x]-@points[o][@x]))
@distance = (a, b)->
return (@points[b][@x]-@points[a][@x])*(@points[b][@x]-@points[a][@x])+(@points[b][@y]-@points[a][@y])*(@points[b][@y]-@points[a][@y])
@compute = (@points,@x="x",@y="y")->
if @points.length < 3
throw new Error('the array should have at the minimum 3 points')
return
min = 0
for i in [1...@points.length] by 1
if(@points[i][@y] == @points[min][@y])
if(@points[i][@x] < @points[min][@x])
min = i
else if(@points[i][@y] < @points[min][@y])
min = i
al = new Array()
ang = 0.0
dist = 0
for i in [0...@points.length] by 1
if(i == min)
continue
ang = @angle(min, i)
if(ang < 0)
ang += Math.PI
dist = @distance(min, i)
al.push(new ConvexHullPoint(i, ang, dist))
al.sort((a, b)->
return a.compare(b)
)
stack = new Array(@points.length + 1)
j = 2
for i in [0...@points.length] by 1
if(i == min)
continue
stack[j] = al[j-2].index
j++
stack[0] = stack[@points.length]
stack[1] = min
M = 2
for i in [3..@points.length] by 1
while(@ccw(stack[M-1], stack[M], stack[i]) <= 0)
M--
M++
tmp = stack[i]
stack[i] = stack[M]
stack[M] = tmp
@indices = new Array(M)
for i in [0...M] by 1
@indices[i] = stack[i + 1]
return @indices
module.exports = ConvexHull
| true | #
# ConvexHullPoint
#
# Algorythme to find the convex shape of an array of points
# @author PI:NAME:<NAME>END_PI / PI:EMAIL:<EMAIL>END_PI / @Makio64
#
class ConvexHullPoint
constructor:(@index, @angle, @distance)->
return
compare:(p)=>
if(@angle < p.angle)
return -1
else if(@angle > p.angle)
return 1
else
if(@distance < p.distance)
return -1
else if(@distance > p.distance)
return 1
return 0
class ConvexHull
@ccw = (p1, p2, p3)->
return (@points[p2][@x]-@points[p1][@x])*(@points[p3][@y]-@points[p1][@y])-(@points[p2][@y]-@points[p1][@y])*(@points[p3][@x]-@points[p1][@x])
@angle = (o, a)->
return Math.atan((@points[a][@y]-@points[o][@y])/(@points[a][@x]-@points[o][@x]))
@distance = (a, b)->
return (@points[b][@x]-@points[a][@x])*(@points[b][@x]-@points[a][@x])+(@points[b][@y]-@points[a][@y])*(@points[b][@y]-@points[a][@y])
@compute = (@points,@x="x",@y="y")->
if @points.length < 3
throw new Error('the array should have at the minimum 3 points')
return
min = 0
for i in [1...@points.length] by 1
if(@points[i][@y] == @points[min][@y])
if(@points[i][@x] < @points[min][@x])
min = i
else if(@points[i][@y] < @points[min][@y])
min = i
al = new Array()
ang = 0.0
dist = 0
for i in [0...@points.length] by 1
if(i == min)
continue
ang = @angle(min, i)
if(ang < 0)
ang += Math.PI
dist = @distance(min, i)
al.push(new ConvexHullPoint(i, ang, dist))
al.sort((a, b)->
return a.compare(b)
)
stack = new Array(@points.length + 1)
j = 2
for i in [0...@points.length] by 1
if(i == min)
continue
stack[j] = al[j-2].index
j++
stack[0] = stack[@points.length]
stack[1] = min
M = 2
for i in [3..@points.length] by 1
while(@ccw(stack[M-1], stack[M], stack[i]) <= 0)
M--
M++
tmp = stack[i]
stack[i] = stack[M]
stack[M] = tmp
@indices = new Array(M)
for i in [0...M] by 1
@indices[i] = stack[i + 1]
return @indices
module.exports = ConvexHull
|
[
{
"context": "# /*\n# * mqtt-rpc\n# * https://github.com/wolfeidau/mqtt-rpc\n# *\n# * Copyright (c) 2013 Mark Wolfe\n",
"end": 52,
"score": 0.9993192553520203,
"start": 43,
"tag": "USERNAME",
"value": "wolfeidau"
},
{
"context": "om/wolfeidau/mqtt-rpc\n# *\n# * Copyright (c) 20... | lib/server.coffee | boomfly/mqtt-methods | 0 | # /*
# * mqtt-rpc
# * https://github.com/wolfeidau/mqtt-rpc
# *
# * Copyright (c) 2013 Mark Wolfe
# * Licensed under the MIT license.
# */
import mqtt from 'mqtt'
import mqttrouter from 'mqtt-router'
import codecs from './codecs.js'
import Debug from 'debug'
debug = Debug('mqtt-rpc:server')
export default class Server
constructor(mqttclient) ->
# default to JSON codec
@codec = codecs.byName('json')
@mqttclient = mqttclient || mqtt.createClient()
@router = mqttrouter.wrap(mqttclient)
_handleReq: (correlationId, prefix, name, err, data) =>
replyTopic = prefix + '/' + name + '/reply'
msg = {err: err, data: data, _correlationId: correlationId}
debug('publish', replyTopic, msg)
@mqttclient.publish(replyTopic, @codec.encode(msg))
_buildRequestHandler = (prefix, name, cb) =>
debug('buildRequestHandler', prefix, name)
(topic, message) =>
debug('handleMsg', topic, message);
msg = @codec.decode(message)
id = msg._correlationId
cb.call(null, msg, @_handleReq.bind(null, id, prefix, name))
provide: (prefix, name, cb) ->
debug('provide', prefix, name)
requestTopic = prefix + '/' + name + '/request'
debug('requestTopic', requestTopic);
@router.subscribe(requestTopic, @_buildRequestHandler(prefix, name, cb))
debug('subscribe', requestTopic)
@format = (format) ->
this.codec = codecs.byName(format)
| 72299 | # /*
# * mqtt-rpc
# * https://github.com/wolfeidau/mqtt-rpc
# *
# * Copyright (c) 2013 <NAME>
# * Licensed under the MIT license.
# */
import mqtt from 'mqtt'
import mqttrouter from 'mqtt-router'
import codecs from './codecs.js'
import Debug from 'debug'
debug = Debug('mqtt-rpc:server')
export default class Server
constructor(mqttclient) ->
# default to JSON codec
@codec = codecs.byName('json')
@mqttclient = mqttclient || mqtt.createClient()
@router = mqttrouter.wrap(mqttclient)
_handleReq: (correlationId, prefix, name, err, data) =>
replyTopic = prefix + '/' + name + '/reply'
msg = {err: err, data: data, _correlationId: correlationId}
debug('publish', replyTopic, msg)
@mqttclient.publish(replyTopic, @codec.encode(msg))
_buildRequestHandler = (prefix, name, cb) =>
debug('buildRequestHandler', prefix, name)
(topic, message) =>
debug('handleMsg', topic, message);
msg = @codec.decode(message)
id = msg._correlationId
cb.call(null, msg, @_handleReq.bind(null, id, prefix, name))
provide: (prefix, name, cb) ->
debug('provide', prefix, name)
requestTopic = prefix + '/' + name + '/request'
debug('requestTopic', requestTopic);
@router.subscribe(requestTopic, @_buildRequestHandler(prefix, name, cb))
debug('subscribe', requestTopic)
@format = (format) ->
this.codec = codecs.byName(format)
| true | # /*
# * mqtt-rpc
# * https://github.com/wolfeidau/mqtt-rpc
# *
# * Copyright (c) 2013 PI:NAME:<NAME>END_PI
# * Licensed under the MIT license.
# */
import mqtt from 'mqtt'
import mqttrouter from 'mqtt-router'
import codecs from './codecs.js'
import Debug from 'debug'
debug = Debug('mqtt-rpc:server')
export default class Server
constructor(mqttclient) ->
# default to JSON codec
@codec = codecs.byName('json')
@mqttclient = mqttclient || mqtt.createClient()
@router = mqttrouter.wrap(mqttclient)
_handleReq: (correlationId, prefix, name, err, data) =>
replyTopic = prefix + '/' + name + '/reply'
msg = {err: err, data: data, _correlationId: correlationId}
debug('publish', replyTopic, msg)
@mqttclient.publish(replyTopic, @codec.encode(msg))
_buildRequestHandler = (prefix, name, cb) =>
debug('buildRequestHandler', prefix, name)
(topic, message) =>
debug('handleMsg', topic, message);
msg = @codec.decode(message)
id = msg._correlationId
cb.call(null, msg, @_handleReq.bind(null, id, prefix, name))
provide: (prefix, name, cb) ->
debug('provide', prefix, name)
requestTopic = prefix + '/' + name + '/request'
debug('requestTopic', requestTopic);
@router.subscribe(requestTopic, @_buildRequestHandler(prefix, name, cb))
debug('subscribe', requestTopic)
@format = (format) ->
this.codec = codecs.byName(format)
|
[
{
"context": "argv[2]\n\npubnub = PUBNUB.init(\n subscribe_key : 'demo' # you should change this!\n publish_key : 'dem",
"end": 466,
"score": 0.9668776392936707,
"start": 462,
"tag": "KEY",
"value": "demo"
},
{
"context": "emo' # you should change this!\n publish_key : 'demo' ... | src/pubnub-redis-listen-simple.coffee | sunnygleason/pubnub-persistence-redis | 2 | #
# PubNub Persistence: node.js replication simple listener
#
# "Connecting your worldwide apps to redis updates within 250ms"
#
# Usage: coffee src/pubnub-redis-listen-simple.coffee CHANNEL_NAME
# - where CHANNEL_NAME is the Redis channel to receive updates
#
PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js')
_ = require('../deps/underscore/underscore.js')
CHANNEL = process.argv[2]
pubnub = PUBNUB.init(
subscribe_key : 'demo' # you should change this!
publish_key : 'demo' # you should change this!
)
#
# Set up a simple event listener - we just log the updates
#
pubnub.subscribe({
channel: CHANNEL
message: (command) -> console.log "got from \##{CHANNEL}:", JSON.stringify(command)
})
console.log "Listening to PubNub redis channel \##{CHANNEL}" | 186995 | #
# PubNub Persistence: node.js replication simple listener
#
# "Connecting your worldwide apps to redis updates within 250ms"
#
# Usage: coffee src/pubnub-redis-listen-simple.coffee CHANNEL_NAME
# - where CHANNEL_NAME is the Redis channel to receive updates
#
PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js')
_ = require('../deps/underscore/underscore.js')
CHANNEL = process.argv[2]
pubnub = PUBNUB.init(
subscribe_key : '<KEY>' # you should change this!
publish_key : '<KEY>' # you should change this!
)
#
# Set up a simple event listener - we just log the updates
#
pubnub.subscribe({
channel: CHANNEL
message: (command) -> console.log "got from \##{CHANNEL}:", JSON.stringify(command)
})
console.log "Listening to PubNub redis channel \##{CHANNEL}" | true | #
# PubNub Persistence: node.js replication simple listener
#
# "Connecting your worldwide apps to redis updates within 250ms"
#
# Usage: coffee src/pubnub-redis-listen-simple.coffee CHANNEL_NAME
# - where CHANNEL_NAME is the Redis channel to receive updates
#
PUBNUB = require('../deps/pubnub-javascript/node.js/pubnub.js')
_ = require('../deps/underscore/underscore.js')
CHANNEL = process.argv[2]
pubnub = PUBNUB.init(
subscribe_key : 'PI:KEY:<KEY>END_PI' # you should change this!
publish_key : 'PI:KEY:<KEY>END_PI' # you should change this!
)
#
# Set up a simple event listener - we just log the updates
#
pubnub.subscribe({
channel: CHANNEL
message: (command) -> console.log "got from \##{CHANNEL}:", JSON.stringify(command)
})
console.log "Listening to PubNub redis channel \##{CHANNEL}" |
[
{
"context": " quality ||= options.quality\n\n cacheKey = \"#{dim || 'original'}/r_#{rotate}-q_#{quality}\"\n ",
"end": 2637,
"score": 0.6258704662322998,
"start": 2634,
"tag": "KEY",
"value": "\"#{"
},
{
"context": "ty ||= options.quality\n\n cacheKey = \"#{dim || ... | src/thumb-cutter.coffee | Sija/express-thumb-cutter | 3 | global[id] ?= require name for id, name of {
'Path' : 'path'
'fs'
'crypto'
'mkdirp'
'sharp'
}
class ImageResizer
__requestCache =
atWork: {}
queue : {}
@convert: (options = {}, callback) ->
{src, dst, width, height, rotate, quality} = options
mkdirp.sync Path.dirname(dst)
pipeline = []
pipeline.push method: 'rotate', args: (if rotate is yes then [] else [rotate]) if rotate
pipeline.push method: 'resize', args: [width, height] if width or height
pipeline.push method: 'quality', args: [quality] if quality
pipeline.push method: 'progressive' if options.progressive is yes
pipeline.push method: 'withMetadata' if options.withMetadata is yes
try
image = sharp(src)
image[method] (args || [])... for {method, args} in pipeline
options.sharpImage? image # TODO:
image.toFile dst, (err, info) ->
if err
callback err
else
callback null, dst
catch err
callback(err)
@static: (root, options = {}) ->
root = Path.normalize root
options.cacheDir ?= Path.join root, '.cache'
options.quality ?= 80
options.progressive ?= yes
options.rotate ?= no
options.withMetadata ?= no
send_with_headers = (res, file) ->
options.setHeaders? res, file
res.sendFile file
send_if_exists = (res, file, callback) ->
return callback() unless fs.existsSync file
send_with_headers res, file
return (req, res, next) ->
# reject funny requests
return next() unless req.method in ['GET', 'HEAD']
# we need req.params[0] when used with * capture groups
file = decodeURI req.params[0] or req.path
orig = Path.normalize Path.join root, file
# bailout if file is not an image
unless file.match /\.(jpe?g|png|webp|tiff)$/i
return send_if_exists res, orig, next
# bailout if file doesn't exists
return next() unless fs.existsSync orig
{dim, rotate, quality} = req.params
dim ||= req.query.dim
rotate ||= req.query.rotate
quality ||= req.query.quality
# parameters validation plz
dim = null if dim and not /^(\d+)?x(\d+)?$/.exec dim
rotate = null if rotate and not /^(\d+|true|false)$/.exec rotate
quality = null if quality and not /^(\d+)$/.exec quality
# no parameters found, returning original file
unless dim? or rotate? or quality?
return send_if_exists res, orig, next
dim ||= options.dim
rotate ||= options.rotate
quality ||= options.quality
cacheKey = "#{dim || 'original'}/r_#{rotate}-q_#{quality}"
# cacheKey = crypto.createHash('md5').update(cacheKey).digest('hex')
dst = Path.join options.cacheDir, cacheKey, file
processRequest = ->
# send image if found or generate it on the fly
send_if_exists res, dst, ->
# mark image conversion start
__requestCache.atWork[dst] = yes
dims = "#{dim}".split /x/
opts =
src : orig
dst : dst
width : Number(dims[0]) or null
height : Number(dims[1]) or null
quality : Number(quality) or null
rotate : switch rotate
when 'true', true then yes
when 'false', false then no
else
Number(rotate) or null
progressive : options.progressive
withMetadata: options.withMetadata
ImageResizer.convert opts, (err, dst) ->
# console.log 'ImageResizer.convert', err, dst, __requestCache
unless err
send_with_headers res, dst
else
next err if err
# execute pending requests
if queue = __requestCache.queue[dst]
callback() for callback in queue
delete __requestCache.atWork[dst]
delete __requestCache.queue[dst]
process.nextTick ->
if __requestCache.atWork[dst]
# queue request until image conversion finishes
__requestCache.queue[dst] ||= []
__requestCache.queue[dst].push processRequest
else
# go ahead, no conversion in progress
processRequest()
module.exports = ImageResizer
| 85251 | global[id] ?= require name for id, name of {
'Path' : 'path'
'fs'
'crypto'
'mkdirp'
'sharp'
}
class ImageResizer
__requestCache =
atWork: {}
queue : {}
@convert: (options = {}, callback) ->
{src, dst, width, height, rotate, quality} = options
mkdirp.sync Path.dirname(dst)
pipeline = []
pipeline.push method: 'rotate', args: (if rotate is yes then [] else [rotate]) if rotate
pipeline.push method: 'resize', args: [width, height] if width or height
pipeline.push method: 'quality', args: [quality] if quality
pipeline.push method: 'progressive' if options.progressive is yes
pipeline.push method: 'withMetadata' if options.withMetadata is yes
try
image = sharp(src)
image[method] (args || [])... for {method, args} in pipeline
options.sharpImage? image # TODO:
image.toFile dst, (err, info) ->
if err
callback err
else
callback null, dst
catch err
callback(err)
@static: (root, options = {}) ->
root = Path.normalize root
options.cacheDir ?= Path.join root, '.cache'
options.quality ?= 80
options.progressive ?= yes
options.rotate ?= no
options.withMetadata ?= no
send_with_headers = (res, file) ->
options.setHeaders? res, file
res.sendFile file
send_if_exists = (res, file, callback) ->
return callback() unless fs.existsSync file
send_with_headers res, file
return (req, res, next) ->
# reject funny requests
return next() unless req.method in ['GET', 'HEAD']
# we need req.params[0] when used with * capture groups
file = decodeURI req.params[0] or req.path
orig = Path.normalize Path.join root, file
# bailout if file is not an image
unless file.match /\.(jpe?g|png|webp|tiff)$/i
return send_if_exists res, orig, next
# bailout if file doesn't exists
return next() unless fs.existsSync orig
{dim, rotate, quality} = req.params
dim ||= req.query.dim
rotate ||= req.query.rotate
quality ||= req.query.quality
# parameters validation plz
dim = null if dim and not /^(\d+)?x(\d+)?$/.exec dim
rotate = null if rotate and not /^(\d+|true|false)$/.exec rotate
quality = null if quality and not /^(\d+)$/.exec quality
# no parameters found, returning original file
unless dim? or rotate? or quality?
return send_if_exists res, orig, next
dim ||= options.dim
rotate ||= options.rotate
quality ||= options.quality
cacheKey = <KEY>dim || <KEY>original'}/<KEY>
# cacheKey = <KEY>(cacheKey).<KEY>('<KEY>')
dst = Path.join options.cacheDir, cacheKey, file
processRequest = ->
# send image if found or generate it on the fly
send_if_exists res, dst, ->
# mark image conversion start
__requestCache.atWork[dst] = yes
dims = "#{dim}".split /x/
opts =
src : orig
dst : dst
width : Number(dims[0]) or null
height : Number(dims[1]) or null
quality : Number(quality) or null
rotate : switch rotate
when 'true', true then yes
when 'false', false then no
else
Number(rotate) or null
progressive : options.progressive
withMetadata: options.withMetadata
ImageResizer.convert opts, (err, dst) ->
# console.log 'ImageResizer.convert', err, dst, __requestCache
unless err
send_with_headers res, dst
else
next err if err
# execute pending requests
if queue = __requestCache.queue[dst]
callback() for callback in queue
delete __requestCache.atWork[dst]
delete __requestCache.queue[dst]
process.nextTick ->
if __requestCache.atWork[dst]
# queue request until image conversion finishes
__requestCache.queue[dst] ||= []
__requestCache.queue[dst].push processRequest
else
# go ahead, no conversion in progress
processRequest()
module.exports = ImageResizer
| true | global[id] ?= require name for id, name of {
'Path' : 'path'
'fs'
'crypto'
'mkdirp'
'sharp'
}
class ImageResizer
__requestCache =
atWork: {}
queue : {}
@convert: (options = {}, callback) ->
{src, dst, width, height, rotate, quality} = options
mkdirp.sync Path.dirname(dst)
pipeline = []
pipeline.push method: 'rotate', args: (if rotate is yes then [] else [rotate]) if rotate
pipeline.push method: 'resize', args: [width, height] if width or height
pipeline.push method: 'quality', args: [quality] if quality
pipeline.push method: 'progressive' if options.progressive is yes
pipeline.push method: 'withMetadata' if options.withMetadata is yes
try
image = sharp(src)
image[method] (args || [])... for {method, args} in pipeline
options.sharpImage? image # TODO:
image.toFile dst, (err, info) ->
if err
callback err
else
callback null, dst
catch err
callback(err)
@static: (root, options = {}) ->
root = Path.normalize root
options.cacheDir ?= Path.join root, '.cache'
options.quality ?= 80
options.progressive ?= yes
options.rotate ?= no
options.withMetadata ?= no
send_with_headers = (res, file) ->
options.setHeaders? res, file
res.sendFile file
send_if_exists = (res, file, callback) ->
return callback() unless fs.existsSync file
send_with_headers res, file
return (req, res, next) ->
# reject funny requests
return next() unless req.method in ['GET', 'HEAD']
# we need req.params[0] when used with * capture groups
file = decodeURI req.params[0] or req.path
orig = Path.normalize Path.join root, file
# bailout if file is not an image
unless file.match /\.(jpe?g|png|webp|tiff)$/i
return send_if_exists res, orig, next
# bailout if file doesn't exists
return next() unless fs.existsSync orig
{dim, rotate, quality} = req.params
dim ||= req.query.dim
rotate ||= req.query.rotate
quality ||= req.query.quality
# parameters validation plz
dim = null if dim and not /^(\d+)?x(\d+)?$/.exec dim
rotate = null if rotate and not /^(\d+|true|false)$/.exec rotate
quality = null if quality and not /^(\d+)$/.exec quality
# no parameters found, returning original file
unless dim? or rotate? or quality?
return send_if_exists res, orig, next
dim ||= options.dim
rotate ||= options.rotate
quality ||= options.quality
cacheKey = PI:KEY:<KEY>END_PIdim || PI:KEY:<KEY>END_PIoriginal'}/PI:KEY:<KEY>END_PI
# cacheKey = PI:KEY:<KEY>END_PI(cacheKey).PI:KEY:<KEY>END_PI('PI:KEY:<KEY>END_PI')
dst = Path.join options.cacheDir, cacheKey, file
processRequest = ->
# send image if found or generate it on the fly
send_if_exists res, dst, ->
# mark image conversion start
__requestCache.atWork[dst] = yes
dims = "#{dim}".split /x/
opts =
src : orig
dst : dst
width : Number(dims[0]) or null
height : Number(dims[1]) or null
quality : Number(quality) or null
rotate : switch rotate
when 'true', true then yes
when 'false', false then no
else
Number(rotate) or null
progressive : options.progressive
withMetadata: options.withMetadata
ImageResizer.convert opts, (err, dst) ->
# console.log 'ImageResizer.convert', err, dst, __requestCache
unless err
send_with_headers res, dst
else
next err if err
# execute pending requests
if queue = __requestCache.queue[dst]
callback() for callback in queue
delete __requestCache.atWork[dst]
delete __requestCache.queue[dst]
process.nextTick ->
if __requestCache.atWork[dst]
# queue request until image conversion finishes
__requestCache.queue[dst] ||= []
__requestCache.queue[dst].push processRequest
else
# go ahead, no conversion in progress
processRequest()
module.exports = ImageResizer
|
[
{
"context": " with @a()\", ->\n point = (new Points {\"id\": \"Stellium\", \"lon\": 9}).a()\n point.get('id').should.eql",
"end": 425,
"score": 0.9202502369880676,
"start": 417,
"tag": "NAME",
"value": "Stellium"
},
{
"context": " \"lon\": 9}).a()\n point.get('id').sh... | test/lib/points.spec.coffee | astrolet/archai | 1 | Points = require("../../index").Points
describe "Points", ->
describe "instantiation of", ->
it "no points or empty array + @a() gracefully returns the '-' id for none", ->
points = new Points []
points.length.should.eql 0
points.a().get('id').should.eql '-'
it "just a point with an Object (any id string + longitude) that can be got with @a()", ->
point = (new Points {"id": "Stellium", "lon": 9}).a()
point.get('id').should.eql "Stellium"
point.get('lon').should.eql 9
point.get('lat').should.eql 0
describe "change of coordinates", ->
it "changes the @at on 'lon' or 'lat' attribute change", ->
point = (new Points id: "c", lon: 1, lat: -1).a()
point.set lon: 3, lat: 2
point.at.lon.dec.should.eql 3
point.at.lat.dec.should.eql 2
| 173900 | Points = require("../../index").Points
describe "Points", ->
describe "instantiation of", ->
it "no points or empty array + @a() gracefully returns the '-' id for none", ->
points = new Points []
points.length.should.eql 0
points.a().get('id').should.eql '-'
it "just a point with an Object (any id string + longitude) that can be got with @a()", ->
point = (new Points {"id": "<NAME>", "lon": 9}).a()
point.get('id').should.eql "<NAME>"
point.get('lon').should.eql 9
point.get('lat').should.eql 0
describe "change of coordinates", ->
it "changes the @at on 'lon' or 'lat' attribute change", ->
point = (new Points id: "c", lon: 1, lat: -1).a()
point.set lon: 3, lat: 2
point.at.lon.dec.should.eql 3
point.at.lat.dec.should.eql 2
| true | Points = require("../../index").Points
describe "Points", ->
describe "instantiation of", ->
it "no points or empty array + @a() gracefully returns the '-' id for none", ->
points = new Points []
points.length.should.eql 0
points.a().get('id').should.eql '-'
it "just a point with an Object (any id string + longitude) that can be got with @a()", ->
point = (new Points {"id": "PI:NAME:<NAME>END_PI", "lon": 9}).a()
point.get('id').should.eql "PI:NAME:<NAME>END_PI"
point.get('lon').should.eql 9
point.get('lat').should.eql 0
describe "change of coordinates", ->
it "changes the @at on 'lon' or 'lat' attribute change", ->
point = (new Points id: "c", lon: 1, lat: -1).a()
point.set lon: 3, lat: 2
point.at.lon.dec.should.eql 3
point.at.lat.dec.should.eql 2
|
[
{
"context": ".FARMA.Keys\n\n @operators: ->\n [\n { key: \"÷\", value: \"\\\\over\", type: \"operator\" },\n { ke",
"end": 63,
"score": 0.9570726156234741,
"start": 62,
"tag": "KEY",
"value": "÷"
},
{
"context": " },\n ]\n\n @specialKeys: ->\n [\n { key: \"... | app/assets/javascripts/keyboard/keys.class.coffee | gzmarques/farma_keyboard_rails | 0 | class window.FARMA.Keys
@operators: ->
[
{ key: "÷", value: "\\over", type: "operator" },
{ key: "x", value: "*", type: "operator" },
{ key: "-", value: "-", type: "operator" },
{ key: "+", value: "+", type: "operator" }
]
@keys: ->
[
{ key: 1, value: 1, type: "key" },
{ key: 2, value: 2, type: "key" },
{ key: 3, value: 3, type: "key" },
# { key: "", value: "", type: "special mdi mdi-sigma" },
{ key: 4, value: 4, type: "key" },
{ key: 5, value: 5, type: "key" },
{ key: 6, value: 6, type: "key" },
# { key: "", value: "", type: "special mdi mdi-function" },
{ key: 7, value: 7, type: "key" },
{ key: 8, value: 8, type: "key" },
{ key: 9, value: 9, type: "key" },
# { key: "", value: "", type: "special mdi mdi-flask-outline" },
{ key: ".", value: ".", type: "key" },
{ key: 0, value: 0, type: "key" },
{ key: "=", value: "=", type: "key" }
# { key: "", value: "\\left[\\begin{matrix}\\end{matrix}\\right]", type: "special mdi mdi-matrix" },
]
@specialKeys: ->
[
{ key: "√", value: "\\sqrt{}", type: "key" },
{ key: "(", value: "{", type: "key" },
{ key: ")", value: "}", type: "key" },
{ key: "", value: "", type: "eval mdi mdi-desktop-mac tooltipped", options: "data-tooltip=Renderizar TeX data-delay=50 data-position=bottom" },
# { key: "", value: "check", type: "eval mdi mdi-account-check" }
# { key: "", value: "\\left[\\begin{matrix}\\end{matrix}\\right]", type: "operator mdi mdi-matrix" },
# { key: "&", value: "&", type: "key" },
# { key: "𝑥²", value: "^2", type: "key" },
# { key: "%", value: "*100", type: "key" },
# { key: "", value: "\\\\", type: "operator mdi mdi-keyboard-return" }
]
@functions: ->
[
{ key: "√", value: "\\sqrt{}", type: "key" },
{ key: "ϰ^y^", value: "{", type: "key" },
{ key: "1/ϰ", value: "{", type: "key" },
{ key: "y√ϰ", value: "{", type: "key" },
{ key: "x/y", value: "{", type: "key" },
{ key: "ln(ϰ)", value: "{", type: "key" },
{ key: "e^ϰ^", value: "{", type: "key" },
{ key: "log(ϰ)", value: "{", type: "key" },
{ key: "n!", value: "{", type: "key" },
{ key: "|ϰ|", value: "}", type: "key" }
]
@matrix: ->
[
{ key: "", value: "\\left[\\begin{matrix}\n\t\n\\end{matrix}\\right]", type: "operator mdi mdi-matrix" },
{ key: "&", value: "&", type: "key" },
{ key: "", value: "\\\\\n\t", type: "operator mdi mdi-keyboard-return" }
]
@trig: ->
[
{ key: "sin(ϰ)", value: "\\sin", type: "key" },
{ key: "sin-¹(ϰ)", value: "\\arcsin", type: "key" },
{ key: "π", value: "π", type: "key" },
{ key: "cos(ϰ)", value: "\\cos", type: "key" },
{ key: "cos-¹(ϰ)", value: "\\arccos", type: "key" },
{ key: "θ", value: "θ", type: "key" },
{ key: "tan(ϰ)", value: "\\tan", type: "key" },
{ key: "tan-¹(ϰ)", value: "\\arctan", type: "key" },
{ key: "α", value: "α", type: "key" }
]
| 70523 | class window.FARMA.Keys
@operators: ->
[
{ key: "<KEY>", value: "\\over", type: "operator" },
{ key: "x", value: "*", type: "operator" },
{ key: "-", value: "-", type: "operator" },
{ key: "+", value: "+", type: "operator" }
]
@keys: ->
[
{ key: 1, value: 1, type: "key" },
{ key: 2, value: 2, type: "key" },
{ key: 3, value: 3, type: "key" },
# { key: "", value: "", type: "special mdi mdi-sigma" },
{ key: 4, value: 4, type: "key" },
{ key: 5, value: 5, type: "key" },
{ key: 6, value: 6, type: "key" },
# { key: "", value: "", type: "special mdi mdi-function" },
{ key: 7, value: 7, type: "key" },
{ key: 8, value: 8, type: "key" },
{ key: 9, value: 9, type: "key" },
# { key: "", value: "", type: "special mdi mdi-flask-outline" },
{ key: ".", value: ".", type: "key" },
{ key: 0, value: 0, type: "key" },
{ key: "=", value: "=", type: "key" }
# { key: "", value: "\\left[\\begin{matrix}\\end{matrix}\\right]", type: "special mdi mdi-matrix" },
]
@specialKeys: ->
[
{ key: "<KEY>", value: "\\sqrt{}", type: "key" },
{ key: "(", value: "{", type: "key" },
{ key: ")", value: "}", type: "key" },
{ key: "", value: "", type: "eval mdi mdi-desktop-mac tooltipped", options: "data-tooltip=Renderizar TeX data-delay=50 data-position=bottom" },
# { key: "", value: "check", type: "eval mdi mdi-account-check" }
# { key: "", value: "\\left[\\begin{matrix}\\end{matrix}\\right]", type: "operator mdi mdi-matrix" },
# { key: "&", value: "&", type: "key" },
# { key: "<KEY>", value: "^2", type: "key" },
# { key: "%", value: "*100", type: "key" },
# { key: "", value: "\\\\", type: "operator mdi mdi-keyboard-return" }
]
@functions: ->
[
{ key: "√", value: "\\sqrt{}", type: "key" },
{ key: "<KEY>", value: "{", type: "key" },
{ key: "1/<KEY>", value: "{", type: "key" },
{ key: "y<KEY>", value: "{", type: "key" },
{ key: "x<KEY>/y", value: "{", type: "key" },
{ key: "ln(ϰ)", value: "{", type: "key" },
{ key: "e^<KEY>^", value: "{", type: "key" },
{ key: "log(ϰ)", value: "{", type: "key" },
{ key: "n!", value: "{", type: "key" },
{ key: "|ϰ|", value: "}", type: "key" }
]
@matrix: ->
[
{ key: "", value: "\\left[\\begin{matrix}\n\t\n\\end{matrix}\\right]", type: "operator mdi mdi-matrix" },
{ key: "&", value: "&", type: "key" },
{ key: "", value: "\\\\\n\t", type: "operator mdi mdi-keyboard-return" }
]
@trig: ->
[
{ key: "sin(ϰ)", value: "\\sin", type: "key" },
{ key: "sin-¹(ϰ)", value: "\\arcsin", type: "key" },
{ key: "π", value: "π", type: "key" },
{ key: "cos(ϰ)", value: "\\cos", type: "key" },
{ key: "cos-¹(ϰ)", value: "\\arccos", type: "key" },
{ key: "θ", value: "θ", type: "key" },
{ key: "tan(ϰ)", value: "\\tan", type: "key" },
{ key: "tan-¹(ϰ)", value: "\\arctan", type: "key" },
{ key: "α", value: "α", type: "key" }
]
| true | class window.FARMA.Keys
@operators: ->
[
{ key: "PI:KEY:<KEY>END_PI", value: "\\over", type: "operator" },
{ key: "x", value: "*", type: "operator" },
{ key: "-", value: "-", type: "operator" },
{ key: "+", value: "+", type: "operator" }
]
@keys: ->
[
{ key: 1, value: 1, type: "key" },
{ key: 2, value: 2, type: "key" },
{ key: 3, value: 3, type: "key" },
# { key: "", value: "", type: "special mdi mdi-sigma" },
{ key: 4, value: 4, type: "key" },
{ key: 5, value: 5, type: "key" },
{ key: 6, value: 6, type: "key" },
# { key: "", value: "", type: "special mdi mdi-function" },
{ key: 7, value: 7, type: "key" },
{ key: 8, value: 8, type: "key" },
{ key: 9, value: 9, type: "key" },
# { key: "", value: "", type: "special mdi mdi-flask-outline" },
{ key: ".", value: ".", type: "key" },
{ key: 0, value: 0, type: "key" },
{ key: "=", value: "=", type: "key" }
# { key: "", value: "\\left[\\begin{matrix}\\end{matrix}\\right]", type: "special mdi mdi-matrix" },
]
@specialKeys: ->
[
{ key: "PI:KEY:<KEY>END_PI", value: "\\sqrt{}", type: "key" },
{ key: "(", value: "{", type: "key" },
{ key: ")", value: "}", type: "key" },
{ key: "", value: "", type: "eval mdi mdi-desktop-mac tooltipped", options: "data-tooltip=Renderizar TeX data-delay=50 data-position=bottom" },
# { key: "", value: "check", type: "eval mdi mdi-account-check" }
# { key: "", value: "\\left[\\begin{matrix}\\end{matrix}\\right]", type: "operator mdi mdi-matrix" },
# { key: "&", value: "&", type: "key" },
# { key: "PI:KEY:<KEY>END_PI", value: "^2", type: "key" },
# { key: "%", value: "*100", type: "key" },
# { key: "", value: "\\\\", type: "operator mdi mdi-keyboard-return" }
]
@functions: ->
[
{ key: "√", value: "\\sqrt{}", type: "key" },
{ key: "PI:KEY:<KEY>END_PI", value: "{", type: "key" },
{ key: "1/PI:KEY:<KEY>END_PI", value: "{", type: "key" },
{ key: "yPI:KEY:<KEY>END_PI", value: "{", type: "key" },
{ key: "xPI:KEY:<KEY>END_PI/y", value: "{", type: "key" },
{ key: "ln(ϰ)", value: "{", type: "key" },
{ key: "e^PI:KEY:<KEY>END_PI^", value: "{", type: "key" },
{ key: "log(ϰ)", value: "{", type: "key" },
{ key: "n!", value: "{", type: "key" },
{ key: "|ϰ|", value: "}", type: "key" }
]
@matrix: ->
[
{ key: "", value: "\\left[\\begin{matrix}\n\t\n\\end{matrix}\\right]", type: "operator mdi mdi-matrix" },
{ key: "&", value: "&", type: "key" },
{ key: "", value: "\\\\\n\t", type: "operator mdi mdi-keyboard-return" }
]
@trig: ->
[
{ key: "sin(ϰ)", value: "\\sin", type: "key" },
{ key: "sin-¹(ϰ)", value: "\\arcsin", type: "key" },
{ key: "π", value: "π", type: "key" },
{ key: "cos(ϰ)", value: "\\cos", type: "key" },
{ key: "cos-¹(ϰ)", value: "\\arccos", type: "key" },
{ key: "θ", value: "θ", type: "key" },
{ key: "tan(ϰ)", value: "\\tan", type: "key" },
{ key: "tan-¹(ϰ)", value: "\\arctan", type: "key" },
{ key: "α", value: "α", type: "key" }
]
|
[
{
"context": "delay time.\n#\n# MIT License\n#\n# Copyright (c) 2018 Dennis Raymondo van der Sluis\n#\n# Permission is hereby granted, free of charge,",
"end": 159,
"score": 0.9998754262924194,
"start": 130,
"tag": "NAME",
"value": "Dennis Raymondo van der Sluis"
}
] | limited-calls.coffee | thght/limited-calls | 0 | # limited-calls - Wraps a function so it will only be called once during a set delay time.
#
# MIT License
#
# Copyright (c) 2018 Dennis Raymondo van der Sluis
#
# 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.
#
{ forceNumber, forceBoolean
forceFunction } = require 'types.js'
MISSING_FUNC_TEXT= 'limit-calls: invalid or missing function, check the first argument of limit-calls invocation.'
# in milliseconds
DELAY_DEFAULT= 100
class LimitedCalls
constructor: ( func, delay, ignorePending ) ->
@func = forceFunction func, -> console.log( MISSING_FUNC_TEXT )
@delay = forceNumber delay, DELAY_DEFAULT
@running = false
@pendingCall = false
@pendingCallArgs = []
@ignorePending = forceBoolean ignorePending
setPendingCall: ( args... ) ->
return if @ignorePending
@pendingCallArgs = args
@pendingCall = true
run: ( args... ) ->
return @setPendingCall(args...) if @running
@func args...
@running= true
setTimeout =>
if @pendingCall
@func @pendingCallArgs...
@pendingCall= false
@running= false
, @delay
# returns a function that can be called as many times, but only executes once during the delay time
#
# the last call of calls made during the delay is executed after the delay ends
# this can be disabled by passing true for ignorePending
#
module.exports= limitedCalls= ( func, delay, ignorePending ) ->
limitedCalls= new LimitedCalls func, delay, ignorePending
return ( args... ) -> limitedCalls.run args...
| 187052 | # limited-calls - Wraps a function so it will only be called once during a set delay time.
#
# MIT License
#
# Copyright (c) 2018 <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.
#
{ forceNumber, forceBoolean
forceFunction } = require 'types.js'
MISSING_FUNC_TEXT= 'limit-calls: invalid or missing function, check the first argument of limit-calls invocation.'
# in milliseconds
DELAY_DEFAULT= 100
class LimitedCalls
constructor: ( func, delay, ignorePending ) ->
@func = forceFunction func, -> console.log( MISSING_FUNC_TEXT )
@delay = forceNumber delay, DELAY_DEFAULT
@running = false
@pendingCall = false
@pendingCallArgs = []
@ignorePending = forceBoolean ignorePending
setPendingCall: ( args... ) ->
return if @ignorePending
@pendingCallArgs = args
@pendingCall = true
run: ( args... ) ->
return @setPendingCall(args...) if @running
@func args...
@running= true
setTimeout =>
if @pendingCall
@func @pendingCallArgs...
@pendingCall= false
@running= false
, @delay
# returns a function that can be called as many times, but only executes once during the delay time
#
# the last call of calls made during the delay is executed after the delay ends
# this can be disabled by passing true for ignorePending
#
module.exports= limitedCalls= ( func, delay, ignorePending ) ->
limitedCalls= new LimitedCalls func, delay, ignorePending
return ( args... ) -> limitedCalls.run args...
| true | # limited-calls - Wraps a function so it will only be called once during a set delay time.
#
# MIT License
#
# Copyright (c) 2018 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.
#
{ forceNumber, forceBoolean
forceFunction } = require 'types.js'
MISSING_FUNC_TEXT= 'limit-calls: invalid or missing function, check the first argument of limit-calls invocation.'
# in milliseconds
DELAY_DEFAULT= 100
class LimitedCalls
constructor: ( func, delay, ignorePending ) ->
@func = forceFunction func, -> console.log( MISSING_FUNC_TEXT )
@delay = forceNumber delay, DELAY_DEFAULT
@running = false
@pendingCall = false
@pendingCallArgs = []
@ignorePending = forceBoolean ignorePending
setPendingCall: ( args... ) ->
return if @ignorePending
@pendingCallArgs = args
@pendingCall = true
run: ( args... ) ->
return @setPendingCall(args...) if @running
@func args...
@running= true
setTimeout =>
if @pendingCall
@func @pendingCallArgs...
@pendingCall= false
@running= false
, @delay
# returns a function that can be called as many times, but only executes once during the delay time
#
# the last call of calls made during the delay is executed after the delay ends
# this can be disabled by passing true for ignorePending
#
module.exports= limitedCalls= ( func, delay, ignorePending ) ->
limitedCalls= new LimitedCalls func, delay, ignorePending
return ( args... ) -> limitedCalls.run args...
|
[
{
"context": "e 'dom' module of Lovely IO\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\ncore = require('core')\ndom = require('",
"end": 95,
"score": 0.999889612197876,
"start": 78,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/sugar/main.coffee | lovely-io/lovely.io-stl | 2 | #
# The syntax sugar for the 'dom' module of Lovely IO
#
# Copyright (C) 2011 Nikolay Nemshilov
#
core = require('core')
dom = require('dom')
A = core.A
ext = core.ext
document = global.document
include 'src/string' # NOTE: should be before the 'src/element' !
include 'src/element'
exports.version = '%{version}' | 12278 | #
# The syntax sugar for the 'dom' module of Lovely IO
#
# Copyright (C) 2011 <NAME>
#
core = require('core')
dom = require('dom')
A = core.A
ext = core.ext
document = global.document
include 'src/string' # NOTE: should be before the 'src/element' !
include 'src/element'
exports.version = '%{version}' | true | #
# The syntax sugar for the 'dom' module of Lovely IO
#
# Copyright (C) 2011 PI:NAME:<NAME>END_PI
#
core = require('core')
dom = require('dom')
A = core.A
ext = core.ext
document = global.document
include 'src/string' # NOTE: should be before the 'src/element' !
include 'src/element'
exports.version = '%{version}' |
[
{
"context": "onsole.log \"More information at http://github.com/fazo96/homework\"\n\n# Router\n###\nImportant: 'home' dispatc",
"end": 1642,
"score": 0.997605562210083,
"start": 1636,
"tag": "USERNAME",
"value": "fazo96"
},
{
"context": "reateUser {\n email: mail,\n pa... | client/client.coffee | fazo96/homework | 1 | # Homework - Client Side
version = "1.3"
# Utilities
tick = new Tracker.Dependency()
Meteor.setInterval (-> tick.changed();), 15000
notes = new Meteor.Collection 'notes'
userSub = Meteor.subscribe 'user'
getUser = -> Meteor.user()
deleteAccount = ->
swal {
title: 'Are you sure?'
text: 'Do you want to permanently delete all your data?'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, -> Meteor.call 'deleteMe', (r) -> if r is yes then Router.go 'home'
amIValid = ->
return no unless getUser()
return yes if getUser().username
return yes for mail in getUser().emails when mail.verified is yes; no
# Common Helpers for the Templates
UI.registerHelper "version", -> version
UI.registerHelper "status", -> Meteor.status()
UI.registerHelper "loading", -> Meteor.loggingIn() or !Meteor.status().connected
UI.registerHelper "APIAvailable", -> Meteor.settings.public?.enableAPI?
UI.registerHelper "facebookAvailable", ->
Accounts.loginServicesConfigured() and ServiceConfiguration.configurations.find(service: "facebook").count() > 0
UI.registerHelper "twitterAvailable", ->
Accounts.loginServicesConfigured() and ServiceConfiguration.configurations.find(service: "twitter").count() > 0
UI.registerHelper "email", ->
if getUser()
if getUser().username then return getUser().username
else return getUser().emails[0].address
UI.registerHelper "verified", -> amIValid()
Meteor.startup ->
console.log "Homework version "+version
console.log "This software is Free Software (MIT License)"
console.log "More information at http://github.com/fazo96/homework"
# Router
###
Important: 'home' dispatches the user to the correct landing page.
Routes are client side, but even if by hacking the client you can access pages
without being logged in, it's impossible to inteact with data because
the server doesn't let the user if he doesn't have permission. It's still safe.
###
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
notFoundTemplate: '404'
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else if Meteor.loggingIn()
@render 'loading'
else @render()
loggedInController = RouteController.extend
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else if !@ready() or Meteor.loggingIn()
@render 'loading'
else @render()
onBeforeAction: ->
if not getUser() then @redirect 'home'
else if not amIValid() then @redirect 'verifyEmail'
@next()
guestController = RouteController.extend
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else @render()
onBeforeAction: ->
if getUser()
if amIValid() is no then @redirect 'verifyEmail' else @redirect 'notes'
@next()
# Page Routing
Router.route '/',
name: 'home'
template: 'homepage'
action: ->
@render 'homepage', to: 'outside'
# Iron Router Workaround for a bug where content from previous renderings carries over if not overwritten
@render 'nothing'
onBeforeAction: ->
# Dispatch user to the right landing page based on his account status
if getUser()
if amIValid() is yes then @redirect 'notes' else @redirect 'verifyEmail'
@next()
Router.route '/login', controller: guestController
Router.route '/register', controller: guestController
Router.route '/account', controller: loggedInController
Router.route '/notes/:_id?',
name: 'notes'
waitOn: -> Meteor.subscribe 'notes', no
data: -> notes.findOne _id: @params._id
controller: loggedInController
Router.route '/verify/:token?',
name: 'verifyEmail'
template: 'verifyEmail'
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else @render(); @render 'nothing', to: 'outside'
onBeforeAction: ->
if getUser()
if amIValid()
@redirect 'home'
@next()
else if @params.token? and @params.token isnt ""
# Automatic verification
@render 'loading'
Accounts.verifyEmail @params.token, (err) =>
if err
errCallback err; Router.go 'verifyEmail', token: @params.token
else
showErr type:'success', msg:'Verification complete'
Router.go 'home'
@next()
@next()
else
@redirect 'home'
@next()
Router.route '/archive/:_id?',
name: 'archive'
waitOn: -> @notes = Meteor.subscribe 'notes', yes
onStop: -> @notes.stop()
controller: loggedInController
# Client Templates
# Some utility callbacks
logoutCallback = (err) ->
if err then errCallback err else Router.go 'home'
errCallback = (err) ->
if err.reason
showError msg: err.reason
else showError msg: err
loginCallback = (e) ->
if e? then errCallback e
else
Router.go 'notes'
swal 'Ok', 'Logged In', 'success'
Template.homepage.events
'click #facebook': -> Meteor.loginWithFacebook loginCallback
'click #twitter': -> Meteor.loginWithTwitter loginCallback
Template.reconnect.helpers
time : ->
tick.depend()
if Meteor.status().retryTime
'(retrying '+moment(Meteor.status().retryTime).fromNow()+')'
# 3 Buttons navigation Menu
Template.menu.events
'click .go-home': -> Router.go 'home'
'click .go-account': -> Router.go 'account'
'click .go-archive': -> Router.go 'archive'
# Account Page
Template.account.helpers
dateformat: -> if getUser() then return getUser().dateformat
apikey: -> if getUser() then return getUser().apiKey
Template.account.events
'click #reset-settings': (e,t) ->
t.find('#set-date-format').value = "MM/DD/YYYY"
t.find('#set-api-key').value = ''
'click #save-settings': (e,t) ->
Meteor.users.update getUser()._id,
$set:
dateformat: t.find('#set-date-format').value
apiKey: t.find('#set-api-key').value
showError msg: 'Settings saved', type: 'success'
'click #btn-logout': -> Meteor.logout logoutCallback
'click #btn-delete-me': -> deleteAccount()
# Notes list
formattedDate = ->
return unless @date
tick.depend()
#dif = moment(@date, getUser().dateformat).diff(moment(), 'days')
dif = moment.unix(@date).diff(moment(), 'days')
color = "primary"
color = "info" if dif < 7
color = "warning" if dif is 1
color = "danger" if dif < 1
msg: moment.unix(@date).fromNow(), color: color
notePaginator = new Paginator(10)
notelist = ->
notePaginator.calibrate(notes.find(archived: no).count())
opt = notePaginator.queryOptions()
notes.find({ archived: no },{
sort: {date: 1}, skip: opt.skip, limit: opt.limit
})
Template.notelist.helpers
notelist: -> notelist().fetch()
active: ->
return no unless Router.current() and Router.current().data()
return @_id is Router.current().data()._id
empty: -> notelist().count() is 0
getDate: formattedDate
paginator: -> notePaginator
pageActive: -> if @active then "btn-primary" else "btn-default"
Template.notelist.events
'click .close-note': -> notes.update @_id, $set: archived: yes
'click .edit-note': -> Router.go 'notes'
'keypress #newNote': (e,template) ->
if e.keyCode is 13 and template.find('#newNote').value isnt ""
notes.insert
title: template.find('#newNote').value
content: "", date: no, archived: no, userId: Meteor.userId()
template.find('#newNote').value = ""
'click .btn': -> notePaginator.page @index
# Archive
archivePaginator = new Paginator(10)
archived = ->
archivePaginator.calibrate(notes.find(archived: yes).count())
opt = archivePaginator.queryOptions()
notes.find({archived: yes},{
sort: {date: 1}, limit: opt.limit, skip: opt.skip
})
Template.archivedlist.helpers
empty: -> archived().count() is 0
getDate: formattedDate
archived: -> archived().fetch()
paginator: -> archivePaginator
pageActive: -> if @active then "btn-primary" else "btn-default"
Template.archivedlist.events
'click .close-note': -> notes.remove @_id
'click .note': -> notes.update @_id, $set: archived: no
'click .clear': ->
notes.remove item._id for item in Template.archivedlist.archived()
'click .btn': (e) -> archivePaginator.page @index
# Note Editor
Template.editor.helpers
note: -> Router.current().data()
dateformat: -> getUser().dateformat
formattedDate: ->
return unless @date
moment.unix(@date).format(getUser().dateformat)
saveCurrentNote = (t,e) ->
if e and e.keyCode isnt 13 then return
dat = no
if t.find('.date').value isnt ""
dat = moment(t.find('.date').value,getUser().dateformat)
if dat.isValid()
dat = dat.unix()
else
dat = no; showError msg: 'Invalid date'
t.find('.date').value = ""
notes.update Router.current().data()._id,
$set:
title: t.find('.editor-title').value
content: t.find('.area').value
date: dat
Template.editor.events
'click .close-editor': -> Router.go 'notes'
'click .save-editor': (e,t) -> saveCurrentNote t
'click .set-date': (e,t) ->
t.find('.date').value = moment().add(1,'days').format(getUser().dateformat)
'keypress .title': (e,t) -> saveCurrentNote t, e
# "Error" visualization template
showError = (err) ->
return unless err?
type = err.type or 'error'
if !err.title?
title = if type is 'error' then 'Error' else 'Ok'
else title = err.title
swal title, err.msg, type
# Verify Email page
Template.verifyEmail.helpers
token: -> Router.current().params.token
Template.verifyEmail.events
'click #btn-verify': (e,template) ->
t = template.find('#token-field').value; t = t.split("/")
t = t[t.length-1] # Remove all the part before the last "/"
Accounts.verifyEmail t, (err) ->
if err then errCallback err else Router.go 'notes'
'click #btn-resend': ->
Meteor.call 'resendConfirmEmail', (err) ->
if err
errCallback err
else showError { type:"success", msg: "Confirmation email sent" }
'click #btn-delete': -> deleteAccount()
'click #btn-logout': -> Meteor.logout logoutCallback
# Login
loginRequest = (e,template) ->
if e and e.keyCode isnt 13 then return
mail = template.find('#l-mail').value; pass = template.find('#l-pass').value
Meteor.loginWithPassword mail, pass, (err) ->
if err then errCallback err else Router.go 'notes'
Template.login.events
'keypress .login': (e,template) -> loginRequest e,template
'click #login-btn': (e,template) -> loginRequest null,template
# New Account page
registerRequest = (e,template) ->
if e and e.keyCode isnt 13 then return
mail = template.find('#r-mail').value; pass = template.find('#r-pass').value
pass2 = template.find('#r-pass-2').value
if not mail
showError msg: "Please enter an Email"
else if not pass
showError msg: "Please enter a password"
else if pass.length < 8
showError msg: "Password too short"
else if pass2 isnt pass
showError msg: "The passwords don't match"
else # Sending actual registration request
try
Accounts.createUser {
email: mail,
password: pass
}, (err) -> if err then errCallback err else Router.go 'confirmEmail'
catch err
showError msg: err
Template.register.events
'click #register-btn': (e,t) -> registerRequest null,t
'keypress .register': (e,t) -> registerRequest e,t
| 75228 | # Homework - Client Side
version = "1.3"
# Utilities
tick = new Tracker.Dependency()
Meteor.setInterval (-> tick.changed();), 15000
notes = new Meteor.Collection 'notes'
userSub = Meteor.subscribe 'user'
getUser = -> Meteor.user()
deleteAccount = ->
swal {
title: 'Are you sure?'
text: 'Do you want to permanently delete all your data?'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, -> Meteor.call 'deleteMe', (r) -> if r is yes then Router.go 'home'
amIValid = ->
return no unless getUser()
return yes if getUser().username
return yes for mail in getUser().emails when mail.verified is yes; no
# Common Helpers for the Templates
UI.registerHelper "version", -> version
UI.registerHelper "status", -> Meteor.status()
UI.registerHelper "loading", -> Meteor.loggingIn() or !Meteor.status().connected
UI.registerHelper "APIAvailable", -> Meteor.settings.public?.enableAPI?
UI.registerHelper "facebookAvailable", ->
Accounts.loginServicesConfigured() and ServiceConfiguration.configurations.find(service: "facebook").count() > 0
UI.registerHelper "twitterAvailable", ->
Accounts.loginServicesConfigured() and ServiceConfiguration.configurations.find(service: "twitter").count() > 0
UI.registerHelper "email", ->
if getUser()
if getUser().username then return getUser().username
else return getUser().emails[0].address
UI.registerHelper "verified", -> amIValid()
Meteor.startup ->
console.log "Homework version "+version
console.log "This software is Free Software (MIT License)"
console.log "More information at http://github.com/fazo96/homework"
# Router
###
Important: 'home' dispatches the user to the correct landing page.
Routes are client side, but even if by hacking the client you can access pages
without being logged in, it's impossible to inteact with data because
the server doesn't let the user if he doesn't have permission. It's still safe.
###
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
notFoundTemplate: '404'
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else if Meteor.loggingIn()
@render 'loading'
else @render()
loggedInController = RouteController.extend
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else if !@ready() or Meteor.loggingIn()
@render 'loading'
else @render()
onBeforeAction: ->
if not getUser() then @redirect 'home'
else if not amIValid() then @redirect 'verifyEmail'
@next()
guestController = RouteController.extend
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else @render()
onBeforeAction: ->
if getUser()
if amIValid() is no then @redirect 'verifyEmail' else @redirect 'notes'
@next()
# Page Routing
Router.route '/',
name: 'home'
template: 'homepage'
action: ->
@render 'homepage', to: 'outside'
# Iron Router Workaround for a bug where content from previous renderings carries over if not overwritten
@render 'nothing'
onBeforeAction: ->
# Dispatch user to the right landing page based on his account status
if getUser()
if amIValid() is yes then @redirect 'notes' else @redirect 'verifyEmail'
@next()
Router.route '/login', controller: guestController
Router.route '/register', controller: guestController
Router.route '/account', controller: loggedInController
Router.route '/notes/:_id?',
name: 'notes'
waitOn: -> Meteor.subscribe 'notes', no
data: -> notes.findOne _id: @params._id
controller: loggedInController
Router.route '/verify/:token?',
name: 'verifyEmail'
template: 'verifyEmail'
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else @render(); @render 'nothing', to: 'outside'
onBeforeAction: ->
if getUser()
if amIValid()
@redirect 'home'
@next()
else if @params.token? and @params.token isnt ""
# Automatic verification
@render 'loading'
Accounts.verifyEmail @params.token, (err) =>
if err
errCallback err; Router.go 'verifyEmail', token: @params.token
else
showErr type:'success', msg:'Verification complete'
Router.go 'home'
@next()
@next()
else
@redirect 'home'
@next()
Router.route '/archive/:_id?',
name: 'archive'
waitOn: -> @notes = Meteor.subscribe 'notes', yes
onStop: -> @notes.stop()
controller: loggedInController
# Client Templates
# Some utility callbacks
logoutCallback = (err) ->
if err then errCallback err else Router.go 'home'
errCallback = (err) ->
if err.reason
showError msg: err.reason
else showError msg: err
loginCallback = (e) ->
if e? then errCallback e
else
Router.go 'notes'
swal 'Ok', 'Logged In', 'success'
Template.homepage.events
'click #facebook': -> Meteor.loginWithFacebook loginCallback
'click #twitter': -> Meteor.loginWithTwitter loginCallback
Template.reconnect.helpers
time : ->
tick.depend()
if Meteor.status().retryTime
'(retrying '+moment(Meteor.status().retryTime).fromNow()+')'
# 3 Buttons navigation Menu
Template.menu.events
'click .go-home': -> Router.go 'home'
'click .go-account': -> Router.go 'account'
'click .go-archive': -> Router.go 'archive'
# Account Page
Template.account.helpers
dateformat: -> if getUser() then return getUser().dateformat
apikey: -> if getUser() then return getUser().apiKey
Template.account.events
'click #reset-settings': (e,t) ->
t.find('#set-date-format').value = "MM/DD/YYYY"
t.find('#set-api-key').value = ''
'click #save-settings': (e,t) ->
Meteor.users.update getUser()._id,
$set:
dateformat: t.find('#set-date-format').value
apiKey: t.find('#set-api-key').value
showError msg: 'Settings saved', type: 'success'
'click #btn-logout': -> Meteor.logout logoutCallback
'click #btn-delete-me': -> deleteAccount()
# Notes list
formattedDate = ->
return unless @date
tick.depend()
#dif = moment(@date, getUser().dateformat).diff(moment(), 'days')
dif = moment.unix(@date).diff(moment(), 'days')
color = "primary"
color = "info" if dif < 7
color = "warning" if dif is 1
color = "danger" if dif < 1
msg: moment.unix(@date).fromNow(), color: color
notePaginator = new Paginator(10)
notelist = ->
notePaginator.calibrate(notes.find(archived: no).count())
opt = notePaginator.queryOptions()
notes.find({ archived: no },{
sort: {date: 1}, skip: opt.skip, limit: opt.limit
})
Template.notelist.helpers
notelist: -> notelist().fetch()
active: ->
return no unless Router.current() and Router.current().data()
return @_id is Router.current().data()._id
empty: -> notelist().count() is 0
getDate: formattedDate
paginator: -> notePaginator
pageActive: -> if @active then "btn-primary" else "btn-default"
Template.notelist.events
'click .close-note': -> notes.update @_id, $set: archived: yes
'click .edit-note': -> Router.go 'notes'
'keypress #newNote': (e,template) ->
if e.keyCode is 13 and template.find('#newNote').value isnt ""
notes.insert
title: template.find('#newNote').value
content: "", date: no, archived: no, userId: Meteor.userId()
template.find('#newNote').value = ""
'click .btn': -> notePaginator.page @index
# Archive
archivePaginator = new Paginator(10)
archived = ->
archivePaginator.calibrate(notes.find(archived: yes).count())
opt = archivePaginator.queryOptions()
notes.find({archived: yes},{
sort: {date: 1}, limit: opt.limit, skip: opt.skip
})
Template.archivedlist.helpers
empty: -> archived().count() is 0
getDate: formattedDate
archived: -> archived().fetch()
paginator: -> archivePaginator
pageActive: -> if @active then "btn-primary" else "btn-default"
Template.archivedlist.events
'click .close-note': -> notes.remove @_id
'click .note': -> notes.update @_id, $set: archived: no
'click .clear': ->
notes.remove item._id for item in Template.archivedlist.archived()
'click .btn': (e) -> archivePaginator.page @index
# Note Editor
Template.editor.helpers
note: -> Router.current().data()
dateformat: -> getUser().dateformat
formattedDate: ->
return unless @date
moment.unix(@date).format(getUser().dateformat)
saveCurrentNote = (t,e) ->
if e and e.keyCode isnt 13 then return
dat = no
if t.find('.date').value isnt ""
dat = moment(t.find('.date').value,getUser().dateformat)
if dat.isValid()
dat = dat.unix()
else
dat = no; showError msg: 'Invalid date'
t.find('.date').value = ""
notes.update Router.current().data()._id,
$set:
title: t.find('.editor-title').value
content: t.find('.area').value
date: dat
Template.editor.events
'click .close-editor': -> Router.go 'notes'
'click .save-editor': (e,t) -> saveCurrentNote t
'click .set-date': (e,t) ->
t.find('.date').value = moment().add(1,'days').format(getUser().dateformat)
'keypress .title': (e,t) -> saveCurrentNote t, e
# "Error" visualization template
showError = (err) ->
return unless err?
type = err.type or 'error'
if !err.title?
title = if type is 'error' then 'Error' else 'Ok'
else title = err.title
swal title, err.msg, type
# Verify Email page
Template.verifyEmail.helpers
token: -> Router.current().params.token
Template.verifyEmail.events
'click #btn-verify': (e,template) ->
t = template.find('#token-field').value; t = t.split("/")
t = t[t.length-1] # Remove all the part before the last "/"
Accounts.verifyEmail t, (err) ->
if err then errCallback err else Router.go 'notes'
'click #btn-resend': ->
Meteor.call 'resendConfirmEmail', (err) ->
if err
errCallback err
else showError { type:"success", msg: "Confirmation email sent" }
'click #btn-delete': -> deleteAccount()
'click #btn-logout': -> Meteor.logout logoutCallback
# Login
loginRequest = (e,template) ->
if e and e.keyCode isnt 13 then return
mail = template.find('#l-mail').value; pass = template.find('#l-pass').value
Meteor.loginWithPassword mail, pass, (err) ->
if err then errCallback err else Router.go 'notes'
Template.login.events
'keypress .login': (e,template) -> loginRequest e,template
'click #login-btn': (e,template) -> loginRequest null,template
# New Account page
registerRequest = (e,template) ->
if e and e.keyCode isnt 13 then return
mail = template.find('#r-mail').value; pass = template.find('#r-pass').value
pass2 = template.find('#r-pass-2').value
if not mail
showError msg: "Please enter an Email"
else if not pass
showError msg: "Please enter a password"
else if pass.length < 8
showError msg: "Password too short"
else if pass2 isnt pass
showError msg: "The passwords don't match"
else # Sending actual registration request
try
Accounts.createUser {
email: mail,
password: <PASSWORD>
}, (err) -> if err then errCallback err else Router.go 'confirmEmail'
catch err
showError msg: err
Template.register.events
'click #register-btn': (e,t) -> registerRequest null,t
'keypress .register': (e,t) -> registerRequest e,t
| true | # Homework - Client Side
version = "1.3"
# Utilities
tick = new Tracker.Dependency()
Meteor.setInterval (-> tick.changed();), 15000
notes = new Meteor.Collection 'notes'
userSub = Meteor.subscribe 'user'
getUser = -> Meteor.user()
deleteAccount = ->
swal {
title: 'Are you sure?'
text: 'Do you want to permanently delete all your data?'
type: 'warning'
showCancelButton: yes
confirmButtonColor: "#DD6B55"
confirmButtonText: "Yes!"
}, -> Meteor.call 'deleteMe', (r) -> if r is yes then Router.go 'home'
amIValid = ->
return no unless getUser()
return yes if getUser().username
return yes for mail in getUser().emails when mail.verified is yes; no
# Common Helpers for the Templates
UI.registerHelper "version", -> version
UI.registerHelper "status", -> Meteor.status()
UI.registerHelper "loading", -> Meteor.loggingIn() or !Meteor.status().connected
UI.registerHelper "APIAvailable", -> Meteor.settings.public?.enableAPI?
UI.registerHelper "facebookAvailable", ->
Accounts.loginServicesConfigured() and ServiceConfiguration.configurations.find(service: "facebook").count() > 0
UI.registerHelper "twitterAvailable", ->
Accounts.loginServicesConfigured() and ServiceConfiguration.configurations.find(service: "twitter").count() > 0
UI.registerHelper "email", ->
if getUser()
if getUser().username then return getUser().username
else return getUser().emails[0].address
UI.registerHelper "verified", -> amIValid()
Meteor.startup ->
console.log "Homework version "+version
console.log "This software is Free Software (MIT License)"
console.log "More information at http://github.com/fazo96/homework"
# Router
###
Important: 'home' dispatches the user to the correct landing page.
Routes are client side, but even if by hacking the client you can access pages
without being logged in, it's impossible to inteact with data because
the server doesn't let the user if he doesn't have permission. It's still safe.
###
Router.configure
layoutTemplate: 'layout'
loadingTemplate: 'loading'
notFoundTemplate: '404'
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else if Meteor.loggingIn()
@render 'loading'
else @render()
loggedInController = RouteController.extend
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else if !@ready() or Meteor.loggingIn()
@render 'loading'
else @render()
onBeforeAction: ->
if not getUser() then @redirect 'home'
else if not amIValid() then @redirect 'verifyEmail'
@next()
guestController = RouteController.extend
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else @render()
onBeforeAction: ->
if getUser()
if amIValid() is no then @redirect 'verifyEmail' else @redirect 'notes'
@next()
# Page Routing
Router.route '/',
name: 'home'
template: 'homepage'
action: ->
@render 'homepage', to: 'outside'
# Iron Router Workaround for a bug where content from previous renderings carries over if not overwritten
@render 'nothing'
onBeforeAction: ->
# Dispatch user to the right landing page based on his account status
if getUser()
if amIValid() is yes then @redirect 'notes' else @redirect 'verifyEmail'
@next()
Router.route '/login', controller: guestController
Router.route '/register', controller: guestController
Router.route '/account', controller: loggedInController
Router.route '/notes/:_id?',
name: 'notes'
waitOn: -> Meteor.subscribe 'notes', no
data: -> notes.findOne _id: @params._id
controller: loggedInController
Router.route '/verify/:token?',
name: 'verifyEmail'
template: 'verifyEmail'
action: ->
if Meteor.status().connected is no
@render 'reconnect'
else @render(); @render 'nothing', to: 'outside'
onBeforeAction: ->
if getUser()
if amIValid()
@redirect 'home'
@next()
else if @params.token? and @params.token isnt ""
# Automatic verification
@render 'loading'
Accounts.verifyEmail @params.token, (err) =>
if err
errCallback err; Router.go 'verifyEmail', token: @params.token
else
showErr type:'success', msg:'Verification complete'
Router.go 'home'
@next()
@next()
else
@redirect 'home'
@next()
Router.route '/archive/:_id?',
name: 'archive'
waitOn: -> @notes = Meteor.subscribe 'notes', yes
onStop: -> @notes.stop()
controller: loggedInController
# Client Templates
# Some utility callbacks
logoutCallback = (err) ->
if err then errCallback err else Router.go 'home'
errCallback = (err) ->
if err.reason
showError msg: err.reason
else showError msg: err
loginCallback = (e) ->
if e? then errCallback e
else
Router.go 'notes'
swal 'Ok', 'Logged In', 'success'
Template.homepage.events
'click #facebook': -> Meteor.loginWithFacebook loginCallback
'click #twitter': -> Meteor.loginWithTwitter loginCallback
Template.reconnect.helpers
time : ->
tick.depend()
if Meteor.status().retryTime
'(retrying '+moment(Meteor.status().retryTime).fromNow()+')'
# 3 Buttons navigation Menu
Template.menu.events
'click .go-home': -> Router.go 'home'
'click .go-account': -> Router.go 'account'
'click .go-archive': -> Router.go 'archive'
# Account Page
Template.account.helpers
dateformat: -> if getUser() then return getUser().dateformat
apikey: -> if getUser() then return getUser().apiKey
Template.account.events
'click #reset-settings': (e,t) ->
t.find('#set-date-format').value = "MM/DD/YYYY"
t.find('#set-api-key').value = ''
'click #save-settings': (e,t) ->
Meteor.users.update getUser()._id,
$set:
dateformat: t.find('#set-date-format').value
apiKey: t.find('#set-api-key').value
showError msg: 'Settings saved', type: 'success'
'click #btn-logout': -> Meteor.logout logoutCallback
'click #btn-delete-me': -> deleteAccount()
# Notes list
formattedDate = ->
return unless @date
tick.depend()
#dif = moment(@date, getUser().dateformat).diff(moment(), 'days')
dif = moment.unix(@date).diff(moment(), 'days')
color = "primary"
color = "info" if dif < 7
color = "warning" if dif is 1
color = "danger" if dif < 1
msg: moment.unix(@date).fromNow(), color: color
notePaginator = new Paginator(10)
notelist = ->
notePaginator.calibrate(notes.find(archived: no).count())
opt = notePaginator.queryOptions()
notes.find({ archived: no },{
sort: {date: 1}, skip: opt.skip, limit: opt.limit
})
Template.notelist.helpers
notelist: -> notelist().fetch()
active: ->
return no unless Router.current() and Router.current().data()
return @_id is Router.current().data()._id
empty: -> notelist().count() is 0
getDate: formattedDate
paginator: -> notePaginator
pageActive: -> if @active then "btn-primary" else "btn-default"
Template.notelist.events
'click .close-note': -> notes.update @_id, $set: archived: yes
'click .edit-note': -> Router.go 'notes'
'keypress #newNote': (e,template) ->
if e.keyCode is 13 and template.find('#newNote').value isnt ""
notes.insert
title: template.find('#newNote').value
content: "", date: no, archived: no, userId: Meteor.userId()
template.find('#newNote').value = ""
'click .btn': -> notePaginator.page @index
# Archive
archivePaginator = new Paginator(10)
archived = ->
archivePaginator.calibrate(notes.find(archived: yes).count())
opt = archivePaginator.queryOptions()
notes.find({archived: yes},{
sort: {date: 1}, limit: opt.limit, skip: opt.skip
})
Template.archivedlist.helpers
empty: -> archived().count() is 0
getDate: formattedDate
archived: -> archived().fetch()
paginator: -> archivePaginator
pageActive: -> if @active then "btn-primary" else "btn-default"
Template.archivedlist.events
'click .close-note': -> notes.remove @_id
'click .note': -> notes.update @_id, $set: archived: no
'click .clear': ->
notes.remove item._id for item in Template.archivedlist.archived()
'click .btn': (e) -> archivePaginator.page @index
# Note Editor
Template.editor.helpers
note: -> Router.current().data()
dateformat: -> getUser().dateformat
formattedDate: ->
return unless @date
moment.unix(@date).format(getUser().dateformat)
saveCurrentNote = (t,e) ->
if e and e.keyCode isnt 13 then return
dat = no
if t.find('.date').value isnt ""
dat = moment(t.find('.date').value,getUser().dateformat)
if dat.isValid()
dat = dat.unix()
else
dat = no; showError msg: 'Invalid date'
t.find('.date').value = ""
notes.update Router.current().data()._id,
$set:
title: t.find('.editor-title').value
content: t.find('.area').value
date: dat
Template.editor.events
'click .close-editor': -> Router.go 'notes'
'click .save-editor': (e,t) -> saveCurrentNote t
'click .set-date': (e,t) ->
t.find('.date').value = moment().add(1,'days').format(getUser().dateformat)
'keypress .title': (e,t) -> saveCurrentNote t, e
# "Error" visualization template
showError = (err) ->
return unless err?
type = err.type or 'error'
if !err.title?
title = if type is 'error' then 'Error' else 'Ok'
else title = err.title
swal title, err.msg, type
# Verify Email page
Template.verifyEmail.helpers
token: -> Router.current().params.token
Template.verifyEmail.events
'click #btn-verify': (e,template) ->
t = template.find('#token-field').value; t = t.split("/")
t = t[t.length-1] # Remove all the part before the last "/"
Accounts.verifyEmail t, (err) ->
if err then errCallback err else Router.go 'notes'
'click #btn-resend': ->
Meteor.call 'resendConfirmEmail', (err) ->
if err
errCallback err
else showError { type:"success", msg: "Confirmation email sent" }
'click #btn-delete': -> deleteAccount()
'click #btn-logout': -> Meteor.logout logoutCallback
# Login
loginRequest = (e,template) ->
if e and e.keyCode isnt 13 then return
mail = template.find('#l-mail').value; pass = template.find('#l-pass').value
Meteor.loginWithPassword mail, pass, (err) ->
if err then errCallback err else Router.go 'notes'
Template.login.events
'keypress .login': (e,template) -> loginRequest e,template
'click #login-btn': (e,template) -> loginRequest null,template
# New Account page
registerRequest = (e,template) ->
if e and e.keyCode isnt 13 then return
mail = template.find('#r-mail').value; pass = template.find('#r-pass').value
pass2 = template.find('#r-pass-2').value
if not mail
showError msg: "Please enter an Email"
else if not pass
showError msg: "Please enter a password"
else if pass.length < 8
showError msg: "Password too short"
else if pass2 isnt pass
showError msg: "The passwords don't match"
else # Sending actual registration request
try
Accounts.createUser {
email: mail,
password: PI:PASSWORD:<PASSWORD>END_PI
}, (err) -> if err then errCallback err else Router.go 'confirmEmail'
catch err
showError msg: err
Template.register.events
'click #register-btn': (e,t) -> registerRequest null,t
'keypress .register': (e,t) -> registerRequest e,t
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.563602089881897,
"start": 33,
"tag": "NAME",
"value": "Technology"
}
] | community/server/src/main/coffeescript/ribcage/Router.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['lib/amd/Backbone', 'lib/amd/HotKeys'],
(Backbone) ->
class Router extends Backbone.Router
# Override in subclasses to add url routes
routes : {}
# Override in subclasses to add keyboard shortcuts
shortcuts : {}
constructor : ->
super()
for definition, method of @shortcuts
$(document).bind("keyup", definition, this[method])
saveLocation : () ->
@navigate(location.hash, false)
)
| 49989 | ###
Copyright (c) 2002-2013 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['lib/amd/Backbone', 'lib/amd/HotKeys'],
(Backbone) ->
class Router extends Backbone.Router
# Override in subclasses to add url routes
routes : {}
# Override in subclasses to add keyboard shortcuts
shortcuts : {}
constructor : ->
super()
for definition, method of @shortcuts
$(document).bind("keyup", definition, this[method])
saveLocation : () ->
@navigate(location.hash, false)
)
| true | ###
Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['lib/amd/Backbone', 'lib/amd/HotKeys'],
(Backbone) ->
class Router extends Backbone.Router
# Override in subclasses to add url routes
routes : {}
# Override in subclasses to add keyboard shortcuts
shortcuts : {}
constructor : ->
super()
for definition, method of @shortcuts
$(document).bind("keyup", definition, this[method])
saveLocation : () ->
@navigate(location.hash, false)
)
|
[
{
"context": "s', 'vis'])\n expect(keys).to.eql(['aap', 'noot', 'mies'])\n expect(iteration",
"end": 10779,
"score": 0.8765714764595032,
"start": 10774,
"tag": "KEY",
"value": "aap',"
},
{
"context": "s'])\n expect(keys).to.eql(['aap', 'no... | test/components/nativestorage_driver_spec.coffee | kabisa/maji-extras | 0 | nativeStorageDriver = require('components/nativestorage_driver')
describe 'NativeStorage Driver', ->
beforeEach ->
delete nativeStorageDriver._dbInfo
describe '#_driver', ->
it 'returns its unique identifier', ->
expect(nativeStorageDriver._driver).to.eql('nativeStorageDriver')
describe '#_support', ->
context 'when NativeStorage is undefined', ->
it 'returns a promise that is resolved to false', ->
expect(nativeStorageDriver._support()).to.eventually.be.false
context 'when NativeStorage is defined', ->
beforeEach ->
window.NativeStorage = {}
afterEach ->
delete window.NativeStorage
it 'returns a promise that is resolved to true', ->
expect(nativeStorageDriver._support()).to.eventually.be.true
context 'with a fake implementation of NativeStorage', ->
beforeEach ->
window.NativeStorage = nativeStorageFake({})
afterEach ->
delete window.NativeStorage
describe '#_initStorage', ->
it 'copies the properties of its argument to the _dbInfo property', ->
nativeStorageDriver._initStorage({ test: 'test' })
.then ->
expect(nativeStorageDriver._dbInfo.test).to.eql('test')
it 'uses the name and store name passed as options to construct the key prefixes', ->
nativeStorageDriver._initStorage({ name: 'someName', storeName: 'someStoreName' })
.then ->
expect(nativeStorageDriver._dbInfo.keyPrefix).to.eql('someName/someStoreName/')
expect(nativeStorageDriver._dbInfo.dataKeyPrefix).to.eql('someName/someStoreName/data/')
expect(nativeStorageDriver._dbInfo.metaKeyPrefix).to.eql('someName/someStoreName/meta/')
context 'with a #ready method that returns a resolved promise', ->
beforeEach ->
nativeStorageDriver.ready = -> Promise.resolve()
context 'with a default name and store name', ->
beforeEach ->
nativeStorageDriver._initStorage({ name: 'name', storeName: 'storeName' })
describe '#getItem', ->
context 'when a key-value pair is stored', ->
beforeEach ->
nativeStorageDriver.setItem('key', 'value')
it 'returns a promise that is resolved with the value for the given key', ->
expect(nativeStorageDriver.getItem('key')).to.eventually.equal('value')
it 'calls the provided callback with the value for the given key', ->
callback = sinon.spy()
nativeStorageDriver.getItem('key', callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'value')
it 'returns a promise that is resolved with null for an unknown key', ->
expect(
nativeStorageDriver.getItem('unknownKey')
).to.be.eventually.eq(null)
it 'calls the provided callback with null for an unknown key', ->
callback = sinon.spy()
nativeStorageDriver.getItem('unknownKey', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback).to.have.been.calledWith(null, null)
it 'rejects a promise when an error occurs', ->
expect(
nativeStorageDriver.getItem('unretrievableKey')
).to.be.rejectedWith(Error, 'Wrong parameter for key \'name/storeName/data/unretrievableKey\'')
describe '#setItem', ->
it 'returns a promise that is resolved with the value passed as argument for a valid key', ->
nativeStorageDriver.setItem('key', 'value')
.then (storedValue) ->
expect(storedValue).to.eql('value')
nativeStorageDriver.getItem('key')
.then (retrievedValue) ->
expect(retrievedValue).to.eql('value')
it 'calls the provided callback with the value passed as argument for a valid key', ->
callback = sinon.spy()
nativeStorageDriver.setItem('key', 'value', callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'value')
expect(nativeStorageDriver.getItem('key')).to.eventually.equal('value')
it 'has no effect on other storages', ->
nativeStorageDriver.setItem('key', 'value')
.then (storedValue) ->
expect(storedValue).to.eql('value')
nativeStorageDriver.getItem('key')
.then (retrievedValue) ->
expect(retrievedValue).to.eql('value')
nativeStorageDriver._initStorage({ name: 'otherName', storeName: 'otherStoreName' })
.then ->
expect(
nativeStorageDriver.getItem('key')
).to.eventually.eq(null)
it 'returns a promise that is rejected with an error for an invalid key-value pair', ->
expect(
nativeStorageDriver.setItem('unstorableKey', 'value')
).to.be.rejectedWith(Error, 'Unable to store key \'name/storeName/data/unstorableKey\' and value \'"value"\'')
it 'calls the provided callback with an error for an invalid key-value pair', ->
callback = sinon.spy()
nativeStorageDriver.setItem('unstorableKey', 'value', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to store key \'name/storeName/data/unstorableKey\' and value \'"value"\'')
describe '#removeItem', ->
context 'when a key-value pair is stored', ->
beforeEach -> nativeStorageDriver.setItem('key', 'value')
it 'returns a promise that is resolved for the valid key', ->
expect(nativeStorageDriver.removeItem('key')).to.eventually.fulfill
it 'calls the provided callback with null as first argument for the valid key', ->
callback = sinon.spy()
nativeStorageDriver.removeItem('key', callback)
.then ->
expect(callback).to.have.been.calledWith(null)
it 'returns a promise that is rejected for an invalid key', ->
expect(
nativeStorageDriver.removeItem('unremovableKey')
).to.be.rejectedWith(Error, 'Unable to remove value for key \'name/storeName/data/unremovableKey\'')
it 'calls the provided callback with an error for an invalid key', ->
callback = sinon.spy()
nativeStorageDriver.removeItem('unremovableKey', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to remove value for key \'name/storeName/data/unremovableKey\'')
describe '#keys', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to an array of keys for the valid prefix', ->
expect(
nativeStorageDriver.keys()
).to.eventually.eql(['aap', 'noot', 'mies'])
it 'calls the provided callback with an array of keys for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.keys(callback)
.then ->
expect(callback).to.have.been.calledWith(null, ['aap', 'noot', 'mies'])
describe '#length', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to the number of keys for the valid prefix', ->
expect(
nativeStorageDriver.length()
).to.eventually.eql(3)
it 'calls the provided callback with the number of keys for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.length(callback)
.then ->
expect(callback).to.have.been.calledWith(null, 3)
describe '#key', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to the key at the given index for the valid prefix', ->
expect(nativeStorageDriver.key(0)).to.eventually.eql('aap')
it 'calls the provided callback with the key at the given index for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.key(1, callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'noot')
it 'returns a promise that resolves to undefined when an out-of-bounds index is provided', ->
expect(nativeStorageDriver.key(10)).to.eventually.eql(undefined)
it 'calls the provided callback with undefined when an out-of-bounds index is provided', ->
callback = sinon.spy()
nativeStorageDriver.key(10, callback)
.then ->
expect(callback).to.have.been.calledWith(null, undefined)
describe '#iterate', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'calls the iterator for each value in storage and returns a promise that is resolved', ->
values = []
keys = []
iterationNumbers = []
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
values.push value
keys.push key
iterationNumbers.push iterationNumber
return
).then ->
expect(values).to.eql(['boom', 'roos', 'vis'])
expect(keys).to.eql(['aap', 'noot', 'mies'])
expect(iterationNumbers).to.eql([1, 2, 3])
it 'calls the iterator for each value in storage and the success callback afterwards', ->
values = []
keys = []
iterationNumbers = []
successCallback = sinon.spy()
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
values.push value
keys.push key
iterationNumbers.push iterationNumber
return
successCallback
).then ->
expect(successCallback).to.have.been.calledOnce
expect(values).to.eql(['boom', 'roos', 'vis'])
expect(keys).to.eql(['aap', 'noot', 'mies'])
expect(iterationNumbers).to.eql([1, 2, 3])
it 'supports early exit', ->
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
return 'some value to force an early exit'
).then (value) ->
expect(value).to.eql('some value to force an early exit')
describe '#clear', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved', ->
expect(nativeStorageDriver.clear()).to.eventually.fulfill
it 'calls the provided callback with null as the first argument', ->
callback = sinon.spy()
nativeStorageDriver.clear(callback)
.then ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0]).to.be.null
it 'removes all key-value pairs', ->
nativeStorageDriver.clear()
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(0)
context 'with another storage containing key-value pairs', ->
beforeEach ->
nativeStorageDriver._initStorage({ name: 'otherName', storeName: 'otherStoreName' })
.then ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'only removes the key-value pairs from the current storage', ->
nativeStorageDriver.clear()
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(0)
nativeStorageDriver._initStorage({ name: 'name', storeName: 'storeName' })
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(3)
context 'when a key-value pair cannot be removed', ->
beforeEach -> nativeStorageDriver.setItem('unremovableKey', 'value')
it 'returns a promise that is rejected', ->
expect(
nativeStorageDriver.clear()
).to.eventually.be.rejectedWith(Error, 'Unable to remove value for key \'name/storeName/data/unremovableKey\'')
it 'returns a promise that supports `catch`', ->
val = 'executed'
expect(
nativeStorageDriver.clear()
.then -> val = 'skipped'
.catch (e) -> val += ' & handled'
.then -> val
).to.eventually.eql 'executed & handled'
it 'calls the provided callback with an error', ->
callback = sinon.spy()
nativeStorageDriver.clear(callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to remove value for key \'name/storeName/data/unremovableKey\'')
nativeStorageFake =
(state) ->
unstorableKey = 'name/storeName/data/unstorableKey'
unremovableKey = 'name/storeName/data/unremovableKey'
unretrievableKey = 'name/storeName/data/unretrievableKey'
{
getItem: (key, success, error) ->
value = state[key]
if key == unretrievableKey
e = new Error("Wrong parameter for key '#{key}'")
# https://github.com/TheCocoaProject/cordova-plugin-nativestorage#error-codes
e.code = 6 # WRONG_PARAMETER
error(e)
else if (value != undefined)
success(value)
else
e = new Error("No value found for key '#{key}'")
# https://github.com/TheCocoaProject/cordova-plugin-nativestorage#error-codes
e.code = 2 # ITEM_NOT_FOUND
error(e)
setItem: (key, value, success, error) ->
if key == unstorableKey
error(new Error("Unable to store key '#{key}' and value '#{value}'"))
else
state[key] = value
success(value)
remove: (key, success, error) ->
if key == unremovableKey
error(new Error("Unable to remove value for key '#{key}'"))
else
delete state[key]
success()
}
| 169169 | nativeStorageDriver = require('components/nativestorage_driver')
describe 'NativeStorage Driver', ->
beforeEach ->
delete nativeStorageDriver._dbInfo
describe '#_driver', ->
it 'returns its unique identifier', ->
expect(nativeStorageDriver._driver).to.eql('nativeStorageDriver')
describe '#_support', ->
context 'when NativeStorage is undefined', ->
it 'returns a promise that is resolved to false', ->
expect(nativeStorageDriver._support()).to.eventually.be.false
context 'when NativeStorage is defined', ->
beforeEach ->
window.NativeStorage = {}
afterEach ->
delete window.NativeStorage
it 'returns a promise that is resolved to true', ->
expect(nativeStorageDriver._support()).to.eventually.be.true
context 'with a fake implementation of NativeStorage', ->
beforeEach ->
window.NativeStorage = nativeStorageFake({})
afterEach ->
delete window.NativeStorage
describe '#_initStorage', ->
it 'copies the properties of its argument to the _dbInfo property', ->
nativeStorageDriver._initStorage({ test: 'test' })
.then ->
expect(nativeStorageDriver._dbInfo.test).to.eql('test')
it 'uses the name and store name passed as options to construct the key prefixes', ->
nativeStorageDriver._initStorage({ name: 'someName', storeName: 'someStoreName' })
.then ->
expect(nativeStorageDriver._dbInfo.keyPrefix).to.eql('someName/someStoreName/')
expect(nativeStorageDriver._dbInfo.dataKeyPrefix).to.eql('someName/someStoreName/data/')
expect(nativeStorageDriver._dbInfo.metaKeyPrefix).to.eql('someName/someStoreName/meta/')
context 'with a #ready method that returns a resolved promise', ->
beforeEach ->
nativeStorageDriver.ready = -> Promise.resolve()
context 'with a default name and store name', ->
beforeEach ->
nativeStorageDriver._initStorage({ name: 'name', storeName: 'storeName' })
describe '#getItem', ->
context 'when a key-value pair is stored', ->
beforeEach ->
nativeStorageDriver.setItem('key', 'value')
it 'returns a promise that is resolved with the value for the given key', ->
expect(nativeStorageDriver.getItem('key')).to.eventually.equal('value')
it 'calls the provided callback with the value for the given key', ->
callback = sinon.spy()
nativeStorageDriver.getItem('key', callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'value')
it 'returns a promise that is resolved with null for an unknown key', ->
expect(
nativeStorageDriver.getItem('unknownKey')
).to.be.eventually.eq(null)
it 'calls the provided callback with null for an unknown key', ->
callback = sinon.spy()
nativeStorageDriver.getItem('unknownKey', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback).to.have.been.calledWith(null, null)
it 'rejects a promise when an error occurs', ->
expect(
nativeStorageDriver.getItem('unretrievableKey')
).to.be.rejectedWith(Error, 'Wrong parameter for key \'name/storeName/data/unretrievableKey\'')
describe '#setItem', ->
it 'returns a promise that is resolved with the value passed as argument for a valid key', ->
nativeStorageDriver.setItem('key', 'value')
.then (storedValue) ->
expect(storedValue).to.eql('value')
nativeStorageDriver.getItem('key')
.then (retrievedValue) ->
expect(retrievedValue).to.eql('value')
it 'calls the provided callback with the value passed as argument for a valid key', ->
callback = sinon.spy()
nativeStorageDriver.setItem('key', 'value', callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'value')
expect(nativeStorageDriver.getItem('key')).to.eventually.equal('value')
it 'has no effect on other storages', ->
nativeStorageDriver.setItem('key', 'value')
.then (storedValue) ->
expect(storedValue).to.eql('value')
nativeStorageDriver.getItem('key')
.then (retrievedValue) ->
expect(retrievedValue).to.eql('value')
nativeStorageDriver._initStorage({ name: 'otherName', storeName: 'otherStoreName' })
.then ->
expect(
nativeStorageDriver.getItem('key')
).to.eventually.eq(null)
it 'returns a promise that is rejected with an error for an invalid key-value pair', ->
expect(
nativeStorageDriver.setItem('unstorableKey', 'value')
).to.be.rejectedWith(Error, 'Unable to store key \'name/storeName/data/unstorableKey\' and value \'"value"\'')
it 'calls the provided callback with an error for an invalid key-value pair', ->
callback = sinon.spy()
nativeStorageDriver.setItem('unstorableKey', 'value', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to store key \'name/storeName/data/unstorableKey\' and value \'"value"\'')
describe '#removeItem', ->
context 'when a key-value pair is stored', ->
beforeEach -> nativeStorageDriver.setItem('key', 'value')
it 'returns a promise that is resolved for the valid key', ->
expect(nativeStorageDriver.removeItem('key')).to.eventually.fulfill
it 'calls the provided callback with null as first argument for the valid key', ->
callback = sinon.spy()
nativeStorageDriver.removeItem('key', callback)
.then ->
expect(callback).to.have.been.calledWith(null)
it 'returns a promise that is rejected for an invalid key', ->
expect(
nativeStorageDriver.removeItem('unremovableKey')
).to.be.rejectedWith(Error, 'Unable to remove value for key \'name/storeName/data/unremovableKey\'')
it 'calls the provided callback with an error for an invalid key', ->
callback = sinon.spy()
nativeStorageDriver.removeItem('unremovableKey', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to remove value for key \'name/storeName/data/unremovableKey\'')
describe '#keys', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to an array of keys for the valid prefix', ->
expect(
nativeStorageDriver.keys()
).to.eventually.eql(['aap', 'noot', 'mies'])
it 'calls the provided callback with an array of keys for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.keys(callback)
.then ->
expect(callback).to.have.been.calledWith(null, ['aap', 'noot', 'mies'])
describe '#length', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to the number of keys for the valid prefix', ->
expect(
nativeStorageDriver.length()
).to.eventually.eql(3)
it 'calls the provided callback with the number of keys for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.length(callback)
.then ->
expect(callback).to.have.been.calledWith(null, 3)
describe '#key', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to the key at the given index for the valid prefix', ->
expect(nativeStorageDriver.key(0)).to.eventually.eql('aap')
it 'calls the provided callback with the key at the given index for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.key(1, callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'noot')
it 'returns a promise that resolves to undefined when an out-of-bounds index is provided', ->
expect(nativeStorageDriver.key(10)).to.eventually.eql(undefined)
it 'calls the provided callback with undefined when an out-of-bounds index is provided', ->
callback = sinon.spy()
nativeStorageDriver.key(10, callback)
.then ->
expect(callback).to.have.been.calledWith(null, undefined)
describe '#iterate', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'calls the iterator for each value in storage and returns a promise that is resolved', ->
values = []
keys = []
iterationNumbers = []
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
values.push value
keys.push key
iterationNumbers.push iterationNumber
return
).then ->
expect(values).to.eql(['boom', 'roos', 'vis'])
expect(keys).to.eql(['<KEY> '<KEY>', '<KEY>'])
expect(iterationNumbers).to.eql([1, 2, 3])
it 'calls the iterator for each value in storage and the success callback afterwards', ->
values = []
keys = []
iterationNumbers = []
successCallback = sinon.spy()
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
values.push value
keys.push key
iterationNumbers.push iterationNumber
return
successCallback
).then ->
expect(successCallback).to.have.been.calledOnce
expect(values).to.eql(['boom', 'roos', 'vis'])
expect(keys).to.eql(['<KEY>', '<KEY>', '<KEY>'])
expect(iterationNumbers).to.eql([1, 2, 3])
it 'supports early exit', ->
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
return 'some value to force an early exit'
).then (value) ->
expect(value).to.eql('some value to force an early exit')
describe '#clear', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved', ->
expect(nativeStorageDriver.clear()).to.eventually.fulfill
it 'calls the provided callback with null as the first argument', ->
callback = sinon.spy()
nativeStorageDriver.clear(callback)
.then ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0]).to.be.null
it 'removes all key-value pairs', ->
nativeStorageDriver.clear()
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(0)
context 'with another storage containing key-value pairs', ->
beforeEach ->
nativeStorageDriver._initStorage({ name: 'otherName', storeName: 'otherStoreName' })
.then ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'only removes the key-value pairs from the current storage', ->
nativeStorageDriver.clear()
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(0)
nativeStorageDriver._initStorage({ name: 'name', storeName: 'storeName' })
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(3)
context 'when a key-value pair cannot be removed', ->
beforeEach -> nativeStorageDriver.setItem('unremovableKey', 'value')
it 'returns a promise that is rejected', ->
expect(
nativeStorageDriver.clear()
).to.eventually.be.rejectedWith(Error, 'Unable to remove value for key \'name/storeName/data/unremovableKey\'')
it 'returns a promise that supports `catch`', ->
val = 'executed'
expect(
nativeStorageDriver.clear()
.then -> val = 'skipped'
.catch (e) -> val += ' & handled'
.then -> val
).to.eventually.eql 'executed & handled'
it 'calls the provided callback with an error', ->
callback = sinon.spy()
nativeStorageDriver.clear(callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to remove value for key \'name/<KEY>Name/data/unremovableKey\'')
nativeStorageFake =
(state) ->
unstorableKey = '<KEY>'
unremovableKey = '<KEY>'
unretrievableKey = '<KEY>retrievable<KEY>'
{
getItem: (key, success, error) ->
value = state[key]
if key == unretrievableKey
e = new Error("Wrong parameter for key '#{key}'")
# https://github.com/TheCocoaProject/cordova-plugin-nativestorage#error-codes
e.code = 6 # WRONG_PARAMETER
error(e)
else if (value != undefined)
success(value)
else
e = new Error("No value found for key '#{key}'")
# https://github.com/TheCocoaProject/cordova-plugin-nativestorage#error-codes
e.code = 2 # ITEM_NOT_FOUND
error(e)
setItem: (key, value, success, error) ->
if key == unstorableKey
error(new Error("Unable to store key '#{key}' and value '#{value}'"))
else
state[key] = value
success(value)
remove: (key, success, error) ->
if key == unremovableKey
error(new Error("Unable to remove value for key '#{key}'"))
else
delete state[key]
success()
}
| true | nativeStorageDriver = require('components/nativestorage_driver')
describe 'NativeStorage Driver', ->
beforeEach ->
delete nativeStorageDriver._dbInfo
describe '#_driver', ->
it 'returns its unique identifier', ->
expect(nativeStorageDriver._driver).to.eql('nativeStorageDriver')
describe '#_support', ->
context 'when NativeStorage is undefined', ->
it 'returns a promise that is resolved to false', ->
expect(nativeStorageDriver._support()).to.eventually.be.false
context 'when NativeStorage is defined', ->
beforeEach ->
window.NativeStorage = {}
afterEach ->
delete window.NativeStorage
it 'returns a promise that is resolved to true', ->
expect(nativeStorageDriver._support()).to.eventually.be.true
context 'with a fake implementation of NativeStorage', ->
beforeEach ->
window.NativeStorage = nativeStorageFake({})
afterEach ->
delete window.NativeStorage
describe '#_initStorage', ->
it 'copies the properties of its argument to the _dbInfo property', ->
nativeStorageDriver._initStorage({ test: 'test' })
.then ->
expect(nativeStorageDriver._dbInfo.test).to.eql('test')
it 'uses the name and store name passed as options to construct the key prefixes', ->
nativeStorageDriver._initStorage({ name: 'someName', storeName: 'someStoreName' })
.then ->
expect(nativeStorageDriver._dbInfo.keyPrefix).to.eql('someName/someStoreName/')
expect(nativeStorageDriver._dbInfo.dataKeyPrefix).to.eql('someName/someStoreName/data/')
expect(nativeStorageDriver._dbInfo.metaKeyPrefix).to.eql('someName/someStoreName/meta/')
context 'with a #ready method that returns a resolved promise', ->
beforeEach ->
nativeStorageDriver.ready = -> Promise.resolve()
context 'with a default name and store name', ->
beforeEach ->
nativeStorageDriver._initStorage({ name: 'name', storeName: 'storeName' })
describe '#getItem', ->
context 'when a key-value pair is stored', ->
beforeEach ->
nativeStorageDriver.setItem('key', 'value')
it 'returns a promise that is resolved with the value for the given key', ->
expect(nativeStorageDriver.getItem('key')).to.eventually.equal('value')
it 'calls the provided callback with the value for the given key', ->
callback = sinon.spy()
nativeStorageDriver.getItem('key', callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'value')
it 'returns a promise that is resolved with null for an unknown key', ->
expect(
nativeStorageDriver.getItem('unknownKey')
).to.be.eventually.eq(null)
it 'calls the provided callback with null for an unknown key', ->
callback = sinon.spy()
nativeStorageDriver.getItem('unknownKey', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback).to.have.been.calledWith(null, null)
it 'rejects a promise when an error occurs', ->
expect(
nativeStorageDriver.getItem('unretrievableKey')
).to.be.rejectedWith(Error, 'Wrong parameter for key \'name/storeName/data/unretrievableKey\'')
describe '#setItem', ->
it 'returns a promise that is resolved with the value passed as argument for a valid key', ->
nativeStorageDriver.setItem('key', 'value')
.then (storedValue) ->
expect(storedValue).to.eql('value')
nativeStorageDriver.getItem('key')
.then (retrievedValue) ->
expect(retrievedValue).to.eql('value')
it 'calls the provided callback with the value passed as argument for a valid key', ->
callback = sinon.spy()
nativeStorageDriver.setItem('key', 'value', callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'value')
expect(nativeStorageDriver.getItem('key')).to.eventually.equal('value')
it 'has no effect on other storages', ->
nativeStorageDriver.setItem('key', 'value')
.then (storedValue) ->
expect(storedValue).to.eql('value')
nativeStorageDriver.getItem('key')
.then (retrievedValue) ->
expect(retrievedValue).to.eql('value')
nativeStorageDriver._initStorage({ name: 'otherName', storeName: 'otherStoreName' })
.then ->
expect(
nativeStorageDriver.getItem('key')
).to.eventually.eq(null)
it 'returns a promise that is rejected with an error for an invalid key-value pair', ->
expect(
nativeStorageDriver.setItem('unstorableKey', 'value')
).to.be.rejectedWith(Error, 'Unable to store key \'name/storeName/data/unstorableKey\' and value \'"value"\'')
it 'calls the provided callback with an error for an invalid key-value pair', ->
callback = sinon.spy()
nativeStorageDriver.setItem('unstorableKey', 'value', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to store key \'name/storeName/data/unstorableKey\' and value \'"value"\'')
describe '#removeItem', ->
context 'when a key-value pair is stored', ->
beforeEach -> nativeStorageDriver.setItem('key', 'value')
it 'returns a promise that is resolved for the valid key', ->
expect(nativeStorageDriver.removeItem('key')).to.eventually.fulfill
it 'calls the provided callback with null as first argument for the valid key', ->
callback = sinon.spy()
nativeStorageDriver.removeItem('key', callback)
.then ->
expect(callback).to.have.been.calledWith(null)
it 'returns a promise that is rejected for an invalid key', ->
expect(
nativeStorageDriver.removeItem('unremovableKey')
).to.be.rejectedWith(Error, 'Unable to remove value for key \'name/storeName/data/unremovableKey\'')
it 'calls the provided callback with an error for an invalid key', ->
callback = sinon.spy()
nativeStorageDriver.removeItem('unremovableKey', callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to remove value for key \'name/storeName/data/unremovableKey\'')
describe '#keys', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to an array of keys for the valid prefix', ->
expect(
nativeStorageDriver.keys()
).to.eventually.eql(['aap', 'noot', 'mies'])
it 'calls the provided callback with an array of keys for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.keys(callback)
.then ->
expect(callback).to.have.been.calledWith(null, ['aap', 'noot', 'mies'])
describe '#length', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to the number of keys for the valid prefix', ->
expect(
nativeStorageDriver.length()
).to.eventually.eql(3)
it 'calls the provided callback with the number of keys for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.length(callback)
.then ->
expect(callback).to.have.been.calledWith(null, 3)
describe '#key', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved to the key at the given index for the valid prefix', ->
expect(nativeStorageDriver.key(0)).to.eventually.eql('aap')
it 'calls the provided callback with the key at the given index for the valid prefix', ->
callback = sinon.spy()
nativeStorageDriver.key(1, callback)
.then ->
expect(callback).to.have.been.calledWith(null, 'noot')
it 'returns a promise that resolves to undefined when an out-of-bounds index is provided', ->
expect(nativeStorageDriver.key(10)).to.eventually.eql(undefined)
it 'calls the provided callback with undefined when an out-of-bounds index is provided', ->
callback = sinon.spy()
nativeStorageDriver.key(10, callback)
.then ->
expect(callback).to.have.been.calledWith(null, undefined)
describe '#iterate', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'calls the iterator for each value in storage and returns a promise that is resolved', ->
values = []
keys = []
iterationNumbers = []
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
values.push value
keys.push key
iterationNumbers.push iterationNumber
return
).then ->
expect(values).to.eql(['boom', 'roos', 'vis'])
expect(keys).to.eql(['PI:KEY:<KEY>END_PI 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'])
expect(iterationNumbers).to.eql([1, 2, 3])
it 'calls the iterator for each value in storage and the success callback afterwards', ->
values = []
keys = []
iterationNumbers = []
successCallback = sinon.spy()
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
values.push value
keys.push key
iterationNumbers.push iterationNumber
return
successCallback
).then ->
expect(successCallback).to.have.been.calledOnce
expect(values).to.eql(['boom', 'roos', 'vis'])
expect(keys).to.eql(['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'])
expect(iterationNumbers).to.eql([1, 2, 3])
it 'supports early exit', ->
nativeStorageDriver.iterate(
(value, key, iterationNumber) ->
return 'some value to force an early exit'
).then (value) ->
expect(value).to.eql('some value to force an early exit')
describe '#clear', ->
context 'when a number of key-value pairs are stored', ->
beforeEach ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'returns a promise that is resolved', ->
expect(nativeStorageDriver.clear()).to.eventually.fulfill
it 'calls the provided callback with null as the first argument', ->
callback = sinon.spy()
nativeStorageDriver.clear(callback)
.then ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0]).to.be.null
it 'removes all key-value pairs', ->
nativeStorageDriver.clear()
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(0)
context 'with another storage containing key-value pairs', ->
beforeEach ->
nativeStorageDriver._initStorage({ name: 'otherName', storeName: 'otherStoreName' })
.then ->
nativeStorageDriver.setItem('aap', 'boom')
.then ->
nativeStorageDriver.setItem('noot', 'roos')
.then ->
nativeStorageDriver.setItem('mies', 'vis')
it 'only removes the key-value pairs from the current storage', ->
nativeStorageDriver.clear()
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(0)
nativeStorageDriver._initStorage({ name: 'name', storeName: 'storeName' })
.then ->
nativeStorageDriver.length()
.then (length) ->
expect(length).to.eql(3)
context 'when a key-value pair cannot be removed', ->
beforeEach -> nativeStorageDriver.setItem('unremovableKey', 'value')
it 'returns a promise that is rejected', ->
expect(
nativeStorageDriver.clear()
).to.eventually.be.rejectedWith(Error, 'Unable to remove value for key \'name/storeName/data/unremovableKey\'')
it 'returns a promise that supports `catch`', ->
val = 'executed'
expect(
nativeStorageDriver.clear()
.then -> val = 'skipped'
.catch (e) -> val += ' & handled'
.then -> val
).to.eventually.eql 'executed & handled'
it 'calls the provided callback with an error', ->
callback = sinon.spy()
nativeStorageDriver.clear(callback)
.catch ->
expect(callback).to.have.been.calledOnce
expect(callback.args[0][0].message).to.eql('Unable to remove value for key \'name/PI:KEY:<KEY>END_PIName/data/unremovableKey\'')
nativeStorageFake =
(state) ->
unstorableKey = 'PI:KEY:<KEY>END_PI'
unremovableKey = 'PI:KEY:<KEY>END_PI'
unretrievableKey = 'PI:KEY:<KEY>END_PIretrievablePI:KEY:<KEY>END_PI'
{
getItem: (key, success, error) ->
value = state[key]
if key == unretrievableKey
e = new Error("Wrong parameter for key '#{key}'")
# https://github.com/TheCocoaProject/cordova-plugin-nativestorage#error-codes
e.code = 6 # WRONG_PARAMETER
error(e)
else if (value != undefined)
success(value)
else
e = new Error("No value found for key '#{key}'")
# https://github.com/TheCocoaProject/cordova-plugin-nativestorage#error-codes
e.code = 2 # ITEM_NOT_FOUND
error(e)
setItem: (key, value, success, error) ->
if key == unstorableKey
error(new Error("Unable to store key '#{key}' and value '#{value}'"))
else
state[key] = value
success(value)
remove: (key, success, error) ->
if key == unremovableKey
error(new Error("Unable to remove value for key '#{key}'"))
else
delete state[key]
success()
}
|
[
{
"context": " @version @@version - @@date\n @author Cory Brown\n @copyright Copyright 2013 by Intellectual Re",
"end": 128,
"score": 0.9987292885780334,
"start": 118,
"tag": "NAME",
"value": "Cory Brown"
}
] | src/ears.coffee | uniqname/ears | 1 | ###!
@name ears
@description An object event manager
@version @@version - @@date
@author Cory Brown
@copyright Copyright 2013 by Intellectual Reserve, Inc.
@usage
# Create a new Ears object passing in the object to be managed
earsObj = new Ears(managedObject)
# Attach event handlers to events
earsObj.on 'eventName', (e) ->
//Do stuff
# ears has an alternative syntax which changes the focus from events managed by the triggering object being managed by the listening object.
earsObj.listenTo 'eventName', objToListenTo, (e) ->
//Do stuff
# Simply trigger events on objects
earsObj.trigger 'test'
# You can also pass data through the event object
earsObj.trigger 'test', evtData
# Data passed through the event object is accessed through the `data` property.
earsSubscriber.listenTo 'eventName', earsPublisher, (evt) ->
evt.data
TODO: Support for namespaced events.
###
# IE <=8 support
if not Array.isArray
Array.isArray = (testObj) ->
Object.prototype.toString.call( testObj ) is '[object Array]'
if not Array.prototype.indexOf
Array.prototype.indexOf = (item) ->
return i for el, i in @ when item is el
###*
* The Ears class. Where Awesome happens
*
* @class Ears
* @constructor
###
class Ears
constructor: (obj = {}) ->
callbacks = {}
###*
* Returns the unwrapped raw object (ie The stuff between the ears ;) )
*
* @method raw
* @return {Object} Returns the original (perhaps mutated) raw object absent any ears funtionality
###
@raw = () ->
return obj
###*
* Attaches an event handler to one or more events on the object
*
* @method on
* @param {String} evts A string consisting of a space speerated list of one or more event names to listen for
* @param {Function} handler The function to be executed upon the occasion of the specfied event(s)
* @return {Ears} Returns the Ears object
###
@on = (evts, handler) ->
for evt in evts.split(' ')
callbacks[evt] = [] if not Array.isArray callbacks[evt]
callbacks[evt].push handler
return @
###*
* Attaches an event handler to one or more events
*
* @method off
* @param {String} evts A string consisting of a space speerated list of one or more event names to cease listening for
* @param {Function} handler The function originally attached as the handler to the specified event(s)
* @return {Ears} Returns the Ears object
###
@off = (evts, handler) ->
for evt in evts.split(' ')
callbacks[evt].splice callbacks.indexOf(handler), 1
return @
###*
* Gets the value of a property on the managed object
*
* @method get
* @param {String} property The name of the property to retrieve the value of.
* @return {Mixed} The value of the property on the object, or undefined if it does not exist
###
@get = (property) ->
@trigger 'observation',
property: property
return obj[property]
###*
* Sets the value of a property on the managed object
*
* @method set
* @param {String} property The name of the property to set the value of.
* @param {String} value The value of the property being set
* @return {Ears} Returns the Ears object
###
@set = (property, value) ->
previous = obj[property]
obj[property] = value;
@trigger 'mutation',
property: property
previousValue: previous
newValue: value
return @
###*
* Removes a property from the managed object
*
* @method remove
* @param {String} property The name of the property to be removed.
* @return {Ears} Returns the Ears object
###
@remove = (property) ->
previous = obj[property]
delete obj[property]?
@trigger 'propertyRemoved',
property: property
previousValue: previous
newValue: obj[property]
@on 'propertyRemoved', (evt) ->
@trigger 'mutation', evt.data
return @
###*
* Attaches an event handler to one or more events on another object.
* This is essentailly the same as `on` only from the perspective of the
* subscriber to the event, rather than the publisher.
*
* @method listenTo
* @param {String} evts A string consisting of a space speerated list of one or more event names to listen for
* @param {Ears} ears The object being lisented to (The event publisher)
* @param {Function} handler The function to be executed upon the occasion of the specfied event(s)
* @return {Ears} Returns the Ears object
###
@listenTo = (evts, ears, handler) ->
ears.on evts, handler
return @
###*
* Removes an event handler from one or more events on another object.
* This is essentailly the same as `off` only from the perspective of the
* subscriber to the event, rather than the publisher.
*
* @method ignore
* @param {String} evts A string consisting of a space speerated list of one or more event names to cease listening to
* @param {Ears} ears The object whos event is no longer to be lisented to (The event publisher)
* @param {Function} handler The function that was originally bound to the event.
* @return {Ears} Returns the Ears object
###
@ignore = (evts, ears, handler) ->
ears.off evts, handler
return @
###*
* Publish (emit, dispatch) an event.
*
* @method trigger
* @param {String} evts A string consisting of a space speerated list of one or more event names to dispatch
* @param {Mixed} Data to be included in the dispached event object.
* @return {Ears} Returns the Ears object
###
@trigger = (evts, data) ->
for evt in evts.split(' ')
evtObj =
type: evt
data: data
handler?(evtObj) for handler in callbacks[evt]
# Objects can subscribe to all events from another object.
# It is left to the subscriber to filter and handle appropriatelychr
handler?(evtObj) for handler in callbacks['*']?
return @
window.Ears = Ears
| 148227 | ###!
@name ears
@description An object event manager
@version @@version - @@date
@author <NAME>
@copyright Copyright 2013 by Intellectual Reserve, Inc.
@usage
# Create a new Ears object passing in the object to be managed
earsObj = new Ears(managedObject)
# Attach event handlers to events
earsObj.on 'eventName', (e) ->
//Do stuff
# ears has an alternative syntax which changes the focus from events managed by the triggering object being managed by the listening object.
earsObj.listenTo 'eventName', objToListenTo, (e) ->
//Do stuff
# Simply trigger events on objects
earsObj.trigger 'test'
# You can also pass data through the event object
earsObj.trigger 'test', evtData
# Data passed through the event object is accessed through the `data` property.
earsSubscriber.listenTo 'eventName', earsPublisher, (evt) ->
evt.data
TODO: Support for namespaced events.
###
# IE <=8 support
if not Array.isArray
Array.isArray = (testObj) ->
Object.prototype.toString.call( testObj ) is '[object Array]'
if not Array.prototype.indexOf
Array.prototype.indexOf = (item) ->
return i for el, i in @ when item is el
###*
* The Ears class. Where Awesome happens
*
* @class Ears
* @constructor
###
class Ears
constructor: (obj = {}) ->
callbacks = {}
###*
* Returns the unwrapped raw object (ie The stuff between the ears ;) )
*
* @method raw
* @return {Object} Returns the original (perhaps mutated) raw object absent any ears funtionality
###
@raw = () ->
return obj
###*
* Attaches an event handler to one or more events on the object
*
* @method on
* @param {String} evts A string consisting of a space speerated list of one or more event names to listen for
* @param {Function} handler The function to be executed upon the occasion of the specfied event(s)
* @return {Ears} Returns the Ears object
###
@on = (evts, handler) ->
for evt in evts.split(' ')
callbacks[evt] = [] if not Array.isArray callbacks[evt]
callbacks[evt].push handler
return @
###*
* Attaches an event handler to one or more events
*
* @method off
* @param {String} evts A string consisting of a space speerated list of one or more event names to cease listening for
* @param {Function} handler The function originally attached as the handler to the specified event(s)
* @return {Ears} Returns the Ears object
###
@off = (evts, handler) ->
for evt in evts.split(' ')
callbacks[evt].splice callbacks.indexOf(handler), 1
return @
###*
* Gets the value of a property on the managed object
*
* @method get
* @param {String} property The name of the property to retrieve the value of.
* @return {Mixed} The value of the property on the object, or undefined if it does not exist
###
@get = (property) ->
@trigger 'observation',
property: property
return obj[property]
###*
* Sets the value of a property on the managed object
*
* @method set
* @param {String} property The name of the property to set the value of.
* @param {String} value The value of the property being set
* @return {Ears} Returns the Ears object
###
@set = (property, value) ->
previous = obj[property]
obj[property] = value;
@trigger 'mutation',
property: property
previousValue: previous
newValue: value
return @
###*
* Removes a property from the managed object
*
* @method remove
* @param {String} property The name of the property to be removed.
* @return {Ears} Returns the Ears object
###
@remove = (property) ->
previous = obj[property]
delete obj[property]?
@trigger 'propertyRemoved',
property: property
previousValue: previous
newValue: obj[property]
@on 'propertyRemoved', (evt) ->
@trigger 'mutation', evt.data
return @
###*
* Attaches an event handler to one or more events on another object.
* This is essentailly the same as `on` only from the perspective of the
* subscriber to the event, rather than the publisher.
*
* @method listenTo
* @param {String} evts A string consisting of a space speerated list of one or more event names to listen for
* @param {Ears} ears The object being lisented to (The event publisher)
* @param {Function} handler The function to be executed upon the occasion of the specfied event(s)
* @return {Ears} Returns the Ears object
###
@listenTo = (evts, ears, handler) ->
ears.on evts, handler
return @
###*
* Removes an event handler from one or more events on another object.
* This is essentailly the same as `off` only from the perspective of the
* subscriber to the event, rather than the publisher.
*
* @method ignore
* @param {String} evts A string consisting of a space speerated list of one or more event names to cease listening to
* @param {Ears} ears The object whos event is no longer to be lisented to (The event publisher)
* @param {Function} handler The function that was originally bound to the event.
* @return {Ears} Returns the Ears object
###
@ignore = (evts, ears, handler) ->
ears.off evts, handler
return @
###*
* Publish (emit, dispatch) an event.
*
* @method trigger
* @param {String} evts A string consisting of a space speerated list of one or more event names to dispatch
* @param {Mixed} Data to be included in the dispached event object.
* @return {Ears} Returns the Ears object
###
@trigger = (evts, data) ->
for evt in evts.split(' ')
evtObj =
type: evt
data: data
handler?(evtObj) for handler in callbacks[evt]
# Objects can subscribe to all events from another object.
# It is left to the subscriber to filter and handle appropriatelychr
handler?(evtObj) for handler in callbacks['*']?
return @
window.Ears = Ears
| true | ###!
@name ears
@description An object event manager
@version @@version - @@date
@author PI:NAME:<NAME>END_PI
@copyright Copyright 2013 by Intellectual Reserve, Inc.
@usage
# Create a new Ears object passing in the object to be managed
earsObj = new Ears(managedObject)
# Attach event handlers to events
earsObj.on 'eventName', (e) ->
//Do stuff
# ears has an alternative syntax which changes the focus from events managed by the triggering object being managed by the listening object.
earsObj.listenTo 'eventName', objToListenTo, (e) ->
//Do stuff
# Simply trigger events on objects
earsObj.trigger 'test'
# You can also pass data through the event object
earsObj.trigger 'test', evtData
# Data passed through the event object is accessed through the `data` property.
earsSubscriber.listenTo 'eventName', earsPublisher, (evt) ->
evt.data
TODO: Support for namespaced events.
###
# IE <=8 support
if not Array.isArray
Array.isArray = (testObj) ->
Object.prototype.toString.call( testObj ) is '[object Array]'
if not Array.prototype.indexOf
Array.prototype.indexOf = (item) ->
return i for el, i in @ when item is el
###*
* The Ears class. Where Awesome happens
*
* @class Ears
* @constructor
###
class Ears
constructor: (obj = {}) ->
callbacks = {}
###*
* Returns the unwrapped raw object (ie The stuff between the ears ;) )
*
* @method raw
* @return {Object} Returns the original (perhaps mutated) raw object absent any ears funtionality
###
@raw = () ->
return obj
###*
* Attaches an event handler to one or more events on the object
*
* @method on
* @param {String} evts A string consisting of a space speerated list of one or more event names to listen for
* @param {Function} handler The function to be executed upon the occasion of the specfied event(s)
* @return {Ears} Returns the Ears object
###
@on = (evts, handler) ->
for evt in evts.split(' ')
callbacks[evt] = [] if not Array.isArray callbacks[evt]
callbacks[evt].push handler
return @
###*
* Attaches an event handler to one or more events
*
* @method off
* @param {String} evts A string consisting of a space speerated list of one or more event names to cease listening for
* @param {Function} handler The function originally attached as the handler to the specified event(s)
* @return {Ears} Returns the Ears object
###
@off = (evts, handler) ->
for evt in evts.split(' ')
callbacks[evt].splice callbacks.indexOf(handler), 1
return @
###*
* Gets the value of a property on the managed object
*
* @method get
* @param {String} property The name of the property to retrieve the value of.
* @return {Mixed} The value of the property on the object, or undefined if it does not exist
###
@get = (property) ->
@trigger 'observation',
property: property
return obj[property]
###*
* Sets the value of a property on the managed object
*
* @method set
* @param {String} property The name of the property to set the value of.
* @param {String} value The value of the property being set
* @return {Ears} Returns the Ears object
###
@set = (property, value) ->
previous = obj[property]
obj[property] = value;
@trigger 'mutation',
property: property
previousValue: previous
newValue: value
return @
###*
* Removes a property from the managed object
*
* @method remove
* @param {String} property The name of the property to be removed.
* @return {Ears} Returns the Ears object
###
@remove = (property) ->
previous = obj[property]
delete obj[property]?
@trigger 'propertyRemoved',
property: property
previousValue: previous
newValue: obj[property]
@on 'propertyRemoved', (evt) ->
@trigger 'mutation', evt.data
return @
###*
* Attaches an event handler to one or more events on another object.
* This is essentailly the same as `on` only from the perspective of the
* subscriber to the event, rather than the publisher.
*
* @method listenTo
* @param {String} evts A string consisting of a space speerated list of one or more event names to listen for
* @param {Ears} ears The object being lisented to (The event publisher)
* @param {Function} handler The function to be executed upon the occasion of the specfied event(s)
* @return {Ears} Returns the Ears object
###
@listenTo = (evts, ears, handler) ->
ears.on evts, handler
return @
###*
* Removes an event handler from one or more events on another object.
* This is essentailly the same as `off` only from the perspective of the
* subscriber to the event, rather than the publisher.
*
* @method ignore
* @param {String} evts A string consisting of a space speerated list of one or more event names to cease listening to
* @param {Ears} ears The object whos event is no longer to be lisented to (The event publisher)
* @param {Function} handler The function that was originally bound to the event.
* @return {Ears} Returns the Ears object
###
@ignore = (evts, ears, handler) ->
ears.off evts, handler
return @
###*
* Publish (emit, dispatch) an event.
*
* @method trigger
* @param {String} evts A string consisting of a space speerated list of one or more event names to dispatch
* @param {Mixed} Data to be included in the dispached event object.
* @return {Ears} Returns the Ears object
###
@trigger = (evts, data) ->
for evt in evts.split(' ')
evtObj =
type: evt
data: data
handler?(evtObj) for handler in callbacks[evt]
# Objects can subscribe to all events from another object.
# It is left to the subscriber to filter and handle appropriatelychr
handler?(evtObj) for handler in callbacks['*']?
return @
window.Ears = Ears
|
[
{
"context": " } = cfg\n\n clientConfig =\n user : username\n password : password\n server : host",
"end": 633,
"score": 0.9978112578392029,
"start": 625,
"tag": "USERNAME",
"value": "username"
},
{
"context": "onfig =\n user : username\n ... | src/index.coffee | jmcochran/node-wait-for-mssql | 0 | P = require 'bluebird'
mssql = require 'mssql'
program = require 'commander'
durations = require 'durations'
config = require './config'
getConnection = (cfg, connectTimeout) ->
client = P.resolve(mssql.connect cfg)
.timeout connectTimeout
.then (client) -> client
.catch (error) ->
mssql.close()
throw error
# Wait for MSSQL to become available
waitForMSSQL = (partialConfig) ->
config.validate partialConfig
.then (cfg) ->
new P (resolve) ->
{
username, password, host, port, database,
connectTimeout, totalTimeout, query,
} = cfg
clientConfig =
user : username
password : password
server : host
port : port
database : database
connectionTimeout : connectTimeout
totalTimeout : totalTimeout
watch = durations.stopwatch().start()
connectWatch = durations.stopwatch()
attempts = 0
# Recursive connection test function
testConnection = () ->
attempts += 1
connectWatch.reset().start()
# Establish a client connection
getConnection clientConfig, connectTimeout
# Run the test query with the connected client
.then (client) ->
connectWatch.stop()
# If a query was supplied, it must succeed before reporting success
if query?
console.log "Connected. Running test query: '#{query}'"
client.request().query query, (error, result) ->
console.log "Query done."
client.close()
if (error)
console.log "[#{error}] Attempt #{attempts} query failure. Time elapsed: #{watch}"
if watch.duration().millis() > totalTimeout
console.log "MSSQL test query failed."
resolve 1
else
totalRemaining = Math.min connectTimeout, Math.max(0, totalTimeout - watch.duration().millis())
connectDelay = Math.min totalRemaining, Math.max(0, connectTimeout - connectWatch.duration().millis())
setTimeout testConnection, connectDelay
else
watch.stop()
console.log "Query succeeded after #{attempts} attempt(s) over #{watch}"
resolve 0
# If a query was not supplied, report success
else
watch.stop()
console.log "Connected after #{attempts} attempt(s) over #{watch}"
client.close()
resolve 0
# Handle connection failure
.catch (error) ->
connectWatch.stop()
console.log "[#{error}] Attempt #{attempts} timed out. Time elapsed: #{watch}"
if watch.duration().millis() > totalTimeout
console.log "Could not connect to MSSQL."
resolve 1
else
totalRemaining = Math.min connectTimeout, Math.max(0, totalTimeout - watch.duration().millis())
connectDelay = Math.min totalRemaining, Math.max(0, connectTimeout - connectWatch.duration().millis())
setTimeout testConnection, connectDelay
# First attempt
testConnection()
# Script was run directly
runScript = () ->
program
.option '-D, --database <database>', 'MSSQL database name (default is master)'
.option '-h, --host <host>', 'MSSQL hostname (default is localhost)'
.option '-p, --port <port>', 'MSSQL port (default is 1433)', parseInt
.option '-P, --password <password>', 'MSSQL user password (default is empty)'
.option '-Q, --query <query_string>', 'Custom query to confirm database state'
.option '-t, --connect-timeout <connect-timeout>', 'Individual connection attempt timeout (default is 1000)', parseInt
.option '-T, --total-timeout <total-timeout>', 'Total timeout across all connect attempts (dfault is 15000)', parseInt
.option '-u, --username <username>', 'MSSAQL user name (default is sa)'
.parse(process.argv)
partialConfig =
host: program.host
port: program.port
username: program.username
password: program.password
database: program.database
connectTimeout: program.connectTimeout
totalTimeout: program.totalTimeout
query: program.query
waitForMSSQL(partialConfig)
.then (code) ->
process.exit code
# Module
module.exports =
wait: waitForMSSQL
run: runScript
# If run directly
if require.main == module
runScript()
| 197090 | P = require 'bluebird'
mssql = require 'mssql'
program = require 'commander'
durations = require 'durations'
config = require './config'
getConnection = (cfg, connectTimeout) ->
client = P.resolve(mssql.connect cfg)
.timeout connectTimeout
.then (client) -> client
.catch (error) ->
mssql.close()
throw error
# Wait for MSSQL to become available
waitForMSSQL = (partialConfig) ->
config.validate partialConfig
.then (cfg) ->
new P (resolve) ->
{
username, password, host, port, database,
connectTimeout, totalTimeout, query,
} = cfg
clientConfig =
user : username
password : <PASSWORD>
server : host
port : port
database : database
connectionTimeout : connectTimeout
totalTimeout : totalTimeout
watch = durations.stopwatch().start()
connectWatch = durations.stopwatch()
attempts = 0
# Recursive connection test function
testConnection = () ->
attempts += 1
connectWatch.reset().start()
# Establish a client connection
getConnection clientConfig, connectTimeout
# Run the test query with the connected client
.then (client) ->
connectWatch.stop()
# If a query was supplied, it must succeed before reporting success
if query?
console.log "Connected. Running test query: '#{query}'"
client.request().query query, (error, result) ->
console.log "Query done."
client.close()
if (error)
console.log "[#{error}] Attempt #{attempts} query failure. Time elapsed: #{watch}"
if watch.duration().millis() > totalTimeout
console.log "MSSQL test query failed."
resolve 1
else
totalRemaining = Math.min connectTimeout, Math.max(0, totalTimeout - watch.duration().millis())
connectDelay = Math.min totalRemaining, Math.max(0, connectTimeout - connectWatch.duration().millis())
setTimeout testConnection, connectDelay
else
watch.stop()
console.log "Query succeeded after #{attempts} attempt(s) over #{watch}"
resolve 0
# If a query was not supplied, report success
else
watch.stop()
console.log "Connected after #{attempts} attempt(s) over #{watch}"
client.close()
resolve 0
# Handle connection failure
.catch (error) ->
connectWatch.stop()
console.log "[#{error}] Attempt #{attempts} timed out. Time elapsed: #{watch}"
if watch.duration().millis() > totalTimeout
console.log "Could not connect to MSSQL."
resolve 1
else
totalRemaining = Math.min connectTimeout, Math.max(0, totalTimeout - watch.duration().millis())
connectDelay = Math.min totalRemaining, Math.max(0, connectTimeout - connectWatch.duration().millis())
setTimeout testConnection, connectDelay
# First attempt
testConnection()
# Script was run directly
runScript = () ->
program
.option '-D, --database <database>', 'MSSQL database name (default is master)'
.option '-h, --host <host>', 'MSSQL hostname (default is localhost)'
.option '-p, --port <port>', 'MSSQL port (default is 1433)', parseInt
.option '-P, --password <password>', 'MSSQL user password (default is empty)'
.option '-Q, --query <query_string>', 'Custom query to confirm database state'
.option '-t, --connect-timeout <connect-timeout>', 'Individual connection attempt timeout (default is 1000)', parseInt
.option '-T, --total-timeout <total-timeout>', 'Total timeout across all connect attempts (dfault is 15000)', parseInt
.option '-u, --username <username>', 'MSSAQL user name (default is sa)'
.parse(process.argv)
partialConfig =
host: program.host
port: program.port
username: program.username
password: <PASSWORD>
database: program.database
connectTimeout: program.connectTimeout
totalTimeout: program.totalTimeout
query: program.query
waitForMSSQL(partialConfig)
.then (code) ->
process.exit code
# Module
module.exports =
wait: waitForMSSQL
run: runScript
# If run directly
if require.main == module
runScript()
| true | P = require 'bluebird'
mssql = require 'mssql'
program = require 'commander'
durations = require 'durations'
config = require './config'
getConnection = (cfg, connectTimeout) ->
client = P.resolve(mssql.connect cfg)
.timeout connectTimeout
.then (client) -> client
.catch (error) ->
mssql.close()
throw error
# Wait for MSSQL to become available
waitForMSSQL = (partialConfig) ->
config.validate partialConfig
.then (cfg) ->
new P (resolve) ->
{
username, password, host, port, database,
connectTimeout, totalTimeout, query,
} = cfg
clientConfig =
user : username
password : PI:PASSWORD:<PASSWORD>END_PI
server : host
port : port
database : database
connectionTimeout : connectTimeout
totalTimeout : totalTimeout
watch = durations.stopwatch().start()
connectWatch = durations.stopwatch()
attempts = 0
# Recursive connection test function
testConnection = () ->
attempts += 1
connectWatch.reset().start()
# Establish a client connection
getConnection clientConfig, connectTimeout
# Run the test query with the connected client
.then (client) ->
connectWatch.stop()
# If a query was supplied, it must succeed before reporting success
if query?
console.log "Connected. Running test query: '#{query}'"
client.request().query query, (error, result) ->
console.log "Query done."
client.close()
if (error)
console.log "[#{error}] Attempt #{attempts} query failure. Time elapsed: #{watch}"
if watch.duration().millis() > totalTimeout
console.log "MSSQL test query failed."
resolve 1
else
totalRemaining = Math.min connectTimeout, Math.max(0, totalTimeout - watch.duration().millis())
connectDelay = Math.min totalRemaining, Math.max(0, connectTimeout - connectWatch.duration().millis())
setTimeout testConnection, connectDelay
else
watch.stop()
console.log "Query succeeded after #{attempts} attempt(s) over #{watch}"
resolve 0
# If a query was not supplied, report success
else
watch.stop()
console.log "Connected after #{attempts} attempt(s) over #{watch}"
client.close()
resolve 0
# Handle connection failure
.catch (error) ->
connectWatch.stop()
console.log "[#{error}] Attempt #{attempts} timed out. Time elapsed: #{watch}"
if watch.duration().millis() > totalTimeout
console.log "Could not connect to MSSQL."
resolve 1
else
totalRemaining = Math.min connectTimeout, Math.max(0, totalTimeout - watch.duration().millis())
connectDelay = Math.min totalRemaining, Math.max(0, connectTimeout - connectWatch.duration().millis())
setTimeout testConnection, connectDelay
# First attempt
testConnection()
# Script was run directly
runScript = () ->
program
.option '-D, --database <database>', 'MSSQL database name (default is master)'
.option '-h, --host <host>', 'MSSQL hostname (default is localhost)'
.option '-p, --port <port>', 'MSSQL port (default is 1433)', parseInt
.option '-P, --password <password>', 'MSSQL user password (default is empty)'
.option '-Q, --query <query_string>', 'Custom query to confirm database state'
.option '-t, --connect-timeout <connect-timeout>', 'Individual connection attempt timeout (default is 1000)', parseInt
.option '-T, --total-timeout <total-timeout>', 'Total timeout across all connect attempts (dfault is 15000)', parseInt
.option '-u, --username <username>', 'MSSAQL user name (default is sa)'
.parse(process.argv)
partialConfig =
host: program.host
port: program.port
username: program.username
password: PI:PASSWORD:<PASSWORD>END_PI
database: program.database
connectTimeout: program.connectTimeout
totalTimeout: program.totalTimeout
query: program.query
waitForMSSQL(partialConfig)
.then (code) ->
process.exit code
# Module
module.exports =
wait: waitForMSSQL
run: runScript
# If run directly
if require.main == module
runScript()
|
[
{
"context": "ve if you can'\n version: '0.2'\n authors: [\n 'Tunnecino @ arrogance.es'\n ]",
"end": 2987,
"score": 0.8388392329216003,
"start": 2986,
"tag": "USERNAME",
"value": "T"
},
{
"context": "e if you can'\n version: '0.2'\n authors: [\n 'Tunnecino @ arrogance.es'\... | plugins/roulette.coffee | Arrogance/nerdobot | 1 |
module.exports = ->
command = @config.prefix + "roulette"
game = []
help = (from) =>
@say from.nick,
banner "How to play?"
@say from.nick,
"In this game you'll try to survive, and each shot can be the last one. " +
"Use the commands #{@BOLD}#{command} shot#{@RESET} to shot or " +
"#{@BOLD}#{command} reload#{@RESET} to start with all the bullets."
banner = (message) =>
"#{@BOLD}#{@color 'red'}Russian Roulette#{@RESET} - #{message}"
render = (bullets) =>
drum = "#{@color 'yellow', 'black'}#{@BOLD}"
for num in [1..bullets]
drum += "|"
drumn = _i
total = 6 - drumn
if total
drum += "#{@color 'white'}"
for num in [total..1]
drum += "|"
drum += " #{@RESET}"
@addCommand 'roulette',
description: 'Play the Russian Roullete and di... live if you can'
help: 'Use the command roullete help to learn how to play'
(from, message, channel) =>
shot = (from) =>
if not game[channel]?
game[channel] =
bullets: 6
channel: channel
running = game[channel]
num = Math.floor(Math.random() * 1.28)
@me running.channel,
"gives #{from.nick} the gun..."
if num is 1
@say running.channel,
"#{@color 'red'}#{@BOLD}BOOM! HeadShot...#{@RESET} We have the " +
"brains of #{@BOLD}#{from.nick}#{@RESET} on all around the " +
"#{@BOLD}#{running.channel}#{@RESET}."
@me running.channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
else
game[channel]['bullets'] = running.bullets-1
running = game[channel]
@say running.channel,
"#{@color 'green'}#{@BOLD}Click!#{@RESET} Oh #{@BOLD}#{from.nick}," +
"#{@RESET} you're a Lucky Bastard... #{render running.bullets} " +
"bullets remaining..."
if game[channel].bullets is 1
@say game[channel].channel,
banner "Nobody died this time..."
@me game[channel].channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
reload = (from) =>
if not game[channel]?
game[channel] =
bullets: 6
channel: channel
@me game[channel].channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
switch message
when "help"
help from
when "reload"
reload from
when "shot"
shot from
else
@say channel,
banner "Play the Russian Roullete and di... live if you can. Use " +
"#{@BOLD}#{command} shot#{@RESET} to defy the Death. Use #{@BOLD} " +
"#{command} help#{@RESET} to learn more about this game."
name: 'Russian Roulette Game'
description: 'Play the Russian Roullete and di... live if you can'
version: '0.2'
authors: [
'Tunnecino @ arrogance.es'
] | 132593 |
module.exports = ->
command = @config.prefix + "roulette"
game = []
help = (from) =>
@say from.nick,
banner "How to play?"
@say from.nick,
"In this game you'll try to survive, and each shot can be the last one. " +
"Use the commands #{@BOLD}#{command} shot#{@RESET} to shot or " +
"#{@BOLD}#{command} reload#{@RESET} to start with all the bullets."
banner = (message) =>
"#{@BOLD}#{@color 'red'}Russian Roulette#{@RESET} - #{message}"
render = (bullets) =>
drum = "#{@color 'yellow', 'black'}#{@BOLD}"
for num in [1..bullets]
drum += "|"
drumn = _i
total = 6 - drumn
if total
drum += "#{@color 'white'}"
for num in [total..1]
drum += "|"
drum += " #{@RESET}"
@addCommand 'roulette',
description: 'Play the Russian Roullete and di... live if you can'
help: 'Use the command roullete help to learn how to play'
(from, message, channel) =>
shot = (from) =>
if not game[channel]?
game[channel] =
bullets: 6
channel: channel
running = game[channel]
num = Math.floor(Math.random() * 1.28)
@me running.channel,
"gives #{from.nick} the gun..."
if num is 1
@say running.channel,
"#{@color 'red'}#{@BOLD}BOOM! HeadShot...#{@RESET} We have the " +
"brains of #{@BOLD}#{from.nick}#{@RESET} on all around the " +
"#{@BOLD}#{running.channel}#{@RESET}."
@me running.channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
else
game[channel]['bullets'] = running.bullets-1
running = game[channel]
@say running.channel,
"#{@color 'green'}#{@BOLD}Click!#{@RESET} Oh #{@BOLD}#{from.nick}," +
"#{@RESET} you're a Lucky Bastard... #{render running.bullets} " +
"bullets remaining..."
if game[channel].bullets is 1
@say game[channel].channel,
banner "Nobody died this time..."
@me game[channel].channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
reload = (from) =>
if not game[channel]?
game[channel] =
bullets: 6
channel: channel
@me game[channel].channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
switch message
when "help"
help from
when "reload"
reload from
when "shot"
shot from
else
@say channel,
banner "Play the Russian Roullete and di... live if you can. Use " +
"#{@BOLD}#{command} shot#{@RESET} to defy the Death. Use #{@BOLD} " +
"#{command} help#{@RESET} to learn more about this game."
name: 'Russian Roulette Game'
description: 'Play the Russian Roullete and di... live if you can'
version: '0.2'
authors: [
'T<NAME>ino @ <EMAIL>'
] | true |
module.exports = ->
command = @config.prefix + "roulette"
game = []
help = (from) =>
@say from.nick,
banner "How to play?"
@say from.nick,
"In this game you'll try to survive, and each shot can be the last one. " +
"Use the commands #{@BOLD}#{command} shot#{@RESET} to shot or " +
"#{@BOLD}#{command} reload#{@RESET} to start with all the bullets."
banner = (message) =>
"#{@BOLD}#{@color 'red'}Russian Roulette#{@RESET} - #{message}"
render = (bullets) =>
drum = "#{@color 'yellow', 'black'}#{@BOLD}"
for num in [1..bullets]
drum += "|"
drumn = _i
total = 6 - drumn
if total
drum += "#{@color 'white'}"
for num in [total..1]
drum += "|"
drum += " #{@RESET}"
@addCommand 'roulette',
description: 'Play the Russian Roullete and di... live if you can'
help: 'Use the command roullete help to learn how to play'
(from, message, channel) =>
shot = (from) =>
if not game[channel]?
game[channel] =
bullets: 6
channel: channel
running = game[channel]
num = Math.floor(Math.random() * 1.28)
@me running.channel,
"gives #{from.nick} the gun..."
if num is 1
@say running.channel,
"#{@color 'red'}#{@BOLD}BOOM! HeadShot...#{@RESET} We have the " +
"brains of #{@BOLD}#{from.nick}#{@RESET} on all around the " +
"#{@BOLD}#{running.channel}#{@RESET}."
@me running.channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
else
game[channel]['bullets'] = running.bullets-1
running = game[channel]
@say running.channel,
"#{@color 'green'}#{@BOLD}Click!#{@RESET} Oh #{@BOLD}#{from.nick}," +
"#{@RESET} you're a Lucky Bastard... #{render running.bullets} " +
"bullets remaining..."
if game[channel].bullets is 1
@say game[channel].channel,
banner "Nobody died this time..."
@me game[channel].channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
reload = (from) =>
if not game[channel]?
game[channel] =
bullets: 6
channel: channel
@me game[channel].channel,
"Reloads the gun..."
game[channel]['bullets'] = 6
switch message
when "help"
help from
when "reload"
reload from
when "shot"
shot from
else
@say channel,
banner "Play the Russian Roullete and di... live if you can. Use " +
"#{@BOLD}#{command} shot#{@RESET} to defy the Death. Use #{@BOLD} " +
"#{command} help#{@RESET} to learn more about this game."
name: 'Russian Roulette Game'
description: 'Play the Russian Roullete and di... live if you can'
version: '0.2'
authors: [
'TPI:NAME:<NAME>END_PIino @ PI:EMAIL:<EMAIL>END_PI'
] |
[
{
"context": "key, time.toString()\n\n updateDevice: =>\n key = UUID.v1()\n @keys[key] = new Date()\n updateProperties ",
"end": 890,
"score": 0.9937294125556946,
"start": 881,
"tag": "KEY",
"value": "UUID.v1()"
},
{
"context": "evice: =>\n key = UUID.v1()\n @keys[key... | config-dangler.coffee | octoblu/meshblu-config-dangler | 0 | _ = require 'lodash'
Meshblu = require 'meshblu'
debug = require('debug')('meshblu-config-dangler:config-dangler')
MeshbluConfig = require 'meshblu-config'
UUID = require 'node-uuid'
class ConfigDangler
constructor: ->
@keys = {}
@deleteKeys = []
@totalCount = 0
@processedCount = 0
@pendingCount = 0
meshbluConfig = new MeshbluConfig
@meshbluJSON = meshbluConfig.toJSON()
run: =>
@connect =>
_.delay @printResult, 1000 * 10
@conn.on 'config', @onConfig
@updateInterval = setInterval @updateDevice, 100
checkInterval: =>
debug 'checking keys', _.size @keys
_.each _.keys(@keys), (key) =>
time = @keys[key]
return unless time.getTime() < (Date.now() - 1000)
@pendingCount++
console.log 'pending config', key, time.toString()
updateDevice: =>
key = UUID.v1()
@keys[key] = new Date()
updateProperties =
uuid: @meshbluJSON.uuid
token: @meshbluJSON.token
updateProperties[key] = true
@totalCount++
@conn.update updateProperties, (error) =>
console.error error if erorr?
debug 'updated'
connect: (callback=->) =>
@conn = Meshblu.createConnection @meshbluJSON
@conn.on 'ready', =>
callback()
onConfig: (device) =>
_.each _.keys(@keys), (key) =>
return unless device[key]?
debug 'found the key, great scott!'
@processedCount++
delete @keys[key]
printResult: =>
@checkInterval()
console.log '================='
console.log 'Total Count ', @totalCount
console.log 'Total Processed', @processedCount
console.log 'Total Pending', @pendingCount
console.log 'Percent', Math.round @pendingCount / @totalCount
console.log '================='
process.exit 0
module.exports = ConfigDangler
| 124956 | _ = require 'lodash'
Meshblu = require 'meshblu'
debug = require('debug')('meshblu-config-dangler:config-dangler')
MeshbluConfig = require 'meshblu-config'
UUID = require 'node-uuid'
class ConfigDangler
constructor: ->
@keys = {}
@deleteKeys = []
@totalCount = 0
@processedCount = 0
@pendingCount = 0
meshbluConfig = new MeshbluConfig
@meshbluJSON = meshbluConfig.toJSON()
run: =>
@connect =>
_.delay @printResult, 1000 * 10
@conn.on 'config', @onConfig
@updateInterval = setInterval @updateDevice, 100
checkInterval: =>
debug 'checking keys', _.size @keys
_.each _.keys(@keys), (key) =>
time = @keys[key]
return unless time.getTime() < (Date.now() - 1000)
@pendingCount++
console.log 'pending config', key, time.toString()
updateDevice: =>
key = <KEY>
@keys[key] = new <KEY>()
updateProperties =
uuid: @meshbluJSON.uuid
token: @meshbluJSON.token
updateProperties[key] = true
@totalCount++
@conn.update updateProperties, (error) =>
console.error error if erorr?
debug 'updated'
connect: (callback=->) =>
@conn = Meshblu.createConnection @meshbluJSON
@conn.on 'ready', =>
callback()
onConfig: (device) =>
_.each _.keys(@keys), (key) =>
return unless device[key]?
debug 'found the key, great scott!'
@processedCount++
delete @keys[key]
printResult: =>
@checkInterval()
console.log '================='
console.log 'Total Count ', @totalCount
console.log 'Total Processed', @processedCount
console.log 'Total Pending', @pendingCount
console.log 'Percent', Math.round @pendingCount / @totalCount
console.log '================='
process.exit 0
module.exports = ConfigDangler
| true | _ = require 'lodash'
Meshblu = require 'meshblu'
debug = require('debug')('meshblu-config-dangler:config-dangler')
MeshbluConfig = require 'meshblu-config'
UUID = require 'node-uuid'
class ConfigDangler
constructor: ->
@keys = {}
@deleteKeys = []
@totalCount = 0
@processedCount = 0
@pendingCount = 0
meshbluConfig = new MeshbluConfig
@meshbluJSON = meshbluConfig.toJSON()
run: =>
@connect =>
_.delay @printResult, 1000 * 10
@conn.on 'config', @onConfig
@updateInterval = setInterval @updateDevice, 100
checkInterval: =>
debug 'checking keys', _.size @keys
_.each _.keys(@keys), (key) =>
time = @keys[key]
return unless time.getTime() < (Date.now() - 1000)
@pendingCount++
console.log 'pending config', key, time.toString()
updateDevice: =>
key = PI:KEY:<KEY>END_PI
@keys[key] = new PI:KEY:<KEY>END_PI()
updateProperties =
uuid: @meshbluJSON.uuid
token: @meshbluJSON.token
updateProperties[key] = true
@totalCount++
@conn.update updateProperties, (error) =>
console.error error if erorr?
debug 'updated'
connect: (callback=->) =>
@conn = Meshblu.createConnection @meshbluJSON
@conn.on 'ready', =>
callback()
onConfig: (device) =>
_.each _.keys(@keys), (key) =>
return unless device[key]?
debug 'found the key, great scott!'
@processedCount++
delete @keys[key]
printResult: =>
@checkInterval()
console.log '================='
console.log 'Total Count ', @totalCount
console.log 'Total Processed', @processedCount
console.log 'Total Pending', @pendingCount
console.log 'Percent', Math.round @pendingCount / @totalCount
console.log '================='
process.exit 0
module.exports = ConfigDangler
|
[
{
"context": " subcommand: 'test'\n author:\n name: 'Test Author'\n email: 'author@example.com'\n url:",
"end": 1099,
"score": 0.9812459349632263,
"start": 1088,
"tag": "NAME",
"value": "Test Author"
},
{
"context": "thor:\n name: 'Test Author'\n ... | src/tests/creation_test.coffee | logankoester/freshbooks-cli-create-plugin | 0 | #global describe, beforeEach, it
path = require 'path'
helpers = require('yeoman-generator').test
describe 'generator', ->
beforeEach (done) ->
helpers.testDirectory path.join(__dirname, 'tmp'), (err) =>
return done(err) if err
@app = helpers.createGenerator('freshbooks:plugin', [
[require('../app'), 'freshbooks:plugin']
])
done()
it 'creates expected files', (done) ->
# add files you expect to exist here.
expected = [
'.gitignore',
'.editorconfig',
'.travis.yml',
'package.json',
'Gruntfile.coffee',
'LICENSE-MIT',
'bin/freshbooks-test',
'src/index.coffee',
'src/lib/mock_freshbooks.coffee',
'src/tests/index_test.coffee',
'src/tests/config_file',
'readme/contributing.md',
'readme/examples.md',
'readme/license.md',
'readme/overview.md',
'readme/usage.md'
]
helpers.mockPrompt @app,
name: 'test-plugin'
version: '0.1.0'
description: 'A test plugin'
subcommand: 'test'
author:
name: 'Test Author'
email: 'author@example.com'
url: 'https://author.example.com'
githubUsername: 'testuser'
@app.run {}, ->
helpers.assertFiles expected
done()
| 58537 | #global describe, beforeEach, it
path = require 'path'
helpers = require('yeoman-generator').test
describe 'generator', ->
beforeEach (done) ->
helpers.testDirectory path.join(__dirname, 'tmp'), (err) =>
return done(err) if err
@app = helpers.createGenerator('freshbooks:plugin', [
[require('../app'), 'freshbooks:plugin']
])
done()
it 'creates expected files', (done) ->
# add files you expect to exist here.
expected = [
'.gitignore',
'.editorconfig',
'.travis.yml',
'package.json',
'Gruntfile.coffee',
'LICENSE-MIT',
'bin/freshbooks-test',
'src/index.coffee',
'src/lib/mock_freshbooks.coffee',
'src/tests/index_test.coffee',
'src/tests/config_file',
'readme/contributing.md',
'readme/examples.md',
'readme/license.md',
'readme/overview.md',
'readme/usage.md'
]
helpers.mockPrompt @app,
name: 'test-plugin'
version: '0.1.0'
description: 'A test plugin'
subcommand: 'test'
author:
name: '<NAME>'
email: '<EMAIL>'
url: 'https://author.example.com'
githubUsername: 'testuser'
@app.run {}, ->
helpers.assertFiles expected
done()
| true | #global describe, beforeEach, it
path = require 'path'
helpers = require('yeoman-generator').test
describe 'generator', ->
beforeEach (done) ->
helpers.testDirectory path.join(__dirname, 'tmp'), (err) =>
return done(err) if err
@app = helpers.createGenerator('freshbooks:plugin', [
[require('../app'), 'freshbooks:plugin']
])
done()
it 'creates expected files', (done) ->
# add files you expect to exist here.
expected = [
'.gitignore',
'.editorconfig',
'.travis.yml',
'package.json',
'Gruntfile.coffee',
'LICENSE-MIT',
'bin/freshbooks-test',
'src/index.coffee',
'src/lib/mock_freshbooks.coffee',
'src/tests/index_test.coffee',
'src/tests/config_file',
'readme/contributing.md',
'readme/examples.md',
'readme/license.md',
'readme/overview.md',
'readme/usage.md'
]
helpers.mockPrompt @app,
name: 'test-plugin'
version: '0.1.0'
description: 'A test plugin'
subcommand: 'test'
author:
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
url: 'https://author.example.com'
githubUsername: 'testuser'
@app.run {}, ->
helpers.assertFiles expected
done()
|
[
{
"context": " beforeEach (done) ->\n auth =\n username: 'team-uuid'\n password: 'team-token'\n\n device =\n ",
"end": 669,
"score": 0.9942721724510193,
"start": 660,
"tag": "USERNAME",
"value": "team-uuid"
},
{
"context": "th =\n username: 'team-uuid'\n ... | test/integration/sample-integration.coffee | kmariano/holidayjs | 0 | http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../src/server'
describe 'POST /some/route', ->
beforeEach ->
@meshblu = shmock 0xd00d
afterEach (done) ->
@meshblu.close => done()
beforeEach (done) ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop => done()
beforeEach (done) ->
auth =
username: 'team-uuid'
password: 'team-token'
device =
uuid: 'some-device-uuid'
foo: 'bar'
options =
auth: auth
json: device
@meshblu.get('/v2/whoami')
.reply(200, '{"uuid": "team-uuid"}')
@patchHandler = @meshblu.patch('/v2/devices/some-device-uuid')
.send(foo: 'bar')
.reply(204, http.STATUS_CODES[204])
request.post "http://localhost:#{@serverPort}/some/route", options, (error, @response, @body) =>
done error
it 'should update the real device in meshblu', ->
expect(@response.statusCode).to.equal 204
expect(@patchHandler.isDone).to.be.true
| 24236 | http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../src/server'
describe 'POST /some/route', ->
beforeEach ->
@meshblu = shmock 0xd00d
afterEach (done) ->
@meshblu.close => done()
beforeEach (done) ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop => done()
beforeEach (done) ->
auth =
username: 'team-uuid'
password: '<PASSWORD>'
device =
uuid: 'some-device-uuid'
foo: 'bar'
options =
auth: auth
json: device
@meshblu.get('/v2/whoami')
.reply(200, '{"uuid": "team-uuid"}')
@patchHandler = @meshblu.patch('/v2/devices/some-device-uuid')
.send(foo: 'bar')
.reply(204, http.STATUS_CODES[204])
request.post "http://localhost:#{@serverPort}/some/route", options, (error, @response, @body) =>
done error
it 'should update the real device in meshblu', ->
expect(@response.statusCode).to.equal 204
expect(@patchHandler.isDone).to.be.true
| true | http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../src/server'
describe 'POST /some/route', ->
beforeEach ->
@meshblu = shmock 0xd00d
afterEach (done) ->
@meshblu.close => done()
beforeEach (done) ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop => done()
beforeEach (done) ->
auth =
username: 'team-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
device =
uuid: 'some-device-uuid'
foo: 'bar'
options =
auth: auth
json: device
@meshblu.get('/v2/whoami')
.reply(200, '{"uuid": "team-uuid"}')
@patchHandler = @meshblu.patch('/v2/devices/some-device-uuid')
.send(foo: 'bar')
.reply(204, http.STATUS_CODES[204])
request.post "http://localhost:#{@serverPort}/some/route", options, (error, @response, @body) =>
done error
it 'should update the real device in meshblu', ->
expect(@response.statusCode).to.equal 204
expect(@patchHandler.isDone).to.be.true
|
[
{
"context": "ffee: Github repository class\n#\n# Copyright © 2011 Pavan Kumar Sunkara. All rights reserved\n#\n\n# Requiring modules\nBase ",
"end": 81,
"score": 0.9998742341995239,
"start": 62,
"tag": "NAME",
"value": "Pavan Kumar Sunkara"
},
{
"context": "ve a user from a repo's c... | src/octonode/repo.coffee | priyaljain919/octonode | 0 | #
# repo.coffee: Github repository class
#
# Copyright © 2011 Pavan Kumar Sunkara. All rights reserved
#
# Requiring modules
Base = require './base'
# Initiate class
class Repo extends Base
constructor: (@name, @client) ->
# Get a repository
# '/repos/pksunkara/hub' GET
info: (cb) ->
@client.get "/repos/#{@name}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo info error")) else cb null, b, h
# Edit a repository
# '/repos/pksunkara/hub' PATCH
update: (info, cb) ->
@client.patch "/repos/#{@name}", info, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo update error")) else cb null, b, h
# Get the collaborators for a repository
# '/repos/pksunkara/hub/collaborators
collaborators: (cbParamOrUser, cb) ->
if cb? and typeof cbParamOrUser isnt 'function' and typeof cbParamOrUser isnt 'object'
@hasCollaborator cbParamOrUser, cb
else
if cb
param = cbParamOrUser
else
cb = cbParamOrUser
param = {}
@client.getOptions "/repos/#{@name}/collaborators", { headers: { Accept: 'application/vnd.github.ironman-preview+json'} }, param, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo collaborators error")) else cb null, b, h
# Add a collaborator to a repository
# '/repos/pksunkara/hub/collaborators/pksunkara' PUT
addCollaborator: (user, cbOrOptions, cb) ->
if !cb? and cbOrOptions
cb = cbOrOptions
param = {}
else if typeof cbOrOptions is 'object'
param = cbOrOptions
@client.put "/repos/#{@name}/collaborators/#{user}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo addCollaborator error")) else cb null, b, h
# Remove a user from a repo's collaborators
# '/repos/pksunkara/hub/collaborators/pksunkara' DELETE
removeCollaborator: (user, cb) ->
@client.del "/repos/#{@name}/collaborators/#{user}", null, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo removeCollaborator error")) else cb null, b, h
# 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, h) ->
return cb(err) if err
cb null, s is 204, h
# Get the commits for a repository
# '/repos/pksunkara/hub/commits' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
commits: (params..., cb) ->
@client.get "/repos/#{@name}/commits", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b, h
# Get a certain commit for a repository
# '/repos/pksunkara/hub/commits/SHA' GET
commit: (sha, cb) ->
@client.get "/repos/#{@name}/commits/#{sha}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b, h
# Compare two branches
# '/repos/pksunkara/hub/compare/master...develop' GET
compare: (base, head, cb) ->
@client.get "/repos/#{@name}/compare/#{base}...#{head}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo compare error")) else cb null, b, h
# Merge branches
# '/repos/pksunkara/hub/merges' POST
merge: (obj, cb) ->
@client.post "/repos/#{@name}/merges", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Merge info error")) else cb null, b, h
# Create a commit
# '/repos/pksunkara/hub/git/commits' POST
createCommit: (message, tree, parents, cbOrOptions, cb) ->
if !cb? and cbOrOptions
cb = cbOrOptions
param = {message: message, parents: parents, tree: tree}
else if typeof cbOrOptions is 'object'
param = cbOrOptions
param['message'] = message
param['parents'] = parents
param['tree'] = tree
@client.post "/repos/#{@name}/git/commits", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createCommit error")) else cb null, b, h
# Get the tags for a repository
# '/repos/pksunkara/hub/tags' GET
tags: (cb) ->
@client.get "/repos/#{@name}/tags", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tags error")) else cb null, b, h
# Get the releases for a repository
# '/repos/pksunkara/hub/releases' GET
releases: (cb) ->
@client.get "/repos/#{@name}/releases", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo releases error")) else cb null, b, h
# Get release instance for a repo
release: (numberOrRelease, cb) ->
if typeof cb is 'function' and typeof numberOrRelease is 'object'
@createRelease numberOrRelease, cb
else
@client.release @name, numberOrRelease
# Create a relase for a repo
# '/repo/pksunkara/releases' POST
createRelease: (release, cb) ->
@client.post "/repos/#{@name}/releases", release, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createRelease error")) else cb null, b, h
# Get the languages for a repository
# '/repos/pksunkara/hub/languages' GET
languages: (cb) ->
@client.get "/repos/#{@name}/languages", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo languages error")) else cb null, b, h
# Get the contributors for a repository
# '/repos/pksunkara/hub/contributors' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
contributors: (params..., cb) ->
@client.get "/repos/#{@name}/contributors", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contributors error")) else cb null, b, h
# Get the contributors for a repository
# '/repos/pksunkara/hub/stats/contributors' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
contributorsStats: (cb) ->
@client.get "/repos/#{@name}/stats/contributors", (err, s, b, h) ->
return cb(err) if err
if s isnt 200
error = new Error("Repo stats contributors error")
error.status = s # 202 means recomputing stats... https://developer.github.com/v3/repos/statistics/#a-word-about-caching
cb(error)
else cb null, b, h
# Get the teams for a repository
# '/repos/pksunkara/hub/teams' GET
teams: (cb) ->
@client.get "/repos/#{@name}/teams", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo teams error")) else cb null, b, h
# Get the branches for a repository
# '/repos/pksunkara/hub/branches' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
branches: (params..., cb) ->
@client.get "/repos/#{@name}/branches", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branches error")) else cb null, b, h
# Get a branch for a repository
# '/repos/pksunkara/hub/branches/master' GET
branch: (branch, cb) ->
@client.get "/repos/#{@name}/branches/#{branch}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branch error")) else cb null, b, h
# Get a reference for a repository
# '/repos/pksunkara/hub/git/refs' POST
createReference: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs", {ref: "refs/heads/#{ref}", sha: sha}, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createReference error")) else cb null, b, h
# Get issue instance for a repo
issue: (numberOrIssue, cb) ->
if typeof cb is 'function' and typeof numberOrIssue is 'object'
@createIssue numberOrIssue, cb
else
@client.issue @name, numberOrIssue
# List 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, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo issues error")) else cb null, b, h
# Create an issue for a repository
# '/repos/pksunkara/hub/issues' POST
createIssue: (issue, cb) ->
@client.post "/repos/#{@name}/issues", issue, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createIssue error")) else cb null, b, h
# Get project instance for a repo
project: (numberOrProject, cb) ->
if typeof cb is 'function' and typeof numberOrProject is 'object'
@createProject numberOrProject, cb
else
@client.project @name, numberOrProject
# List projects for a repository
# '/repos/pksunkara/hub/projects' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
projects: (params..., cb) ->
@client.get "/repos/#{@name}/projects", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo projects error")) else cb null, b, h
# Create an project for a repository
# '/repos/pksunkara/hub/projects' POST
createProject: (project, cb) ->
@client.post "/repos/#{@name}/projects", project, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createProject error")) else cb null, b, h
# Get milestone instance for a repo
milestone: (numberOrMilestone, cb) ->
if typeof cb is 'function' and typeof numberOrMilestone is 'object'
@createMilestone numberOrMilestone, cb
else
@client.milestone @name, numberOrMilestone
# List milestones for a repository
# '/repos/pksunkara/hub/milestones' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
milestones: (params..., cb) ->
@client.get "/repos/#{@name}/milestones", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo milestones error")) else cb null, b, h
# Create a milestone for a repository
# '/repos/pksunkara/hub/milestones' POST
createMilestone: (milestone, cb) ->
@client.post "/repos/#{@name}/milestones", milestone, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createMilestone error")) else cb null, b, h
# Get label instance for a repo
label: (nameOrLabel, cb) ->
if typeof cb is 'function' and typeof nameOrLabel is 'object'
@createLabel nameOrLabel, cb
else
@client.label @name, nameOrLabel
# List labels for a repository
# '/repos/pksunkara/hub/labels' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
labels: (params..., cb) ->
@client.get "/repos/#{@name}/labels", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo labels error")) else cb null, b, h
# Create a label for a repository
# '/repos/pksunkara/hub/labels' POST
createLabel: (label, cb) ->
@client.post "/repos/#{@name}/labels", label, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createLabel error")) else cb null, b, h
# Get the README for a repository
# '/repos/pksunkara/hub/readme' GET
readme: (cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = null
if cbOrRef
cbOrRef = {ref: cbOrRef}
@client.get "/repos/#{@name}/readme", cbOrRef, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo readme error")) else cb null, b, h
# 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 = null
if cbOrRef
cbOrRef = {ref: cbOrRef}
@client.get "/repos/#{@name}/contents/#{path}", cbOrRef, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contents error")) else cb null, b, h
# Create a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' PUT
createContents: (path, message, content, cbOrBranchOrOptions, cb) ->
content = new Buffer(content).toString('base64')
if !cb? and cbOrBranchOrOptions
cb = cbOrBranchOrOptions
cbOrBranchOrOptions = 'master'
if typeof cbOrBranchOrOptions is 'string'
param = {branch: cbOrBranchOrOptions, message: message, content: content}
else if typeof cbOrBranchOrOptions is 'object'
param = cbOrBranchOrOptions
param['message'] = message
param['content'] = content
@client.put "/repos/#{@name}/contents/#{path}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createContents error")) else cb null, b, h
# Update a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' PUT
updateContents: (path, message, content, sha, cbOrBranchOrOptions, cb) ->
content = new Buffer(content).toString('base64')
if !cb? and cbOrBranchOrOptions
cb = cbOrBranchOrOptions
cbOrBranchOrOptions = 'master'
if typeof cbOrBranchOrOptions is 'string'
params = {branch: cbOrBranchOrOptions, message: message, content: content, sha: sha}
else if typeof cbOrBranchOrOptions is 'object'
params = cbOrBranchOrOptions
params['message'] = message
params['content'] = content
params['sha'] = sha
@client.put "/repos/#{@name}/contents/#{path}", params, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo updateContents error")) else cb null, b, h
# Delete a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' DELETE
deleteContents: (path, message, sha, cbOrBranch, cb) ->
if !cb? and cbOrBranch
cb = cbOrBranch
cbOrBranch = 'master'
@client.del "/repos/#{@name}/contents/#{path}", {branch: cbOrBranch, message: message, sha: sha}, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo deleteContents error")) else cb null, b, h
# 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.getNoFollow "/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'], h
# Get the forks for a repository
# '/repos/pksunkara/hub/forks' GET
# - page , optional - params[0]
# - per_page, optional - params[1]
forks: (params..., cb) ->
@client.get "/repos/#{@name}/forks", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo forks error")) else cb null, b, h
# 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, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo blob error")) else cb null, b, h
# Create a blob (for a future commit)
# '/repos/pksunkara/hub/git/blobs' POST
createBlob: (content, encoding, cb) ->
@client.post "/repos/#{@name}/git/blobs", {content: content, encoding: encoding}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createBlob 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
param = {recursive: 1} if cbOrRecursive
@client.get "/repos/#{@name}/git/trees/#{sha}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tree error")) else cb null, b, h
# Create a tree object
# '/repos/pksunkara/hub/git/trees' POST
createTree: (tree, cbOrBase, cb) ->
if !cb? and cbOrBase
cb = cbOrBase
cbOrBase = null
@client.post "/repos/#{@name}/git/trees", {tree: tree, base_tree: cbOrBase}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createTree error")) else cb null, b
# Get a reference
# '/repos/pksunkara/hub/git/refs/REF' GET
ref: (ref, cb) ->
@client.get "/repos/#{@name}/git/refs/#{ref}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo ref error")) else cb null, b
# Create a reference
# '/repos/pksunkara/hub/git/refs' POST
createRef: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs", {ref: ref, sha: sha}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createRef error")) else cb null, b
# Update a reference
# '/repos/pksunkara/hub/git/refs/REF' PATCH
updateRef: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs/#{ref}", {sha: sha}, (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo updateRef error")) else cb null, b
# Delete a reference
# '/repos/pksunkara/hub/git/refs/REF' DELETE
deleteRef: (ref, cb) ->
@client.del "/repos/#{@name}/git/refs/#{ref}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Ref delete error")) else cb null
# Delete the repository
# '/repos/pksunkara/hub' DELETE
destroy: (cb) ->
@client.del "/repos/#{@name}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo destroy error")) else cb null
# Get pull-request instance for repo
pr: (numberOrPr, cb) ->
if typeof cb is 'function' and typeof numberOrPr is 'object'
@createPr numberOrPr, cb
else
@client.pr @name, numberOrPr
# List pull requests
# '/repos/pksunkara/hub/pulls' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
prs: (params..., cb) ->
@client.get "/repos/#{@name}/pulls", params..., (err, s, b, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo prs error")) else cb null, b, h
# Create a pull request
# '/repos/pksunkara/hub/pulls' POST
createPr: (pr, cb) ->
@client.post "/repos/#{@name}/pulls", pr, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createPr error")) else cb null, b, h
# List hooks
# '/repos/pksunkara/hub/hooks' GET
hooks: (params..., cb) ->
@client.get "/repos/#{@name}/hooks",params..., (err, s, b, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo hooks error")) else cb null, b, h
# Create a hook
# '/repos/pksunkara/hub/hooks' POST
hook: (hook, cb) ->
@client.post "/repos/#{@name}/hooks", hook, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createHook error")) else cb null, b, h
# Delete a hook
# '/repos/pksunkara/hub/hooks/37' DELETE
deleteHook: (id, cb) ->
@client.del "/repos/#{@name}/hooks/#{id}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo deleteHook error")) else cb null, b, h
# List statuses for a specific ref
# '/repos/pksunkara/hub/statuses/master' GET
statuses: (ref, cb) ->
@client.get "/repos/#{@name}/statuses/#{ref}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b, h
# Get the combined status for a specific ref
# '/repos/pksunkara/hub/commits/master/status' GET
combinedStatus: (ref, cb) ->
@client.get "/repos/#{@name}/commits/#{ref}/status", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b, h
# Create a status
# '/repos/pksunkara/hub/statuses/18e129c213848c7f239b93fe5c67971a64f183ff' POST
status: (sha, obj, cb) ->
@client.post "/repos/#{@name}/statuses/#{sha}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo status error")) else cb null, b, h
# List Stargazers
# '/repos/:owner/:repo/stargazers' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
stargazers: (params..., cb)->
@client.get "/repos/#{@name}/stargazers", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo stargazers error")) else cb null, b, h
# Export module
module.exports = Repo
| 62226 | #
# repo.coffee: Github repository class
#
# Copyright © 2011 <NAME>. All rights reserved
#
# Requiring modules
Base = require './base'
# Initiate class
class Repo extends Base
constructor: (@name, @client) ->
# Get a repository
# '/repos/pksunkara/hub' GET
info: (cb) ->
@client.get "/repos/#{@name}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo info error")) else cb null, b, h
# Edit a repository
# '/repos/pksunkara/hub' PATCH
update: (info, cb) ->
@client.patch "/repos/#{@name}", info, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo update error")) else cb null, b, h
# Get the collaborators for a repository
# '/repos/pksunkara/hub/collaborators
collaborators: (cbParamOrUser, cb) ->
if cb? and typeof cbParamOrUser isnt 'function' and typeof cbParamOrUser isnt 'object'
@hasCollaborator cbParamOrUser, cb
else
if cb
param = cbParamOrUser
else
cb = cbParamOrUser
param = {}
@client.getOptions "/repos/#{@name}/collaborators", { headers: { Accept: 'application/vnd.github.ironman-preview+json'} }, param, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo collaborators error")) else cb null, b, h
# Add a collaborator to a repository
# '/repos/pksunkara/hub/collaborators/pksunkara' PUT
addCollaborator: (user, cbOrOptions, cb) ->
if !cb? and cbOrOptions
cb = cbOrOptions
param = {}
else if typeof cbOrOptions is 'object'
param = cbOrOptions
@client.put "/repos/#{@name}/collaborators/#{user}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo addCollaborator error")) else cb null, b, h
# Remove a user from a repo's collaborators
# '/repos/pksunkara/hub/collaborators/pksunkara' DELETE
removeCollaborator: (user, cb) ->
@client.del "/repos/#{@name}/collaborators/#{user}", null, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo removeCollaborator error")) else cb null, b, h
# 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, h) ->
return cb(err) if err
cb null, s is 204, h
# Get the commits for a repository
# '/repos/pksunkara/hub/commits' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
commits: (params..., cb) ->
@client.get "/repos/#{@name}/commits", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b, h
# Get a certain commit for a repository
# '/repos/pksunkara/hub/commits/SHA' GET
commit: (sha, cb) ->
@client.get "/repos/#{@name}/commits/#{sha}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b, h
# Compare two branches
# '/repos/pksunkara/hub/compare/master...develop' GET
compare: (base, head, cb) ->
@client.get "/repos/#{@name}/compare/#{base}...#{head}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo compare error")) else cb null, b, h
# Merge branches
# '/repos/pksunkara/hub/merges' POST
merge: (obj, cb) ->
@client.post "/repos/#{@name}/merges", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Merge info error")) else cb null, b, h
# Create a commit
# '/repos/pksunkara/hub/git/commits' POST
createCommit: (message, tree, parents, cbOrOptions, cb) ->
if !cb? and cbOrOptions
cb = cbOrOptions
param = {message: message, parents: parents, tree: tree}
else if typeof cbOrOptions is 'object'
param = cbOrOptions
param['message'] = message
param['parents'] = parents
param['tree'] = tree
@client.post "/repos/#{@name}/git/commits", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createCommit error")) else cb null, b, h
# Get the tags for a repository
# '/repos/pksunkara/hub/tags' GET
tags: (cb) ->
@client.get "/repos/#{@name}/tags", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tags error")) else cb null, b, h
# Get the releases for a repository
# '/repos/pksunkara/hub/releases' GET
releases: (cb) ->
@client.get "/repos/#{@name}/releases", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo releases error")) else cb null, b, h
# Get release instance for a repo
release: (numberOrRelease, cb) ->
if typeof cb is 'function' and typeof numberOrRelease is 'object'
@createRelease numberOrRelease, cb
else
@client.release @name, numberOrRelease
# Create a relase for a repo
# '/repo/pksunkara/releases' POST
createRelease: (release, cb) ->
@client.post "/repos/#{@name}/releases", release, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createRelease error")) else cb null, b, h
# Get the languages for a repository
# '/repos/pksunkara/hub/languages' GET
languages: (cb) ->
@client.get "/repos/#{@name}/languages", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo languages error")) else cb null, b, h
# Get the contributors for a repository
# '/repos/pksunkara/hub/contributors' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
contributors: (params..., cb) ->
@client.get "/repos/#{@name}/contributors", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contributors error")) else cb null, b, h
# Get the contributors for a repository
# '/repos/pksunkara/hub/stats/contributors' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
contributorsStats: (cb) ->
@client.get "/repos/#{@name}/stats/contributors", (err, s, b, h) ->
return cb(err) if err
if s isnt 200
error = new Error("Repo stats contributors error")
error.status = s # 202 means recomputing stats... https://developer.github.com/v3/repos/statistics/#a-word-about-caching
cb(error)
else cb null, b, h
# Get the teams for a repository
# '/repos/pksunkara/hub/teams' GET
teams: (cb) ->
@client.get "/repos/#{@name}/teams", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo teams error")) else cb null, b, h
# Get the branches for a repository
# '/repos/pksunkara/hub/branches' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
branches: (params..., cb) ->
@client.get "/repos/#{@name}/branches", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branches error")) else cb null, b, h
# Get a branch for a repository
# '/repos/pksunkara/hub/branches/master' GET
branch: (branch, cb) ->
@client.get "/repos/#{@name}/branches/#{branch}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branch error")) else cb null, b, h
# Get a reference for a repository
# '/repos/pksunkara/hub/git/refs' POST
createReference: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs", {ref: "refs/heads/#{ref}", sha: sha}, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createReference error")) else cb null, b, h
# Get issue instance for a repo
issue: (numberOrIssue, cb) ->
if typeof cb is 'function' and typeof numberOrIssue is 'object'
@createIssue numberOrIssue, cb
else
@client.issue @name, numberOrIssue
# List 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, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo issues error")) else cb null, b, h
# Create an issue for a repository
# '/repos/pksunkara/hub/issues' POST
createIssue: (issue, cb) ->
@client.post "/repos/#{@name}/issues", issue, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createIssue error")) else cb null, b, h
# Get project instance for a repo
project: (numberOrProject, cb) ->
if typeof cb is 'function' and typeof numberOrProject is 'object'
@createProject numberOrProject, cb
else
@client.project @name, numberOrProject
# List projects for a repository
# '/repos/pksunkara/hub/projects' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
projects: (params..., cb) ->
@client.get "/repos/#{@name}/projects", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo projects error")) else cb null, b, h
# Create an project for a repository
# '/repos/pksunkara/hub/projects' POST
createProject: (project, cb) ->
@client.post "/repos/#{@name}/projects", project, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createProject error")) else cb null, b, h
# Get milestone instance for a repo
milestone: (numberOrMilestone, cb) ->
if typeof cb is 'function' and typeof numberOrMilestone is 'object'
@createMilestone numberOrMilestone, cb
else
@client.milestone @name, numberOrMilestone
# List milestones for a repository
# '/repos/pksunkara/hub/milestones' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
milestones: (params..., cb) ->
@client.get "/repos/#{@name}/milestones", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo milestones error")) else cb null, b, h
# Create a milestone for a repository
# '/repos/pksunkara/hub/milestones' POST
createMilestone: (milestone, cb) ->
@client.post "/repos/#{@name}/milestones", milestone, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createMilestone error")) else cb null, b, h
# Get label instance for a repo
label: (nameOrLabel, cb) ->
if typeof cb is 'function' and typeof nameOrLabel is 'object'
@createLabel nameOrLabel, cb
else
@client.label @name, nameOrLabel
# List labels for a repository
# '/repos/pksunkara/hub/labels' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
labels: (params..., cb) ->
@client.get "/repos/#{@name}/labels", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo labels error")) else cb null, b, h
# Create a label for a repository
# '/repos/pksunkara/hub/labels' POST
createLabel: (label, cb) ->
@client.post "/repos/#{@name}/labels", label, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createLabel error")) else cb null, b, h
# Get the README for a repository
# '/repos/pksunkara/hub/readme' GET
readme: (cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = null
if cbOrRef
cbOrRef = {ref: cbOrRef}
@client.get "/repos/#{@name}/readme", cbOrRef, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo readme error")) else cb null, b, h
# 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 = null
if cbOrRef
cbOrRef = {ref: cbOrRef}
@client.get "/repos/#{@name}/contents/#{path}", cbOrRef, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contents error")) else cb null, b, h
# Create a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' PUT
createContents: (path, message, content, cbOrBranchOrOptions, cb) ->
content = new Buffer(content).toString('base64')
if !cb? and cbOrBranchOrOptions
cb = cbOrBranchOrOptions
cbOrBranchOrOptions = 'master'
if typeof cbOrBranchOrOptions is 'string'
param = {branch: cbOrBranchOrOptions, message: message, content: content}
else if typeof cbOrBranchOrOptions is 'object'
param = cbOrBranchOrOptions
param['message'] = message
param['content'] = content
@client.put "/repos/#{@name}/contents/#{path}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createContents error")) else cb null, b, h
# Update a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' PUT
updateContents: (path, message, content, sha, cbOrBranchOrOptions, cb) ->
content = new Buffer(content).toString('base64')
if !cb? and cbOrBranchOrOptions
cb = cbOrBranchOrOptions
cbOrBranchOrOptions = 'master'
if typeof cbOrBranchOrOptions is 'string'
params = {branch: cbOrBranchOrOptions, message: message, content: content, sha: sha}
else if typeof cbOrBranchOrOptions is 'object'
params = cbOrBranchOrOptions
params['message'] = message
params['content'] = content
params['sha'] = sha
@client.put "/repos/#{@name}/contents/#{path}", params, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo updateContents error")) else cb null, b, h
# Delete a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' DELETE
deleteContents: (path, message, sha, cbOrBranch, cb) ->
if !cb? and cbOrBranch
cb = cbOrBranch
cbOrBranch = 'master'
@client.del "/repos/#{@name}/contents/#{path}", {branch: cbOrBranch, message: message, sha: sha}, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo deleteContents error")) else cb null, b, h
# 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.getNoFollow "/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'], h
# Get the forks for a repository
# '/repos/pksunkara/hub/forks' GET
# - page , optional - params[0]
# - per_page, optional - params[1]
forks: (params..., cb) ->
@client.get "/repos/#{@name}/forks", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo forks error")) else cb null, b, h
# 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, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo blob error")) else cb null, b, h
# Create a blob (for a future commit)
# '/repos/pksunkara/hub/git/blobs' POST
createBlob: (content, encoding, cb) ->
@client.post "/repos/#{@name}/git/blobs", {content: content, encoding: encoding}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createBlob 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
param = {recursive: 1} if cbOrRecursive
@client.get "/repos/#{@name}/git/trees/#{sha}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tree error")) else cb null, b, h
# Create a tree object
# '/repos/pksunkara/hub/git/trees' POST
createTree: (tree, cbOrBase, cb) ->
if !cb? and cbOrBase
cb = cbOrBase
cbOrBase = null
@client.post "/repos/#{@name}/git/trees", {tree: tree, base_tree: cbOrBase}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createTree error")) else cb null, b
# Get a reference
# '/repos/pksunkara/hub/git/refs/REF' GET
ref: (ref, cb) ->
@client.get "/repos/#{@name}/git/refs/#{ref}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo ref error")) else cb null, b
# Create a reference
# '/repos/pksunkara/hub/git/refs' POST
createRef: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs", {ref: ref, sha: sha}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createRef error")) else cb null, b
# Update a reference
# '/repos/pksunkara/hub/git/refs/REF' PATCH
updateRef: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs/#{ref}", {sha: sha}, (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo updateRef error")) else cb null, b
# Delete a reference
# '/repos/pksunkara/hub/git/refs/REF' DELETE
deleteRef: (ref, cb) ->
@client.del "/repos/#{@name}/git/refs/#{ref}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Ref delete error")) else cb null
# Delete the repository
# '/repos/pksunkara/hub' DELETE
destroy: (cb) ->
@client.del "/repos/#{@name}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo destroy error")) else cb null
# Get pull-request instance for repo
pr: (numberOrPr, cb) ->
if typeof cb is 'function' and typeof numberOrPr is 'object'
@createPr numberOrPr, cb
else
@client.pr @name, numberOrPr
# List pull requests
# '/repos/pksunkara/hub/pulls' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
prs: (params..., cb) ->
@client.get "/repos/#{@name}/pulls", params..., (err, s, b, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo prs error")) else cb null, b, h
# Create a pull request
# '/repos/pksunkara/hub/pulls' POST
createPr: (pr, cb) ->
@client.post "/repos/#{@name}/pulls", pr, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createPr error")) else cb null, b, h
# List hooks
# '/repos/pksunkara/hub/hooks' GET
hooks: (params..., cb) ->
@client.get "/repos/#{@name}/hooks",params..., (err, s, b, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo hooks error")) else cb null, b, h
# Create a hook
# '/repos/pksunkara/hub/hooks' POST
hook: (hook, cb) ->
@client.post "/repos/#{@name}/hooks", hook, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createHook error")) else cb null, b, h
# Delete a hook
# '/repos/pksunkara/hub/hooks/37' DELETE
deleteHook: (id, cb) ->
@client.del "/repos/#{@name}/hooks/#{id}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo deleteHook error")) else cb null, b, h
# List statuses for a specific ref
# '/repos/pksunkara/hub/statuses/master' GET
statuses: (ref, cb) ->
@client.get "/repos/#{@name}/statuses/#{ref}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b, h
# Get the combined status for a specific ref
# '/repos/pksunkara/hub/commits/master/status' GET
combinedStatus: (ref, cb) ->
@client.get "/repos/#{@name}/commits/#{ref}/status", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b, h
# Create a status
# '/repos/pksunkara/hub/statuses/18e129c213848c7f239b93fe5c67971a64f183ff' POST
status: (sha, obj, cb) ->
@client.post "/repos/#{@name}/statuses/#{sha}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo status error")) else cb null, b, h
# List Stargazers
# '/repos/:owner/:repo/stargazers' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
stargazers: (params..., cb)->
@client.get "/repos/#{@name}/stargazers", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo stargazers error")) else cb null, b, h
# Export module
module.exports = Repo
| true | #
# repo.coffee: Github repository class
#
# Copyright © 2011 PI:NAME:<NAME>END_PI. All rights reserved
#
# Requiring modules
Base = require './base'
# Initiate class
class Repo extends Base
constructor: (@name, @client) ->
# Get a repository
# '/repos/pksunkara/hub' GET
info: (cb) ->
@client.get "/repos/#{@name}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo info error")) else cb null, b, h
# Edit a repository
# '/repos/pksunkara/hub' PATCH
update: (info, cb) ->
@client.patch "/repos/#{@name}", info, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo update error")) else cb null, b, h
# Get the collaborators for a repository
# '/repos/pksunkara/hub/collaborators
collaborators: (cbParamOrUser, cb) ->
if cb? and typeof cbParamOrUser isnt 'function' and typeof cbParamOrUser isnt 'object'
@hasCollaborator cbParamOrUser, cb
else
if cb
param = cbParamOrUser
else
cb = cbParamOrUser
param = {}
@client.getOptions "/repos/#{@name}/collaborators", { headers: { Accept: 'application/vnd.github.ironman-preview+json'} }, param, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo collaborators error")) else cb null, b, h
# Add a collaborator to a repository
# '/repos/pksunkara/hub/collaborators/pksunkara' PUT
addCollaborator: (user, cbOrOptions, cb) ->
if !cb? and cbOrOptions
cb = cbOrOptions
param = {}
else if typeof cbOrOptions is 'object'
param = cbOrOptions
@client.put "/repos/#{@name}/collaborators/#{user}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo addCollaborator error")) else cb null, b, h
# Remove a user from a repo's collaborators
# '/repos/pksunkara/hub/collaborators/pksunkara' DELETE
removeCollaborator: (user, cb) ->
@client.del "/repos/#{@name}/collaborators/#{user}", null, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo removeCollaborator error")) else cb null, b, h
# 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, h) ->
return cb(err) if err
cb null, s is 204, h
# Get the commits for a repository
# '/repos/pksunkara/hub/commits' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
commits: (params..., cb) ->
@client.get "/repos/#{@name}/commits", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b, h
# Get a certain commit for a repository
# '/repos/pksunkara/hub/commits/SHA' GET
commit: (sha, cb) ->
@client.get "/repos/#{@name}/commits/#{sha}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo commits error")) else cb null, b, h
# Compare two branches
# '/repos/pksunkara/hub/compare/master...develop' GET
compare: (base, head, cb) ->
@client.get "/repos/#{@name}/compare/#{base}...#{head}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo compare error")) else cb null, b, h
# Merge branches
# '/repos/pksunkara/hub/merges' POST
merge: (obj, cb) ->
@client.post "/repos/#{@name}/merges", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Merge info error")) else cb null, b, h
# Create a commit
# '/repos/pksunkara/hub/git/commits' POST
createCommit: (message, tree, parents, cbOrOptions, cb) ->
if !cb? and cbOrOptions
cb = cbOrOptions
param = {message: message, parents: parents, tree: tree}
else if typeof cbOrOptions is 'object'
param = cbOrOptions
param['message'] = message
param['parents'] = parents
param['tree'] = tree
@client.post "/repos/#{@name}/git/commits", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createCommit error")) else cb null, b, h
# Get the tags for a repository
# '/repos/pksunkara/hub/tags' GET
tags: (cb) ->
@client.get "/repos/#{@name}/tags", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tags error")) else cb null, b, h
# Get the releases for a repository
# '/repos/pksunkara/hub/releases' GET
releases: (cb) ->
@client.get "/repos/#{@name}/releases", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo releases error")) else cb null, b, h
# Get release instance for a repo
release: (numberOrRelease, cb) ->
if typeof cb is 'function' and typeof numberOrRelease is 'object'
@createRelease numberOrRelease, cb
else
@client.release @name, numberOrRelease
# Create a relase for a repo
# '/repo/pksunkara/releases' POST
createRelease: (release, cb) ->
@client.post "/repos/#{@name}/releases", release, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createRelease error")) else cb null, b, h
# Get the languages for a repository
# '/repos/pksunkara/hub/languages' GET
languages: (cb) ->
@client.get "/repos/#{@name}/languages", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo languages error")) else cb null, b, h
# Get the contributors for a repository
# '/repos/pksunkara/hub/contributors' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
contributors: (params..., cb) ->
@client.get "/repos/#{@name}/contributors", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contributors error")) else cb null, b, h
# Get the contributors for a repository
# '/repos/pksunkara/hub/stats/contributors' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
contributorsStats: (cb) ->
@client.get "/repos/#{@name}/stats/contributors", (err, s, b, h) ->
return cb(err) if err
if s isnt 200
error = new Error("Repo stats contributors error")
error.status = s # 202 means recomputing stats... https://developer.github.com/v3/repos/statistics/#a-word-about-caching
cb(error)
else cb null, b, h
# Get the teams for a repository
# '/repos/pksunkara/hub/teams' GET
teams: (cb) ->
@client.get "/repos/#{@name}/teams", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo teams error")) else cb null, b, h
# Get the branches for a repository
# '/repos/pksunkara/hub/branches' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
branches: (params..., cb) ->
@client.get "/repos/#{@name}/branches", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branches error")) else cb null, b, h
# Get a branch for a repository
# '/repos/pksunkara/hub/branches/master' GET
branch: (branch, cb) ->
@client.get "/repos/#{@name}/branches/#{branch}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo branch error")) else cb null, b, h
# Get a reference for a repository
# '/repos/pksunkara/hub/git/refs' POST
createReference: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs", {ref: "refs/heads/#{ref}", sha: sha}, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createReference error")) else cb null, b, h
# Get issue instance for a repo
issue: (numberOrIssue, cb) ->
if typeof cb is 'function' and typeof numberOrIssue is 'object'
@createIssue numberOrIssue, cb
else
@client.issue @name, numberOrIssue
# List 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, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo issues error")) else cb null, b, h
# Create an issue for a repository
# '/repos/pksunkara/hub/issues' POST
createIssue: (issue, cb) ->
@client.post "/repos/#{@name}/issues", issue, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createIssue error")) else cb null, b, h
# Get project instance for a repo
project: (numberOrProject, cb) ->
if typeof cb is 'function' and typeof numberOrProject is 'object'
@createProject numberOrProject, cb
else
@client.project @name, numberOrProject
# List projects for a repository
# '/repos/pksunkara/hub/projects' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
projects: (params..., cb) ->
@client.get "/repos/#{@name}/projects", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo projects error")) else cb null, b, h
# Create an project for a repository
# '/repos/pksunkara/hub/projects' POST
createProject: (project, cb) ->
@client.post "/repos/#{@name}/projects", project, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createProject error")) else cb null, b, h
# Get milestone instance for a repo
milestone: (numberOrMilestone, cb) ->
if typeof cb is 'function' and typeof numberOrMilestone is 'object'
@createMilestone numberOrMilestone, cb
else
@client.milestone @name, numberOrMilestone
# List milestones for a repository
# '/repos/pksunkara/hub/milestones' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
milestones: (params..., cb) ->
@client.get "/repos/#{@name}/milestones", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo milestones error")) else cb null, b, h
# Create a milestone for a repository
# '/repos/pksunkara/hub/milestones' POST
createMilestone: (milestone, cb) ->
@client.post "/repos/#{@name}/milestones", milestone, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createMilestone error")) else cb null, b, h
# Get label instance for a repo
label: (nameOrLabel, cb) ->
if typeof cb is 'function' and typeof nameOrLabel is 'object'
@createLabel nameOrLabel, cb
else
@client.label @name, nameOrLabel
# List labels for a repository
# '/repos/pksunkara/hub/labels' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
labels: (params..., cb) ->
@client.get "/repos/#{@name}/labels", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo labels error")) else cb null, b, h
# Create a label for a repository
# '/repos/pksunkara/hub/labels' POST
createLabel: (label, cb) ->
@client.post "/repos/#{@name}/labels", label, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createLabel error")) else cb null, b, h
# Get the README for a repository
# '/repos/pksunkara/hub/readme' GET
readme: (cbOrRef, cb) ->
if !cb? and cbOrRef
cb = cbOrRef
cbOrRef = null
if cbOrRef
cbOrRef = {ref: cbOrRef}
@client.get "/repos/#{@name}/readme", cbOrRef, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo readme error")) else cb null, b, h
# 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 = null
if cbOrRef
cbOrRef = {ref: cbOrRef}
@client.get "/repos/#{@name}/contents/#{path}", cbOrRef, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo contents error")) else cb null, b, h
# Create a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' PUT
createContents: (path, message, content, cbOrBranchOrOptions, cb) ->
content = new Buffer(content).toString('base64')
if !cb? and cbOrBranchOrOptions
cb = cbOrBranchOrOptions
cbOrBranchOrOptions = 'master'
if typeof cbOrBranchOrOptions is 'string'
param = {branch: cbOrBranchOrOptions, message: message, content: content}
else if typeof cbOrBranchOrOptions is 'object'
param = cbOrBranchOrOptions
param['message'] = message
param['content'] = content
@client.put "/repos/#{@name}/contents/#{path}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createContents error")) else cb null, b, h
# Update a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' PUT
updateContents: (path, message, content, sha, cbOrBranchOrOptions, cb) ->
content = new Buffer(content).toString('base64')
if !cb? and cbOrBranchOrOptions
cb = cbOrBranchOrOptions
cbOrBranchOrOptions = 'master'
if typeof cbOrBranchOrOptions is 'string'
params = {branch: cbOrBranchOrOptions, message: message, content: content, sha: sha}
else if typeof cbOrBranchOrOptions is 'object'
params = cbOrBranchOrOptions
params['message'] = message
params['content'] = content
params['sha'] = sha
@client.put "/repos/#{@name}/contents/#{path}", params, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo updateContents error")) else cb null, b, h
# Delete a file at a path in repository
# '/repos/pksunkara/hub/contents/lib/index.js' DELETE
deleteContents: (path, message, sha, cbOrBranch, cb) ->
if !cb? and cbOrBranch
cb = cbOrBranch
cbOrBranch = 'master'
@client.del "/repos/#{@name}/contents/#{path}", {branch: cbOrBranch, message: message, sha: sha}, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo deleteContents error")) else cb null, b, h
# 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.getNoFollow "/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'], h
# Get the forks for a repository
# '/repos/pksunkara/hub/forks' GET
# - page , optional - params[0]
# - per_page, optional - params[1]
forks: (params..., cb) ->
@client.get "/repos/#{@name}/forks", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo forks error")) else cb null, b, h
# 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, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo blob error")) else cb null, b, h
# Create a blob (for a future commit)
# '/repos/pksunkara/hub/git/blobs' POST
createBlob: (content, encoding, cb) ->
@client.post "/repos/#{@name}/git/blobs", {content: content, encoding: encoding}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createBlob 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
param = {recursive: 1} if cbOrRecursive
@client.get "/repos/#{@name}/git/trees/#{sha}", param, (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo tree error")) else cb null, b, h
# Create a tree object
# '/repos/pksunkara/hub/git/trees' POST
createTree: (tree, cbOrBase, cb) ->
if !cb? and cbOrBase
cb = cbOrBase
cbOrBase = null
@client.post "/repos/#{@name}/git/trees", {tree: tree, base_tree: cbOrBase}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createTree error")) else cb null, b
# Get a reference
# '/repos/pksunkara/hub/git/refs/REF' GET
ref: (ref, cb) ->
@client.get "/repos/#{@name}/git/refs/#{ref}", (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo ref error")) else cb null, b
# Create a reference
# '/repos/pksunkara/hub/git/refs' POST
createRef: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs", {ref: ref, sha: sha}, (err, s, b) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createRef error")) else cb null, b
# Update a reference
# '/repos/pksunkara/hub/git/refs/REF' PATCH
updateRef: (ref, sha, cb) ->
@client.post "/repos/#{@name}/git/refs/#{ref}", {sha: sha}, (err, s, b) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo updateRef error")) else cb null, b
# Delete a reference
# '/repos/pksunkara/hub/git/refs/REF' DELETE
deleteRef: (ref, cb) ->
@client.del "/repos/#{@name}/git/refs/#{ref}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Ref delete error")) else cb null
# Delete the repository
# '/repos/pksunkara/hub' DELETE
destroy: (cb) ->
@client.del "/repos/#{@name}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo destroy error")) else cb null
# Get pull-request instance for repo
pr: (numberOrPr, cb) ->
if typeof cb is 'function' and typeof numberOrPr is 'object'
@createPr numberOrPr, cb
else
@client.pr @name, numberOrPr
# List pull requests
# '/repos/pksunkara/hub/pulls' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
prs: (params..., cb) ->
@client.get "/repos/#{@name}/pulls", params..., (err, s, b, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo prs error")) else cb null, b, h
# Create a pull request
# '/repos/pksunkara/hub/pulls' POST
createPr: (pr, cb) ->
@client.post "/repos/#{@name}/pulls", pr, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createPr error")) else cb null, b, h
# List hooks
# '/repos/pksunkara/hub/hooks' GET
hooks: (params..., cb) ->
@client.get "/repos/#{@name}/hooks",params..., (err, s, b, h) ->
return cb(err) if (err)
if s isnt 200 then cb(new Error("Repo hooks error")) else cb null, b, h
# Create a hook
# '/repos/pksunkara/hub/hooks' POST
hook: (hook, cb) ->
@client.post "/repos/#{@name}/hooks", hook, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo createHook error")) else cb null, b, h
# Delete a hook
# '/repos/pksunkara/hub/hooks/37' DELETE
deleteHook: (id, cb) ->
@client.del "/repos/#{@name}/hooks/#{id}", {}, (err, s, b, h) ->
return cb(err) if err
if s isnt 204 then cb(new Error("Repo deleteHook error")) else cb null, b, h
# List statuses for a specific ref
# '/repos/pksunkara/hub/statuses/master' GET
statuses: (ref, cb) ->
@client.get "/repos/#{@name}/statuses/#{ref}", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b, h
# Get the combined status for a specific ref
# '/repos/pksunkara/hub/commits/master/status' GET
combinedStatus: (ref, cb) ->
@client.get "/repos/#{@name}/commits/#{ref}/status", (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo statuses error")) else cb null, b, h
# Create a status
# '/repos/pksunkara/hub/statuses/18e129c213848c7f239b93fe5c67971a64f183ff' POST
status: (sha, obj, cb) ->
@client.post "/repos/#{@name}/statuses/#{sha}", obj, (err, s, b, h) ->
return cb(err) if err
if s isnt 201 then cb(new Error("Repo status error")) else cb null, b, h
# List Stargazers
# '/repos/:owner/:repo/stargazers' GET
# - page or query object, optional - params[0]
# - per_page, optional - params[1]
stargazers: (params..., cb)->
@client.get "/repos/#{@name}/stargazers", params..., (err, s, b, h) ->
return cb(err) if err
if s isnt 200 then cb(new Error("Repo stargazers error")) else cb null, b, h
# Export module
module.exports = Repo
|
[
{
"context": "ns[pMain]\n align = positions[pAlign]\n\n key = pMain+\"|\"+pAlign\n anchor = globalAnchors[key]\n un",
"end": 7597,
"score": 0.9796764850616455,
"start": 7592,
"tag": "KEY",
"value": "pMain"
}
] | static/plugins/notifyjs/src/notify.coffee | softwareuptx/poa_uptx | 71 |
'use strict'
#plugin constants
pluginName = 'notify'
pluginClassName = pluginName+'js'
blankFieldName = pluginName+"!blank"
# ================================
# POSITIONING
# ================================
positions =
t: 'top'
m: 'middle'
b: 'bottom'
l: 'left'
c: 'center'
r: 'right'
hAligns = ['l','c','r']
vAligns = ['t','m','b']
mainPositions = ['t','b','l','r']
#positions mapped to opposites
opposites =
t: 'b'
m: null
b: 't'
l: 'r'
c: null
r: 'l'
parsePosition = (str) ->
pos = []
$.each str.split(/\W+/), (i,word) ->
w = word.toLowerCase().charAt(0)
pos.push w if positions[w]
pos
# ================================
# STYLES
# ================================
styles = {}
coreStyle =
name: 'core'
html: """
<div class="#{pluginClassName}-wrapper">
<div class="#{pluginClassName}-arrow"></div>
<div class="#{pluginClassName}-container"></div>
</div>
"""
# <div class="#{pluginClassName}-debug"></div>
# .#{pluginClassName}-debug {
# position: absolute;
# border: 3px solid red;
# height: 0;
# width: 0;
# }
css: """
.#{pluginClassName}-corner {
position: fixed;
margin: 5px;
z-index: 1050;
}
.#{pluginClassName}-corner .#{pluginClassName}-wrapper,
.#{pluginClassName}-corner .#{pluginClassName}-container {
position: relative;
display: block;
height: inherit;
width: inherit;
margin: 3px;
}
.#{pluginClassName}-wrapper {
z-index: 1;
position: absolute;
display: inline-block;
height: 0;
width: 0;
}
.#{pluginClassName}-container {
display: none;
z-index: 1;
position: absolute;
}
.#{pluginClassName}-hidable {
cursor: pointer;
}
[data-notify-text],[data-notify-html] {
position: relative;
}
.#{pluginClassName}-arrow {
position: absolute;
z-index: 2;
width: 0;
height: 0;
}
"""
stylePrefixes =
"border-radius": ["-webkit-", "-moz-"]
getStyle = (name) ->
styles[name]
addStyle = (name, def) ->
unless name
throw "Missing Style name"
unless def
throw "Missing Style definition"
unless def.html
throw "Missing Style HTML"
if styles[name]?.cssElem
if window.console
console.warn "#{pluginName}: overwriting style '#{name}'"
styles[name].cssElem.remove()
def.name = name
styles[name] = def
cssText = ""
if def.classes
$.each def.classes, (className, props) ->
cssText += ".#{pluginClassName}-#{def.name}-#{className} {\n"
$.each props, (name, val) ->
#vendor prefixes
if stylePrefixes[name]
$.each stylePrefixes[name], (i, prefix) ->
cssText += " #{prefix}#{name}: #{val};\n"
#add prop
cssText += " #{name}: #{val};\n"
cssText += "}\n"
if def.css
cssText += """
/* styles for #{def.name} */
#{def.css}
"""
if cssText
def.cssElem = insertCSS cssText
def.cssElem.attr('id', "notify-#{def.name}")
#precompute usable text fields
fields = {}
elem = $(def.html)
findFields 'html', elem, fields
findFields 'text', elem, fields
def.fields = fields
insertCSS = (cssText) ->
elem = createElem("style")
elem.attr 'type', 'text/css'
$("head").append elem
try
elem.html cssText
catch e #ie fix
elem[0].styleSheet.cssText = cssText
elem
# style.html helper
findFields = (type, elem, fields) ->
type = 'text' if type isnt 'html'
attr = "data-notify-#{type}"
find(elem,"[#{attr}]").each ->
name = $(@).attr attr
name = blankFieldName unless name
fields[name] = type
find = (elem, selector) ->
if elem.is(selector) then elem else elem.find selector
# ================================
# OPTIONS
# ================================
#overridable options
pluginOptions =
clickToHide: true
autoHide: true
autoHideDelay: 5000
arrowShow: true
arrowSize: 5
breakNewLines: true
# autoReposition: true
elementPosition: 'bottom'
globalPosition: 'top right'
style: 'bootstrap'
className: 'error'
showAnimation: 'slideDown'
showDuration: 400
hideAnimation: 'slideUp'
hideDuration: 200
gap: 5
inherit = (a, b) ->
F = () ->
F.prototype = a
$.extend true, new F(), b
defaults = (opts) ->
$.extend pluginOptions, opts
# ================================
# DOM MANIPULATION
# ================================
# plugin helpers
createElem = (tag) ->
$ "<#{tag}></#{tag}>"
# references to global anchor positions
globalAnchors = {}
#gets first on n radios, and gets the fancy stylised input for hidden inputs
getAnchorElement = (element) ->
#choose the first of n radios
if element.is('[type=radio]')
radios = element.parents('form:first').find('[type=radio]').filter (i, e) ->
$(e).attr('name') is element.attr('name')
element = radios.first()
#custom-styled inputs - find thier real element
element
incr = (obj, pos, val) ->
# console.log "incr ---- #{pos} #{val} (#{typeof val})"
if typeof val is 'string'
val = parseInt val, 10
else if typeof val isnt 'number'
return
return if isNaN val
opp = positions[opposites[pos.charAt(0)]]
temp = pos
#use the opposite if exists
if obj[opp] isnt `undefined`
pos = positions[opp.charAt(0)]
val = -val
if obj[pos] is `undefined`
obj[pos] = val
else
obj[pos] += val
null
realign = (alignment, inner, outer) ->
return if alignment in ['l','t']
0
else if alignment in ['c','m']
outer/2 - inner/2
else if alignment in ['r','b']
outer - inner
throw "Invalid alignment"
encode = (text) ->
encode.e = encode.e or createElem "div"
encode.e.text(text).html()
# ================================
# NOTIFY CLASS
# ================================
#define plugin
class Notification
#setup instance variables
constructor: (elem, data, options) ->
options = {className: options} if typeof options is 'string'
@options = inherit pluginOptions, if $.isPlainObject(options) then options else {}
#load style html into @userContainer
@loadHTML()
@wrapper = $(coreStyle.html)
@wrapper.addClass "#{pluginClassName}-hidable" if @options.clickToHide
@wrapper.data pluginClassName, @
@arrow = @wrapper.find ".#{pluginClassName}-arrow"
@container = @wrapper.find ".#{pluginClassName}-container"
@container.append @userContainer
if elem and elem.length
@elementType = elem.attr('type')
@originalElement = elem
@elem = getAnchorElement(elem)
@elem.data pluginClassName, @
# add into dom above elem
@elem.before @wrapper
@container.hide()
@run(data)
loadHTML: ->
style = @getStyle()
@userContainer = $(style.html)
@userFields = style.fields
show: (show, userCallback) ->
callback = =>
@destroy() if not show and not @elem
userCallback() if userCallback
hidden = @container.parent().parents(':hidden').length > 0
elems = @container.add @arrow
args = []
if hidden and show
fn = 'show'
else if hidden and not show
fn = 'hide'
else if not hidden and show
fn = @options.showAnimation
args.push @options.showDuration
else if not hidden and not show
fn = @options.hideAnimation
args.push @options.hideDuration
else
return callback()
args.push callback
elems[fn].apply elems, args
setGlobalPosition: () ->
[pMain, pAlign] = @getPosition()
main = positions[pMain]
align = positions[pAlign]
key = pMain+"|"+pAlign
anchor = globalAnchors[key]
unless anchor
anchor = globalAnchors[key] = createElem("div")
css = {}
css[main] = 0
if align is 'middle'
css.top = '45%'
else if align is 'center'
css.left = '45%'
else
css[align] = 0
anchor.css(css).addClass("#{pluginClassName}-corner")
$("body").append anchor
anchor.prepend @wrapper
setElementPosition: () ->
position = @getPosition()
[pMain, pAlign, pArrow] = position
#grab some dimensions
elemPos = @elem.position()
elemH = @elem.outerHeight()
elemW = @elem.outerWidth()
elemIH = @elem.innerHeight()
elemIW = @elem.innerWidth()
wrapPos = @wrapper.position()
contH = @container.height()
contW = @container.width()
#start calculations
mainFull = positions[pMain]
opp = opposites[pMain]
oppFull = positions[opp]
#initial positioning
css = {}
css[oppFull] = if pMain is 'b'
elemH
else if pMain is 'r'
elemW
else
0
#correct for elem-wrapper offset
# unless navigator.userAgent.match /MSIE/
incr css, 'top', elemPos.top - wrapPos.top
incr css, 'left', elemPos.left - wrapPos.left
#correct for margins
for pos in ['top', 'left']
margin = parseInt @elem.css("margin-#{pos}"), 10
incr css, pos, margin if margin
#correct for paddings (only for inline)
# if /^inline/.test @elem.css('display')
# padding = parseInt @elem.css("padding-#{pos}"), 10
# incr css, pos, -padding if padding
#add gap
gap = Math.max 0, @options.gap - if @options.arrowShow then arrowSize else 0
incr css, oppFull, gap
#calculate arrow
if not @options.arrowShow
@arrow.hide()
else
arrowSize = @options.arrowSize
arrowCss = $.extend {}, css
arrowColor = @userContainer.css("border-color") or
@userContainer.css("background-color") or
'white'
#build arrow
for pos in mainPositions
posFull = positions[pos]
continue if pos is opp
color = if posFull is mainFull then arrowColor else 'transparent'
arrowCss["border-#{posFull}"] = "#{arrowSize}px solid #{color}"
#add some room for the arrow
incr css, positions[opp], arrowSize
incr arrowCss, positions[pAlign], arrowSize*2 if pAlign in mainPositions
#calculate container alignment
if pMain in vAligns
incr css, 'left', realign(pAlign, contW, elemW)
incr arrowCss, 'left', realign(pAlign, arrowSize, elemIW) if arrowCss
else if pMain in hAligns
incr css, 'top', realign(pAlign, contH, elemH)
incr arrowCss, 'top', realign(pAlign, arrowSize, elemIH) if arrowCss
css.display = 'block' if @container.is(":visible")
#apply css
@container.removeAttr('style').css css
@arrow.removeAttr('style').css(arrowCss) if arrowCss
getPosition: ->
text = @options.position or if @elem then @options.elementPosition else @options.globalPosition
pos = parsePosition text
#validate position
pos[0] = 'b' if pos.length is 0
if pos[0] not in mainPositions
throw "Must be one of [#{mainPositions}]"
#validate alignment
if pos.length is 1 or
(pos[0] in vAligns and pos[1] not in hAligns) or
(pos[0] in hAligns and pos[1] not in vAligns)
pos[1] = if pos[0] in hAligns then 'm' else 'l'
if pos.length is 2
pos[2] = pos[1]
return pos
getStyle: (name) ->
name = @options.style unless name
name = 'default' unless name
style = styles[name]
throw "Missing style: #{name}"unless style
style
updateClasses: ->
classes = ['base']
if $.isArray @options.className
classes = classes.concat @options.className
else if @options.className
classes.push @options.className
style = @getStyle()
classes = $.map(classes, (n) -> "#{pluginClassName}-#{style.name}-#{n}").join ' '
@userContainer.attr 'class', classes
#run plugin
run: (data, options) ->
#update options
if $.isPlainObject(options)
$.extend @options, options
#shortcut special case
else if $.type(options) is 'string'
@options.className = options
if @container and not data
@show false
return
else if not @container and not data
return
datas = {}
if $.isPlainObject data
datas = data
else
datas[blankFieldName] = data
for name, d of datas
type = @userFields[name]
continue unless type
if type is 'text'
#escape
d = encode(d)
d = d.replace(/\n/g,'<br/>') if @options.breakNewLines
#update content
value = if name is blankFieldName then '' else '='+name
find(@userContainer,"[data-notify-#{type}#{value}]").html(d)
#set styles
@updateClasses()
#positioning
if @elem
@setElementPosition()
else
@setGlobalPosition()
@show true
#autohide
if @options.autoHide
clearTimeout @autohideTimer
@autohideTimer = setTimeout =>
@show false
, @options.autoHideDelay
destroy: ->
@wrapper.remove()
# ================================
# API
# ================================
# $.pluginName( { ... } ) changes options for all instances
$[pluginName] = (elem, data, options) ->
if (elem and elem.nodeName) or elem.jquery
$(elem)[pluginName](data, options)
else
options = data
data = elem
new Notification null, data, options
elem
# $( ... ).pluginName( { .. } ) creates a cached instance on each
$.fn[pluginName] = (data, options) ->
$(@).each ->
inst = getAnchorElement($(@)).data(pluginClassName)
if inst
inst.run data, options
else
new Notification $(@), data, options
@
#extra methods
$.extend $[pluginName], { defaults, addStyle, pluginOptions, getStyle, insertCSS }
#when ready
$ ->
#insert default style
insertCSS(coreStyle.css).attr('id', 'core-notify')
#watch all notifications clicks
$(document).on 'click', ".#{pluginClassName}-hidable", (e) ->
$(@).trigger 'notify-hide'
$(document).on 'notify-hide', ".#{pluginClassName}-wrapper", (e) ->
$(@).data(pluginClassName)?.show false
| 206881 |
'use strict'
#plugin constants
pluginName = 'notify'
pluginClassName = pluginName+'js'
blankFieldName = pluginName+"!blank"
# ================================
# POSITIONING
# ================================
positions =
t: 'top'
m: 'middle'
b: 'bottom'
l: 'left'
c: 'center'
r: 'right'
hAligns = ['l','c','r']
vAligns = ['t','m','b']
mainPositions = ['t','b','l','r']
#positions mapped to opposites
opposites =
t: 'b'
m: null
b: 't'
l: 'r'
c: null
r: 'l'
parsePosition = (str) ->
pos = []
$.each str.split(/\W+/), (i,word) ->
w = word.toLowerCase().charAt(0)
pos.push w if positions[w]
pos
# ================================
# STYLES
# ================================
styles = {}
coreStyle =
name: 'core'
html: """
<div class="#{pluginClassName}-wrapper">
<div class="#{pluginClassName}-arrow"></div>
<div class="#{pluginClassName}-container"></div>
</div>
"""
# <div class="#{pluginClassName}-debug"></div>
# .#{pluginClassName}-debug {
# position: absolute;
# border: 3px solid red;
# height: 0;
# width: 0;
# }
css: """
.#{pluginClassName}-corner {
position: fixed;
margin: 5px;
z-index: 1050;
}
.#{pluginClassName}-corner .#{pluginClassName}-wrapper,
.#{pluginClassName}-corner .#{pluginClassName}-container {
position: relative;
display: block;
height: inherit;
width: inherit;
margin: 3px;
}
.#{pluginClassName}-wrapper {
z-index: 1;
position: absolute;
display: inline-block;
height: 0;
width: 0;
}
.#{pluginClassName}-container {
display: none;
z-index: 1;
position: absolute;
}
.#{pluginClassName}-hidable {
cursor: pointer;
}
[data-notify-text],[data-notify-html] {
position: relative;
}
.#{pluginClassName}-arrow {
position: absolute;
z-index: 2;
width: 0;
height: 0;
}
"""
stylePrefixes =
"border-radius": ["-webkit-", "-moz-"]
getStyle = (name) ->
styles[name]
addStyle = (name, def) ->
unless name
throw "Missing Style name"
unless def
throw "Missing Style definition"
unless def.html
throw "Missing Style HTML"
if styles[name]?.cssElem
if window.console
console.warn "#{pluginName}: overwriting style '#{name}'"
styles[name].cssElem.remove()
def.name = name
styles[name] = def
cssText = ""
if def.classes
$.each def.classes, (className, props) ->
cssText += ".#{pluginClassName}-#{def.name}-#{className} {\n"
$.each props, (name, val) ->
#vendor prefixes
if stylePrefixes[name]
$.each stylePrefixes[name], (i, prefix) ->
cssText += " #{prefix}#{name}: #{val};\n"
#add prop
cssText += " #{name}: #{val};\n"
cssText += "}\n"
if def.css
cssText += """
/* styles for #{def.name} */
#{def.css}
"""
if cssText
def.cssElem = insertCSS cssText
def.cssElem.attr('id', "notify-#{def.name}")
#precompute usable text fields
fields = {}
elem = $(def.html)
findFields 'html', elem, fields
findFields 'text', elem, fields
def.fields = fields
insertCSS = (cssText) ->
elem = createElem("style")
elem.attr 'type', 'text/css'
$("head").append elem
try
elem.html cssText
catch e #ie fix
elem[0].styleSheet.cssText = cssText
elem
# style.html helper
findFields = (type, elem, fields) ->
type = 'text' if type isnt 'html'
attr = "data-notify-#{type}"
find(elem,"[#{attr}]").each ->
name = $(@).attr attr
name = blankFieldName unless name
fields[name] = type
find = (elem, selector) ->
if elem.is(selector) then elem else elem.find selector
# ================================
# OPTIONS
# ================================
#overridable options
pluginOptions =
clickToHide: true
autoHide: true
autoHideDelay: 5000
arrowShow: true
arrowSize: 5
breakNewLines: true
# autoReposition: true
elementPosition: 'bottom'
globalPosition: 'top right'
style: 'bootstrap'
className: 'error'
showAnimation: 'slideDown'
showDuration: 400
hideAnimation: 'slideUp'
hideDuration: 200
gap: 5
inherit = (a, b) ->
F = () ->
F.prototype = a
$.extend true, new F(), b
defaults = (opts) ->
$.extend pluginOptions, opts
# ================================
# DOM MANIPULATION
# ================================
# plugin helpers
createElem = (tag) ->
$ "<#{tag}></#{tag}>"
# references to global anchor positions
globalAnchors = {}
#gets first on n radios, and gets the fancy stylised input for hidden inputs
getAnchorElement = (element) ->
#choose the first of n radios
if element.is('[type=radio]')
radios = element.parents('form:first').find('[type=radio]').filter (i, e) ->
$(e).attr('name') is element.attr('name')
element = radios.first()
#custom-styled inputs - find thier real element
element
incr = (obj, pos, val) ->
# console.log "incr ---- #{pos} #{val} (#{typeof val})"
if typeof val is 'string'
val = parseInt val, 10
else if typeof val isnt 'number'
return
return if isNaN val
opp = positions[opposites[pos.charAt(0)]]
temp = pos
#use the opposite if exists
if obj[opp] isnt `undefined`
pos = positions[opp.charAt(0)]
val = -val
if obj[pos] is `undefined`
obj[pos] = val
else
obj[pos] += val
null
realign = (alignment, inner, outer) ->
return if alignment in ['l','t']
0
else if alignment in ['c','m']
outer/2 - inner/2
else if alignment in ['r','b']
outer - inner
throw "Invalid alignment"
encode = (text) ->
encode.e = encode.e or createElem "div"
encode.e.text(text).html()
# ================================
# NOTIFY CLASS
# ================================
#define plugin
class Notification
#setup instance variables
constructor: (elem, data, options) ->
options = {className: options} if typeof options is 'string'
@options = inherit pluginOptions, if $.isPlainObject(options) then options else {}
#load style html into @userContainer
@loadHTML()
@wrapper = $(coreStyle.html)
@wrapper.addClass "#{pluginClassName}-hidable" if @options.clickToHide
@wrapper.data pluginClassName, @
@arrow = @wrapper.find ".#{pluginClassName}-arrow"
@container = @wrapper.find ".#{pluginClassName}-container"
@container.append @userContainer
if elem and elem.length
@elementType = elem.attr('type')
@originalElement = elem
@elem = getAnchorElement(elem)
@elem.data pluginClassName, @
# add into dom above elem
@elem.before @wrapper
@container.hide()
@run(data)
loadHTML: ->
style = @getStyle()
@userContainer = $(style.html)
@userFields = style.fields
show: (show, userCallback) ->
callback = =>
@destroy() if not show and not @elem
userCallback() if userCallback
hidden = @container.parent().parents(':hidden').length > 0
elems = @container.add @arrow
args = []
if hidden and show
fn = 'show'
else if hidden and not show
fn = 'hide'
else if not hidden and show
fn = @options.showAnimation
args.push @options.showDuration
else if not hidden and not show
fn = @options.hideAnimation
args.push @options.hideDuration
else
return callback()
args.push callback
elems[fn].apply elems, args
setGlobalPosition: () ->
[pMain, pAlign] = @getPosition()
main = positions[pMain]
align = positions[pAlign]
key = <KEY>+"|"+pAlign
anchor = globalAnchors[key]
unless anchor
anchor = globalAnchors[key] = createElem("div")
css = {}
css[main] = 0
if align is 'middle'
css.top = '45%'
else if align is 'center'
css.left = '45%'
else
css[align] = 0
anchor.css(css).addClass("#{pluginClassName}-corner")
$("body").append anchor
anchor.prepend @wrapper
setElementPosition: () ->
position = @getPosition()
[pMain, pAlign, pArrow] = position
#grab some dimensions
elemPos = @elem.position()
elemH = @elem.outerHeight()
elemW = @elem.outerWidth()
elemIH = @elem.innerHeight()
elemIW = @elem.innerWidth()
wrapPos = @wrapper.position()
contH = @container.height()
contW = @container.width()
#start calculations
mainFull = positions[pMain]
opp = opposites[pMain]
oppFull = positions[opp]
#initial positioning
css = {}
css[oppFull] = if pMain is 'b'
elemH
else if pMain is 'r'
elemW
else
0
#correct for elem-wrapper offset
# unless navigator.userAgent.match /MSIE/
incr css, 'top', elemPos.top - wrapPos.top
incr css, 'left', elemPos.left - wrapPos.left
#correct for margins
for pos in ['top', 'left']
margin = parseInt @elem.css("margin-#{pos}"), 10
incr css, pos, margin if margin
#correct for paddings (only for inline)
# if /^inline/.test @elem.css('display')
# padding = parseInt @elem.css("padding-#{pos}"), 10
# incr css, pos, -padding if padding
#add gap
gap = Math.max 0, @options.gap - if @options.arrowShow then arrowSize else 0
incr css, oppFull, gap
#calculate arrow
if not @options.arrowShow
@arrow.hide()
else
arrowSize = @options.arrowSize
arrowCss = $.extend {}, css
arrowColor = @userContainer.css("border-color") or
@userContainer.css("background-color") or
'white'
#build arrow
for pos in mainPositions
posFull = positions[pos]
continue if pos is opp
color = if posFull is mainFull then arrowColor else 'transparent'
arrowCss["border-#{posFull}"] = "#{arrowSize}px solid #{color}"
#add some room for the arrow
incr css, positions[opp], arrowSize
incr arrowCss, positions[pAlign], arrowSize*2 if pAlign in mainPositions
#calculate container alignment
if pMain in vAligns
incr css, 'left', realign(pAlign, contW, elemW)
incr arrowCss, 'left', realign(pAlign, arrowSize, elemIW) if arrowCss
else if pMain in hAligns
incr css, 'top', realign(pAlign, contH, elemH)
incr arrowCss, 'top', realign(pAlign, arrowSize, elemIH) if arrowCss
css.display = 'block' if @container.is(":visible")
#apply css
@container.removeAttr('style').css css
@arrow.removeAttr('style').css(arrowCss) if arrowCss
getPosition: ->
text = @options.position or if @elem then @options.elementPosition else @options.globalPosition
pos = parsePosition text
#validate position
pos[0] = 'b' if pos.length is 0
if pos[0] not in mainPositions
throw "Must be one of [#{mainPositions}]"
#validate alignment
if pos.length is 1 or
(pos[0] in vAligns and pos[1] not in hAligns) or
(pos[0] in hAligns and pos[1] not in vAligns)
pos[1] = if pos[0] in hAligns then 'm' else 'l'
if pos.length is 2
pos[2] = pos[1]
return pos
getStyle: (name) ->
name = @options.style unless name
name = 'default' unless name
style = styles[name]
throw "Missing style: #{name}"unless style
style
updateClasses: ->
classes = ['base']
if $.isArray @options.className
classes = classes.concat @options.className
else if @options.className
classes.push @options.className
style = @getStyle()
classes = $.map(classes, (n) -> "#{pluginClassName}-#{style.name}-#{n}").join ' '
@userContainer.attr 'class', classes
#run plugin
run: (data, options) ->
#update options
if $.isPlainObject(options)
$.extend @options, options
#shortcut special case
else if $.type(options) is 'string'
@options.className = options
if @container and not data
@show false
return
else if not @container and not data
return
datas = {}
if $.isPlainObject data
datas = data
else
datas[blankFieldName] = data
for name, d of datas
type = @userFields[name]
continue unless type
if type is 'text'
#escape
d = encode(d)
d = d.replace(/\n/g,'<br/>') if @options.breakNewLines
#update content
value = if name is blankFieldName then '' else '='+name
find(@userContainer,"[data-notify-#{type}#{value}]").html(d)
#set styles
@updateClasses()
#positioning
if @elem
@setElementPosition()
else
@setGlobalPosition()
@show true
#autohide
if @options.autoHide
clearTimeout @autohideTimer
@autohideTimer = setTimeout =>
@show false
, @options.autoHideDelay
destroy: ->
@wrapper.remove()
# ================================
# API
# ================================
# $.pluginName( { ... } ) changes options for all instances
$[pluginName] = (elem, data, options) ->
if (elem and elem.nodeName) or elem.jquery
$(elem)[pluginName](data, options)
else
options = data
data = elem
new Notification null, data, options
elem
# $( ... ).pluginName( { .. } ) creates a cached instance on each
$.fn[pluginName] = (data, options) ->
$(@).each ->
inst = getAnchorElement($(@)).data(pluginClassName)
if inst
inst.run data, options
else
new Notification $(@), data, options
@
#extra methods
$.extend $[pluginName], { defaults, addStyle, pluginOptions, getStyle, insertCSS }
#when ready
$ ->
#insert default style
insertCSS(coreStyle.css).attr('id', 'core-notify')
#watch all notifications clicks
$(document).on 'click', ".#{pluginClassName}-hidable", (e) ->
$(@).trigger 'notify-hide'
$(document).on 'notify-hide', ".#{pluginClassName}-wrapper", (e) ->
$(@).data(pluginClassName)?.show false
| true |
'use strict'
#plugin constants
pluginName = 'notify'
pluginClassName = pluginName+'js'
blankFieldName = pluginName+"!blank"
# ================================
# POSITIONING
# ================================
positions =
t: 'top'
m: 'middle'
b: 'bottom'
l: 'left'
c: 'center'
r: 'right'
hAligns = ['l','c','r']
vAligns = ['t','m','b']
mainPositions = ['t','b','l','r']
#positions mapped to opposites
opposites =
t: 'b'
m: null
b: 't'
l: 'r'
c: null
r: 'l'
parsePosition = (str) ->
pos = []
$.each str.split(/\W+/), (i,word) ->
w = word.toLowerCase().charAt(0)
pos.push w if positions[w]
pos
# ================================
# STYLES
# ================================
styles = {}
coreStyle =
name: 'core'
html: """
<div class="#{pluginClassName}-wrapper">
<div class="#{pluginClassName}-arrow"></div>
<div class="#{pluginClassName}-container"></div>
</div>
"""
# <div class="#{pluginClassName}-debug"></div>
# .#{pluginClassName}-debug {
# position: absolute;
# border: 3px solid red;
# height: 0;
# width: 0;
# }
css: """
.#{pluginClassName}-corner {
position: fixed;
margin: 5px;
z-index: 1050;
}
.#{pluginClassName}-corner .#{pluginClassName}-wrapper,
.#{pluginClassName}-corner .#{pluginClassName}-container {
position: relative;
display: block;
height: inherit;
width: inherit;
margin: 3px;
}
.#{pluginClassName}-wrapper {
z-index: 1;
position: absolute;
display: inline-block;
height: 0;
width: 0;
}
.#{pluginClassName}-container {
display: none;
z-index: 1;
position: absolute;
}
.#{pluginClassName}-hidable {
cursor: pointer;
}
[data-notify-text],[data-notify-html] {
position: relative;
}
.#{pluginClassName}-arrow {
position: absolute;
z-index: 2;
width: 0;
height: 0;
}
"""
stylePrefixes =
"border-radius": ["-webkit-", "-moz-"]
getStyle = (name) ->
styles[name]
addStyle = (name, def) ->
unless name
throw "Missing Style name"
unless def
throw "Missing Style definition"
unless def.html
throw "Missing Style HTML"
if styles[name]?.cssElem
if window.console
console.warn "#{pluginName}: overwriting style '#{name}'"
styles[name].cssElem.remove()
def.name = name
styles[name] = def
cssText = ""
if def.classes
$.each def.classes, (className, props) ->
cssText += ".#{pluginClassName}-#{def.name}-#{className} {\n"
$.each props, (name, val) ->
#vendor prefixes
if stylePrefixes[name]
$.each stylePrefixes[name], (i, prefix) ->
cssText += " #{prefix}#{name}: #{val};\n"
#add prop
cssText += " #{name}: #{val};\n"
cssText += "}\n"
if def.css
cssText += """
/* styles for #{def.name} */
#{def.css}
"""
if cssText
def.cssElem = insertCSS cssText
def.cssElem.attr('id', "notify-#{def.name}")
#precompute usable text fields
fields = {}
elem = $(def.html)
findFields 'html', elem, fields
findFields 'text', elem, fields
def.fields = fields
insertCSS = (cssText) ->
elem = createElem("style")
elem.attr 'type', 'text/css'
$("head").append elem
try
elem.html cssText
catch e #ie fix
elem[0].styleSheet.cssText = cssText
elem
# style.html helper
findFields = (type, elem, fields) ->
type = 'text' if type isnt 'html'
attr = "data-notify-#{type}"
find(elem,"[#{attr}]").each ->
name = $(@).attr attr
name = blankFieldName unless name
fields[name] = type
find = (elem, selector) ->
if elem.is(selector) then elem else elem.find selector
# ================================
# OPTIONS
# ================================
#overridable options
pluginOptions =
clickToHide: true
autoHide: true
autoHideDelay: 5000
arrowShow: true
arrowSize: 5
breakNewLines: true
# autoReposition: true
elementPosition: 'bottom'
globalPosition: 'top right'
style: 'bootstrap'
className: 'error'
showAnimation: 'slideDown'
showDuration: 400
hideAnimation: 'slideUp'
hideDuration: 200
gap: 5
inherit = (a, b) ->
F = () ->
F.prototype = a
$.extend true, new F(), b
defaults = (opts) ->
$.extend pluginOptions, opts
# ================================
# DOM MANIPULATION
# ================================
# plugin helpers
createElem = (tag) ->
$ "<#{tag}></#{tag}>"
# references to global anchor positions
globalAnchors = {}
#gets first on n radios, and gets the fancy stylised input for hidden inputs
getAnchorElement = (element) ->
#choose the first of n radios
if element.is('[type=radio]')
radios = element.parents('form:first').find('[type=radio]').filter (i, e) ->
$(e).attr('name') is element.attr('name')
element = radios.first()
#custom-styled inputs - find thier real element
element
incr = (obj, pos, val) ->
# console.log "incr ---- #{pos} #{val} (#{typeof val})"
if typeof val is 'string'
val = parseInt val, 10
else if typeof val isnt 'number'
return
return if isNaN val
opp = positions[opposites[pos.charAt(0)]]
temp = pos
#use the opposite if exists
if obj[opp] isnt `undefined`
pos = positions[opp.charAt(0)]
val = -val
if obj[pos] is `undefined`
obj[pos] = val
else
obj[pos] += val
null
realign = (alignment, inner, outer) ->
return if alignment in ['l','t']
0
else if alignment in ['c','m']
outer/2 - inner/2
else if alignment in ['r','b']
outer - inner
throw "Invalid alignment"
encode = (text) ->
encode.e = encode.e or createElem "div"
encode.e.text(text).html()
# ================================
# NOTIFY CLASS
# ================================
#define plugin
class Notification
#setup instance variables
constructor: (elem, data, options) ->
options = {className: options} if typeof options is 'string'
@options = inherit pluginOptions, if $.isPlainObject(options) then options else {}
#load style html into @userContainer
@loadHTML()
@wrapper = $(coreStyle.html)
@wrapper.addClass "#{pluginClassName}-hidable" if @options.clickToHide
@wrapper.data pluginClassName, @
@arrow = @wrapper.find ".#{pluginClassName}-arrow"
@container = @wrapper.find ".#{pluginClassName}-container"
@container.append @userContainer
if elem and elem.length
@elementType = elem.attr('type')
@originalElement = elem
@elem = getAnchorElement(elem)
@elem.data pluginClassName, @
# add into dom above elem
@elem.before @wrapper
@container.hide()
@run(data)
loadHTML: ->
style = @getStyle()
@userContainer = $(style.html)
@userFields = style.fields
show: (show, userCallback) ->
callback = =>
@destroy() if not show and not @elem
userCallback() if userCallback
hidden = @container.parent().parents(':hidden').length > 0
elems = @container.add @arrow
args = []
if hidden and show
fn = 'show'
else if hidden and not show
fn = 'hide'
else if not hidden and show
fn = @options.showAnimation
args.push @options.showDuration
else if not hidden and not show
fn = @options.hideAnimation
args.push @options.hideDuration
else
return callback()
args.push callback
elems[fn].apply elems, args
setGlobalPosition: () ->
[pMain, pAlign] = @getPosition()
main = positions[pMain]
align = positions[pAlign]
key = PI:KEY:<KEY>END_PI+"|"+pAlign
anchor = globalAnchors[key]
unless anchor
anchor = globalAnchors[key] = createElem("div")
css = {}
css[main] = 0
if align is 'middle'
css.top = '45%'
else if align is 'center'
css.left = '45%'
else
css[align] = 0
anchor.css(css).addClass("#{pluginClassName}-corner")
$("body").append anchor
anchor.prepend @wrapper
setElementPosition: () ->
position = @getPosition()
[pMain, pAlign, pArrow] = position
#grab some dimensions
elemPos = @elem.position()
elemH = @elem.outerHeight()
elemW = @elem.outerWidth()
elemIH = @elem.innerHeight()
elemIW = @elem.innerWidth()
wrapPos = @wrapper.position()
contH = @container.height()
contW = @container.width()
#start calculations
mainFull = positions[pMain]
opp = opposites[pMain]
oppFull = positions[opp]
#initial positioning
css = {}
css[oppFull] = if pMain is 'b'
elemH
else if pMain is 'r'
elemW
else
0
#correct for elem-wrapper offset
# unless navigator.userAgent.match /MSIE/
incr css, 'top', elemPos.top - wrapPos.top
incr css, 'left', elemPos.left - wrapPos.left
#correct for margins
for pos in ['top', 'left']
margin = parseInt @elem.css("margin-#{pos}"), 10
incr css, pos, margin if margin
#correct for paddings (only for inline)
# if /^inline/.test @elem.css('display')
# padding = parseInt @elem.css("padding-#{pos}"), 10
# incr css, pos, -padding if padding
#add gap
gap = Math.max 0, @options.gap - if @options.arrowShow then arrowSize else 0
incr css, oppFull, gap
#calculate arrow
if not @options.arrowShow
@arrow.hide()
else
arrowSize = @options.arrowSize
arrowCss = $.extend {}, css
arrowColor = @userContainer.css("border-color") or
@userContainer.css("background-color") or
'white'
#build arrow
for pos in mainPositions
posFull = positions[pos]
continue if pos is opp
color = if posFull is mainFull then arrowColor else 'transparent'
arrowCss["border-#{posFull}"] = "#{arrowSize}px solid #{color}"
#add some room for the arrow
incr css, positions[opp], arrowSize
incr arrowCss, positions[pAlign], arrowSize*2 if pAlign in mainPositions
#calculate container alignment
if pMain in vAligns
incr css, 'left', realign(pAlign, contW, elemW)
incr arrowCss, 'left', realign(pAlign, arrowSize, elemIW) if arrowCss
else if pMain in hAligns
incr css, 'top', realign(pAlign, contH, elemH)
incr arrowCss, 'top', realign(pAlign, arrowSize, elemIH) if arrowCss
css.display = 'block' if @container.is(":visible")
#apply css
@container.removeAttr('style').css css
@arrow.removeAttr('style').css(arrowCss) if arrowCss
getPosition: ->
text = @options.position or if @elem then @options.elementPosition else @options.globalPosition
pos = parsePosition text
#validate position
pos[0] = 'b' if pos.length is 0
if pos[0] not in mainPositions
throw "Must be one of [#{mainPositions}]"
#validate alignment
if pos.length is 1 or
(pos[0] in vAligns and pos[1] not in hAligns) or
(pos[0] in hAligns and pos[1] not in vAligns)
pos[1] = if pos[0] in hAligns then 'm' else 'l'
if pos.length is 2
pos[2] = pos[1]
return pos
getStyle: (name) ->
name = @options.style unless name
name = 'default' unless name
style = styles[name]
throw "Missing style: #{name}"unless style
style
updateClasses: ->
classes = ['base']
if $.isArray @options.className
classes = classes.concat @options.className
else if @options.className
classes.push @options.className
style = @getStyle()
classes = $.map(classes, (n) -> "#{pluginClassName}-#{style.name}-#{n}").join ' '
@userContainer.attr 'class', classes
#run plugin
run: (data, options) ->
#update options
if $.isPlainObject(options)
$.extend @options, options
#shortcut special case
else if $.type(options) is 'string'
@options.className = options
if @container and not data
@show false
return
else if not @container and not data
return
datas = {}
if $.isPlainObject data
datas = data
else
datas[blankFieldName] = data
for name, d of datas
type = @userFields[name]
continue unless type
if type is 'text'
#escape
d = encode(d)
d = d.replace(/\n/g,'<br/>') if @options.breakNewLines
#update content
value = if name is blankFieldName then '' else '='+name
find(@userContainer,"[data-notify-#{type}#{value}]").html(d)
#set styles
@updateClasses()
#positioning
if @elem
@setElementPosition()
else
@setGlobalPosition()
@show true
#autohide
if @options.autoHide
clearTimeout @autohideTimer
@autohideTimer = setTimeout =>
@show false
, @options.autoHideDelay
destroy: ->
@wrapper.remove()
# ================================
# API
# ================================
# $.pluginName( { ... } ) changes options for all instances
$[pluginName] = (elem, data, options) ->
if (elem and elem.nodeName) or elem.jquery
$(elem)[pluginName](data, options)
else
options = data
data = elem
new Notification null, data, options
elem
# $( ... ).pluginName( { .. } ) creates a cached instance on each
$.fn[pluginName] = (data, options) ->
$(@).each ->
inst = getAnchorElement($(@)).data(pluginClassName)
if inst
inst.run data, options
else
new Notification $(@), data, options
@
#extra methods
$.extend $[pluginName], { defaults, addStyle, pluginOptions, getStyle, insertCSS }
#when ready
$ ->
#insert default style
insertCSS(coreStyle.css).attr('id', 'core-notify')
#watch all notifications clicks
$(document).on 'click', ".#{pluginClassName}-hidable", (e) ->
$(@).trigger 'notify-hide'
$(document).on 'notify-hide', ".#{pluginClassName}-wrapper", (e) ->
$(@).data(pluginClassName)?.show false
|
[
{
"context": "###\n scroll-proxy's Gruntfile\n Author: Matheus Kautzmann\n Description:\n Build the project files, three",
"end": 58,
"score": 0.999873161315918,
"start": 41,
"tag": "NAME",
"value": "Matheus Kautzmann"
},
{
"context": " options: {\n username: process.e... | Gruntfile.coffee | mkautzmann/scroll-proxy | 50 | ###
scroll-proxy's Gruntfile
Author: Matheus Kautzmann
Description:
Build the project files, three main modes are available:
- grunt watch = useful while developing features or fixing bugs, keeps
running CoffeeScript compilation.
- grunt demo = Spawns a demo server where you can debug ScrollProxy.
- grunt test = Runs local tests and coverage checks.
- grunt build = Builds the whole project leaving the CommonJS modules on
lib folder and full packaged ready-to-use code on dist folder.
Also, there are some individual grunt tasks, for more info run `grunt help`
###
module.exports = (grunt) ->
grunt.initConfig({
pkg: grunt.file.readJSON('package.json')
# Lint all the CoffeeScript files
coffeelint: {
app: {
files: {
src: ['src/*.coffee', 'Gruntfile.coffee']
}
}
test: {
files: {
src: ['test/*.coffee']
}
}
options: {
configFile: 'coffeelint.json'
}
}
# Browserify bundles
browserify: {
standalone: {
src: ['src/*.coffee']
dest: 'dist/<%= pkg.name %>.min.js'
options: {
transform: ['coffeeify', 'uglifyify']
browserifyOptions: {
standalone: 'ScrollProxy'
extensions: '.coffee'
}
banner: '/*<%= pkg.name %>@<%= pkg.version %>*/'
}
}
demo: {
src: ['src/*.coffee', 'demo/*.coffee']
dest: 'demo/<%= pkg.name %>.js'
options: {
transform: ['coffeeify']
browserifyOptions: {
extensions: '.coffee'
debug: true
}
}
}
test: {
src: ['test/*.coffee']
dest: 'test/testBundle.js'
options: {
transform: ['browserify-coffee-coverage']
browserifyOptions: {
extensions: '.coffee'
debug: true
}
}
}
}
# Compile Coffee for NPM bundle
coffee: {
main: {
files: {
'dist/scroll-proxy.js': 'src/ScrollProxy.coffee'
'dist/SUtil.js': 'src/SUtil.coffee'
}
}
options: {
bare: true
banner: '/*<%= pkg.name %>@<%= pkg.version %>*/'
}
}
# Run tests using Mocha locally
mochify: {
test: {
options: {
reporter: 'spec'
extension: '.coffee'
transform: 'coffeeify'
cover: true
}
src: ['test/*.coffee']
}
}
# Generate documentation with Codo
codo: {
app: {
src: ['src/*.coffee']
options: {
name: '<%= pkg.name %>'
output: './docs'
title: '<%= pkg.name %>\'s Documentation'
}
}
}
# Clean all builds, get back to default state you were when cloning
clean: [
'dist'
'docs'
'demo/scroll-proxy.js'
'test/testBundle.js'
'bower_components'
'node_modules'
]
# Watch tasks to run while developing
watch: {
options: {
spawn: true
}
coffeelint: {
files: ['src/*.coffee', 'Gruntfile.coffee']
tasks: ['coffeelint']
}
browserifyDemo: {
files: ['src/*.coffee', 'demo/*.coffee']
tasks: ['browserify:demo']
}
browserifyTest: {
files: ['src/*.coffee', 'test/*.coffee']
tasks: ['browserify:test']
}
}
# Run connect server for testing purposes
connect: {
server: {
options: {
port: 8080
base: '.'
}
}
}
# Run demo server and open demo page
'http-server': {
demo: {
root: './demo'
port: 3000
ext: 'html'
runInBackground: false
openBrowser: true
}
}
# Runs browser tests on Sauce Labs (only Circle CI must run it)
'saucelabs-mocha': {
all: {
options: {
username: process.env.SAUCE_USERNAME
key: process.env.SAUCE_ACCESSKEY
urls: ['localhost:8080/test/index.html']
testname: 'scroll-proxy'
build: 'build-ci' + process.env.CIRCLE_BUILD_NUM
pollInterval: 5000
'max-duration': 500
maxRetries: 1
browsers: grunt.file.readJSON('browserSupport.json').browsers
}
}
}
})
# Load grunt tasks
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-codo')
grunt.loadNpmTasks('grunt-coffeelint')
grunt.loadNpmTasks('grunt-contrib-clean')
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-mochify')
grunt.loadNpmTasks('grunt-contrib-connect')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-http-server')
grunt.loadNpmTasks('grunt-saucelabs')
# Set up the task aliases
grunt.registerTask('lint', ['coffeelint:app', 'coffeelint:test'])
grunt.registerTask('renew', ['clean'])
grunt.registerTask('docs', ['codo'])
grunt.registerTask('test', [
'lint'
'mochify:test'
])
grunt.registerTask('demo', [
'browserify:demo'
'http-server'
])
grunt.registerTask('build', [
'test'
'coffee'
'browserify:standalone'
'docs'
])
if process.env.CI
grunt.registerTask('ci', [
'test'
'browserify:test'
'connect'
'saucelabs-mocha'
])
grunt.registerTask('default', ['build'])
| 164790 | ###
scroll-proxy's Gruntfile
Author: <NAME>
Description:
Build the project files, three main modes are available:
- grunt watch = useful while developing features or fixing bugs, keeps
running CoffeeScript compilation.
- grunt demo = Spawns a demo server where you can debug ScrollProxy.
- grunt test = Runs local tests and coverage checks.
- grunt build = Builds the whole project leaving the CommonJS modules on
lib folder and full packaged ready-to-use code on dist folder.
Also, there are some individual grunt tasks, for more info run `grunt help`
###
module.exports = (grunt) ->
grunt.initConfig({
pkg: grunt.file.readJSON('package.json')
# Lint all the CoffeeScript files
coffeelint: {
app: {
files: {
src: ['src/*.coffee', 'Gruntfile.coffee']
}
}
test: {
files: {
src: ['test/*.coffee']
}
}
options: {
configFile: 'coffeelint.json'
}
}
# Browserify bundles
browserify: {
standalone: {
src: ['src/*.coffee']
dest: 'dist/<%= pkg.name %>.min.js'
options: {
transform: ['coffeeify', 'uglifyify']
browserifyOptions: {
standalone: 'ScrollProxy'
extensions: '.coffee'
}
banner: '/*<%= pkg.name %>@<%= pkg.version %>*/'
}
}
demo: {
src: ['src/*.coffee', 'demo/*.coffee']
dest: 'demo/<%= pkg.name %>.js'
options: {
transform: ['coffeeify']
browserifyOptions: {
extensions: '.coffee'
debug: true
}
}
}
test: {
src: ['test/*.coffee']
dest: 'test/testBundle.js'
options: {
transform: ['browserify-coffee-coverage']
browserifyOptions: {
extensions: '.coffee'
debug: true
}
}
}
}
# Compile Coffee for NPM bundle
coffee: {
main: {
files: {
'dist/scroll-proxy.js': 'src/ScrollProxy.coffee'
'dist/SUtil.js': 'src/SUtil.coffee'
}
}
options: {
bare: true
banner: '/*<%= pkg.name %>@<%= pkg.version %>*/'
}
}
# Run tests using Mocha locally
mochify: {
test: {
options: {
reporter: 'spec'
extension: '.coffee'
transform: 'coffeeify'
cover: true
}
src: ['test/*.coffee']
}
}
# Generate documentation with Codo
codo: {
app: {
src: ['src/*.coffee']
options: {
name: '<%= pkg.name %>'
output: './docs'
title: '<%= pkg.name %>\'s Documentation'
}
}
}
# Clean all builds, get back to default state you were when cloning
clean: [
'dist'
'docs'
'demo/scroll-proxy.js'
'test/testBundle.js'
'bower_components'
'node_modules'
]
# Watch tasks to run while developing
watch: {
options: {
spawn: true
}
coffeelint: {
files: ['src/*.coffee', 'Gruntfile.coffee']
tasks: ['coffeelint']
}
browserifyDemo: {
files: ['src/*.coffee', 'demo/*.coffee']
tasks: ['browserify:demo']
}
browserifyTest: {
files: ['src/*.coffee', 'test/*.coffee']
tasks: ['browserify:test']
}
}
# Run connect server for testing purposes
connect: {
server: {
options: {
port: 8080
base: '.'
}
}
}
# Run demo server and open demo page
'http-server': {
demo: {
root: './demo'
port: 3000
ext: 'html'
runInBackground: false
openBrowser: true
}
}
# Runs browser tests on Sauce Labs (only Circle CI must run it)
'saucelabs-mocha': {
all: {
options: {
username: process.env.SAUCE_USERNAME
key: process.env.SAUCE_ACCESSKEY
urls: ['localhost:8080/test/index.html']
testname: 'scroll-proxy'
build: 'build-ci' + process.env.CIRCLE_BUILD_NUM
pollInterval: 5000
'max-duration': 500
maxRetries: 1
browsers: grunt.file.readJSON('browserSupport.json').browsers
}
}
}
})
# Load grunt tasks
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-codo')
grunt.loadNpmTasks('grunt-coffeelint')
grunt.loadNpmTasks('grunt-contrib-clean')
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-mochify')
grunt.loadNpmTasks('grunt-contrib-connect')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-http-server')
grunt.loadNpmTasks('grunt-saucelabs')
# Set up the task aliases
grunt.registerTask('lint', ['coffeelint:app', 'coffeelint:test'])
grunt.registerTask('renew', ['clean'])
grunt.registerTask('docs', ['codo'])
grunt.registerTask('test', [
'lint'
'mochify:test'
])
grunt.registerTask('demo', [
'browserify:demo'
'http-server'
])
grunt.registerTask('build', [
'test'
'coffee'
'browserify:standalone'
'docs'
])
if process.env.CI
grunt.registerTask('ci', [
'test'
'browserify:test'
'connect'
'saucelabs-mocha'
])
grunt.registerTask('default', ['build'])
| true | ###
scroll-proxy's Gruntfile
Author: PI:NAME:<NAME>END_PI
Description:
Build the project files, three main modes are available:
- grunt watch = useful while developing features or fixing bugs, keeps
running CoffeeScript compilation.
- grunt demo = Spawns a demo server where you can debug ScrollProxy.
- grunt test = Runs local tests and coverage checks.
- grunt build = Builds the whole project leaving the CommonJS modules on
lib folder and full packaged ready-to-use code on dist folder.
Also, there are some individual grunt tasks, for more info run `grunt help`
###
module.exports = (grunt) ->
grunt.initConfig({
pkg: grunt.file.readJSON('package.json')
# Lint all the CoffeeScript files
coffeelint: {
app: {
files: {
src: ['src/*.coffee', 'Gruntfile.coffee']
}
}
test: {
files: {
src: ['test/*.coffee']
}
}
options: {
configFile: 'coffeelint.json'
}
}
# Browserify bundles
browserify: {
standalone: {
src: ['src/*.coffee']
dest: 'dist/<%= pkg.name %>.min.js'
options: {
transform: ['coffeeify', 'uglifyify']
browserifyOptions: {
standalone: 'ScrollProxy'
extensions: '.coffee'
}
banner: '/*<%= pkg.name %>@<%= pkg.version %>*/'
}
}
demo: {
src: ['src/*.coffee', 'demo/*.coffee']
dest: 'demo/<%= pkg.name %>.js'
options: {
transform: ['coffeeify']
browserifyOptions: {
extensions: '.coffee'
debug: true
}
}
}
test: {
src: ['test/*.coffee']
dest: 'test/testBundle.js'
options: {
transform: ['browserify-coffee-coverage']
browserifyOptions: {
extensions: '.coffee'
debug: true
}
}
}
}
# Compile Coffee for NPM bundle
coffee: {
main: {
files: {
'dist/scroll-proxy.js': 'src/ScrollProxy.coffee'
'dist/SUtil.js': 'src/SUtil.coffee'
}
}
options: {
bare: true
banner: '/*<%= pkg.name %>@<%= pkg.version %>*/'
}
}
# Run tests using Mocha locally
mochify: {
test: {
options: {
reporter: 'spec'
extension: '.coffee'
transform: 'coffeeify'
cover: true
}
src: ['test/*.coffee']
}
}
# Generate documentation with Codo
codo: {
app: {
src: ['src/*.coffee']
options: {
name: '<%= pkg.name %>'
output: './docs'
title: '<%= pkg.name %>\'s Documentation'
}
}
}
# Clean all builds, get back to default state you were when cloning
clean: [
'dist'
'docs'
'demo/scroll-proxy.js'
'test/testBundle.js'
'bower_components'
'node_modules'
]
# Watch tasks to run while developing
watch: {
options: {
spawn: true
}
coffeelint: {
files: ['src/*.coffee', 'Gruntfile.coffee']
tasks: ['coffeelint']
}
browserifyDemo: {
files: ['src/*.coffee', 'demo/*.coffee']
tasks: ['browserify:demo']
}
browserifyTest: {
files: ['src/*.coffee', 'test/*.coffee']
tasks: ['browserify:test']
}
}
# Run connect server for testing purposes
connect: {
server: {
options: {
port: 8080
base: '.'
}
}
}
# Run demo server and open demo page
'http-server': {
demo: {
root: './demo'
port: 3000
ext: 'html'
runInBackground: false
openBrowser: true
}
}
# Runs browser tests on Sauce Labs (only Circle CI must run it)
'saucelabs-mocha': {
all: {
options: {
username: process.env.SAUCE_USERNAME
key: process.env.SAUCE_ACCESSKEY
urls: ['localhost:8080/test/index.html']
testname: 'scroll-proxy'
build: 'build-ci' + process.env.CIRCLE_BUILD_NUM
pollInterval: 5000
'max-duration': 500
maxRetries: 1
browsers: grunt.file.readJSON('browserSupport.json').browsers
}
}
}
})
# Load grunt tasks
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-codo')
grunt.loadNpmTasks('grunt-coffeelint')
grunt.loadNpmTasks('grunt-contrib-clean')
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-mochify')
grunt.loadNpmTasks('grunt-contrib-connect')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-http-server')
grunt.loadNpmTasks('grunt-saucelabs')
# Set up the task aliases
grunt.registerTask('lint', ['coffeelint:app', 'coffeelint:test'])
grunt.registerTask('renew', ['clean'])
grunt.registerTask('docs', ['codo'])
grunt.registerTask('test', [
'lint'
'mochify:test'
])
grunt.registerTask('demo', [
'browserify:demo'
'http-server'
])
grunt.registerTask('build', [
'test'
'coffee'
'browserify:standalone'
'docs'
])
if process.env.CI
grunt.registerTask('ci', [
'test'
'browserify:test'
'connect'
'saucelabs-mocha'
])
grunt.registerTask('default', ['build'])
|
[
{
"context": "rsts\n name = @name_map[name]\n return \"Michelle\" if name is \"michelle\"\n return \"Cousin Amy\" ",
"end": 182,
"score": 0.9993936419487,
"start": 174,
"tag": "NAME",
"value": "Michelle"
},
{
"context": "ame_map[name]\n return \"Michelle\" if na... | src/javascript/duggarify.coffee | adampash/dug_name_generator | 0 | Duggarify =
name: (name) ->
orig = name
name = name.toLowerCase().trim()
if @exists(name)
if name in @firsts
name = @name_map[name]
return "Michelle" if name is "michelle"
return "Cousin Amy" if name is "amy"
return "Grandma" if name is "grandma"
name = name[1..-1]
else if @vowel(name)
name = name
else if @double_cons(name)
name = "'#{name[1..-1]}"
else if @j_start(name)
name = "#{orig[1..-1]} Bob"
else
name = name[1..-1]
"J#{name}"
exists: (name) ->
name.toLowerCase() in @names or name.toLowerCase() in @firsts
vowel: (name) ->
vowel_regex = /^[aeiou]/i
name.match(vowel_regex)?
double_cons: (name) ->
return false if @vowel(name)
double_cons_regex = /^[b-df-hj-np-tv-z]{2}/i
name.match(double_cons_regex)?
j_start: (name) ->
j_regex = /^j/i
name.match(j_regex)?
name_map:
"joshua": "joshua"
"jim": "jim Bob"
"michelle": "michelle"
"amy": "amy"
"grandma": "grandma"
"john": "john-David"
"joseph": "joseph"
"josiah": "josiah"
"jedidiah": "jedidiah"
"jeremiah": "jeremiah"
"jason": "jason"
"james": "james Andrew"
"justin": "justin"
"jackson": "jackson"
"jana": "jana"
"jill": "jill"
"jessa": "jessa"
"jinger": "jinger"
"joy": "joy-Anna"
"johannah": "johannah Faith"
"jennifer": "jennifer"
"jordyn": "jordyn-Grace"
"josie": "josie"
names: [
"jim Bob"
"michelle"
"amy"
"grandma"
"joshua"
"john-David"
"joseph"
"josiah"
"jedidiah"
"jeremiah"
"jason"
"james Andrew"
"justin"
"jackson"
"jana"
"jill"
"jessa"
"jinger"
"joy-Anna"
"johannah Faith"
"jennifer"
"jordyn-Grace"
"josie"
]
firsts: [
"jim"
"michelle"
"grandma"
"amy"
"joshua"
"john"
"joseph"
"josiah"
"jedidiah"
"jeremiah"
"jason"
"james"
"justin"
"jackson"
"jana"
"jill"
"jessa"
"jinger"
"joy"
"johannah"
"jennifer"
"jordyn"
"josie"
]
module.exports = Duggarify
| 28221 | Duggarify =
name: (name) ->
orig = name
name = name.toLowerCase().trim()
if @exists(name)
if name in @firsts
name = @name_map[name]
return "<NAME>" if name is "<NAME>"
return "<NAME>" if name is "<NAME>"
return "<NAME>" if name is "<NAME>"
name = name[1..-1]
else if @vowel(name)
name = name
else if @double_cons(name)
name = "'#{name[1..-1]}"
else if @j_start(name)
name = "#{orig[1..-1]} <NAME>"
else
name = name[1..-1]
"J#{name}"
exists: (name) ->
name.toLowerCase() in @names or name.toLowerCase() in @firsts
vowel: (name) ->
vowel_regex = /^[aeiou]/i
name.match(vowel_regex)?
double_cons: (name) ->
return false if @vowel(name)
double_cons_regex = /^[b-df-hj-np-tv-z]{2}/i
name.match(double_cons_regex)?
j_start: (name) ->
j_regex = /^j/i
name.match(j_regex)?
name_map:
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"joy": "<NAME>-<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>": "<NAME>"
names: [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>-<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
firsts: [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
module.exports = Duggarify
| true | Duggarify =
name: (name) ->
orig = name
name = name.toLowerCase().trim()
if @exists(name)
if name in @firsts
name = @name_map[name]
return "PI:NAME:<NAME>END_PI" if name is "PI:NAME:<NAME>END_PI"
return "PI:NAME:<NAME>END_PI" if name is "PI:NAME:<NAME>END_PI"
return "PI:NAME:<NAME>END_PI" if name is "PI:NAME:<NAME>END_PI"
name = name[1..-1]
else if @vowel(name)
name = name
else if @double_cons(name)
name = "'#{name[1..-1]}"
else if @j_start(name)
name = "#{orig[1..-1]} PI:NAME:<NAME>END_PI"
else
name = name[1..-1]
"J#{name}"
exists: (name) ->
name.toLowerCase() in @names or name.toLowerCase() in @firsts
vowel: (name) ->
vowel_regex = /^[aeiou]/i
name.match(vowel_regex)?
double_cons: (name) ->
return false if @vowel(name)
double_cons_regex = /^[b-df-hj-np-tv-z]{2}/i
name.match(double_cons_regex)?
j_start: (name) ->
j_regex = /^j/i
name.match(j_regex)?
name_map:
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"joy": "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
names: [
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
firsts: [
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
module.exports = Duggarify
|
[
{
"context": "###*\n# Created by andrey on 13.02.17.\n###\n\n### menu resize ###\n$(document)",
"end": 24,
"score": 0.9981473684310913,
"start": 18,
"tag": "NAME",
"value": "andrey"
}
] | resources/themes/default/assets/coffee/script.coffee | Andrey9/A-V-CMS | 0 | ###*
# Created by andrey on 13.02.17.
###
### menu resize ###
$(document).on 'scroll', ->
if $(document).scrollTop() > 600
$('header').addClass 'smaller'
else
$('header').removeClass 'smaller'
return
### hamburger ###
$('.hamburger').on 'click', ->
if $(this).hasClass('is-active')
$(this).removeClass 'is-active'
$('.main_menu').removeClass 'active'
else
$(this).addClass 'is-active'
$('.main_menu').addClass 'active'
return
### ajax request for first 6 photos ###
get_first_photos = (id) ->
$.ajax(
type: 'GET'
url: 'get_first_photos'
data: id: id).done (response) ->
$('#first_photos').html response
overlay_width_calc()
return
return
### photo overlay width calculating ###
overlay_width_calc = ->
$('.photo').each ->
width = $(this).find('img').width()
image = $(this).find('.image-wrap')
hover = $(this).find('.hover-wrap')
image.width width
hover.width width
return
return
### email validation ###
isEmail = (email) ->
regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/
regex.test email
### set full photoalbum link ###
$(document).ready ->
# overlay_width_calc()
# get_first_photos 0
_href = $('.get_first_photos').first().attr('href')
$('#show_full_album').attr 'href', _href
return
$(window).resize ->
overlay_width_calc()
return
### photoalbum link click ###
$(document).on 'click', '.get_first_photos', (event) ->
event.preventDefault()
_id = $(this).data('id')
_href = $(this).attr('href')
# get_first_photos _id
$('#show_full_album').attr 'href', _href
return
### mail send function ###
###$('.contacts_form').on 'submit', (event) ->
event.preventDefault()
if isEmail($(this).find('input[name=email]').val())
formData = $(this).serialize()
formMethod = $(this).attr('method')
formUrl = $(this).attr('action')
fio = $(this).find('input[name=fio]')
email = $(this).find('input[name=email]')
mess = $(this).find('textarea[name=message]')
$.ajax(
type: formMethod
url: formUrl
data: formData).done (response) ->
fio.val ''
email.val ''
mess.val ''
message.show response['message'], response['status']
return
else
message.show $('.message-container').data('email-error'), 'error'
return###
### language setter toggler ###
###$('.languageSet .toggler').on 'click', (e) ->
e.preventDefault()
console.log('lang')
langMenu = $('.languageSet')
if !langMenu.hasClass('opened')
langMenu.css 'right', '-68px'
langMenu.addClass 'opened'
$(this).find('img.opened').show()
$(this).find('img.closed').hide()
else
langMenu.css 'right', '-200px'
langMenu.removeClass 'opened'
$(this).find('img.opened').hide()
$(this).find('img.closed').show()
return###
# ---
# generated by js2coffee 2.2.0 | 197479 | ###*
# Created by <NAME> on 13.02.17.
###
### menu resize ###
$(document).on 'scroll', ->
if $(document).scrollTop() > 600
$('header').addClass 'smaller'
else
$('header').removeClass 'smaller'
return
### hamburger ###
$('.hamburger').on 'click', ->
if $(this).hasClass('is-active')
$(this).removeClass 'is-active'
$('.main_menu').removeClass 'active'
else
$(this).addClass 'is-active'
$('.main_menu').addClass 'active'
return
### ajax request for first 6 photos ###
get_first_photos = (id) ->
$.ajax(
type: 'GET'
url: 'get_first_photos'
data: id: id).done (response) ->
$('#first_photos').html response
overlay_width_calc()
return
return
### photo overlay width calculating ###
overlay_width_calc = ->
$('.photo').each ->
width = $(this).find('img').width()
image = $(this).find('.image-wrap')
hover = $(this).find('.hover-wrap')
image.width width
hover.width width
return
return
### email validation ###
isEmail = (email) ->
regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/
regex.test email
### set full photoalbum link ###
$(document).ready ->
# overlay_width_calc()
# get_first_photos 0
_href = $('.get_first_photos').first().attr('href')
$('#show_full_album').attr 'href', _href
return
$(window).resize ->
overlay_width_calc()
return
### photoalbum link click ###
$(document).on 'click', '.get_first_photos', (event) ->
event.preventDefault()
_id = $(this).data('id')
_href = $(this).attr('href')
# get_first_photos _id
$('#show_full_album').attr 'href', _href
return
### mail send function ###
###$('.contacts_form').on 'submit', (event) ->
event.preventDefault()
if isEmail($(this).find('input[name=email]').val())
formData = $(this).serialize()
formMethod = $(this).attr('method')
formUrl = $(this).attr('action')
fio = $(this).find('input[name=fio]')
email = $(this).find('input[name=email]')
mess = $(this).find('textarea[name=message]')
$.ajax(
type: formMethod
url: formUrl
data: formData).done (response) ->
fio.val ''
email.val ''
mess.val ''
message.show response['message'], response['status']
return
else
message.show $('.message-container').data('email-error'), 'error'
return###
### language setter toggler ###
###$('.languageSet .toggler').on 'click', (e) ->
e.preventDefault()
console.log('lang')
langMenu = $('.languageSet')
if !langMenu.hasClass('opened')
langMenu.css 'right', '-68px'
langMenu.addClass 'opened'
$(this).find('img.opened').show()
$(this).find('img.closed').hide()
else
langMenu.css 'right', '-200px'
langMenu.removeClass 'opened'
$(this).find('img.opened').hide()
$(this).find('img.closed').show()
return###
# ---
# generated by js2coffee 2.2.0 | true | ###*
# Created by PI:NAME:<NAME>END_PI on 13.02.17.
###
### menu resize ###
$(document).on 'scroll', ->
if $(document).scrollTop() > 600
$('header').addClass 'smaller'
else
$('header').removeClass 'smaller'
return
### hamburger ###
$('.hamburger').on 'click', ->
if $(this).hasClass('is-active')
$(this).removeClass 'is-active'
$('.main_menu').removeClass 'active'
else
$(this).addClass 'is-active'
$('.main_menu').addClass 'active'
return
### ajax request for first 6 photos ###
get_first_photos = (id) ->
$.ajax(
type: 'GET'
url: 'get_first_photos'
data: id: id).done (response) ->
$('#first_photos').html response
overlay_width_calc()
return
return
### photo overlay width calculating ###
overlay_width_calc = ->
$('.photo').each ->
width = $(this).find('img').width()
image = $(this).find('.image-wrap')
hover = $(this).find('.hover-wrap')
image.width width
hover.width width
return
return
### email validation ###
isEmail = (email) ->
regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/
regex.test email
### set full photoalbum link ###
$(document).ready ->
# overlay_width_calc()
# get_first_photos 0
_href = $('.get_first_photos').first().attr('href')
$('#show_full_album').attr 'href', _href
return
$(window).resize ->
overlay_width_calc()
return
### photoalbum link click ###
$(document).on 'click', '.get_first_photos', (event) ->
event.preventDefault()
_id = $(this).data('id')
_href = $(this).attr('href')
# get_first_photos _id
$('#show_full_album').attr 'href', _href
return
### mail send function ###
###$('.contacts_form').on 'submit', (event) ->
event.preventDefault()
if isEmail($(this).find('input[name=email]').val())
formData = $(this).serialize()
formMethod = $(this).attr('method')
formUrl = $(this).attr('action')
fio = $(this).find('input[name=fio]')
email = $(this).find('input[name=email]')
mess = $(this).find('textarea[name=message]')
$.ajax(
type: formMethod
url: formUrl
data: formData).done (response) ->
fio.val ''
email.val ''
mess.val ''
message.show response['message'], response['status']
return
else
message.show $('.message-container').data('email-error'), 'error'
return###
### language setter toggler ###
###$('.languageSet .toggler').on 'click', (e) ->
e.preventDefault()
console.log('lang')
langMenu = $('.languageSet')
if !langMenu.hasClass('opened')
langMenu.css 'right', '-68px'
langMenu.addClass 'opened'
$(this).find('img.opened').show()
$(this).find('img.closed').hide()
else
langMenu.css 'right', '-200px'
langMenu.removeClass 'opened'
$(this).find('img.opened').hide()
$(this).find('img.closed').show()
return###
# ---
# generated by js2coffee 2.2.0 |
[
{
"context": "ed.should.have.property 'ref'\n\n username: 'admin'\n id: '1'\n token: '1'\n passw",
"end": 384,
"score": 0.9990052580833435,
"start": 379,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "username: 'admin'\n id: '1'\n token... | test/reference.coffee | wearefractal/seedling | 1 | seedling = require '../'
should = require 'should'
config = require './config/config'
goose = require 'goosestrap'
module.exports =
"functions should get ref to seedling": ->
db = goose config.db.url, config.paths.models
User = db.model 'User'
seeds =
User: (seed) ->
# seedling
seed.should.have.property 'ref'
username: 'admin'
id: '1'
token: '1'
password: 'secret'
seed = new seedling db, seeds
seed.create (err) ->
should.not.exist err
| 202861 | seedling = require '../'
should = require 'should'
config = require './config/config'
goose = require 'goosestrap'
module.exports =
"functions should get ref to seedling": ->
db = goose config.db.url, config.paths.models
User = db.model 'User'
seeds =
User: (seed) ->
# seedling
seed.should.have.property 'ref'
username: 'admin'
id: '1'
token: '<KEY>'
password: '<PASSWORD>'
seed = new seedling db, seeds
seed.create (err) ->
should.not.exist err
| true | seedling = require '../'
should = require 'should'
config = require './config/config'
goose = require 'goosestrap'
module.exports =
"functions should get ref to seedling": ->
db = goose config.db.url, config.paths.models
User = db.model 'User'
seeds =
User: (seed) ->
# seedling
seed.should.have.property 'ref'
username: 'admin'
id: '1'
token: 'PI:KEY:<KEY>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
seed = new seedling db, seeds
seed.create (err) ->
should.not.exist err
|
[
{
"context": "p1: {key1: 'key1'}, prop2: {key2: 'key2', key3: ['a', 'b', 'c']}})\n\ntest \"#1435 Indented property acc",
"end": 9817,
"score": 0.9282191395759583,
"start": 9816,
"tag": "KEY",
"value": "a"
},
{
"context": "key1: 'key1'}, prop2: {key2: 'key2', key3: ['a', 'b', 'c']}})\... | test/functions.coffee | bazineta/coffeescript | 1 | # Function Literals
# -----------------
# TODO: add indexing and method invocation tests: (->)[0], (->).call()
# * Function Definition
# * Bound Function Definition
# * Parameter List Features
# * Splat Parameters
# * Context (@) Parameters
# * Parameter Destructuring
# * Default Parameters
# Function Definition
x = 1
y = {}
y.x = -> 3
ok x is 1
ok typeof(y.x) is 'function'
ok y.x instanceof Function
ok y.x() is 3
# The empty function should not cause a syntax error.
->
() ->
# Multiple nested function declarations mixed with implicit calls should not
# cause a syntax error.
(one) -> (two) -> three four, (five) -> six seven, eight, (nine) ->
# with multiple single-line functions on the same line.
func = (x) -> (x) -> (x) -> x
ok func(1)(2)(3) is 3
# Make incorrect indentation safe.
func = ->
obj = {
key: 10
}
obj.key - 5
eq func(), 5
# Ensure that functions with the same name don't clash with helper functions.
del = -> 5
ok del() is 5
# Bound Function Definition
obj =
bound: ->
(=> this)()
unbound: ->
(-> this)()
nested: ->
(=>
(=>
(=> this)()
)()
)()
eq obj, obj.bound()
ok obj isnt obj.unbound()
eq obj, obj.nested()
test "even more fancy bound functions", ->
obj =
one: ->
do =>
return this.two()
two: ->
do =>
do =>
do =>
return this.three
three: 3
eq obj.one(), 3
test "arguments in bound functions inherit from parent function", ->
# The `arguments` object in an ES arrow function refers to the `arguments`
# of the parent scope, just like `this`. In the CoffeeScript 1.x
# implementation of `=>`, the `arguments` object referred to the arguments
# of the arrow function; but per the ES2015 spec, `arguments` should refer
# to the parent.
arrayEq ((a...) -> a)([1, 2, 3]), ((a...) => a)([1, 2, 3])
parent = (a, b, c) ->
(bound = =>
[arguments[0], arguments[1], arguments[2]]
)()
arrayEq [1, 2, 3], parent(1, 2, 3)
test "self-referencing functions", ->
changeMe = ->
changeMe = 2
changeMe()
eq changeMe, 2
# Parameter List Features
test "splats", ->
arrayEq [0, 1, 2], (((splat...) -> splat) 0, 1, 2)
arrayEq [2, 3], (((_, _1, splat...) -> splat) 0, 1, 2, 3)
arrayEq [0, 1], (((splat..., _, _1) -> splat) 0, 1, 2, 3)
arrayEq [2], (((_, _1, splat..., _2) -> splat) 0, 1, 2, 3)
# Should not trigger implicit call, e.g. rest ... => rest(...)
arrayEq [0, 1, 2], (((splat ...) -> splat) 0, 1, 2)
arrayEq [2, 3], (((_, _1, splat ...) -> splat) 0, 1, 2, 3)
arrayEq [0, 1], (((splat ..., _, _1) -> splat) 0, 1, 2, 3)
arrayEq [2], (((_, _1, splat ..., _2) -> splat) 0, 1, 2, 3)
test "destructured splatted parameters", ->
arr = [0,1,2]
splatArray = ([a...]) -> a
splatArrayRest = ([a...],b...) -> arrayEq(a,b); b
arrayEq splatArray(arr), arr
arrayEq splatArrayRest(arr,0,1,2), arr
# Should not trigger implicit call, e.g. rest ... => rest(...)
splatArray = ([a ...]) -> a
splatArrayRest = ([a ...],b ...) -> arrayEq(a,b); b
test "#4884: object-destructured splatted parameters", ->
f = ({length}...) -> length
eq f(4, 5, 6), 3
f = ({length: len}...) -> len
eq f(4, 5, 6), 3
f = ({length}..., last) -> [length, last]
arrayEq f(4, 5, 6), [2, 6]
f = ({length: len}..., last) -> [len, last]
arrayEq f(4, 5, 6), [2, 6]
test "@-parameters: automatically assign an argument's value to a property of the context", ->
nonce = {}
((@prop) ->).call context = {}, nonce
eq nonce, context.prop
# Allow splats alongside the special argument
((splat..., @prop) ->).apply context = {}, [0, 0, nonce]
eq nonce, context.prop
# Should not trigger implicit call, e.g. rest ... => rest(...)
((splat ..., @prop) ->).apply context = {}, [0, 0, nonce]
eq nonce, context.prop
# Allow the argument itself to be a splat
((@prop...) ->).call context = {}, 0, nonce, 0
eq nonce, context.prop[1]
# Should not trigger implicit call, e.g. rest ... => rest(...)
((@prop ...) ->).call context = {}, 0, nonce, 0
eq nonce, context.prop[1]
# The argument should not be able to be referenced normally
code = '((@prop) -> prop).call {}'
doesNotThrow -> CoffeeScript.compile code
throws (-> CoffeeScript.run code), ReferenceError
code = '((@prop) -> _at_prop).call {}'
doesNotThrow -> CoffeeScript.compile code
throws (-> CoffeeScript.run code), ReferenceError
test "@-parameters and splats with constructors", ->
a = {}
b = {}
class Klass
constructor: (@first, splat..., @last) ->
obj = new Klass a, 0, 0, b
eq a, obj.first
eq b, obj.last
# Should not trigger implicit call, e.g. rest ... => rest(...)
class Klass
constructor: (@first, splat ..., @last) ->
obj = new Klass a, 0, 0, b
eq a, obj.first
eq b, obj.last
test "destructuring in function definition", ->
(([{a: [b], c}]...) ->
eq 1, b
eq 2, c
) {a: [1], c: 2}
# Should not trigger implicit call, e.g. rest ... => rest(...)
(([{a: [b], c}] ...) ->
eq 1, b
eq 2, c
) {a: [1], c: 2}
context = {}
(([{a: [b, c = 2], @d, e = 4}]...) ->
eq 1, b
eq 2, c
eq @d, 3
eq context.d, 3
eq e, 4
).call context, {a: [1], d: 3}
(({a: aa = 1, b: bb = 2}) ->
eq 5, aa
eq 2, bb
) {a: 5}
ajax = (url, {
async = true,
beforeSend = (->),
cache = true,
method = 'get',
data = {}
}) ->
{url, async, beforeSend, cache, method, data}
fn = ->
deepEqual ajax('/home', beforeSend: fn, method: 'post'), {
url: '/home', async: true, beforeSend: fn, cache: true, method: 'post', data: {}
}
test "#4005: `([a = {}]..., b) ->` weirdness", ->
fn = ([a = {}]..., b) -> [a, b]
deepEqual fn(5), [{}, 5]
# Should not trigger implicit call, e.g. rest ... => rest(...)
fn = ([a = {}] ..., b) -> [a, b]
deepEqual fn(5), [{}, 5]
test "default values", ->
nonceA = {}
nonceB = {}
a = (_,_1,arg=nonceA) -> arg
eq nonceA, a()
eq nonceA, a(0)
eq nonceB, a(0,0,nonceB)
eq nonceA, a(0,0,undefined)
eq null, a(0,0,null) # Per ES2015, `null` doesn’t trigger a parameter default value
eq false , a(0,0,false)
eq nonceB, a(undefined,undefined,nonceB,undefined)
b = (_,arg=nonceA,_1,_2) -> arg
eq nonceA, b()
eq nonceA, b(0)
eq nonceB, b(0,nonceB)
eq nonceA, b(0,undefined)
eq null, b(0,null)
eq false , b(0,false)
eq nonceB, b(undefined,nonceB,undefined)
c = (arg=nonceA,_,_1) -> arg
eq nonceA, c()
eq 0, c(0)
eq nonceB, c(nonceB)
eq nonceA, c(undefined)
eq null, c(null)
eq false , c(false)
eq nonceB, c(nonceB,undefined,undefined)
test "default values with @-parameters", ->
a = {}
b = {}
obj = f: (q = a, @p = b) -> q
eq a, obj.f()
eq b, obj.p
test "default values with splatted arguments", ->
withSplats = (a = 2, b..., c = 3, d = 5) -> a * (b.length + 1) * c * d
eq 30, withSplats()
eq 15, withSplats(1)
eq 5, withSplats(1,1)
eq 1, withSplats(1,1,1)
eq 2, withSplats(1,1,1,1)
# Should not trigger implicit call, e.g. rest ... => rest(...)
withSplats = (a = 2, b ..., c = 3, d = 5) -> a * (b.length + 1) * c * d
eq 30, withSplats()
eq 15, withSplats(1)
eq 5, withSplats(1,1)
eq 1, withSplats(1,1,1)
eq 2, withSplats(1,1,1,1)
test "#156: parameter lists with expansion", ->
expandArguments = (first, ..., lastButOne, last) ->
eq 1, first
eq 4, lastButOne
last
eq 5, expandArguments 1, 2, 3, 4, 5
throws (-> CoffeeScript.compile "(..., a, b...) ->"), null, "prohibit expansion and a splat"
throws (-> CoffeeScript.compile "(...) ->"), null, "prohibit lone expansion"
test "#156: parameter lists with expansion in array destructuring", ->
expandArray = (..., [..., last]) ->
last
eq 3, expandArray 1, 2, 3, [1, 2, 3]
test "#3502: variable definitions and expansion", ->
a = b = 0
f = (a, ..., b) -> [a, b]
arrayEq [1, 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
test "variable definitions and splat", ->
a = b = 0
f = (a, middle..., b) -> [a, middle, b]
arrayEq [1, [2, 3, 4], 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
# Should not trigger implicit call, e.g. rest ... => rest(...)
f = (a, middle ..., b) -> [a, middle, b]
arrayEq [1, [2, 3, 4], 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
test "default values with function calls", ->
doesNotThrow -> CoffeeScript.compile "(x = f()) ->"
test "arguments vs parameters", ->
doesNotThrow -> CoffeeScript.compile "f(x) ->"
f = (g) -> g()
eq 5, f (x) -> 5
test "reserved keyword as parameters", ->
f = (_case, @case) -> [_case, @case]
[a, b] = f(1, 2)
eq 1, a
eq 2, b
f = (@case, _case...) -> [@case, _case...]
[a, b, c] = f(1, 2, 3)
eq 1, a
eq 2, b
eq 3, c
test "reserved keyword at-splat", ->
f = (@case...) -> @case
[a, b] = f(1, 2)
eq 1, a
eq 2, b
# Should not trigger implicit call, e.g. rest ... => rest(...)
f = (@case ...) -> @case
[a, b] = f(1, 2)
eq 1, a
eq 2, b
test "#1574: Destructuring and a parameter named _arg", ->
f = ({a, b}, _arg, _arg1) -> [a, b, _arg, _arg1]
arrayEq [1, 2, 3, 4], f a: 1, b: 2, 3, 4
test "#1844: bound functions in nested comprehensions causing empty var statements", ->
a = ((=>) for a in [0] for b in [0])
eq 1, a.length
test "#1859: inline function bodies shouldn't modify prior postfix ifs", ->
list = [1, 2, 3]
ok true if list.some (x) -> x is 2
test "#2258: allow whitespace-style parameter lists in function definitions", ->
func = (
a, b, c
) -> c
eq func(1, 2, 3), 3
func = (
a
b
c
) -> b
eq func(1, 2, 3), 2
test "#2621: fancy destructuring in parameter lists", ->
func = ({ prop1: { key1 }, prop2: { key2, key3: [a, b, c] } }) ->
eq(key2, 'key2')
eq(a, 'a')
func({prop1: {key1: 'key1'}, prop2: {key2: 'key2', key3: ['a', 'b', 'c']}})
test "#1435 Indented property access", ->
rec = -> rec: rec
eq 1, do ->
rec()
.rec ->
rec()
.rec ->
rec.rec()
.rec()
1
test "#1038 Optimize trailing return statements", ->
compile = (code) -> CoffeeScript.compile(code, bare: yes).trim().replace(/\s+/g, " ")
eq "(function() {});", compile("->")
eq "(function() {});", compile("-> return")
eq "(function() { return void 0; });", compile("-> undefined")
eq "(function() { return void 0; });", compile("-> return undefined")
eq "(function() { foo(); });", compile("""
->
foo()
return
""")
test "#4406 Destructured parameter default evaluation order with incrementing variable", ->
i = 0
f = ({ a = ++i }, b = ++i) -> [a, b]
arrayEq f({}), [1, 2]
test "#4406 Destructured parameter default evaluation order with generator function", ->
current = 0
next = -> ++current
foo = ({ a = next() }, b = next()) -> [ a, b ]
arrayEq foo({}), [1, 2]
test "Destructured parameter with default value, that itself has a default value", ->
# Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
draw = ({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) -> "#{size}-#{coords.x}-#{coords.y}-#{radius}"
output = draw
coords:
x: 18
y: 30
radius: 30
eq output, 'big-18-30-30'
test "#4566: destructuring with nested default values", ->
f = ({a: {b = 1}}) ->
b
eq 2, f a: b: 2
test "#1043: comma after function glyph", ->
x = (a=->, b=2) ->
a()
eq x(), undefined
f = (a) -> a()
g = f ->, 2
eq g, undefined
h = f(=>, 2)
eq h, undefined
test "#3845/#3446: chain after function glyph", ->
angular = module: -> controller: -> controller: ->
eq undefined,
angular.module 'foo'
.controller 'EmailLoginCtrl', ->
.controller 'EmailSignupCtrl', ->
beforeEach = (f) -> f()
getPromise = -> then: -> catch: ->
eq undefined,
beforeEach ->
getPromise()
.then (@result) =>
.catch (@error) =>
doThing = -> then: -> catch: (f) -> f()
handleError = -> 3
eq 3,
doThing()
.then (@result) =>
.catch handleError
test "#4413: expressions in function parameters that create generated variables have those variables declared correctly", ->
'use strict'
# We’re in strict mode because we want an error to be thrown if the generated
# variable (`ref`) is assigned before being declared.
foo = -> null
bar = -> 33
f = (a = foo() ? bar()) -> a
g = (a = foo() ? bar()) -> a + 1
eq f(), 33
eq g(), 34
test "#4657: destructured array param declarations", ->
a = 1
b = 2
f = ([a..., b]) ->
f [3, 4, 5]
eq a, 1
eq b, 2
test "#4657: destructured array parameters", ->
f = ([a..., b]) -> {a, b}
result = f [1, 2, 3, 4]
arrayEq result.a, [1, 2, 3]
eq result.b, 4
| 155063 | # Function Literals
# -----------------
# TODO: add indexing and method invocation tests: (->)[0], (->).call()
# * Function Definition
# * Bound Function Definition
# * Parameter List Features
# * Splat Parameters
# * Context (@) Parameters
# * Parameter Destructuring
# * Default Parameters
# Function Definition
x = 1
y = {}
y.x = -> 3
ok x is 1
ok typeof(y.x) is 'function'
ok y.x instanceof Function
ok y.x() is 3
# The empty function should not cause a syntax error.
->
() ->
# Multiple nested function declarations mixed with implicit calls should not
# cause a syntax error.
(one) -> (two) -> three four, (five) -> six seven, eight, (nine) ->
# with multiple single-line functions on the same line.
func = (x) -> (x) -> (x) -> x
ok func(1)(2)(3) is 3
# Make incorrect indentation safe.
func = ->
obj = {
key: 10
}
obj.key - 5
eq func(), 5
# Ensure that functions with the same name don't clash with helper functions.
del = -> 5
ok del() is 5
# Bound Function Definition
obj =
bound: ->
(=> this)()
unbound: ->
(-> this)()
nested: ->
(=>
(=>
(=> this)()
)()
)()
eq obj, obj.bound()
ok obj isnt obj.unbound()
eq obj, obj.nested()
test "even more fancy bound functions", ->
obj =
one: ->
do =>
return this.two()
two: ->
do =>
do =>
do =>
return this.three
three: 3
eq obj.one(), 3
test "arguments in bound functions inherit from parent function", ->
# The `arguments` object in an ES arrow function refers to the `arguments`
# of the parent scope, just like `this`. In the CoffeeScript 1.x
# implementation of `=>`, the `arguments` object referred to the arguments
# of the arrow function; but per the ES2015 spec, `arguments` should refer
# to the parent.
arrayEq ((a...) -> a)([1, 2, 3]), ((a...) => a)([1, 2, 3])
parent = (a, b, c) ->
(bound = =>
[arguments[0], arguments[1], arguments[2]]
)()
arrayEq [1, 2, 3], parent(1, 2, 3)
test "self-referencing functions", ->
changeMe = ->
changeMe = 2
changeMe()
eq changeMe, 2
# Parameter List Features
test "splats", ->
arrayEq [0, 1, 2], (((splat...) -> splat) 0, 1, 2)
arrayEq [2, 3], (((_, _1, splat...) -> splat) 0, 1, 2, 3)
arrayEq [0, 1], (((splat..., _, _1) -> splat) 0, 1, 2, 3)
arrayEq [2], (((_, _1, splat..., _2) -> splat) 0, 1, 2, 3)
# Should not trigger implicit call, e.g. rest ... => rest(...)
arrayEq [0, 1, 2], (((splat ...) -> splat) 0, 1, 2)
arrayEq [2, 3], (((_, _1, splat ...) -> splat) 0, 1, 2, 3)
arrayEq [0, 1], (((splat ..., _, _1) -> splat) 0, 1, 2, 3)
arrayEq [2], (((_, _1, splat ..., _2) -> splat) 0, 1, 2, 3)
test "destructured splatted parameters", ->
arr = [0,1,2]
splatArray = ([a...]) -> a
splatArrayRest = ([a...],b...) -> arrayEq(a,b); b
arrayEq splatArray(arr), arr
arrayEq splatArrayRest(arr,0,1,2), arr
# Should not trigger implicit call, e.g. rest ... => rest(...)
splatArray = ([a ...]) -> a
splatArrayRest = ([a ...],b ...) -> arrayEq(a,b); b
test "#4884: object-destructured splatted parameters", ->
f = ({length}...) -> length
eq f(4, 5, 6), 3
f = ({length: len}...) -> len
eq f(4, 5, 6), 3
f = ({length}..., last) -> [length, last]
arrayEq f(4, 5, 6), [2, 6]
f = ({length: len}..., last) -> [len, last]
arrayEq f(4, 5, 6), [2, 6]
test "@-parameters: automatically assign an argument's value to a property of the context", ->
nonce = {}
((@prop) ->).call context = {}, nonce
eq nonce, context.prop
# Allow splats alongside the special argument
((splat..., @prop) ->).apply context = {}, [0, 0, nonce]
eq nonce, context.prop
# Should not trigger implicit call, e.g. rest ... => rest(...)
((splat ..., @prop) ->).apply context = {}, [0, 0, nonce]
eq nonce, context.prop
# Allow the argument itself to be a splat
((@prop...) ->).call context = {}, 0, nonce, 0
eq nonce, context.prop[1]
# Should not trigger implicit call, e.g. rest ... => rest(...)
((@prop ...) ->).call context = {}, 0, nonce, 0
eq nonce, context.prop[1]
# The argument should not be able to be referenced normally
code = '((@prop) -> prop).call {}'
doesNotThrow -> CoffeeScript.compile code
throws (-> CoffeeScript.run code), ReferenceError
code = '((@prop) -> _at_prop).call {}'
doesNotThrow -> CoffeeScript.compile code
throws (-> CoffeeScript.run code), ReferenceError
test "@-parameters and splats with constructors", ->
a = {}
b = {}
class Klass
constructor: (@first, splat..., @last) ->
obj = new Klass a, 0, 0, b
eq a, obj.first
eq b, obj.last
# Should not trigger implicit call, e.g. rest ... => rest(...)
class Klass
constructor: (@first, splat ..., @last) ->
obj = new Klass a, 0, 0, b
eq a, obj.first
eq b, obj.last
test "destructuring in function definition", ->
(([{a: [b], c}]...) ->
eq 1, b
eq 2, c
) {a: [1], c: 2}
# Should not trigger implicit call, e.g. rest ... => rest(...)
(([{a: [b], c}] ...) ->
eq 1, b
eq 2, c
) {a: [1], c: 2}
context = {}
(([{a: [b, c = 2], @d, e = 4}]...) ->
eq 1, b
eq 2, c
eq @d, 3
eq context.d, 3
eq e, 4
).call context, {a: [1], d: 3}
(({a: aa = 1, b: bb = 2}) ->
eq 5, aa
eq 2, bb
) {a: 5}
ajax = (url, {
async = true,
beforeSend = (->),
cache = true,
method = 'get',
data = {}
}) ->
{url, async, beforeSend, cache, method, data}
fn = ->
deepEqual ajax('/home', beforeSend: fn, method: 'post'), {
url: '/home', async: true, beforeSend: fn, cache: true, method: 'post', data: {}
}
test "#4005: `([a = {}]..., b) ->` weirdness", ->
fn = ([a = {}]..., b) -> [a, b]
deepEqual fn(5), [{}, 5]
# Should not trigger implicit call, e.g. rest ... => rest(...)
fn = ([a = {}] ..., b) -> [a, b]
deepEqual fn(5), [{}, 5]
test "default values", ->
nonceA = {}
nonceB = {}
a = (_,_1,arg=nonceA) -> arg
eq nonceA, a()
eq nonceA, a(0)
eq nonceB, a(0,0,nonceB)
eq nonceA, a(0,0,undefined)
eq null, a(0,0,null) # Per ES2015, `null` doesn’t trigger a parameter default value
eq false , a(0,0,false)
eq nonceB, a(undefined,undefined,nonceB,undefined)
b = (_,arg=nonceA,_1,_2) -> arg
eq nonceA, b()
eq nonceA, b(0)
eq nonceB, b(0,nonceB)
eq nonceA, b(0,undefined)
eq null, b(0,null)
eq false , b(0,false)
eq nonceB, b(undefined,nonceB,undefined)
c = (arg=nonceA,_,_1) -> arg
eq nonceA, c()
eq 0, c(0)
eq nonceB, c(nonceB)
eq nonceA, c(undefined)
eq null, c(null)
eq false , c(false)
eq nonceB, c(nonceB,undefined,undefined)
test "default values with @-parameters", ->
a = {}
b = {}
obj = f: (q = a, @p = b) -> q
eq a, obj.f()
eq b, obj.p
test "default values with splatted arguments", ->
withSplats = (a = 2, b..., c = 3, d = 5) -> a * (b.length + 1) * c * d
eq 30, withSplats()
eq 15, withSplats(1)
eq 5, withSplats(1,1)
eq 1, withSplats(1,1,1)
eq 2, withSplats(1,1,1,1)
# Should not trigger implicit call, e.g. rest ... => rest(...)
withSplats = (a = 2, b ..., c = 3, d = 5) -> a * (b.length + 1) * c * d
eq 30, withSplats()
eq 15, withSplats(1)
eq 5, withSplats(1,1)
eq 1, withSplats(1,1,1)
eq 2, withSplats(1,1,1,1)
test "#156: parameter lists with expansion", ->
expandArguments = (first, ..., lastButOne, last) ->
eq 1, first
eq 4, lastButOne
last
eq 5, expandArguments 1, 2, 3, 4, 5
throws (-> CoffeeScript.compile "(..., a, b...) ->"), null, "prohibit expansion and a splat"
throws (-> CoffeeScript.compile "(...) ->"), null, "prohibit lone expansion"
test "#156: parameter lists with expansion in array destructuring", ->
expandArray = (..., [..., last]) ->
last
eq 3, expandArray 1, 2, 3, [1, 2, 3]
test "#3502: variable definitions and expansion", ->
a = b = 0
f = (a, ..., b) -> [a, b]
arrayEq [1, 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
test "variable definitions and splat", ->
a = b = 0
f = (a, middle..., b) -> [a, middle, b]
arrayEq [1, [2, 3, 4], 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
# Should not trigger implicit call, e.g. rest ... => rest(...)
f = (a, middle ..., b) -> [a, middle, b]
arrayEq [1, [2, 3, 4], 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
test "default values with function calls", ->
doesNotThrow -> CoffeeScript.compile "(x = f()) ->"
test "arguments vs parameters", ->
doesNotThrow -> CoffeeScript.compile "f(x) ->"
f = (g) -> g()
eq 5, f (x) -> 5
test "reserved keyword as parameters", ->
f = (_case, @case) -> [_case, @case]
[a, b] = f(1, 2)
eq 1, a
eq 2, b
f = (@case, _case...) -> [@case, _case...]
[a, b, c] = f(1, 2, 3)
eq 1, a
eq 2, b
eq 3, c
test "reserved keyword at-splat", ->
f = (@case...) -> @case
[a, b] = f(1, 2)
eq 1, a
eq 2, b
# Should not trigger implicit call, e.g. rest ... => rest(...)
f = (@case ...) -> @case
[a, b] = f(1, 2)
eq 1, a
eq 2, b
test "#1574: Destructuring and a parameter named _arg", ->
f = ({a, b}, _arg, _arg1) -> [a, b, _arg, _arg1]
arrayEq [1, 2, 3, 4], f a: 1, b: 2, 3, 4
test "#1844: bound functions in nested comprehensions causing empty var statements", ->
a = ((=>) for a in [0] for b in [0])
eq 1, a.length
test "#1859: inline function bodies shouldn't modify prior postfix ifs", ->
list = [1, 2, 3]
ok true if list.some (x) -> x is 2
test "#2258: allow whitespace-style parameter lists in function definitions", ->
func = (
a, b, c
) -> c
eq func(1, 2, 3), 3
func = (
a
b
c
) -> b
eq func(1, 2, 3), 2
test "#2621: fancy destructuring in parameter lists", ->
func = ({ prop1: { key1 }, prop2: { key2, key3: [a, b, c] } }) ->
eq(key2, 'key2')
eq(a, 'a')
func({prop1: {key1: 'key1'}, prop2: {key2: 'key2', key3: ['<KEY>', '<KEY>', '<KEY>']}})
test "#1435 Indented property access", ->
rec = -> rec: rec
eq 1, do ->
rec()
.rec ->
rec()
.rec ->
rec.rec()
.rec()
1
test "#1038 Optimize trailing return statements", ->
compile = (code) -> CoffeeScript.compile(code, bare: yes).trim().replace(/\s+/g, " ")
eq "(function() {});", compile("->")
eq "(function() {});", compile("-> return")
eq "(function() { return void 0; });", compile("-> undefined")
eq "(function() { return void 0; });", compile("-> return undefined")
eq "(function() { foo(); });", compile("""
->
foo()
return
""")
test "#4406 Destructured parameter default evaluation order with incrementing variable", ->
i = 0
f = ({ a = ++i }, b = ++i) -> [a, b]
arrayEq f({}), [1, 2]
test "#4406 Destructured parameter default evaluation order with generator function", ->
current = 0
next = -> ++current
foo = ({ a = next() }, b = next()) -> [ a, b ]
arrayEq foo({}), [1, 2]
test "Destructured parameter with default value, that itself has a default value", ->
# Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
draw = ({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) -> "#{size}-#{coords.x}-#{coords.y}-#{radius}"
output = draw
coords:
x: 18
y: 30
radius: 30
eq output, 'big-18-30-30'
test "#4566: destructuring with nested default values", ->
f = ({a: {b = 1}}) ->
b
eq 2, f a: b: 2
test "#1043: comma after function glyph", ->
x = (a=->, b=2) ->
a()
eq x(), undefined
f = (a) -> a()
g = f ->, 2
eq g, undefined
h = f(=>, 2)
eq h, undefined
test "#3845/#3446: chain after function glyph", ->
angular = module: -> controller: -> controller: ->
eq undefined,
angular.module 'foo'
.controller 'EmailLoginCtrl', ->
.controller 'EmailSignupCtrl', ->
beforeEach = (f) -> f()
getPromise = -> then: -> catch: ->
eq undefined,
beforeEach ->
getPromise()
.then (@result) =>
.catch (@error) =>
doThing = -> then: -> catch: (f) -> f()
handleError = -> 3
eq 3,
doThing()
.then (@result) =>
.catch handleError
test "#4413: expressions in function parameters that create generated variables have those variables declared correctly", ->
'use strict'
# We’re in strict mode because we want an error to be thrown if the generated
# variable (`ref`) is assigned before being declared.
foo = -> null
bar = -> 33
f = (a = foo() ? bar()) -> a
g = (a = foo() ? bar()) -> a + 1
eq f(), 33
eq g(), 34
test "#4657: destructured array param declarations", ->
a = 1
b = 2
f = ([a..., b]) ->
f [3, 4, 5]
eq a, 1
eq b, 2
test "#4657: destructured array parameters", ->
f = ([a..., b]) -> {a, b}
result = f [1, 2, 3, 4]
arrayEq result.a, [1, 2, 3]
eq result.b, 4
| true | # Function Literals
# -----------------
# TODO: add indexing and method invocation tests: (->)[0], (->).call()
# * Function Definition
# * Bound Function Definition
# * Parameter List Features
# * Splat Parameters
# * Context (@) Parameters
# * Parameter Destructuring
# * Default Parameters
# Function Definition
x = 1
y = {}
y.x = -> 3
ok x is 1
ok typeof(y.x) is 'function'
ok y.x instanceof Function
ok y.x() is 3
# The empty function should not cause a syntax error.
->
() ->
# Multiple nested function declarations mixed with implicit calls should not
# cause a syntax error.
(one) -> (two) -> three four, (five) -> six seven, eight, (nine) ->
# with multiple single-line functions on the same line.
func = (x) -> (x) -> (x) -> x
ok func(1)(2)(3) is 3
# Make incorrect indentation safe.
func = ->
obj = {
key: 10
}
obj.key - 5
eq func(), 5
# Ensure that functions with the same name don't clash with helper functions.
del = -> 5
ok del() is 5
# Bound Function Definition
obj =
bound: ->
(=> this)()
unbound: ->
(-> this)()
nested: ->
(=>
(=>
(=> this)()
)()
)()
eq obj, obj.bound()
ok obj isnt obj.unbound()
eq obj, obj.nested()
test "even more fancy bound functions", ->
obj =
one: ->
do =>
return this.two()
two: ->
do =>
do =>
do =>
return this.three
three: 3
eq obj.one(), 3
test "arguments in bound functions inherit from parent function", ->
# The `arguments` object in an ES arrow function refers to the `arguments`
# of the parent scope, just like `this`. In the CoffeeScript 1.x
# implementation of `=>`, the `arguments` object referred to the arguments
# of the arrow function; but per the ES2015 spec, `arguments` should refer
# to the parent.
arrayEq ((a...) -> a)([1, 2, 3]), ((a...) => a)([1, 2, 3])
parent = (a, b, c) ->
(bound = =>
[arguments[0], arguments[1], arguments[2]]
)()
arrayEq [1, 2, 3], parent(1, 2, 3)
test "self-referencing functions", ->
changeMe = ->
changeMe = 2
changeMe()
eq changeMe, 2
# Parameter List Features
test "splats", ->
arrayEq [0, 1, 2], (((splat...) -> splat) 0, 1, 2)
arrayEq [2, 3], (((_, _1, splat...) -> splat) 0, 1, 2, 3)
arrayEq [0, 1], (((splat..., _, _1) -> splat) 0, 1, 2, 3)
arrayEq [2], (((_, _1, splat..., _2) -> splat) 0, 1, 2, 3)
# Should not trigger implicit call, e.g. rest ... => rest(...)
arrayEq [0, 1, 2], (((splat ...) -> splat) 0, 1, 2)
arrayEq [2, 3], (((_, _1, splat ...) -> splat) 0, 1, 2, 3)
arrayEq [0, 1], (((splat ..., _, _1) -> splat) 0, 1, 2, 3)
arrayEq [2], (((_, _1, splat ..., _2) -> splat) 0, 1, 2, 3)
test "destructured splatted parameters", ->
arr = [0,1,2]
splatArray = ([a...]) -> a
splatArrayRest = ([a...],b...) -> arrayEq(a,b); b
arrayEq splatArray(arr), arr
arrayEq splatArrayRest(arr,0,1,2), arr
# Should not trigger implicit call, e.g. rest ... => rest(...)
splatArray = ([a ...]) -> a
splatArrayRest = ([a ...],b ...) -> arrayEq(a,b); b
test "#4884: object-destructured splatted parameters", ->
f = ({length}...) -> length
eq f(4, 5, 6), 3
f = ({length: len}...) -> len
eq f(4, 5, 6), 3
f = ({length}..., last) -> [length, last]
arrayEq f(4, 5, 6), [2, 6]
f = ({length: len}..., last) -> [len, last]
arrayEq f(4, 5, 6), [2, 6]
test "@-parameters: automatically assign an argument's value to a property of the context", ->
nonce = {}
((@prop) ->).call context = {}, nonce
eq nonce, context.prop
# Allow splats alongside the special argument
((splat..., @prop) ->).apply context = {}, [0, 0, nonce]
eq nonce, context.prop
# Should not trigger implicit call, e.g. rest ... => rest(...)
((splat ..., @prop) ->).apply context = {}, [0, 0, nonce]
eq nonce, context.prop
# Allow the argument itself to be a splat
((@prop...) ->).call context = {}, 0, nonce, 0
eq nonce, context.prop[1]
# Should not trigger implicit call, e.g. rest ... => rest(...)
((@prop ...) ->).call context = {}, 0, nonce, 0
eq nonce, context.prop[1]
# The argument should not be able to be referenced normally
code = '((@prop) -> prop).call {}'
doesNotThrow -> CoffeeScript.compile code
throws (-> CoffeeScript.run code), ReferenceError
code = '((@prop) -> _at_prop).call {}'
doesNotThrow -> CoffeeScript.compile code
throws (-> CoffeeScript.run code), ReferenceError
test "@-parameters and splats with constructors", ->
a = {}
b = {}
class Klass
constructor: (@first, splat..., @last) ->
obj = new Klass a, 0, 0, b
eq a, obj.first
eq b, obj.last
# Should not trigger implicit call, e.g. rest ... => rest(...)
class Klass
constructor: (@first, splat ..., @last) ->
obj = new Klass a, 0, 0, b
eq a, obj.first
eq b, obj.last
test "destructuring in function definition", ->
(([{a: [b], c}]...) ->
eq 1, b
eq 2, c
) {a: [1], c: 2}
# Should not trigger implicit call, e.g. rest ... => rest(...)
(([{a: [b], c}] ...) ->
eq 1, b
eq 2, c
) {a: [1], c: 2}
context = {}
(([{a: [b, c = 2], @d, e = 4}]...) ->
eq 1, b
eq 2, c
eq @d, 3
eq context.d, 3
eq e, 4
).call context, {a: [1], d: 3}
(({a: aa = 1, b: bb = 2}) ->
eq 5, aa
eq 2, bb
) {a: 5}
ajax = (url, {
async = true,
beforeSend = (->),
cache = true,
method = 'get',
data = {}
}) ->
{url, async, beforeSend, cache, method, data}
fn = ->
deepEqual ajax('/home', beforeSend: fn, method: 'post'), {
url: '/home', async: true, beforeSend: fn, cache: true, method: 'post', data: {}
}
test "#4005: `([a = {}]..., b) ->` weirdness", ->
fn = ([a = {}]..., b) -> [a, b]
deepEqual fn(5), [{}, 5]
# Should not trigger implicit call, e.g. rest ... => rest(...)
fn = ([a = {}] ..., b) -> [a, b]
deepEqual fn(5), [{}, 5]
test "default values", ->
nonceA = {}
nonceB = {}
a = (_,_1,arg=nonceA) -> arg
eq nonceA, a()
eq nonceA, a(0)
eq nonceB, a(0,0,nonceB)
eq nonceA, a(0,0,undefined)
eq null, a(0,0,null) # Per ES2015, `null` doesn’t trigger a parameter default value
eq false , a(0,0,false)
eq nonceB, a(undefined,undefined,nonceB,undefined)
b = (_,arg=nonceA,_1,_2) -> arg
eq nonceA, b()
eq nonceA, b(0)
eq nonceB, b(0,nonceB)
eq nonceA, b(0,undefined)
eq null, b(0,null)
eq false , b(0,false)
eq nonceB, b(undefined,nonceB,undefined)
c = (arg=nonceA,_,_1) -> arg
eq nonceA, c()
eq 0, c(0)
eq nonceB, c(nonceB)
eq nonceA, c(undefined)
eq null, c(null)
eq false , c(false)
eq nonceB, c(nonceB,undefined,undefined)
test "default values with @-parameters", ->
a = {}
b = {}
obj = f: (q = a, @p = b) -> q
eq a, obj.f()
eq b, obj.p
test "default values with splatted arguments", ->
withSplats = (a = 2, b..., c = 3, d = 5) -> a * (b.length + 1) * c * d
eq 30, withSplats()
eq 15, withSplats(1)
eq 5, withSplats(1,1)
eq 1, withSplats(1,1,1)
eq 2, withSplats(1,1,1,1)
# Should not trigger implicit call, e.g. rest ... => rest(...)
withSplats = (a = 2, b ..., c = 3, d = 5) -> a * (b.length + 1) * c * d
eq 30, withSplats()
eq 15, withSplats(1)
eq 5, withSplats(1,1)
eq 1, withSplats(1,1,1)
eq 2, withSplats(1,1,1,1)
test "#156: parameter lists with expansion", ->
expandArguments = (first, ..., lastButOne, last) ->
eq 1, first
eq 4, lastButOne
last
eq 5, expandArguments 1, 2, 3, 4, 5
throws (-> CoffeeScript.compile "(..., a, b...) ->"), null, "prohibit expansion and a splat"
throws (-> CoffeeScript.compile "(...) ->"), null, "prohibit lone expansion"
test "#156: parameter lists with expansion in array destructuring", ->
expandArray = (..., [..., last]) ->
last
eq 3, expandArray 1, 2, 3, [1, 2, 3]
test "#3502: variable definitions and expansion", ->
a = b = 0
f = (a, ..., b) -> [a, b]
arrayEq [1, 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
test "variable definitions and splat", ->
a = b = 0
f = (a, middle..., b) -> [a, middle, b]
arrayEq [1, [2, 3, 4], 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
# Should not trigger implicit call, e.g. rest ... => rest(...)
f = (a, middle ..., b) -> [a, middle, b]
arrayEq [1, [2, 3, 4], 5], f 1, 2, 3, 4, 5
eq 0, a
eq 0, b
test "default values with function calls", ->
doesNotThrow -> CoffeeScript.compile "(x = f()) ->"
test "arguments vs parameters", ->
doesNotThrow -> CoffeeScript.compile "f(x) ->"
f = (g) -> g()
eq 5, f (x) -> 5
test "reserved keyword as parameters", ->
f = (_case, @case) -> [_case, @case]
[a, b] = f(1, 2)
eq 1, a
eq 2, b
f = (@case, _case...) -> [@case, _case...]
[a, b, c] = f(1, 2, 3)
eq 1, a
eq 2, b
eq 3, c
test "reserved keyword at-splat", ->
f = (@case...) -> @case
[a, b] = f(1, 2)
eq 1, a
eq 2, b
# Should not trigger implicit call, e.g. rest ... => rest(...)
f = (@case ...) -> @case
[a, b] = f(1, 2)
eq 1, a
eq 2, b
test "#1574: Destructuring and a parameter named _arg", ->
f = ({a, b}, _arg, _arg1) -> [a, b, _arg, _arg1]
arrayEq [1, 2, 3, 4], f a: 1, b: 2, 3, 4
test "#1844: bound functions in nested comprehensions causing empty var statements", ->
a = ((=>) for a in [0] for b in [0])
eq 1, a.length
test "#1859: inline function bodies shouldn't modify prior postfix ifs", ->
list = [1, 2, 3]
ok true if list.some (x) -> x is 2
test "#2258: allow whitespace-style parameter lists in function definitions", ->
func = (
a, b, c
) -> c
eq func(1, 2, 3), 3
func = (
a
b
c
) -> b
eq func(1, 2, 3), 2
test "#2621: fancy destructuring in parameter lists", ->
func = ({ prop1: { key1 }, prop2: { key2, key3: [a, b, c] } }) ->
eq(key2, 'key2')
eq(a, 'a')
func({prop1: {key1: 'key1'}, prop2: {key2: 'key2', key3: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']}})
test "#1435 Indented property access", ->
rec = -> rec: rec
eq 1, do ->
rec()
.rec ->
rec()
.rec ->
rec.rec()
.rec()
1
test "#1038 Optimize trailing return statements", ->
compile = (code) -> CoffeeScript.compile(code, bare: yes).trim().replace(/\s+/g, " ")
eq "(function() {});", compile("->")
eq "(function() {});", compile("-> return")
eq "(function() { return void 0; });", compile("-> undefined")
eq "(function() { return void 0; });", compile("-> return undefined")
eq "(function() { foo(); });", compile("""
->
foo()
return
""")
test "#4406 Destructured parameter default evaluation order with incrementing variable", ->
i = 0
f = ({ a = ++i }, b = ++i) -> [a, b]
arrayEq f({}), [1, 2]
test "#4406 Destructured parameter default evaluation order with generator function", ->
current = 0
next = -> ++current
foo = ({ a = next() }, b = next()) -> [ a, b ]
arrayEq foo({}), [1, 2]
test "Destructured parameter with default value, that itself has a default value", ->
# Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
draw = ({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) -> "#{size}-#{coords.x}-#{coords.y}-#{radius}"
output = draw
coords:
x: 18
y: 30
radius: 30
eq output, 'big-18-30-30'
test "#4566: destructuring with nested default values", ->
f = ({a: {b = 1}}) ->
b
eq 2, f a: b: 2
test "#1043: comma after function glyph", ->
x = (a=->, b=2) ->
a()
eq x(), undefined
f = (a) -> a()
g = f ->, 2
eq g, undefined
h = f(=>, 2)
eq h, undefined
test "#3845/#3446: chain after function glyph", ->
angular = module: -> controller: -> controller: ->
eq undefined,
angular.module 'foo'
.controller 'EmailLoginCtrl', ->
.controller 'EmailSignupCtrl', ->
beforeEach = (f) -> f()
getPromise = -> then: -> catch: ->
eq undefined,
beforeEach ->
getPromise()
.then (@result) =>
.catch (@error) =>
doThing = -> then: -> catch: (f) -> f()
handleError = -> 3
eq 3,
doThing()
.then (@result) =>
.catch handleError
test "#4413: expressions in function parameters that create generated variables have those variables declared correctly", ->
'use strict'
# We’re in strict mode because we want an error to be thrown if the generated
# variable (`ref`) is assigned before being declared.
foo = -> null
bar = -> 33
f = (a = foo() ? bar()) -> a
g = (a = foo() ? bar()) -> a + 1
eq f(), 33
eq g(), 34
test "#4657: destructured array param declarations", ->
a = 1
b = 2
f = ([a..., b]) ->
f [3, 4, 5]
eq a, 1
eq b, 2
test "#4657: destructured array parameters", ->
f = ([a..., b]) -> {a, b}
result = f [1, 2, 3, 4]
arrayEq result.a, [1, 2, 3]
eq result.b, 4
|
[
{
"context": "obal_msg = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmI0EWcknrwEEAK2X5lKA76pf6i5D1aVcApUAH6NnZ4NkFeSxKT92soiSWkFn+I/G\nVKJfTvx2dzxOAB4rvyFjUzjgAwhK3FblCnfXwgPAh6/vukF/YBwynCVyNxOVAVHY\ngCkw/+7zIM24RUxzI3V9wzJ6i/SpfNnWKkKqJXIt4Xzv3Rs/UXk5DMY5ABEBAAG0\nI01heCBUZXN0IDc3NyA8dGhlbWF4Kzc3N0BnbWFpbC5... | test/files/strict.iced | AngelKey/Angelkey.pgputils | 20 | {decode,clearsign_header,Parser} = require('../../lib/main').armor
{katch} = require '../../lib/util'
decode_strict = (data) -> katch () -> (new Parser data, { strict: true }).parse()
global_msg = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mI0EWcknrwEEAK2X5lKA76pf6i5D1aVcApUAH6NnZ4NkFeSxKT92soiSWkFn+I/G
VKJfTvx2dzxOAB4rvyFjUzjgAwhK3FblCnfXwgPAh6/vukF/YBwynCVyNxOVAVHY
gCkw/+7zIM24RUxzI3V9wzJ6i/SpfNnWKkKqJXIt4Xzv3Rs/UXk5DMY5ABEBAAG0
I01heCBUZXN0IDc3NyA8dGhlbWF4Kzc3N0BnbWFpbC5jb20+iLgEEwECACIFAlnJ
J68CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEM5jclcHa4v8ssQD/RJA
JTrfydAkLzffGgZyKafs/aTraVDNtDv1sF+5iBtZvOB0FFjzivl3BGlplEqnPquB
bg8/OQuxFLYM/f8+WgP5MDqBce8s6h5kGZPj73zP4GQLZWojS5/H3J1sDBmNTSnd
ByELhvVxJmJiHdz2jMb74+thB/ZK4xf+zAkRF4WZuI0EWcknrwEEALk0Bsp/xJ+4
75hswySLZmvNh79CyIC0K1gzXiEPDwqGy6xT1PbXLJ5HcXna4HJdNAgXf1T/n+zR
19xJMAB6NSv2zigRaYAyy4It2p2cRPHseWWTcP7lMUpwqtQsnqNKJ14RuAaMOQtG
xSaQMgMGZx6lxFWNaK40SxSnqFRtfRs9ABEBAAGInwQYAQIACQUCWcknrwIbDAAK
CRDOY3JXB2uL/PX/A/9HvpLPVDrEMr9+vzmS8Ez0br2kgeoPh7yOAlEotS7OBNWU
UzzykQlAfLl74336wrkSZfa2GnBBJQHvlnLosnmbGCzsd3KMkuJv90hxxt1rqjN6
3GFiwBVdsSuyEb3uQJ/ytAyVozwwxjMQZ+gJTYfK8syPdf2T1W6cv7lfHp8E8g==
=sJQD
-----END PGP PUBLIC KEY BLOCK-----"""
exports.test_bundle_no_newlines = (T, cb) ->
msg = global_msg
# Remove newlines from the base64 part
k = msg.split '\n'
mangled_key = k[0..1].join('\n') + '\n' + k[2..-2].join('') + '\n' + k[-1..].join('\n')
[err, decoded] = decode_strict mangled_key
T.assert err?, 'mangled key should not decode under strict mode'
[err, decoded] = decode mangled_key
T.assert not err?, 'mangled key should decode under normal mode'
# Another case is where newlines are replaced with spaces, only
# keeping last newline before crc line.
k = msg.split '\n'
mangled_key = k[0..1].join('\n') + '\n' + k[2..-3].join(' ') + '\n' + k[-2..].join('\n')
[err, decoded] = decode_strict mangled_key
T.assert err?, 'mangled key 2 should not decode under strict mode'
[err, decoded] = decode mangled_key
T.assert not err?, 'mangled key 2 should decode under normal mode'
cb null
exports.clearsign_long_lines = (T, cb) ->
# A really long line in clearsign section should not trip the
# line limit in parser.
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Version: xf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKhxf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKhThisIsARealProgramISwear
Regardless of where you run it, a heavy math operation can be written with single-thread concurrency in mind. You just have to (1) do work in batches, (2) defer to the event loop periodically via setTimeout or process.nextTick, and (3) call back with an answer, instead of returning one.
-----BEGIN PGP SIGNATURE-----
iQEzBAEBCAAdFiEEoFFhUQ7mlmAboOx7P9U7SHFSjO8FAlnXtT8ACgkQP9U7SHFS
jO+NJAf+M7+hbUDVJ/T+iNyNzh3s0o4sK1Glk21bWlYN+cBOPLoTg8zeNDtz28zE
HZ69ln6WsirXfR1FuytLVjAsrW9fjGSgYOaVXGNNToi/UMZWqw60r4BV8MTrou9U
KWWAdjXAI7/2xwsX7MlEN4q4uzmetQ5kAeRzbBtKfPL115NsTh1fSPm0rN7OpZNE
F2YURWpHVJkcqL/49RWDFGHdmoghO5NNVpxKfGd0X1JXIRbjTIU5DDZ9dBe54/5X
PfAkUucuvxMEB6vXD58/M1vXp0bKCrEz7sJy0T1AHAvnOhJr5ET9xqzSckNnVn8I
PTfgSSzEioqv3qaunjwm0ZjRtPabMg==
=9ssu
-----END PGP SIGNATURE-----
"""
# Both should decode - strict mode should not apply for clearsign section or header section.
[err, decoded] = decode_strict message
T.assert not err?, "clearsign armor should decode under strict mode"
[err, decoded] = decode message
T.assert not err?, "clearsign armor should decode under normal mode"
cb null
exports.non_base64_characters = (T, cb) ->
message = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
hQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr
U3fm/0/SxTdTJRaZsAjbVLH4jYg6cXyNIxdE5uw2ywxQ9Zi8iWylD(((ixsPT5bD6Q7
xlFLhr4BTt7P/oTUMANybuFU6ntss8jbzKZ7SdHbylLrkaUylSWqH1d7bffMxCAl
JOOAHBOXowpcswAurwQpaDZGX3rGUXjAcMDS5ykr/tgHIwo25A+WbIdNCYMkYm0d
BT83PUMIZm351LJWIv/tBqraNc9kEyftAMbVlh5xC0EfPt+ipyRJDh5XKTvh0xQW
T6nM9Z0qLVwUhaG9RqRM1H6D083IE9fKF6sFdce7MtI/ARo3wPa7qll1hyY5vfaT
baAzKLJPcPDf1vu2+S1c1kt5ljvao8MCCebgK7E8CPT/ajLr1xU05G7Eg0zrkstk
=ni0M
-----END PGP MESSAGE-----"""
[err, decoded] = decode_strict message
T.assert err?, "should decode under strict mode"
T.waypoint "decode_strict failed with error \"#{err.message}\""
# Note - the checksum still matches, because only additional
# characters were added, which are ignored during base64 reading. So
# it should still decode properly.
[err, decoded] = decode message
T.assert not err?, "should decode under normal mode"
cb null
| 92378 | {decode,clearsign_header,Parser} = require('../../lib/main').armor
{katch} = require '../../lib/util'
decode_strict = (data) -> katch () -> (new Parser data, { strict: true }).parse()
global_msg = """-----BEGIN PGP PUBLIC KEY BLOCK-----
<KEY>
-----END PGP PUBLIC KEY BLOCK-----"""
exports.test_bundle_no_newlines = (T, cb) ->
msg = global_msg
# Remove newlines from the base64 part
k = msg.split '\n'
mangled_key = k[0..1].join('\n') + '\n' + k[2..-2].join('') + '\n' + k[-1..].join('\n')
[err, decoded] = decode_strict mangled_key
T.assert err?, 'mangled key should not decode under strict mode'
[err, decoded] = decode mangled_key
T.assert not err?, 'mangled key should decode under normal mode'
# Another case is where newlines are replaced with spaces, only
# keeping last newline before crc line.
k = msg.split '\n'
mangled_key = k[0..1].join('\n') + '\n' + k[2..-3].join(' ') + '\n' + k[-2..].join('\n')
[err, decoded] = decode_strict mangled_key
T.assert err?, 'mangled key 2 should not decode under strict mode'
[err, decoded] = decode mangled_key
T.assert not err?, 'mangled key 2 should decode under normal mode'
cb null
exports.clearsign_long_lines = (T, cb) ->
# A really long line in clearsign section should not trip the
# line limit in parser.
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Version: xf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKhxf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKhThisIsARealProgramISwear
Regardless of where you run it, a heavy math operation can be written with single-thread concurrency in mind. You just have to (1) do work in batches, (2) defer to the event loop periodically via setTimeout or process.nextTick, and (3) call back with an answer, instead of returning one.
-----BEGIN PGP SIGNATURE-----
<KEY>
PTfg<KEY>qv3qaunjwm0ZjRtPabMg<KEY>==
=9ssu
-----END PGP SIGNATURE-----
"""
# Both should decode - strict mode should not apply for clearsign section or header section.
[err, decoded] = decode_strict message
T.assert not err?, "clearsign armor should decode under strict mode"
[err, decoded] = decode message
T.assert not err?, "clearsign armor should decode under normal mode"
cb null
exports.non_base64_characters = (T, cb) ->
message = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
-----END PGP MESSAGE-----"""
[err, decoded] = decode_strict message
T.assert err?, "should decode under strict mode"
T.waypoint "decode_strict failed with error \"#{err.message}\""
# Note - the checksum still matches, because only additional
# characters were added, which are ignored during base64 reading. So
# it should still decode properly.
[err, decoded] = decode message
T.assert not err?, "should decode under normal mode"
cb null
| true | {decode,clearsign_header,Parser} = require('../../lib/main').armor
{katch} = require '../../lib/util'
decode_strict = (data) -> katch () -> (new Parser data, { strict: true }).parse()
global_msg = """-----BEGIN PGP PUBLIC KEY BLOCK-----
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----"""
exports.test_bundle_no_newlines = (T, cb) ->
msg = global_msg
# Remove newlines from the base64 part
k = msg.split '\n'
mangled_key = k[0..1].join('\n') + '\n' + k[2..-2].join('') + '\n' + k[-1..].join('\n')
[err, decoded] = decode_strict mangled_key
T.assert err?, 'mangled key should not decode under strict mode'
[err, decoded] = decode mangled_key
T.assert not err?, 'mangled key should decode under normal mode'
# Another case is where newlines are replaced with spaces, only
# keeping last newline before crc line.
k = msg.split '\n'
mangled_key = k[0..1].join('\n') + '\n' + k[2..-3].join(' ') + '\n' + k[-2..].join('\n')
[err, decoded] = decode_strict mangled_key
T.assert err?, 'mangled key 2 should not decode under strict mode'
[err, decoded] = decode mangled_key
T.assert not err?, 'mangled key 2 should decode under normal mode'
cb null
exports.clearsign_long_lines = (T, cb) ->
# A really long line in clearsign section should not trip the
# line limit in parser.
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Version: xf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKhxf8AAAB3BFOsKbATCCqGSM49AwEHAgMEhEKmGdZix3AbyoAVe6Bd4WZE8jGVUbKhThisIsARealProgramISwear
Regardless of where you run it, a heavy math operation can be written with single-thread concurrency in mind. You just have to (1) do work in batches, (2) defer to the event loop periodically via setTimeout or process.nextTick, and (3) call back with an answer, instead of returning one.
-----BEGIN PGP SIGNATURE-----
PI:KEY:<KEY>END_PI
PTfgPI:KEY:<KEY>END_PIqv3qaunjwm0ZjRtPabMgPI:KEY:<KEY>END_PI==
=9ssu
-----END PGP SIGNATURE-----
"""
# Both should decode - strict mode should not apply for clearsign section or header section.
[err, decoded] = decode_strict message
T.assert not err?, "clearsign armor should decode under strict mode"
[err, decoded] = decode message
T.assert not err?, "clearsign armor should decode under normal mode"
cb null
exports.non_base64_characters = (T, cb) ->
message = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----"""
[err, decoded] = decode_strict message
T.assert err?, "should decode under strict mode"
T.waypoint "decode_strict failed with error \"#{err.message}\""
# Note - the checksum still matches, because only additional
# characters were added, which are ignored during base64 reading. So
# it should still decode properly.
[err, decoded] = decode message
T.assert not err?, "should decode under normal mode"
cb null
|
[
{
"context": "noreferrer.js, version 0.1.3\n https://github.com/knu/noreferrer\n\n Copyright (c) 2011 Akinori MUSHA\n ",
"end": 76,
"score": 0.997086763381958,
"start": 73,
"tag": "USERNAME",
"value": "knu"
},
{
"context": "://github.com/knu/noreferrer\n\n Copyright (c) 2011 Akin... | src/jquery.noreferrer.coffee | knu/noreferrer | 100 | `/**
@license jquery.noreferrer.js, version 0.1.3
https://github.com/knu/noreferrer
Copyright (c) 2011 Akinori MUSHA
Licensed under the 2-clause BSD license.
*/`
###
Cross-browser support for HTML5's noreferrer link type.
This version is for use with jQuery.
###
do ->
# WebKit based browsers do support rel="noreferrer"
return if $.browser.webkit
$.event.add window, 'load', ->
$('a[href][rel~=noreferrer], area[href][rel~=noreferrer]').each ->
a = this
href = a.href
# Opera seems to have no way to stop sending a Referer header.
if $.browser.opera
# Use Google's redirector to hide the real referrer URL
a.href = 'http://www.google.com/url?q=' + encodeURIComponent(href)
a.title ||= 'Go to ' + href
return
# Disable opening a link in a new window with middle click
middlebutton = false
kill_href = (ev) ->
a.href = 'javascript:void(0)'
return
restore_href = (ev) ->
a.href = href
return
$(a).bind('mouseout mouseover focus blur', restore_href
).mousedown((ev) ->
if ev.which == 2
middlebutton = true
return
).blur((ev) ->
middlebutton = false
return
).mouseup((ev) ->
return true unless ev.which == 2 && middlebutton
kill_href()
middlebutton = false
setTimeout (->
alert '''
Middle clicking on this link is disabled to keep the browser from sending a referrer.
'''
restore_href()
return
), 500
false
)
body = "<html><head><meta http-equiv='Refresh' content='0; URL=#{$('<p/>').text(href).html()}' /></head><body></body></html>"
if $.browser.msie
$(a).click (ev) ->
switch target = @target || '_self'
when '_self', window.name
win = window
else
win = window.open(null, target)
# This may be an existing window, hence always call clear().
doc = win.document
doc.clear()
doc.write body
doc.close()
false
else
uri = "data:text/html;charset=utf-8,#{encodeURIComponent(body)}"
$(a).click (ev) ->
@href = uri
true
return
return
return
| 18803 | `/**
@license jquery.noreferrer.js, version 0.1.3
https://github.com/knu/noreferrer
Copyright (c) 2011 <NAME>
Licensed under the 2-clause BSD license.
*/`
###
Cross-browser support for HTML5's noreferrer link type.
This version is for use with jQuery.
###
do ->
# WebKit based browsers do support rel="noreferrer"
return if $.browser.webkit
$.event.add window, 'load', ->
$('a[href][rel~=noreferrer], area[href][rel~=noreferrer]').each ->
a = this
href = a.href
# Opera seems to have no way to stop sending a Referer header.
if $.browser.opera
# Use Google's redirector to hide the real referrer URL
a.href = 'http://www.google.com/url?q=' + encodeURIComponent(href)
a.title ||= 'Go to ' + href
return
# Disable opening a link in a new window with middle click
middlebutton = false
kill_href = (ev) ->
a.href = 'javascript:void(0)'
return
restore_href = (ev) ->
a.href = href
return
$(a).bind('mouseout mouseover focus blur', restore_href
).mousedown((ev) ->
if ev.which == 2
middlebutton = true
return
).blur((ev) ->
middlebutton = false
return
).mouseup((ev) ->
return true unless ev.which == 2 && middlebutton
kill_href()
middlebutton = false
setTimeout (->
alert '''
Middle clicking on this link is disabled to keep the browser from sending a referrer.
'''
restore_href()
return
), 500
false
)
body = "<html><head><meta http-equiv='Refresh' content='0; URL=#{$('<p/>').text(href).html()}' /></head><body></body></html>"
if $.browser.msie
$(a).click (ev) ->
switch target = @target || '_self'
when '_self', window.name
win = window
else
win = window.open(null, target)
# This may be an existing window, hence always call clear().
doc = win.document
doc.clear()
doc.write body
doc.close()
false
else
uri = "data:text/html;charset=utf-8,#{encodeURIComponent(body)}"
$(a).click (ev) ->
@href = uri
true
return
return
return
| true | `/**
@license jquery.noreferrer.js, version 0.1.3
https://github.com/knu/noreferrer
Copyright (c) 2011 PI:NAME:<NAME>END_PI
Licensed under the 2-clause BSD license.
*/`
###
Cross-browser support for HTML5's noreferrer link type.
This version is for use with jQuery.
###
do ->
# WebKit based browsers do support rel="noreferrer"
return if $.browser.webkit
$.event.add window, 'load', ->
$('a[href][rel~=noreferrer], area[href][rel~=noreferrer]').each ->
a = this
href = a.href
# Opera seems to have no way to stop sending a Referer header.
if $.browser.opera
# Use Google's redirector to hide the real referrer URL
a.href = 'http://www.google.com/url?q=' + encodeURIComponent(href)
a.title ||= 'Go to ' + href
return
# Disable opening a link in a new window with middle click
middlebutton = false
kill_href = (ev) ->
a.href = 'javascript:void(0)'
return
restore_href = (ev) ->
a.href = href
return
$(a).bind('mouseout mouseover focus blur', restore_href
).mousedown((ev) ->
if ev.which == 2
middlebutton = true
return
).blur((ev) ->
middlebutton = false
return
).mouseup((ev) ->
return true unless ev.which == 2 && middlebutton
kill_href()
middlebutton = false
setTimeout (->
alert '''
Middle clicking on this link is disabled to keep the browser from sending a referrer.
'''
restore_href()
return
), 500
false
)
body = "<html><head><meta http-equiv='Refresh' content='0; URL=#{$('<p/>').text(href).html()}' /></head><body></body></html>"
if $.browser.msie
$(a).click (ev) ->
switch target = @target || '_self'
when '_self', window.name
win = window
else
win = window.open(null, target)
# This may be an existing window, hence always call clear().
doc = win.document
doc.clear()
doc.write body
doc.close()
false
else
uri = "data:text/html;charset=utf-8,#{encodeURIComponent(body)}"
$(a).click (ev) ->
@href = uri
true
return
return
return
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9987279772758484,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-zlib-random-byte-pipes.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# emit random bytes, and keep a shasum
RandomReadStream = (opt) ->
Stream.call this
@readable = true
@_paused = false
@_processing = false
@_hasher = crypto.createHash("sha1")
opt = opt or {}
# base block size.
opt.block = opt.block or 256 * 1024
# total number of bytes to emit
opt.total = opt.total or 256 * 1024 * 1024
@_remaining = opt.total
# how variable to make the block sizes
opt.jitter = opt.jitter or 1024
@_opt = opt
@_process = @_process.bind(this)
process.nextTick @_process
return
# console.error("rrs resume");
# figure out how many bytes to output
# if finished, then just emit end.
# a filter that just verifies a shasum
HashStream = ->
Stream.call this
@readable = @writable = true
@_hasher = crypto.createHash("sha1")
return
common = require("../common")
crypto = require("crypto")
stream = require("stream")
Stream = stream.Stream
util = require("util")
assert = require("assert")
zlib = require("zlib")
util.inherits RandomReadStream, Stream
RandomReadStream::pause = ->
@_paused = true
@emit "pause"
return
RandomReadStream::resume = ->
@_paused = false
@emit "resume"
@_process()
return
RandomReadStream::_process = ->
return if @_processing
return if @_paused
@_processing = true
unless @_remaining
@_hash = @_hasher.digest("hex").toLowerCase().trim()
@_processing = false
@emit "end"
return
block = @_opt.block
jitter = @_opt.jitter
block += Math.ceil(Math.random() * jitter - (jitter / 2)) if jitter
block = Math.min(block, @_remaining)
buf = new Buffer(block)
i = 0
while i < block
buf[i] = Math.random() * 256
i++
@_hasher.update buf
@_remaining -= block
console.error "block=%d\nremain=%d\n", block, @_remaining
@_processing = false
@emit "data", buf
process.nextTick @_process
return
util.inherits HashStream, Stream
HashStream::write = (c) ->
# Simulate the way that an fs.ReadStream returns false
# on *every* write like a jerk, only to resume a
# moment later.
@_hasher.update c
process.nextTick @resume.bind(this)
false
HashStream::resume = ->
@emit "resume"
process.nextTick @emit.bind(this, "drain")
return
HashStream::end = (c) ->
@write c if c
@_hash = @_hasher.digest("hex").toLowerCase().trim()
@emit "data", @_hash
@emit "end"
return
inp = new RandomReadStream(
total: 1024
block: 256
jitter: 16
)
out = new HashStream()
gzip = zlib.createGzip()
gunz = zlib.createGunzip()
inp.pipe(gzip).pipe(gunz).pipe out
inp.on "data", (c) ->
console.error "inp data", c.length
return
gzip.on "data", (c) ->
console.error "gzip data", c.length
return
gunz.on "data", (c) ->
console.error "gunz data", c.length
return
out.on "data", (c) ->
console.error "out data", c.length
return
didSomething = false
out.on "data", (c) ->
didSomething = true
console.error "hash=%s", c
assert.equal c, inp._hash, "hashes should match"
return
process.on "exit", ->
assert didSomething, "should have done something"
return
| 121430 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# emit random bytes, and keep a shasum
RandomReadStream = (opt) ->
Stream.call this
@readable = true
@_paused = false
@_processing = false
@_hasher = crypto.createHash("sha1")
opt = opt or {}
# base block size.
opt.block = opt.block or 256 * 1024
# total number of bytes to emit
opt.total = opt.total or 256 * 1024 * 1024
@_remaining = opt.total
# how variable to make the block sizes
opt.jitter = opt.jitter or 1024
@_opt = opt
@_process = @_process.bind(this)
process.nextTick @_process
return
# console.error("rrs resume");
# figure out how many bytes to output
# if finished, then just emit end.
# a filter that just verifies a shasum
HashStream = ->
Stream.call this
@readable = @writable = true
@_hasher = crypto.createHash("sha1")
return
common = require("../common")
crypto = require("crypto")
stream = require("stream")
Stream = stream.Stream
util = require("util")
assert = require("assert")
zlib = require("zlib")
util.inherits RandomReadStream, Stream
RandomReadStream::pause = ->
@_paused = true
@emit "pause"
return
RandomReadStream::resume = ->
@_paused = false
@emit "resume"
@_process()
return
RandomReadStream::_process = ->
return if @_processing
return if @_paused
@_processing = true
unless @_remaining
@_hash = @_hasher.digest("hex").toLowerCase().trim()
@_processing = false
@emit "end"
return
block = @_opt.block
jitter = @_opt.jitter
block += Math.ceil(Math.random() * jitter - (jitter / 2)) if jitter
block = Math.min(block, @_remaining)
buf = new Buffer(block)
i = 0
while i < block
buf[i] = Math.random() * 256
i++
@_hasher.update buf
@_remaining -= block
console.error "block=%d\nremain=%d\n", block, @_remaining
@_processing = false
@emit "data", buf
process.nextTick @_process
return
util.inherits HashStream, Stream
HashStream::write = (c) ->
# Simulate the way that an fs.ReadStream returns false
# on *every* write like a jerk, only to resume a
# moment later.
@_hasher.update c
process.nextTick @resume.bind(this)
false
HashStream::resume = ->
@emit "resume"
process.nextTick @emit.bind(this, "drain")
return
HashStream::end = (c) ->
@write c if c
@_hash = @_hasher.digest("hex").toLowerCase().trim()
@emit "data", @_hash
@emit "end"
return
inp = new RandomReadStream(
total: 1024
block: 256
jitter: 16
)
out = new HashStream()
gzip = zlib.createGzip()
gunz = zlib.createGunzip()
inp.pipe(gzip).pipe(gunz).pipe out
inp.on "data", (c) ->
console.error "inp data", c.length
return
gzip.on "data", (c) ->
console.error "gzip data", c.length
return
gunz.on "data", (c) ->
console.error "gunz data", c.length
return
out.on "data", (c) ->
console.error "out data", c.length
return
didSomething = false
out.on "data", (c) ->
didSomething = true
console.error "hash=%s", c
assert.equal c, inp._hash, "hashes should match"
return
process.on "exit", ->
assert didSomething, "should have done something"
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# emit random bytes, and keep a shasum
RandomReadStream = (opt) ->
Stream.call this
@readable = true
@_paused = false
@_processing = false
@_hasher = crypto.createHash("sha1")
opt = opt or {}
# base block size.
opt.block = opt.block or 256 * 1024
# total number of bytes to emit
opt.total = opt.total or 256 * 1024 * 1024
@_remaining = opt.total
# how variable to make the block sizes
opt.jitter = opt.jitter or 1024
@_opt = opt
@_process = @_process.bind(this)
process.nextTick @_process
return
# console.error("rrs resume");
# figure out how many bytes to output
# if finished, then just emit end.
# a filter that just verifies a shasum
HashStream = ->
Stream.call this
@readable = @writable = true
@_hasher = crypto.createHash("sha1")
return
common = require("../common")
crypto = require("crypto")
stream = require("stream")
Stream = stream.Stream
util = require("util")
assert = require("assert")
zlib = require("zlib")
util.inherits RandomReadStream, Stream
RandomReadStream::pause = ->
@_paused = true
@emit "pause"
return
RandomReadStream::resume = ->
@_paused = false
@emit "resume"
@_process()
return
RandomReadStream::_process = ->
return if @_processing
return if @_paused
@_processing = true
unless @_remaining
@_hash = @_hasher.digest("hex").toLowerCase().trim()
@_processing = false
@emit "end"
return
block = @_opt.block
jitter = @_opt.jitter
block += Math.ceil(Math.random() * jitter - (jitter / 2)) if jitter
block = Math.min(block, @_remaining)
buf = new Buffer(block)
i = 0
while i < block
buf[i] = Math.random() * 256
i++
@_hasher.update buf
@_remaining -= block
console.error "block=%d\nremain=%d\n", block, @_remaining
@_processing = false
@emit "data", buf
process.nextTick @_process
return
util.inherits HashStream, Stream
HashStream::write = (c) ->
# Simulate the way that an fs.ReadStream returns false
# on *every* write like a jerk, only to resume a
# moment later.
@_hasher.update c
process.nextTick @resume.bind(this)
false
HashStream::resume = ->
@emit "resume"
process.nextTick @emit.bind(this, "drain")
return
HashStream::end = (c) ->
@write c if c
@_hash = @_hasher.digest("hex").toLowerCase().trim()
@emit "data", @_hash
@emit "end"
return
inp = new RandomReadStream(
total: 1024
block: 256
jitter: 16
)
out = new HashStream()
gzip = zlib.createGzip()
gunz = zlib.createGunzip()
inp.pipe(gzip).pipe(gunz).pipe out
inp.on "data", (c) ->
console.error "inp data", c.length
return
gzip.on "data", (c) ->
console.error "gzip data", c.length
return
gunz.on "data", (c) ->
console.error "gunz data", c.length
return
out.on "data", (c) ->
console.error "out data", c.length
return
didSomething = false
out.on "data", (c) ->
didSomething = true
console.error "hash=%s", c
assert.equal c, inp._hash, "hashes should match"
return
process.on "exit", ->
assert didSomething, "should have done something"
return
|
[
{
"context": " *@description:#{pkg.description}\\n *@author:Pang.J.G\\n *@homepage:#{pkg.homepage}\\n */\\n\"\n\n @",
"end": 926,
"score": 0.5597691535949707,
"start": 925,
"tag": "NAME",
"value": "J"
}
] | node_modules/vbuilder/lib/jsCtl/jsInit.coffee | duolaimi/v.builder.site | 0 | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
amdclean = require 'amdclean'
gutil = require 'gulp-util'
color = gutil.colors
Utils = require '../utils'
pkg = require '../../package.json'
###*
* @fileOverview js构建基础类库
###
class JsInit
constructor:(@opts)->
# console.log @opts
@amdReg = /;?\s*define\s*\(([^(]*),?\s*?function\s*\([^\)]*\)/
@expStr = /define\s*\(([^(]*),?\s*?function/
@depArrReg = /^[^\[]*(\[[^\]\[]*\]).*$/
@jsImgReg = /STATIC_PATH\s*\+\s*(('|")\/img\/.*?\.(jpg|png|gif)('|"))/g
#@jsImgReg = /STATIC_PATH\s*\+\s*(('|")[\s\S]*?(.jpg|.png|.gif)('|"))/g
@staticUriReg = /(getStaticUri\.(img|css|js)\(??.*\.(jpg|png|gif|css|js)('|")\))|(STATIC_PATH\s*\+\s*(('|")\/img\/.*?\.(jpg|png|gif)('|")))/g
@info = "/**\n *Uglify by #{pkg.name}@v#{pkg.version}\n *@description:#{pkg.description}\n *@author:Pang.J.G\n *@homepage:#{pkg.homepage}\n */\n"
@root = @opts.root
@env = @opts.env
@isDebug = @opts.isDebug
@srcPath = @opts.srcPath + 'js/'
@debugPath = @opts.debugPath + 'js/'
@distPath = @opts.distPath + 'js/'
@mapPath = @opts.mapPath
@prefix = @opts.prefix
@hashLen = @opts.hashLen
@coreMods = @opts.coreJs.mods
@coreModsName = @opts.coreJs.name
@vendorPath = @debugPath + 'vendor'
@jsMap = @mapPath + 'jsmap.json'
@jsLibs = @mapPath + 'jslibs.json'
# 字符串转化为对象
tryEval: (str)->
try
json = eval('(' + str + ')')
catch err
# 过滤依赖表里的关键词,排除空依赖
filterDepMap: (depMap)->
_depMap = depMap.filter (dep)->
return ["require", "exports", "module", ""].indexOf(dep) == -1
_depMap.map (dep) ->
return dep.replace(/\.js$/,'')
return _depMap
# 将绝对路径转换为AMD模块ID
madeModId: (filepath)->
return filepath.replace(/\\/g,'/')
.split('/js/')[1]
.replace(/.js$/,'')
# 将相对路径转换为AMD模块ID
madeModList: (depArr,curPath)->
_this = @
_arr = []
if depArr.length > 0
_.forEach depArr,(val)->
_val = val
if _val.indexOf('../') is 0 or _val.indexOf('./') is 0
_filePath = path.join curPath,_val
_val = _this.madeModId(_filePath)
_arr.push _val
return _arr
# 将js数组转字符串
arrToString: (arr)->
_str = ""
if arr.length > 0
_.forEach arr,(val,n)->
_str += (if n > 0 then "," else "") + "'#{val}'"
return "[#{_str}]"
# 获取正则表达式中的key
getRegKey: (str,type)->
return str.replace("getStaticUri.#{type}(","")
.replace(')','')
.replace(/(^\'|\")|(\'|\"$)/g, '')
# 获取key对应的生产名字
getDistName: (key,map)->
return if _.has(map,key) then map[key].distname else key #+ '?t=' + String(new Date().getTime()).substr(0,8)
# 替换js中的getStaticUri,给请求的资源增加MD5戳,解决缓存问题
replaceStaticResName: (res)->
_this = @
_getStr = (strs,type)->
map = Utils.getMap(type)
key = _this.getRegKey(strs,type)
val = _this.getDistName(key,map)
# console.log val
return strs.replace(key, val)
_res = res.replace _this.staticUriReg,(str)->
if str.indexOf('/img/') > -1
_map = Utils.getMap('img')
key = str.match(/\/img\/.*\.(png|jpg|gif)/)[0]
.replace('/img/', '')
val = _this.getDistName(key,_map)
return str.replace(key, val)
else if str.indexOf('getStaticUri.img(') is 0
return _getStr(str,'img')
else if str.indexOf('getStaticUri.css(') is 0
return _getStr(str,'css')
else if str.indexOf('getStaticUri.js(') is 0
return _getStr(str,'js')
else
return str
return _res
###*
* 获取具名AMD模块的依赖表
* @param {String} file_path [AMD模块文件的路径]
* @return {Array} [模块的依赖数组]
###
getOneJsDep: (source)=>
_this = @
_list = []
source.replace _this.amdReg, (str, map)->
depStr = map.replace _this.depArrReg, "$1"
if /^\[/.test(depStr)
_arr = _this.tryEval depStr
try
_list = _this.filterDepMap _arr
catch err
console.log err
return _list
# 核心模块过滤方法
coreModsFilter: (arr)->
_temp = []
for f in arr
_temp.push f if f not in @coreMods
return _temp
# 过滤AMD,输出原生js
amdClean: (source)->
s = amdclean.clean({
code: source
wrap:
start: ''
end:''
})
return s
module.exports = JsInit | 140041 | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
amdclean = require 'amdclean'
gutil = require 'gulp-util'
color = gutil.colors
Utils = require '../utils'
pkg = require '../../package.json'
###*
* @fileOverview js构建基础类库
###
class JsInit
constructor:(@opts)->
# console.log @opts
@amdReg = /;?\s*define\s*\(([^(]*),?\s*?function\s*\([^\)]*\)/
@expStr = /define\s*\(([^(]*),?\s*?function/
@depArrReg = /^[^\[]*(\[[^\]\[]*\]).*$/
@jsImgReg = /STATIC_PATH\s*\+\s*(('|")\/img\/.*?\.(jpg|png|gif)('|"))/g
#@jsImgReg = /STATIC_PATH\s*\+\s*(('|")[\s\S]*?(.jpg|.png|.gif)('|"))/g
@staticUriReg = /(getStaticUri\.(img|css|js)\(??.*\.(jpg|png|gif|css|js)('|")\))|(STATIC_PATH\s*\+\s*(('|")\/img\/.*?\.(jpg|png|gif)('|")))/g
@info = "/**\n *Uglify by #{pkg.name}@v#{pkg.version}\n *@description:#{pkg.description}\n *@author:Pang.<NAME>.G\n *@homepage:#{pkg.homepage}\n */\n"
@root = @opts.root
@env = @opts.env
@isDebug = @opts.isDebug
@srcPath = @opts.srcPath + 'js/'
@debugPath = @opts.debugPath + 'js/'
@distPath = @opts.distPath + 'js/'
@mapPath = @opts.mapPath
@prefix = @opts.prefix
@hashLen = @opts.hashLen
@coreMods = @opts.coreJs.mods
@coreModsName = @opts.coreJs.name
@vendorPath = @debugPath + 'vendor'
@jsMap = @mapPath + 'jsmap.json'
@jsLibs = @mapPath + 'jslibs.json'
# 字符串转化为对象
tryEval: (str)->
try
json = eval('(' + str + ')')
catch err
# 过滤依赖表里的关键词,排除空依赖
filterDepMap: (depMap)->
_depMap = depMap.filter (dep)->
return ["require", "exports", "module", ""].indexOf(dep) == -1
_depMap.map (dep) ->
return dep.replace(/\.js$/,'')
return _depMap
# 将绝对路径转换为AMD模块ID
madeModId: (filepath)->
return filepath.replace(/\\/g,'/')
.split('/js/')[1]
.replace(/.js$/,'')
# 将相对路径转换为AMD模块ID
madeModList: (depArr,curPath)->
_this = @
_arr = []
if depArr.length > 0
_.forEach depArr,(val)->
_val = val
if _val.indexOf('../') is 0 or _val.indexOf('./') is 0
_filePath = path.join curPath,_val
_val = _this.madeModId(_filePath)
_arr.push _val
return _arr
# 将js数组转字符串
arrToString: (arr)->
_str = ""
if arr.length > 0
_.forEach arr,(val,n)->
_str += (if n > 0 then "," else "") + "'#{val}'"
return "[#{_str}]"
# 获取正则表达式中的key
getRegKey: (str,type)->
return str.replace("getStaticUri.#{type}(","")
.replace(')','')
.replace(/(^\'|\")|(\'|\"$)/g, '')
# 获取key对应的生产名字
getDistName: (key,map)->
return if _.has(map,key) then map[key].distname else key #+ '?t=' + String(new Date().getTime()).substr(0,8)
# 替换js中的getStaticUri,给请求的资源增加MD5戳,解决缓存问题
replaceStaticResName: (res)->
_this = @
_getStr = (strs,type)->
map = Utils.getMap(type)
key = _this.getRegKey(strs,type)
val = _this.getDistName(key,map)
# console.log val
return strs.replace(key, val)
_res = res.replace _this.staticUriReg,(str)->
if str.indexOf('/img/') > -1
_map = Utils.getMap('img')
key = str.match(/\/img\/.*\.(png|jpg|gif)/)[0]
.replace('/img/', '')
val = _this.getDistName(key,_map)
return str.replace(key, val)
else if str.indexOf('getStaticUri.img(') is 0
return _getStr(str,'img')
else if str.indexOf('getStaticUri.css(') is 0
return _getStr(str,'css')
else if str.indexOf('getStaticUri.js(') is 0
return _getStr(str,'js')
else
return str
return _res
###*
* 获取具名AMD模块的依赖表
* @param {String} file_path [AMD模块文件的路径]
* @return {Array} [模块的依赖数组]
###
getOneJsDep: (source)=>
_this = @
_list = []
source.replace _this.amdReg, (str, map)->
depStr = map.replace _this.depArrReg, "$1"
if /^\[/.test(depStr)
_arr = _this.tryEval depStr
try
_list = _this.filterDepMap _arr
catch err
console.log err
return _list
# 核心模块过滤方法
coreModsFilter: (arr)->
_temp = []
for f in arr
_temp.push f if f not in @coreMods
return _temp
# 过滤AMD,输出原生js
amdClean: (source)->
s = amdclean.clean({
code: source
wrap:
start: ''
end:''
})
return s
module.exports = JsInit | true | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
amdclean = require 'amdclean'
gutil = require 'gulp-util'
color = gutil.colors
Utils = require '../utils'
pkg = require '../../package.json'
###*
* @fileOverview js构建基础类库
###
class JsInit
constructor:(@opts)->
# console.log @opts
@amdReg = /;?\s*define\s*\(([^(]*),?\s*?function\s*\([^\)]*\)/
@expStr = /define\s*\(([^(]*),?\s*?function/
@depArrReg = /^[^\[]*(\[[^\]\[]*\]).*$/
@jsImgReg = /STATIC_PATH\s*\+\s*(('|")\/img\/.*?\.(jpg|png|gif)('|"))/g
#@jsImgReg = /STATIC_PATH\s*\+\s*(('|")[\s\S]*?(.jpg|.png|.gif)('|"))/g
@staticUriReg = /(getStaticUri\.(img|css|js)\(??.*\.(jpg|png|gif|css|js)('|")\))|(STATIC_PATH\s*\+\s*(('|")\/img\/.*?\.(jpg|png|gif)('|")))/g
@info = "/**\n *Uglify by #{pkg.name}@v#{pkg.version}\n *@description:#{pkg.description}\n *@author:Pang.PI:NAME:<NAME>END_PI.G\n *@homepage:#{pkg.homepage}\n */\n"
@root = @opts.root
@env = @opts.env
@isDebug = @opts.isDebug
@srcPath = @opts.srcPath + 'js/'
@debugPath = @opts.debugPath + 'js/'
@distPath = @opts.distPath + 'js/'
@mapPath = @opts.mapPath
@prefix = @opts.prefix
@hashLen = @opts.hashLen
@coreMods = @opts.coreJs.mods
@coreModsName = @opts.coreJs.name
@vendorPath = @debugPath + 'vendor'
@jsMap = @mapPath + 'jsmap.json'
@jsLibs = @mapPath + 'jslibs.json'
# 字符串转化为对象
tryEval: (str)->
try
json = eval('(' + str + ')')
catch err
# 过滤依赖表里的关键词,排除空依赖
filterDepMap: (depMap)->
_depMap = depMap.filter (dep)->
return ["require", "exports", "module", ""].indexOf(dep) == -1
_depMap.map (dep) ->
return dep.replace(/\.js$/,'')
return _depMap
# 将绝对路径转换为AMD模块ID
madeModId: (filepath)->
return filepath.replace(/\\/g,'/')
.split('/js/')[1]
.replace(/.js$/,'')
# 将相对路径转换为AMD模块ID
madeModList: (depArr,curPath)->
_this = @
_arr = []
if depArr.length > 0
_.forEach depArr,(val)->
_val = val
if _val.indexOf('../') is 0 or _val.indexOf('./') is 0
_filePath = path.join curPath,_val
_val = _this.madeModId(_filePath)
_arr.push _val
return _arr
# 将js数组转字符串
arrToString: (arr)->
_str = ""
if arr.length > 0
_.forEach arr,(val,n)->
_str += (if n > 0 then "," else "") + "'#{val}'"
return "[#{_str}]"
# 获取正则表达式中的key
getRegKey: (str,type)->
return str.replace("getStaticUri.#{type}(","")
.replace(')','')
.replace(/(^\'|\")|(\'|\"$)/g, '')
# 获取key对应的生产名字
getDistName: (key,map)->
return if _.has(map,key) then map[key].distname else key #+ '?t=' + String(new Date().getTime()).substr(0,8)
# 替换js中的getStaticUri,给请求的资源增加MD5戳,解决缓存问题
replaceStaticResName: (res)->
_this = @
_getStr = (strs,type)->
map = Utils.getMap(type)
key = _this.getRegKey(strs,type)
val = _this.getDistName(key,map)
# console.log val
return strs.replace(key, val)
_res = res.replace _this.staticUriReg,(str)->
if str.indexOf('/img/') > -1
_map = Utils.getMap('img')
key = str.match(/\/img\/.*\.(png|jpg|gif)/)[0]
.replace('/img/', '')
val = _this.getDistName(key,_map)
return str.replace(key, val)
else if str.indexOf('getStaticUri.img(') is 0
return _getStr(str,'img')
else if str.indexOf('getStaticUri.css(') is 0
return _getStr(str,'css')
else if str.indexOf('getStaticUri.js(') is 0
return _getStr(str,'js')
else
return str
return _res
###*
* 获取具名AMD模块的依赖表
* @param {String} file_path [AMD模块文件的路径]
* @return {Array} [模块的依赖数组]
###
getOneJsDep: (source)=>
_this = @
_list = []
source.replace _this.amdReg, (str, map)->
depStr = map.replace _this.depArrReg, "$1"
if /^\[/.test(depStr)
_arr = _this.tryEval depStr
try
_list = _this.filterDepMap _arr
catch err
console.log err
return _list
# 核心模块过滤方法
coreModsFilter: (arr)->
_temp = []
for f in arr
_temp.push f if f not in @coreMods
return _temp
# 过滤AMD,输出原生js
amdClean: (source)->
s = amdclean.clean({
code: source
wrap:
start: ''
end:''
})
return s
module.exports = JsInit |
[
{
"context": "ull\n\n beforeEach ->\n User.create\n name: 'jysperm'\n age: 19\n .then (result) ->\n jysper",
"end": 200,
"score": 0.9991791844367981,
"start": 193,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": "sperm.modify (jysperm) ->\n jysperm.... | test/document.modify.test.coffee | jysperm/Mabolo | 33 | describe 'document.modify', ->
mabolo = new Mabolo mongodb_uri
User = mabolo.model 'User',
name: String
age: Number
jysperm = null
beforeEach ->
User.create
name: 'jysperm'
age: 19
.then (result) ->
jysperm = result
it 'modify without conflict', ->
jysperm.modify (jysperm) ->
jysperm.age = 20
.then ->
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 20
it 'modify without conflict async', ->
jysperm.modify (jysperm) ->
Q.delay(10).then ->
jysperm.age = 20
.then ->
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 20
it 'modify and rollback', ->
jysperm.modify (jysperm) ->
jysperm.age = 20
return Q.reject new Error 'rollback'
.catch (err) ->
err.message.should.match /rollback/
.thenResolve().then ->
jysperm.age.should.be.equal 19
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 19
it 'modify and validating fail', ->
jysperm.modify (jysperm) ->
jysperm.age = 'invalid-number'
.catch (err) ->
err.message.should.match /age/
.thenResolve().then ->
jysperm.age.should.be.equal 19
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 19
it 'modify and conflict', ->
User.findByIdAndUpdate jysperm._id,
$set:
age: 20
.then ->
jysperm.modify (jysperm) ->
jysperm.name = 'JYSPERM'
.then ->
jysperm.name.should.be.equal 'JYSPERM'
jysperm.age.should.be.equal 20
User.findById jysperm._id
.then (jysperm) ->
jysperm.name.should.be.equal 'JYSPERM'
jysperm.age.should.be.equal 20
| 55583 | describe 'document.modify', ->
mabolo = new Mabolo mongodb_uri
User = mabolo.model 'User',
name: String
age: Number
jysperm = null
beforeEach ->
User.create
name: 'jysperm'
age: 19
.then (result) ->
jysperm = result
it 'modify without conflict', ->
jysperm.modify (jysperm) ->
jysperm.age = 20
.then ->
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 20
it 'modify without conflict async', ->
jysperm.modify (jysperm) ->
Q.delay(10).then ->
jysperm.age = 20
.then ->
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 20
it 'modify and rollback', ->
jysperm.modify (jysperm) ->
jysperm.age = 20
return Q.reject new Error 'rollback'
.catch (err) ->
err.message.should.match /rollback/
.thenResolve().then ->
jysperm.age.should.be.equal 19
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 19
it 'modify and validating fail', ->
jysperm.modify (jysperm) ->
jysperm.age = 'invalid-number'
.catch (err) ->
err.message.should.match /age/
.thenResolve().then ->
jysperm.age.should.be.equal 19
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 19
it 'modify and conflict', ->
User.findByIdAndUpdate jysperm._id,
$set:
age: 20
.then ->
jysperm.modify (jysperm) ->
jysperm.name = 'JYSPERM'
.then ->
jysperm.name.should.be.equal 'JYSPERM'
jysperm.age.should.be.equal 20
User.findById jysperm._id
.then (jysperm) ->
jysperm.name.should.be.equal '<NAME>SPERM'
jysperm.age.should.be.equal 20
| true | describe 'document.modify', ->
mabolo = new Mabolo mongodb_uri
User = mabolo.model 'User',
name: String
age: Number
jysperm = null
beforeEach ->
User.create
name: 'jysperm'
age: 19
.then (result) ->
jysperm = result
it 'modify without conflict', ->
jysperm.modify (jysperm) ->
jysperm.age = 20
.then ->
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 20
it 'modify without conflict async', ->
jysperm.modify (jysperm) ->
Q.delay(10).then ->
jysperm.age = 20
.then ->
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 20
it 'modify and rollback', ->
jysperm.modify (jysperm) ->
jysperm.age = 20
return Q.reject new Error 'rollback'
.catch (err) ->
err.message.should.match /rollback/
.thenResolve().then ->
jysperm.age.should.be.equal 19
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 19
it 'modify and validating fail', ->
jysperm.modify (jysperm) ->
jysperm.age = 'invalid-number'
.catch (err) ->
err.message.should.match /age/
.thenResolve().then ->
jysperm.age.should.be.equal 19
User.findById jysperm._id
.then (jysperm) ->
jysperm.age.should.be.equal 19
it 'modify and conflict', ->
User.findByIdAndUpdate jysperm._id,
$set:
age: 20
.then ->
jysperm.modify (jysperm) ->
jysperm.name = 'JYSPERM'
.then ->
jysperm.name.should.be.equal 'JYSPERM'
jysperm.age.should.be.equal 20
User.findById jysperm._id
.then (jysperm) ->
jysperm.name.should.be.equal 'PI:NAME:<NAME>END_PISPERM'
jysperm.age.should.be.equal 20
|
[
{
"context": "---------------------------------------\n# Author : Edouard Richard <edou4rd@gmail.c",
"end": 210,
"score": 0.9998810887336731,
"start": 195,
"tag": "NAME",
"value": "Edouard Richard"
},
{
"context": "Edouard Richard ... | plugins/admin-users/static/dw.admin.users.coffee | webvariants/datawrapper | 1 | # -----------------------------------------------------------------------------
# Project : Datawrapper
# -----------------------------------------------------------------------------
# Author : Edouard Richard <edou4rd@gmail.com>
# -----------------------------------------------------------------------------
# License : MIT Licence
# -----------------------------------------------------------------------------
# Creation : 29-May-2013
# Last mod : 09-Jun-2013
# -----------------------------------------------------------------------------
#
# USERS ADMIN
#
# To compile this file, run `$ ./src-js/make` with coffee installed
# For developement, use `$ coffee -w -b -c -o www/static/js/ src-js/dw.admin.users.coffee`
window.admin_users = {}
Widget = window.serious.Widget
States = new window.serious.States()
AJAX_USERS = '/api/users'
AJAX_SALT = '/api/auth/salt'
AJAX_ACCOUNT = '/api/account'
AJAX_RESET_PASSWORD = '/api/account/reset-password'
# -----------------------------------------------------------------------------
#
# Admin Users: add/edit/delete users
#
# -----------------------------------------------------------------------------
class admin_users.AdminUsers extends Widget
constructor: ->
@UIS = {
usersList : '.users'
emailField : 'input[name=email]'
statusField : 'select[name=status]'
loading : '.loading'
addButton : 'input[name=addUser]'
confirmDeleteUser : '.confirm-delete'
editionTmpl : '.user.edition.template'
msgError : '.alert-error'
msgSuccess : '.alert-success'
}
@ACTIONS = [
'showAddUserForm'
'addUserAction'
'removeAction'
'editAction'
'saveEditAction'
'cancelEditAction'
'resendAction',
'resetAction']
@cache = {
editedUser : null
}
bindUI: (ui) =>
super
States.set('addUserForm', false)
editUser: (id) =>
this.cancelEditAction()
@cache.editedUser = this.__getUserById(id) # save edtied user
nui = this.cloneTemplate(@uis.editionTmpl, {
id : @cache.editedUser.Id
creation : @cache.editedUser.CreatedAt
})
nui.find(".email input").val(@cache.editedUser.Email)
nui.find("select[name=status] option[value=#{@cache.editedUser.Role}]").attr('selected', 'selected')
current_line = @uis.usersList.find(".user[data-id=#{@cache.editedUser.Id}]")
current_line.addClass('hidden').after(nui)
enableLoading: =>
@uis.loading.removeClass('hidden')
@uis.addButton.prop('disabled', true)
disableLoading: =>
@uis.loading.addClass('hidden')
@uis.addButton.prop('disabled', false)
hideMessages: =>
@uis.msgError.addClass 'hidden'
# -----------------------------------------------------------------------------
# ACTIONS
# -----------------------------------------------------------------------------
addUserAction: (evnt) =>
this.hideMessages()
email = @uis.emailField.val()
status = @uis.statusField.val()
this.addUser(email, status)
showAddUserForm: (evnt) =>
this.hideMessages()
States.set('addUserForm', true)
removeAction: (evnt) =>
this.hideMessages()
this.removeUser($(evnt.currentTarget).data('id'))
editAction: (evnt) =>
this.hideMessages()
this.editUser($(evnt.currentTarget).data('id'))
saveEditAction: (evnt) =>
this.hideMessages()
### Prepare the new user object and call the update method ###
$row = @uis.usersList.find(".user.edition.actual")
email = $row.find(".email input").val()
status = $row.find("select[name=status]").val()
user = @cache.editedUser
@cache.editedUser.Role = status
@cache.editedUser.Email = email
this.updateUser(@cache.editedUser)
cancelEditAction: (evnt) =>
this.hideMessages()
### Cancel the edition mode, reset the orginal row ###
if @cache.editedUser?
$edited_row = @uis.usersList.find(".user.edition.actual")
$edited_row.prev('.user').removeClass('hidden')
$edited_row.remove()
@cache.editedUser = null
resendAction: (evnt) =>
this.hideMessages()
this.resendInvitation($(evnt.currentTarget).data('id'))
resetAction: (evnt) =>
this.hideMessages()
this.resetPassword($(evnt.currentTarget).data('id'))
# -----------------------------------------------------------------------------
# API
# -----------------------------------------------------------------------------
__getUserById: (id) =>
res = $.ajax("#{AJAX_USERS}/#{id}", {async : false}).responseText
res = eval('(' + res + ')')
if res.status == "ok"
return res.data
addUser: (email, status) =>
this.enableLoading()
$.ajax(AJAX_USERS, {
dataType : 'json'
type : 'POST'
data : JSON.stringify {
email : email
role : status
invitation : true
}
success : (data) =>
this.disableLoading()
if data.status == "error"
@uis.msgError.filter(".error-#{data.message}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
removeUser: (id) =>
user = this.__getUserById(id)
if confirm("#{user.Email} #{@uis.confirmDeleteUser.text()}")
$.ajax("#{AJAX_USERS}/#{id}", {
dataType : 'json'
type : 'DELETE'
data : JSON.stringify {pwd:"pouet"} # hack for API
success : (data) =>
this.disableLoading()
if data.status == "error"
@uis.msgError.filter(".error-#{data.message}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
updateUser: (user) =>
$.ajax("#{AJAX_USERS}/#{user.Id}", {
dataType : 'json'
type : 'PUT'
data : JSON.stringify({role : user.Role, email: user.Email})
success : (data) =>
this.disableLoading()
if data.data.errors? and not (data.data.updated? and data.data.errors[0] == "email-already-exists" and data.data.updated[0] == "role")
@uis.msgError.filter(".error-#{data.data.errors[0]}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
resetPassword: (id) =>
user = this.__getUserById(id)
$.ajax('/api/account/reset-password', {
dataType : "json"
type : "POST"
data : JSON.stringify({email:user.Email})
success : (data) =>
if data.status == "ok"
@uis.msgSuccess.html(data.data).removeClass('hidden')
else
@uis.msgError.filter(".error-#{data.code}").removeClass('hidden')
})
resendInvitation: (id) =>
user = this.__getUserById(id)
$.ajax('/api/account/resend-invitation', {
dataType : "json"
type : "POST"
data : JSON.stringify({email:user.Email})
success : (data) =>
if data.status == "ok"
@uis.msgSuccess.html(data.data).removeClass('hidden')
else
@uis.msgError.filter(".error-#{data.code}").removeClass('hidden')
})
# -----------------------------------------------------------------------------
#
# MAIN FUNCTION
#
# -----------------------------------------------------------------------------
$(window).load ()->
Widget.bindAll()
| 147084 | # -----------------------------------------------------------------------------
# Project : Datawrapper
# -----------------------------------------------------------------------------
# Author : <NAME> <<EMAIL>>
# -----------------------------------------------------------------------------
# License : MIT Licence
# -----------------------------------------------------------------------------
# Creation : 29-May-2013
# Last mod : 09-Jun-2013
# -----------------------------------------------------------------------------
#
# USERS ADMIN
#
# To compile this file, run `$ ./src-js/make` with coffee installed
# For developement, use `$ coffee -w -b -c -o www/static/js/ src-js/dw.admin.users.coffee`
window.admin_users = {}
Widget = window.serious.Widget
States = new window.serious.States()
AJAX_USERS = '/api/users'
AJAX_SALT = '/api/auth/salt'
AJAX_ACCOUNT = '/api/account'
AJAX_RESET_PASSWORD = '/api/account/reset-password'
# -----------------------------------------------------------------------------
#
# Admin Users: add/edit/delete users
#
# -----------------------------------------------------------------------------
class admin_users.AdminUsers extends Widget
constructor: ->
@UIS = {
usersList : '.users'
emailField : 'input[name=email]'
statusField : 'select[name=status]'
loading : '.loading'
addButton : 'input[name=addUser]'
confirmDeleteUser : '.confirm-delete'
editionTmpl : '.user.edition.template'
msgError : '.alert-error'
msgSuccess : '.alert-success'
}
@ACTIONS = [
'showAddUserForm'
'addUserAction'
'removeAction'
'editAction'
'saveEditAction'
'cancelEditAction'
'resendAction',
'resetAction']
@cache = {
editedUser : null
}
bindUI: (ui) =>
super
States.set('addUserForm', false)
editUser: (id) =>
this.cancelEditAction()
@cache.editedUser = this.__getUserById(id) # save edtied user
nui = this.cloneTemplate(@uis.editionTmpl, {
id : @cache.editedUser.Id
creation : @cache.editedUser.CreatedAt
})
nui.find(".email input").val(@cache.editedUser.Email)
nui.find("select[name=status] option[value=#{@cache.editedUser.Role}]").attr('selected', 'selected')
current_line = @uis.usersList.find(".user[data-id=#{@cache.editedUser.Id}]")
current_line.addClass('hidden').after(nui)
enableLoading: =>
@uis.loading.removeClass('hidden')
@uis.addButton.prop('disabled', true)
disableLoading: =>
@uis.loading.addClass('hidden')
@uis.addButton.prop('disabled', false)
hideMessages: =>
@uis.msgError.addClass 'hidden'
# -----------------------------------------------------------------------------
# ACTIONS
# -----------------------------------------------------------------------------
addUserAction: (evnt) =>
this.hideMessages()
email = @uis.emailField.val()
status = @uis.statusField.val()
this.addUser(email, status)
showAddUserForm: (evnt) =>
this.hideMessages()
States.set('addUserForm', true)
removeAction: (evnt) =>
this.hideMessages()
this.removeUser($(evnt.currentTarget).data('id'))
editAction: (evnt) =>
this.hideMessages()
this.editUser($(evnt.currentTarget).data('id'))
saveEditAction: (evnt) =>
this.hideMessages()
### Prepare the new user object and call the update method ###
$row = @uis.usersList.find(".user.edition.actual")
email = $row.find(".email input").val()
status = $row.find("select[name=status]").val()
user = @cache.editedUser
@cache.editedUser.Role = status
@cache.editedUser.Email = email
this.updateUser(@cache.editedUser)
cancelEditAction: (evnt) =>
this.hideMessages()
### Cancel the edition mode, reset the orginal row ###
if @cache.editedUser?
$edited_row = @uis.usersList.find(".user.edition.actual")
$edited_row.prev('.user').removeClass('hidden')
$edited_row.remove()
@cache.editedUser = null
resendAction: (evnt) =>
this.hideMessages()
this.resendInvitation($(evnt.currentTarget).data('id'))
resetAction: (evnt) =>
this.hideMessages()
this.resetPassword($(evnt.currentTarget).data('id'))
# -----------------------------------------------------------------------------
# API
# -----------------------------------------------------------------------------
__getUserById: (id) =>
res = $.ajax("#{AJAX_USERS}/#{id}", {async : false}).responseText
res = eval('(' + res + ')')
if res.status == "ok"
return res.data
addUser: (email, status) =>
this.enableLoading()
$.ajax(AJAX_USERS, {
dataType : 'json'
type : 'POST'
data : JSON.stringify {
email : email
role : status
invitation : true
}
success : (data) =>
this.disableLoading()
if data.status == "error"
@uis.msgError.filter(".error-#{data.message}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
removeUser: (id) =>
user = this.__getUserById(id)
if confirm("#{user.Email} #{@uis.confirmDeleteUser.text()}")
$.ajax("#{AJAX_USERS}/#{id}", {
dataType : 'json'
type : 'DELETE'
data : JSON.stringify {pwd:"<PASSWORD>"} # hack for API
success : (data) =>
this.disableLoading()
if data.status == "error"
@uis.msgError.filter(".error-#{data.message}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
updateUser: (user) =>
$.ajax("#{AJAX_USERS}/#{user.Id}", {
dataType : 'json'
type : 'PUT'
data : JSON.stringify({role : user.Role, email: user.Email})
success : (data) =>
this.disableLoading()
if data.data.errors? and not (data.data.updated? and data.data.errors[0] == "email-already-exists" and data.data.updated[0] == "role")
@uis.msgError.filter(".error-#{data.data.errors[0]}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
resetPassword: (id) =>
user = this.__getUserById(id)
$.ajax('/api/account/reset-password', {
dataType : "json"
type : "POST"
data : JSON.stringify({email:user.Email})
success : (data) =>
if data.status == "ok"
@uis.msgSuccess.html(data.data).removeClass('hidden')
else
@uis.msgError.filter(".error-#{data.code}").removeClass('hidden')
})
resendInvitation: (id) =>
user = this.__getUserById(id)
$.ajax('/api/account/resend-invitation', {
dataType : "json"
type : "POST"
data : JSON.stringify({email:user.Email})
success : (data) =>
if data.status == "ok"
@uis.msgSuccess.html(data.data).removeClass('hidden')
else
@uis.msgError.filter(".error-#{data.code}").removeClass('hidden')
})
# -----------------------------------------------------------------------------
#
# MAIN FUNCTION
#
# -----------------------------------------------------------------------------
$(window).load ()->
Widget.bindAll()
| true | # -----------------------------------------------------------------------------
# Project : Datawrapper
# -----------------------------------------------------------------------------
# Author : PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# -----------------------------------------------------------------------------
# License : MIT Licence
# -----------------------------------------------------------------------------
# Creation : 29-May-2013
# Last mod : 09-Jun-2013
# -----------------------------------------------------------------------------
#
# USERS ADMIN
#
# To compile this file, run `$ ./src-js/make` with coffee installed
# For developement, use `$ coffee -w -b -c -o www/static/js/ src-js/dw.admin.users.coffee`
window.admin_users = {}
Widget = window.serious.Widget
States = new window.serious.States()
AJAX_USERS = '/api/users'
AJAX_SALT = '/api/auth/salt'
AJAX_ACCOUNT = '/api/account'
AJAX_RESET_PASSWORD = '/api/account/reset-password'
# -----------------------------------------------------------------------------
#
# Admin Users: add/edit/delete users
#
# -----------------------------------------------------------------------------
class admin_users.AdminUsers extends Widget
constructor: ->
@UIS = {
usersList : '.users'
emailField : 'input[name=email]'
statusField : 'select[name=status]'
loading : '.loading'
addButton : 'input[name=addUser]'
confirmDeleteUser : '.confirm-delete'
editionTmpl : '.user.edition.template'
msgError : '.alert-error'
msgSuccess : '.alert-success'
}
@ACTIONS = [
'showAddUserForm'
'addUserAction'
'removeAction'
'editAction'
'saveEditAction'
'cancelEditAction'
'resendAction',
'resetAction']
@cache = {
editedUser : null
}
bindUI: (ui) =>
super
States.set('addUserForm', false)
editUser: (id) =>
this.cancelEditAction()
@cache.editedUser = this.__getUserById(id) # save edtied user
nui = this.cloneTemplate(@uis.editionTmpl, {
id : @cache.editedUser.Id
creation : @cache.editedUser.CreatedAt
})
nui.find(".email input").val(@cache.editedUser.Email)
nui.find("select[name=status] option[value=#{@cache.editedUser.Role}]").attr('selected', 'selected')
current_line = @uis.usersList.find(".user[data-id=#{@cache.editedUser.Id}]")
current_line.addClass('hidden').after(nui)
enableLoading: =>
@uis.loading.removeClass('hidden')
@uis.addButton.prop('disabled', true)
disableLoading: =>
@uis.loading.addClass('hidden')
@uis.addButton.prop('disabled', false)
hideMessages: =>
@uis.msgError.addClass 'hidden'
# -----------------------------------------------------------------------------
# ACTIONS
# -----------------------------------------------------------------------------
addUserAction: (evnt) =>
this.hideMessages()
email = @uis.emailField.val()
status = @uis.statusField.val()
this.addUser(email, status)
showAddUserForm: (evnt) =>
this.hideMessages()
States.set('addUserForm', true)
removeAction: (evnt) =>
this.hideMessages()
this.removeUser($(evnt.currentTarget).data('id'))
editAction: (evnt) =>
this.hideMessages()
this.editUser($(evnt.currentTarget).data('id'))
saveEditAction: (evnt) =>
this.hideMessages()
### Prepare the new user object and call the update method ###
$row = @uis.usersList.find(".user.edition.actual")
email = $row.find(".email input").val()
status = $row.find("select[name=status]").val()
user = @cache.editedUser
@cache.editedUser.Role = status
@cache.editedUser.Email = email
this.updateUser(@cache.editedUser)
cancelEditAction: (evnt) =>
this.hideMessages()
### Cancel the edition mode, reset the orginal row ###
if @cache.editedUser?
$edited_row = @uis.usersList.find(".user.edition.actual")
$edited_row.prev('.user').removeClass('hidden')
$edited_row.remove()
@cache.editedUser = null
resendAction: (evnt) =>
this.hideMessages()
this.resendInvitation($(evnt.currentTarget).data('id'))
resetAction: (evnt) =>
this.hideMessages()
this.resetPassword($(evnt.currentTarget).data('id'))
# -----------------------------------------------------------------------------
# API
# -----------------------------------------------------------------------------
__getUserById: (id) =>
res = $.ajax("#{AJAX_USERS}/#{id}", {async : false}).responseText
res = eval('(' + res + ')')
if res.status == "ok"
return res.data
addUser: (email, status) =>
this.enableLoading()
$.ajax(AJAX_USERS, {
dataType : 'json'
type : 'POST'
data : JSON.stringify {
email : email
role : status
invitation : true
}
success : (data) =>
this.disableLoading()
if data.status == "error"
@uis.msgError.filter(".error-#{data.message}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
removeUser: (id) =>
user = this.__getUserById(id)
if confirm("#{user.Email} #{@uis.confirmDeleteUser.text()}")
$.ajax("#{AJAX_USERS}/#{id}", {
dataType : 'json'
type : 'DELETE'
data : JSON.stringify {pwd:"PI:PASSWORD:<PASSWORD>END_PI"} # hack for API
success : (data) =>
this.disableLoading()
if data.status == "error"
@uis.msgError.filter(".error-#{data.message}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
updateUser: (user) =>
$.ajax("#{AJAX_USERS}/#{user.Id}", {
dataType : 'json'
type : 'PUT'
data : JSON.stringify({role : user.Role, email: user.Email})
success : (data) =>
this.disableLoading()
if data.data.errors? and not (data.data.updated? and data.data.errors[0] == "email-already-exists" and data.data.updated[0] == "role")
@uis.msgError.filter(".error-#{data.data.errors[0]}").removeClass('hidden')
else
window.location.reload()
error : => window.location.reload()
})
resetPassword: (id) =>
user = this.__getUserById(id)
$.ajax('/api/account/reset-password', {
dataType : "json"
type : "POST"
data : JSON.stringify({email:user.Email})
success : (data) =>
if data.status == "ok"
@uis.msgSuccess.html(data.data).removeClass('hidden')
else
@uis.msgError.filter(".error-#{data.code}").removeClass('hidden')
})
resendInvitation: (id) =>
user = this.__getUserById(id)
$.ajax('/api/account/resend-invitation', {
dataType : "json"
type : "POST"
data : JSON.stringify({email:user.Email})
success : (data) =>
if data.status == "ok"
@uis.msgSuccess.html(data.data).removeClass('hidden')
else
@uis.msgError.filter(".error-#{data.code}").removeClass('hidden')
})
# -----------------------------------------------------------------------------
#
# MAIN FUNCTION
#
# -----------------------------------------------------------------------------
$(window).load ()->
Widget.bindAll()
|
[
{
"context": "ex'\nMONGO_TEST_IP = process.env.MONGO_TEST_IP or '127.0.0.1'\nMONGO_TEST_PORT = process.env.MONGO_TEST_PORT or",
"end": 399,
"score": 0.9989410042762756,
"start": 390,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " Awesome.plugin any_index, [\n { keys... | test/test.coffee | Clever/ARCHIVED-mongoose-any-index | 0 | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
debug = require('debug') 'mongoose-any-index:test/test.coffee'
mongoose = require 'mongoose'
{Db,Server} = require 'mongodb'
mongoose = require 'mongoose'
Schema = mongoose.Schema
util = require 'util'
any_index = require '../index'
MONGO_TEST_DB = 'test-any-index'
MONGO_TEST_IP = process.env.MONGO_TEST_IP or '127.0.0.1'
MONGO_TEST_PORT = process.env.MONGO_TEST_PORT or 27017
describe 'mongoose-any-index', ->
before (done) ->
debug "BEGIN #{__filename}"
db = new Db(MONGO_TEST_DB, new Server(MONGO_TEST_IP, MONGO_TEST_PORT), {w:1})
db.open (err) => db.dropDatabase (err) =>
@db = new Db(MONGO_TEST_DB, new Server(MONGO_TEST_IP, MONGO_TEST_PORT), {w:1})
@db.open done
beforeEach () ->
@connection = mongoose.createConnection MONGO_TEST_IP, MONGO_TEST_DB, MONGO_TEST_PORT
it 'adds a schema with normal mongoose indexes', (done) ->
Normal = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
@connection.model 'Normal', Normal
setTimeout () =>
@db.indexInformation 'normals', {full:true}, (err, index_information) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.normals"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.normals"
name: 'email_1'
background: true
safe: null
]
done()
, 1000
it 'adds a schema with custom indexes', (done) ->
Awesome = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
Awesome.plugin any_index, [
{ keys: { 'data.whatever_you_want': 1 }, options: { unique: true, sparse: true } }
{ keys: { 'data.something_else': 1, 'data.second_key': 1 }, options: { unique: true } }
]
@connection.model 'Awesome', Awesome
setTimeout () =>
@db.indexInformation 'awesomes', {full:true}, (err, index_information) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
]
done()
, 1000
it "adds a schema with different custom indexes, asserts that mongoose doesn't drop old indexes", (done) ->
Awesome = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
Awesome.plugin any_index, [
{ keys: { 'data.something_different': 1 }, options: { unique: true, sparse: true } }
]
@connection.model 'Awesome', Awesome
async.waterfall [
(cb_wf) => setTimeout cb_wf, 1000
(cb_wf) => @db.indexInformation 'awesomes', {full:true}, cb_wf
(index_information, cb_wf) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
,
v: 1
key: { 'data.something_different': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.something_different_1'
sparse: true
background: true
safe: null
]
@connection.models.Awesome.fullEnsureIndexes cb_wf
(cb_wf) => setTimeout cb_wf, 1000
(cb_wf) => @db.indexInformation 'awesomes', {full:true}, cb_wf
(index_information, cb_wf) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
,
v: 1
key: { 'data.something_different': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.something_different_1'
sparse: true
background: true
safe: null
]
cb_wf()
], done
| 75338 | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
debug = require('debug') 'mongoose-any-index:test/test.coffee'
mongoose = require 'mongoose'
{Db,Server} = require 'mongodb'
mongoose = require 'mongoose'
Schema = mongoose.Schema
util = require 'util'
any_index = require '../index'
MONGO_TEST_DB = 'test-any-index'
MONGO_TEST_IP = process.env.MONGO_TEST_IP or '127.0.0.1'
MONGO_TEST_PORT = process.env.MONGO_TEST_PORT or 27017
describe 'mongoose-any-index', ->
before (done) ->
debug "BEGIN #{__filename}"
db = new Db(MONGO_TEST_DB, new Server(MONGO_TEST_IP, MONGO_TEST_PORT), {w:1})
db.open (err) => db.dropDatabase (err) =>
@db = new Db(MONGO_TEST_DB, new Server(MONGO_TEST_IP, MONGO_TEST_PORT), {w:1})
@db.open done
beforeEach () ->
@connection = mongoose.createConnection MONGO_TEST_IP, MONGO_TEST_DB, MONGO_TEST_PORT
it 'adds a schema with normal mongoose indexes', (done) ->
Normal = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
@connection.model 'Normal', Normal
setTimeout () =>
@db.indexInformation 'normals', {full:true}, (err, index_information) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.normals"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.normals"
name: 'email_1'
background: true
safe: null
]
done()
, 1000
it 'adds a schema with custom indexes', (done) ->
Awesome = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
Awesome.plugin any_index, [
{ keys: { 'data.<KEY>atever<KEY>_you<KEY>_want': 1 }, options: { unique: true, sparse: true } }
{ keys: { 'data.<KEY>': 1, 'data<KEY>.second_key': 1 }, options: { unique: true } }
]
@connection.model 'Awesome', Awesome
setTimeout () =>
@db.indexInformation 'awesomes', {full:true}, (err, index_information) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { '<KEY>': 1, 'data.<KEY>key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
]
done()
, 1000
it "adds a schema with different custom indexes, asserts that mongoose doesn't drop old indexes", (done) ->
Awesome = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
Awesome.plugin any_index, [
{ keys: { 'data<KEY>.something<KEY>_different': 1 }, options: { unique: true, sparse: true } }
]
@connection.model 'Awesome', Awesome
async.waterfall [
(cb_wf) => setTimeout cb_wf, 1000
(cb_wf) => @db.indexInformation 'awesomes', {full:true}, cb_wf
(index_information, cb_wf) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { '<KEY>you<KEY>_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
,
v: 1
key: { '<KEY>different': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.something_different_1'
sparse: true
background: true
safe: null
]
@connection.models.Awesome.fullEnsureIndexes cb_wf
(cb_wf) => setTimeout cb_wf, 1000
(cb_wf) => @db.indexInformation 'awesomes', {full:true}, cb_wf
(index_information, cb_wf) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
,
v: 1
key: { 'data.something_different': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.something_different_1'
sparse: true
background: true
safe: null
]
cb_wf()
], done
| true | assert = require 'assert'
async = require 'async'
_ = require 'underscore'
debug = require('debug') 'mongoose-any-index:test/test.coffee'
mongoose = require 'mongoose'
{Db,Server} = require 'mongodb'
mongoose = require 'mongoose'
Schema = mongoose.Schema
util = require 'util'
any_index = require '../index'
MONGO_TEST_DB = 'test-any-index'
MONGO_TEST_IP = process.env.MONGO_TEST_IP or '127.0.0.1'
MONGO_TEST_PORT = process.env.MONGO_TEST_PORT or 27017
describe 'mongoose-any-index', ->
before (done) ->
debug "BEGIN #{__filename}"
db = new Db(MONGO_TEST_DB, new Server(MONGO_TEST_IP, MONGO_TEST_PORT), {w:1})
db.open (err) => db.dropDatabase (err) =>
@db = new Db(MONGO_TEST_DB, new Server(MONGO_TEST_IP, MONGO_TEST_PORT), {w:1})
@db.open done
beforeEach () ->
@connection = mongoose.createConnection MONGO_TEST_IP, MONGO_TEST_DB, MONGO_TEST_PORT
it 'adds a schema with normal mongoose indexes', (done) ->
Normal = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
@connection.model 'Normal', Normal
setTimeout () =>
@db.indexInformation 'normals', {full:true}, (err, index_information) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.normals"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.normals"
name: 'email_1'
background: true
safe: null
]
done()
, 1000
it 'adds a schema with custom indexes', (done) ->
Awesome = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
Awesome.plugin any_index, [
{ keys: { 'data.PI:KEY:<KEY>END_PIateverPI:KEY:<KEY>END_PI_youPI:KEY:<KEY>END_PI_want': 1 }, options: { unique: true, sparse: true } }
{ keys: { 'data.PI:KEY:<KEY>END_PI': 1, 'dataPI:KEY:<KEY>END_PI.second_key': 1 }, options: { unique: true } }
]
@connection.model 'Awesome', Awesome
setTimeout () =>
@db.indexInformation 'awesomes', {full:true}, (err, index_information) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'PI:KEY:<KEY>END_PI': 1, 'data.PI:KEY:<KEY>END_PIkey': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
]
done()
, 1000
it "adds a schema with different custom indexes, asserts that mongoose doesn't drop old indexes", (done) ->
Awesome = new Schema
email: { type: String, index: true, unique: true, required: true }
tags: [{type: String}]
data: { type: Schema.Types.Mixed }
Awesome.plugin any_index, [
{ keys: { 'dataPI:KEY:<KEY>END_PI.somethingPI:KEY:<KEY>END_PI_different': 1 }, options: { unique: true, sparse: true } }
]
@connection.model 'Awesome', Awesome
async.waterfall [
(cb_wf) => setTimeout cb_wf, 1000
(cb_wf) => @db.indexInformation 'awesomes', {full:true}, cb_wf
(index_information, cb_wf) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'PI:KEY:<KEY>END_PIyouPI:KEY:<KEY>END_PI_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
,
v: 1
key: { 'PI:KEY:<KEY>END_PIdifferent': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.something_different_1'
sparse: true
background: true
safe: null
]
@connection.models.Awesome.fullEnsureIndexes cb_wf
(cb_wf) => setTimeout cb_wf, 1000
(cb_wf) => @db.indexInformation 'awesomes', {full:true}, cb_wf
(index_information, cb_wf) =>
debug util.inspect(index_information)
assert.deepEqual index_information, [
v: 1
key: { _id: 1 }
ns: "#{MONGO_TEST_DB}.awesomes"
name: '_id_'
,
v: 1
key: { email: 1 }
unique: true
ns: "#{MONGO_TEST_DB}.awesomes"
name: 'email_1'
background: true
safe: null
,
v: 1
key: { 'data.whatever_you_want': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.whatever_you_want_1'
sparse: true
background: true
safe: null
,
v: 1
unique: true
key: { 'data.something_else': 1, 'data.second_key': 1 }
name: 'data.something_else_1_data.second_key_1'
ns: 'test-any-index.awesomes'
background: true
safe: null
,
v: 1
key: { 'data.something_different': 1 }
unique: true
ns: 'test-any-index.awesomes'
name: 'data.something_different_1'
sparse: true
background: true
safe: null
]
cb_wf()
], done
|
[
{
"context": "###\n\t(c) 2016 Julian Gonggrijp\n###\n\ndefine [\n\t'jquery'\n\t'view/home'\n], ($, HomeV",
"end": 30,
"score": 0.9998794794082642,
"start": 14,
"tag": "NAME",
"value": "Julian Gonggrijp"
}
] | client/script/view/home_test.coffee | NBOCampbellToets/CampbellSoup | 0 | ###
(c) 2016 Julian Gonggrijp
###
define [
'jquery'
'view/home'
], ($, HomeView) ->
'use strict'
# $ = require 'jquery'
# HomeView = require 'view/home'
describe 'HomeView', ->
beforeEach ->
setFixtures $ '<main>'
@home = new HomeView()
it 'renders a title and some intro text', ->
@home.render()
main = $ 'main'
expect(main.children()).toHaveLength 2
expect(main).toContainElement 'h1'
expect(main).toContainElement 'p'
expect(main.children 'h1').toContainText 'CampbellSoup'
expect(main.children 'p').toContainText 'Welcome'
| 92541 | ###
(c) 2016 <NAME>
###
define [
'jquery'
'view/home'
], ($, HomeView) ->
'use strict'
# $ = require 'jquery'
# HomeView = require 'view/home'
describe 'HomeView', ->
beforeEach ->
setFixtures $ '<main>'
@home = new HomeView()
it 'renders a title and some intro text', ->
@home.render()
main = $ 'main'
expect(main.children()).toHaveLength 2
expect(main).toContainElement 'h1'
expect(main).toContainElement 'p'
expect(main.children 'h1').toContainText 'CampbellSoup'
expect(main.children 'p').toContainText 'Welcome'
| true | ###
(c) 2016 PI:NAME:<NAME>END_PI
###
define [
'jquery'
'view/home'
], ($, HomeView) ->
'use strict'
# $ = require 'jquery'
# HomeView = require 'view/home'
describe 'HomeView', ->
beforeEach ->
setFixtures $ '<main>'
@home = new HomeView()
it 'renders a title and some intro text', ->
@home.render()
main = $ 'main'
expect(main.children()).toHaveLength 2
expect(main).toContainElement 'h1'
expect(main).toContainElement 'p'
expect(main.children 'h1').toContainText 'CampbellSoup'
expect(main.children 'p').toContainText 'Welcome'
|
[
{
"context": "IpVerifier\n\n assert.isTrue verifier.ipIsValid(\"192.30.252.1\")\n assert.isTrue verifier.ipIsValid(\"192.30.25",
"end": 393,
"score": 0.9996862411499023,
"start": 381,
"tag": "IP_ADDRESS",
"value": "192.30.252.1"
},
{
"context": ".30.252.1\")\n assert.isTrue ... | test/models/verifiers_test.coffee | pulibrary/hubot-deploy | 0 | VCR = require "ys-vcr"
Path = require('path')
Verifiers = require(Path.join(__dirname, "..", "..", "src", "models", "verifiers"))
describe "GitHubWebHookIpVerifier", () ->
afterEach () ->
delete process.env.HUBOT_DEPLOY_GITHUB_SUBNETS
it "verifies correct ip addresses", () ->
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isTrue verifier.ipIsValid("192.30.252.1")
assert.isTrue verifier.ipIsValid("192.30.253.1")
assert.isTrue verifier.ipIsValid("192.30.254.1")
assert.isTrue verifier.ipIsValid("192.30.255.1")
it "rejects incorrect ip addresses", () ->
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isFalse verifier.ipIsValid("192.30.250.1")
assert.isFalse verifier.ipIsValid("192.30.251.1")
assert.isFalse verifier.ipIsValid("192.168.1.1")
assert.isFalse verifier.ipIsValid("127.0.0.1")
it "verifies correct ip addresses with custom subnets", () ->
process.env.HUBOT_DEPLOY_GITHUB_SUBNETS = '207.97.227.0/22,198.41.190.0/22'
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isTrue verifier.ipIsValid("207.97.224.1")
assert.isTrue verifier.ipIsValid("198.41.188.1")
assert.isFalse verifier.ipIsValid("192.30.252.1")
assert.isFalse verifier.ipIsValid("207.97.228.1")
assert.isFalse verifier.ipIsValid("198.41.194.1")
assert.isFalse verifier.ipIsValid("192.168.1.1")
assert.isFalse verifier.ipIsValid("127.0.0.1")
describe "ApiTokenVerifier", () ->
it "returns false when the GitHub token is invalid", (done) ->
VCR.play "/user-invalid-auth"
verifier = new Verifiers.ApiTokenVerifier("123456789")
verifier.valid (result) ->
assert.isFalse result
done()
it "returns false when the GitHub token has incorrect scopes", (done) ->
VCR.play "/user-invalid-scopes"
verifier = new Verifiers.ApiTokenVerifier("123456789")
verifier.valid (result) ->
assert.isFalse result
done()
it "tells you when your provided GitHub token is valid", (done) ->
VCR.play "/user-valid"
verifier = new Verifiers.ApiTokenVerifier("123456789")
verifier.valid (result) ->
assert.isTrue result
done()
| 41151 | VCR = require "ys-vcr"
Path = require('path')
Verifiers = require(Path.join(__dirname, "..", "..", "src", "models", "verifiers"))
describe "GitHubWebHookIpVerifier", () ->
afterEach () ->
delete process.env.HUBOT_DEPLOY_GITHUB_SUBNETS
it "verifies correct ip addresses", () ->
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isTrue verifier.ipIsValid("192.168.3.11")
assert.isTrue verifier.ipIsValid("172.16.31.10")
assert.isTrue verifier.ipIsValid("192.168.3.11")
assert.isTrue verifier.ipIsValid("172.16.17.32")
it "rejects incorrect ip addresses", () ->
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isFalse verifier.ipIsValid("172.16.17.32")
assert.isFalse verifier.ipIsValid("172.16.31.10")
assert.isFalse verifier.ipIsValid("192.168.1.1")
assert.isFalse verifier.ipIsValid("127.0.0.1")
it "verifies correct ip addresses with custom subnets", () ->
process.env.HUBOT_DEPLOY_GITHUB_SUBNETS = '172.16.17.32/22,172.16.58.3/22'
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isTrue verifier.ipIsValid("172.16.17.32")
assert.isTrue verifier.ipIsValid("192.168.127.12")
assert.isFalse verifier.ipIsValid("192.168.3.11")
assert.isFalse verifier.ipIsValid("172.16.58.3")
assert.isFalse verifier.ipIsValid("172.16.58.3")
assert.isFalse verifier.ipIsValid("192.168.1.1")
assert.isFalse verifier.ipIsValid("1172.16.31.10")
describe "ApiTokenVerifier", () ->
it "returns false when the GitHub token is invalid", (done) ->
VCR.play "/user-invalid-auth"
verifier = new Verifiers.ApiTokenVerifier("<PASSWORD>")
verifier.valid (result) ->
assert.isFalse result
done()
it "returns false when the GitHub token has incorrect scopes", (done) ->
VCR.play "/user-invalid-scopes"
verifier = new Verifiers.ApiTokenVerifier("<PASSWORD>")
verifier.valid (result) ->
assert.isFalse result
done()
it "tells you when your provided GitHub token is valid", (done) ->
VCR.play "/user-valid"
verifier = new Verifiers.ApiTokenVerifier("<PASSWORD>")
verifier.valid (result) ->
assert.isTrue result
done()
| true | VCR = require "ys-vcr"
Path = require('path')
Verifiers = require(Path.join(__dirname, "..", "..", "src", "models", "verifiers"))
describe "GitHubWebHookIpVerifier", () ->
afterEach () ->
delete process.env.HUBOT_DEPLOY_GITHUB_SUBNETS
it "verifies correct ip addresses", () ->
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isTrue verifier.ipIsValid("PI:IP_ADDRESS:192.168.3.11END_PI")
assert.isTrue verifier.ipIsValid("PI:IP_ADDRESS:172.16.31.10END_PI")
assert.isTrue verifier.ipIsValid("PI:IP_ADDRESS:192.168.3.11END_PI")
assert.isTrue verifier.ipIsValid("PI:IP_ADDRESS:172.16.17.32END_PI")
it "rejects incorrect ip addresses", () ->
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isFalse verifier.ipIsValid("PI:IP_ADDRESS:172.16.17.32END_PI")
assert.isFalse verifier.ipIsValid("PI:IP_ADDRESS:172.16.31.10END_PI")
assert.isFalse verifier.ipIsValid("192.168.1.1")
assert.isFalse verifier.ipIsValid("127.0.0.1")
it "verifies correct ip addresses with custom subnets", () ->
process.env.HUBOT_DEPLOY_GITHUB_SUBNETS = 'PI:IP_ADDRESS:172.16.17.32END_PI/22,PI:IP_ADDRESS:172.16.58.3END_PI/22'
verifier = new Verifiers.GitHubWebHookIpVerifier
assert.isTrue verifier.ipIsValid("PI:IP_ADDRESS:172.16.17.32END_PI")
assert.isTrue verifier.ipIsValid("PI:IP_ADDRESS:192.168.127.12END_PI")
assert.isFalse verifier.ipIsValid("PI:IP_ADDRESS:192.168.3.11END_PI")
assert.isFalse verifier.ipIsValid("PI:IP_ADDRESS:172.16.58.3END_PI")
assert.isFalse verifier.ipIsValid("PI:IP_ADDRESS:172.16.58.3END_PI")
assert.isFalse verifier.ipIsValid("192.168.1.1")
assert.isFalse verifier.ipIsValid("1PI:IP_ADDRESS:172.16.31.10END_PI")
describe "ApiTokenVerifier", () ->
it "returns false when the GitHub token is invalid", (done) ->
VCR.play "/user-invalid-auth"
verifier = new Verifiers.ApiTokenVerifier("PI:PASSWORD:<PASSWORD>END_PI")
verifier.valid (result) ->
assert.isFalse result
done()
it "returns false when the GitHub token has incorrect scopes", (done) ->
VCR.play "/user-invalid-scopes"
verifier = new Verifiers.ApiTokenVerifier("PI:PASSWORD:<PASSWORD>END_PI")
verifier.valid (result) ->
assert.isFalse result
done()
it "tells you when your provided GitHub token is valid", (done) ->
VCR.play "/user-valid"
verifier = new Verifiers.ApiTokenVerifier("PI:PASSWORD:<PASSWORD>END_PI")
verifier.valid (result) ->
assert.isTrue result
done()
|
[
{
"context": "{GCM} = require 'gcm'\n\napiKey = 'fill-in-your-api-key'\ngcm = new GCM apiKey\n\nmessage =\n registration_i",
"end": 53,
"score": 0.9886151552200317,
"start": 33,
"tag": "KEY",
"value": "fill-in-your-api-key"
}
] | sender.coffee | kaosf/nodejs-gcm | 0 | {GCM} = require 'gcm'
apiKey = 'fill-in-your-api-key'
gcm = new GCM apiKey
message =
registration_id: 'fill-in-your-registration-id'
collapse_key: 'Collapse key'
'data.key1': 'value1'
'data.key2': 'value2'
gcm.send message, (err, messageId) ->
if err
console.log "Something has gone wrong!"
else
console.log "Sent with message ID: ", messageId
| 142877 | {GCM} = require 'gcm'
apiKey = '<KEY>'
gcm = new GCM apiKey
message =
registration_id: 'fill-in-your-registration-id'
collapse_key: 'Collapse key'
'data.key1': 'value1'
'data.key2': 'value2'
gcm.send message, (err, messageId) ->
if err
console.log "Something has gone wrong!"
else
console.log "Sent with message ID: ", messageId
| true | {GCM} = require 'gcm'
apiKey = 'PI:KEY:<KEY>END_PI'
gcm = new GCM apiKey
message =
registration_id: 'fill-in-your-registration-id'
collapse_key: 'Collapse key'
'data.key1': 'value1'
'data.key2': 'value2'
gcm.send message, (err, messageId) ->
if err
console.log "Something has gone wrong!"
else
console.log "Sent with message ID: ", messageId
|
[
{
"context": "\r\n @class bkcore.OrientationController\r\n @author Thibaut 'BKcore' Despoulain <http://bkcore.com>\r\n###\r\ncla",
"end": 132,
"score": 0.9998703002929688,
"start": 125,
"tag": "NAME",
"value": "Thibaut"
},
{
"context": ".OrientationController\r\n @author Thibaut '... | bkcore.coffee/controllers/OrientationController.coffee | slithe-r-io/slithe-r-io.github.io | 0 | ###
OrientationController (Orientation + buttons) for touch devices
@class bkcore.OrientationController
@author Thibaut 'BKcore' Despoulain <http://bkcore.com>
###
class OrientationController
@isCompatible: ->
return ('DeviceOrientationEvent' of window)
###
Creates a new OrientationController
@param dom DOMElement The element that will listen to touch events
@param registerTouch bool Enable touch detection
@param touchCallback function Callback for touches
###
constructor: (@dom, @registerTouch=true, @touchCallback=null) ->
@active = true
@alpha = 0.0
@beta = 0.0
@gamma = 0.0
@dalpha = null
@dbeta = null
@dgamma = null
@touches = null
window.addEventListener('deviceorientation', ((e)=> @orientationChange(e)), false)
if @registerTouch
@dom.addEventListener('touchstart', ((e)=> @touchStart(e)), false)
@dom.addEventListener('touchend', ((e)=> @touchEnd(e)), false)
###
@private
###
orientationChange: (event) ->
return if not @active
if(@dalpha == null)
console.log "calbrate", event.beta
@dalpha = event.alpha
@dbeta = event.beta
@dgamma = event.gamma
@alpha = event.alpha - @dalpha
@beta = event.beta - @dbeta
@gamma = event.gamma - @dgamma
false
###
@private
###
touchStart: (event) ->
return if not @active
for touch in event.changedTouches
@touchCallback?(on, touch, event)
@touches = event.touches
false
###
@private
###
touchEnd: (event) ->
return if not @active
for touch in event.changedTouches
@touchCallback?(on, touch, event)
@touches = event.touches
false
exports = exports ? @
exports.bkcore ||= {}
exports.bkcore.controllers ||= {}
exports.bkcore.controllers.OrientationController = OrientationController | 210342 | ###
OrientationController (Orientation + buttons) for touch devices
@class bkcore.OrientationController
@author <NAME> 'BKcore' <NAME> <http://bkcore.com>
###
class OrientationController
@isCompatible: ->
return ('DeviceOrientationEvent' of window)
###
Creates a new OrientationController
@param dom DOMElement The element that will listen to touch events
@param registerTouch bool Enable touch detection
@param touchCallback function Callback for touches
###
constructor: (@dom, @registerTouch=true, @touchCallback=null) ->
@active = true
@alpha = 0.0
@beta = 0.0
@gamma = 0.0
@dalpha = null
@dbeta = null
@dgamma = null
@touches = null
window.addEventListener('deviceorientation', ((e)=> @orientationChange(e)), false)
if @registerTouch
@dom.addEventListener('touchstart', ((e)=> @touchStart(e)), false)
@dom.addEventListener('touchend', ((e)=> @touchEnd(e)), false)
###
@private
###
orientationChange: (event) ->
return if not @active
if(@dalpha == null)
console.log "calbrate", event.beta
@dalpha = event.alpha
@dbeta = event.beta
@dgamma = event.gamma
@alpha = event.alpha - @dalpha
@beta = event.beta - @dbeta
@gamma = event.gamma - @dgamma
false
###
@private
###
touchStart: (event) ->
return if not @active
for touch in event.changedTouches
@touchCallback?(on, touch, event)
@touches = event.touches
false
###
@private
###
touchEnd: (event) ->
return if not @active
for touch in event.changedTouches
@touchCallback?(on, touch, event)
@touches = event.touches
false
exports = exports ? @
exports.bkcore ||= {}
exports.bkcore.controllers ||= {}
exports.bkcore.controllers.OrientationController = OrientationController | true | ###
OrientationController (Orientation + buttons) for touch devices
@class bkcore.OrientationController
@author PI:NAME:<NAME>END_PI 'BKcore' PI:NAME:<NAME>END_PI <http://bkcore.com>
###
class OrientationController
@isCompatible: ->
return ('DeviceOrientationEvent' of window)
###
Creates a new OrientationController
@param dom DOMElement The element that will listen to touch events
@param registerTouch bool Enable touch detection
@param touchCallback function Callback for touches
###
constructor: (@dom, @registerTouch=true, @touchCallback=null) ->
@active = true
@alpha = 0.0
@beta = 0.0
@gamma = 0.0
@dalpha = null
@dbeta = null
@dgamma = null
@touches = null
window.addEventListener('deviceorientation', ((e)=> @orientationChange(e)), false)
if @registerTouch
@dom.addEventListener('touchstart', ((e)=> @touchStart(e)), false)
@dom.addEventListener('touchend', ((e)=> @touchEnd(e)), false)
###
@private
###
orientationChange: (event) ->
return if not @active
if(@dalpha == null)
console.log "calbrate", event.beta
@dalpha = event.alpha
@dbeta = event.beta
@dgamma = event.gamma
@alpha = event.alpha - @dalpha
@beta = event.beta - @dbeta
@gamma = event.gamma - @dgamma
false
###
@private
###
touchStart: (event) ->
return if not @active
for touch in event.changedTouches
@touchCallback?(on, touch, event)
@touches = event.touches
false
###
@private
###
touchEnd: (event) ->
return if not @active
for touch in event.changedTouches
@touchCallback?(on, touch, event)
@touches = event.touches
false
exports = exports ? @
exports.bkcore ||= {}
exports.bkcore.controllers ||= {}
exports.bkcore.controllers.OrientationController = OrientationController |
[
{
"context": " ->\n roundNumber = roundNumber or 0\n key = \"sma#{range}\"\n d_key = \"smad#{range}\"\n items.forEach (ite",
"end": 788,
"score": 0.9866776466369629,
"start": 776,
"tag": "KEY",
"value": "sma#{range}\""
},
{
"context": "dNumber or 0\n key = \"sma#{range... | coffee/lib/calc.coffee | yugn27/ohlc-node | 1 | Big = require('../node_modules/big.js/big.min.js')
_ = require '../node_modules/lodash/lodash.min.js'
module.exports = calc =
sum:(arr)->
initialValue = Big(0)
reducer = (result, current, i, arr)->
return result.plus(current)
res = arr.reduce(reducer, initialValue)
return parseFloat(res)
sumBy:(arr,key)->
newArr = _.map(arr,key)
return calc.sum(newArr)
mean:(arr)->
sum = calc.sum(arr)
res = Big(sum).div(arr.length)
return parseFloat(res)
meanBy: (arr, key)->
newArr = _.map(arr,key)
return calc.mean(newArr)
changeIn: (base,target)->
res = Big(target).minus(base).div(base).times(100).round(2)
return parseFloat(res)
addSma: (range,items,roundNumber) ->
roundNumber = roundNumber or 0
key = "sma#{range}"
d_key = "smad#{range}"
items.forEach (item,i,arr)->
if i < range - 1
item[key] = null
item[d_key] = null
else
refItems = arr[i-(range-1)..i]
sma = calc.meanBy(refItems,'Close')
item[key] = parseFloat Big(sma).round(roundNumber)
item[d_key] = calc.changeIn(sma,item.Close)
return items
addVwma: (range,items,roundNumber) ->
roundNumber = roundNumber or 0
key = "vwma#{range}"
d_key = "vwmad#{range}"
items.forEach (item,i,arr)->
if i < range - 1
item[key] = null
item[d_key] = null
else
refItems = arr[i-(range-1)..i]
sumPrice = calc.sumBy refItems, (o)-> o.Close * o.Volume
sumVolume = calc.sumBy(refItems,'Volume')
vwma = Big(sumPrice).div(sumVolume)
item[key] = parseFloat vwma.round(roundNumber)
item[d_key] = calc.changeIn(parseFloat(vwma),item.Close)
return items
| 202916 | Big = require('../node_modules/big.js/big.min.js')
_ = require '../node_modules/lodash/lodash.min.js'
module.exports = calc =
sum:(arr)->
initialValue = Big(0)
reducer = (result, current, i, arr)->
return result.plus(current)
res = arr.reduce(reducer, initialValue)
return parseFloat(res)
sumBy:(arr,key)->
newArr = _.map(arr,key)
return calc.sum(newArr)
mean:(arr)->
sum = calc.sum(arr)
res = Big(sum).div(arr.length)
return parseFloat(res)
meanBy: (arr, key)->
newArr = _.map(arr,key)
return calc.mean(newArr)
changeIn: (base,target)->
res = Big(target).minus(base).div(base).times(100).round(2)
return parseFloat(res)
addSma: (range,items,roundNumber) ->
roundNumber = roundNumber or 0
key = "<KEY>
d_key = "<KEY>
items.forEach (item,i,arr)->
if i < range - 1
item[key] = null
item[d_key] = null
else
refItems = arr[i-(range-1)..i]
sma = calc.meanBy(refItems,'Close')
item[key] = parseFloat Big(sma).round(roundNumber)
item[d_key] = calc.changeIn(sma,item.Close)
return items
addVwma: (range,items,roundNumber) ->
roundNumber = roundNumber or 0
key = "<KEY>
d_key = "<KEY>
items.forEach (item,i,arr)->
if i < range - 1
item[key] = null
item[d_key] = null
else
refItems = arr[i-(range-1)..i]
sumPrice = calc.sumBy refItems, (o)-> o.Close * o.Volume
sumVolume = calc.sumBy(refItems,'Volume')
vwma = Big(sumPrice).div(sumVolume)
item[key] = parseFloat vwma.round(roundNumber)
item[d_key] = calc.changeIn(parseFloat(vwma),item.Close)
return items
| true | Big = require('../node_modules/big.js/big.min.js')
_ = require '../node_modules/lodash/lodash.min.js'
module.exports = calc =
sum:(arr)->
initialValue = Big(0)
reducer = (result, current, i, arr)->
return result.plus(current)
res = arr.reduce(reducer, initialValue)
return parseFloat(res)
sumBy:(arr,key)->
newArr = _.map(arr,key)
return calc.sum(newArr)
mean:(arr)->
sum = calc.sum(arr)
res = Big(sum).div(arr.length)
return parseFloat(res)
meanBy: (arr, key)->
newArr = _.map(arr,key)
return calc.mean(newArr)
changeIn: (base,target)->
res = Big(target).minus(base).div(base).times(100).round(2)
return parseFloat(res)
addSma: (range,items,roundNumber) ->
roundNumber = roundNumber or 0
key = "PI:KEY:<KEY>END_PI
d_key = "PI:KEY:<KEY>END_PI
items.forEach (item,i,arr)->
if i < range - 1
item[key] = null
item[d_key] = null
else
refItems = arr[i-(range-1)..i]
sma = calc.meanBy(refItems,'Close')
item[key] = parseFloat Big(sma).round(roundNumber)
item[d_key] = calc.changeIn(sma,item.Close)
return items
addVwma: (range,items,roundNumber) ->
roundNumber = roundNumber or 0
key = "PI:KEY:<KEY>END_PI
d_key = "PI:KEY:<KEY>END_PI
items.forEach (item,i,arr)->
if i < range - 1
item[key] = null
item[d_key] = null
else
refItems = arr[i-(range-1)..i]
sumPrice = calc.sumBy refItems, (o)-> o.Close * o.Volume
sumVolume = calc.sumBy(refItems,'Volume')
vwma = Big(sumPrice).div(sumVolume)
item[key] = parseFloat vwma.round(roundNumber)
item[d_key] = calc.changeIn(parseFloat(vwma),item.Close)
return items
|
[
{
"context": "###\njQuery.Turbolinks ~ https://github.com/kossnocorp/jquery.turbolinks\njQuery plugin for drop-in fix b",
"end": 53,
"score": 0.9960035085678101,
"start": 43,
"tag": "USERNAME",
"value": "kossnocorp"
},
{
"context": "urbolinks\n\nThe MIT License\nCopyright (c) 2012-20... | vendor/helthe/turbolinks/Resources/public/coffee/jquery.turbolinks.coffee | dev-inf/shopping-laravel | 0 | ###
jQuery.Turbolinks ~ https://github.com/kossnocorp/jquery.turbolinks
jQuery plugin for drop-in fix binded events problem caused by Turbolinks
The MIT License
Copyright (c) 2012-2013 Sasha Koss & Rico Sta. Cruz
###
$ = window.jQuery or require?('jquery')
$document = $(document)
$.turbo =
version: '2.0.2'
isReady: false
# Hook onto the events that Turbolinks triggers.
use: (load, fetch) ->
$document
.off('.turbo')
.on("#{load}.turbo", @onLoad)
.on("#{fetch}.turbo", @onFetch)
addCallback: (callback) ->
if $.turbo.isReady
callback($)
else
$document.on 'turbo:ready', -> callback($)
onLoad: ->
$.turbo.isReady = true
$document.trigger('turbo:ready')
onFetch: ->
$.turbo.isReady = false
# Registers jQuery.Turbolinks by monkey-patching jQuery's
# `ready` handler. (Internal)
#
# [1] Trigger the stored `ready` events on first load.
# [2] Override `$(function)` and `$(document).ready(function)` by
# registering callbacks under a new event called `turbo:ready`.
#
register: ->
$(@onLoad) #[1]
$.fn.ready = @addCallback #[2]
# Use with Turbolinks.
$.turbo.register()
$.turbo.use('page:load', 'page:fetch') | 25443 | ###
jQuery.Turbolinks ~ https://github.com/kossnocorp/jquery.turbolinks
jQuery plugin for drop-in fix binded events problem caused by Turbolinks
The MIT License
Copyright (c) 2012-2013 <NAME> & <NAME>
###
$ = window.jQuery or require?('jquery')
$document = $(document)
$.turbo =
version: '2.0.2'
isReady: false
# Hook onto the events that Turbolinks triggers.
use: (load, fetch) ->
$document
.off('.turbo')
.on("#{load}.turbo", @onLoad)
.on("#{fetch}.turbo", @onFetch)
addCallback: (callback) ->
if $.turbo.isReady
callback($)
else
$document.on 'turbo:ready', -> callback($)
onLoad: ->
$.turbo.isReady = true
$document.trigger('turbo:ready')
onFetch: ->
$.turbo.isReady = false
# Registers jQuery.Turbolinks by monkey-patching jQuery's
# `ready` handler. (Internal)
#
# [1] Trigger the stored `ready` events on first load.
# [2] Override `$(function)` and `$(document).ready(function)` by
# registering callbacks under a new event called `turbo:ready`.
#
register: ->
$(@onLoad) #[1]
$.fn.ready = @addCallback #[2]
# Use with Turbolinks.
$.turbo.register()
$.turbo.use('page:load', 'page:fetch') | true | ###
jQuery.Turbolinks ~ https://github.com/kossnocorp/jquery.turbolinks
jQuery plugin for drop-in fix binded events problem caused by Turbolinks
The MIT License
Copyright (c) 2012-2013 PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI
###
$ = window.jQuery or require?('jquery')
$document = $(document)
$.turbo =
version: '2.0.2'
isReady: false
# Hook onto the events that Turbolinks triggers.
use: (load, fetch) ->
$document
.off('.turbo')
.on("#{load}.turbo", @onLoad)
.on("#{fetch}.turbo", @onFetch)
addCallback: (callback) ->
if $.turbo.isReady
callback($)
else
$document.on 'turbo:ready', -> callback($)
onLoad: ->
$.turbo.isReady = true
$document.trigger('turbo:ready')
onFetch: ->
$.turbo.isReady = false
# Registers jQuery.Turbolinks by monkey-patching jQuery's
# `ready` handler. (Internal)
#
# [1] Trigger the stored `ready` events on first load.
# [2] Override `$(function)` and `$(document).ready(function)` by
# registering callbacks under a new event called `turbo:ready`.
#
register: ->
$(@onLoad) #[1]
$.fn.ready = @addCallback #[2]
# Use with Turbolinks.
$.turbo.register()
$.turbo.use('page:load', 'page:fetch') |
[
{
"context": " cb(null, key)\n\n job = (next) =>\n key = @db.next(@id)\n @setJob(key, value, next)\n\n if cb t",
"end": 350,
"score": 0.5762012600898743,
"start": 343,
"tag": "KEY",
"value": "db.next"
}
] | src/domain_base.coffee | tarruda/archdb | 5 | {Emitter, ObjectType, typeOf} = require('./util')
BitArray = require('./bit_array')
{CursorError} = require('./errors')
class DomainBase
constructor: (@name, @queue, @uidGenerator) ->
ins: (value, cb) ->
key = undef
insCb = (err) =>
if err then return cb(err, null)
cb(null, key)
job = (next) =>
key = @db.next(@id)
@setJob(key, value, next)
if cb then @queue.add(insCb, job)
else @queue.add(null, job)
set: (key, value, cb) ->
job = (next) => @setJob(key, value, next)
@queue.add(cb, job)
del: (key, cb) ->
job = (next) => @delJob(key, next)
@queue.add(cb, job)
find: -> throw new Error('not implemented')
setJob: -> throw new Error('not implemented')
delJob: -> throw new Error('not implemented')
class CursorBase extends Emitter
constructor: (@queue, @query) ->
super()
@closed = false
@started = false
@err = null
@nextNodeCb = null
@thenCb = null
count: -> throw new Error('not implemented')
all: (cb) ->
rv =
total: 0
rows: []
rowCb = (row) =>
rv.rows.push(row)
if @hasNext() then @next()
endCb = (err) =>
if err then return cb(err, null)
rv.total = @count()
cb(null, rv)
@each(rowCb).then(endCb)
one: (cb) ->
rv = null
rowCb = (row) =>
rv = row
@close()
endCb = (err) =>
if err then return cb(err, null)
cb(null, rv)
@each(rowCb).then(endCb)
each: (cb) ->
jobCb = null
job = (cb) =>
jobCb = cb
@once('end', endCb)
@find(visitCb)
visitCb = (err, next, key, val) =>
@nextNodeCb = next
if err or not next then return @emit('end', err)
@fetchValue(key, val, fetchValueCb)
fetchValueCb = (err, row) =>
if err then return @emit('end', err)
cb.call(this, row)
endCb = (err) =>
if err then @err = err
# if (@hasNext()) @nextNodeCb(true)
@nextNodeCb = null
if @thenCb
@thenCb(err)
@thenCb = null
if jobCb
jobCb(err)
jobCb = null
if @closed
throw new CursorError('Cursor already closed')
if @started
throw new CursorError('Cursor already started')
@started = true
@queue.add(null, job)
return this
then: (cb) -> @thenCb = cb
hasNext: -> !!@nextNodeCb
next: ->
if not @hasNext()
throw new CursorError('No more rows')
@nextNodeCb()
close: ->
if @closed
return
@closed = true
@emit('end')
find: (cb) ->
if @query
if @query.$eq then return @findEq(cb)
if @query.$like then return @findLike(cb)
@findRange(cb)
findEq: (cb) ->
getCb = (err, obj) =>
if err then return cb(err, null, null, null)
cb(null, nextCb, @query.$eq, obj)
nextCb = => cb(null, null, null, null)
@fetchKey(@query.$eq, getCb)
findLike: (cb) ->
# 'like' queries are nothing but range queries where we derive
# the upper key from the '$like' parameter. That is, we find an upper
# key so that all keys within the resulting range 'start' with the
# '$like' parameter. It only makes sense for strings and arrays, eg:
# [1, 2, 3] is starts with [1, 2]
# 'ab' starts with 'abc'
gte = new BitArray(@query.$like); lte = gte.clone()
if (type = typeOf(@query.$like)) == ObjectType.Array
# to properly create the 'upper bound key' for array, we must
# insert the '1' before its terminator
lte.rewind(4)
lte.write(1, 1)
lte.write(0, 4)
else if (type == ObjectType.String)
lte.write(1, 1)
else
throw new Error('invalid object type for $like parameter')
if @query.$rev
return @findRangeDesc(gte, null, lte, null, cb)
@findRangeAsc(gte, null, lte, null, cb)
findRange: (cb) ->
if @query
gte = if @query.$gte then new BitArray(@query.$gte) else null
gt = if @query.$gt then new BitArray(@query.$gt) else null
lte = if @query.$lte then new BitArray(@query.$lte) else null
lt = if @query.$lt then new BitArray(@query.$lt) else null
if @query.$rev then return @findRangeDesc(gte, gt, lte, lt, cb)
@findRangeAsc(gte, gt, lte, lt, cb)
findRangeAsc: (gte, gt, lte, lt, cb) -> throw new Error('not implemented')
findRangeDesc: (gte, gt, lte, lt, cb) -> throw new Error('not implemented')
fetchKey: (ref, cb) -> throw new Error('not implemented')
fetchValue: (ref, cb) -> throw new Error('not implemented')
class DomainRow
constructor: (@key, @value, @ref) ->
exports.DomainBase = DomainBase
exports.CursorBase = CursorBase
exports.DomainRow = DomainRow
| 198738 | {Emitter, ObjectType, typeOf} = require('./util')
BitArray = require('./bit_array')
{CursorError} = require('./errors')
class DomainBase
constructor: (@name, @queue, @uidGenerator) ->
ins: (value, cb) ->
key = undef
insCb = (err) =>
if err then return cb(err, null)
cb(null, key)
job = (next) =>
key = @<KEY>(@id)
@setJob(key, value, next)
if cb then @queue.add(insCb, job)
else @queue.add(null, job)
set: (key, value, cb) ->
job = (next) => @setJob(key, value, next)
@queue.add(cb, job)
del: (key, cb) ->
job = (next) => @delJob(key, next)
@queue.add(cb, job)
find: -> throw new Error('not implemented')
setJob: -> throw new Error('not implemented')
delJob: -> throw new Error('not implemented')
class CursorBase extends Emitter
constructor: (@queue, @query) ->
super()
@closed = false
@started = false
@err = null
@nextNodeCb = null
@thenCb = null
count: -> throw new Error('not implemented')
all: (cb) ->
rv =
total: 0
rows: []
rowCb = (row) =>
rv.rows.push(row)
if @hasNext() then @next()
endCb = (err) =>
if err then return cb(err, null)
rv.total = @count()
cb(null, rv)
@each(rowCb).then(endCb)
one: (cb) ->
rv = null
rowCb = (row) =>
rv = row
@close()
endCb = (err) =>
if err then return cb(err, null)
cb(null, rv)
@each(rowCb).then(endCb)
each: (cb) ->
jobCb = null
job = (cb) =>
jobCb = cb
@once('end', endCb)
@find(visitCb)
visitCb = (err, next, key, val) =>
@nextNodeCb = next
if err or not next then return @emit('end', err)
@fetchValue(key, val, fetchValueCb)
fetchValueCb = (err, row) =>
if err then return @emit('end', err)
cb.call(this, row)
endCb = (err) =>
if err then @err = err
# if (@hasNext()) @nextNodeCb(true)
@nextNodeCb = null
if @thenCb
@thenCb(err)
@thenCb = null
if jobCb
jobCb(err)
jobCb = null
if @closed
throw new CursorError('Cursor already closed')
if @started
throw new CursorError('Cursor already started')
@started = true
@queue.add(null, job)
return this
then: (cb) -> @thenCb = cb
hasNext: -> !!@nextNodeCb
next: ->
if not @hasNext()
throw new CursorError('No more rows')
@nextNodeCb()
close: ->
if @closed
return
@closed = true
@emit('end')
find: (cb) ->
if @query
if @query.$eq then return @findEq(cb)
if @query.$like then return @findLike(cb)
@findRange(cb)
findEq: (cb) ->
getCb = (err, obj) =>
if err then return cb(err, null, null, null)
cb(null, nextCb, @query.$eq, obj)
nextCb = => cb(null, null, null, null)
@fetchKey(@query.$eq, getCb)
findLike: (cb) ->
# 'like' queries are nothing but range queries where we derive
# the upper key from the '$like' parameter. That is, we find an upper
# key so that all keys within the resulting range 'start' with the
# '$like' parameter. It only makes sense for strings and arrays, eg:
# [1, 2, 3] is starts with [1, 2]
# 'ab' starts with 'abc'
gte = new BitArray(@query.$like); lte = gte.clone()
if (type = typeOf(@query.$like)) == ObjectType.Array
# to properly create the 'upper bound key' for array, we must
# insert the '1' before its terminator
lte.rewind(4)
lte.write(1, 1)
lte.write(0, 4)
else if (type == ObjectType.String)
lte.write(1, 1)
else
throw new Error('invalid object type for $like parameter')
if @query.$rev
return @findRangeDesc(gte, null, lte, null, cb)
@findRangeAsc(gte, null, lte, null, cb)
findRange: (cb) ->
if @query
gte = if @query.$gte then new BitArray(@query.$gte) else null
gt = if @query.$gt then new BitArray(@query.$gt) else null
lte = if @query.$lte then new BitArray(@query.$lte) else null
lt = if @query.$lt then new BitArray(@query.$lt) else null
if @query.$rev then return @findRangeDesc(gte, gt, lte, lt, cb)
@findRangeAsc(gte, gt, lte, lt, cb)
findRangeAsc: (gte, gt, lte, lt, cb) -> throw new Error('not implemented')
findRangeDesc: (gte, gt, lte, lt, cb) -> throw new Error('not implemented')
fetchKey: (ref, cb) -> throw new Error('not implemented')
fetchValue: (ref, cb) -> throw new Error('not implemented')
class DomainRow
constructor: (@key, @value, @ref) ->
exports.DomainBase = DomainBase
exports.CursorBase = CursorBase
exports.DomainRow = DomainRow
| true | {Emitter, ObjectType, typeOf} = require('./util')
BitArray = require('./bit_array')
{CursorError} = require('./errors')
class DomainBase
constructor: (@name, @queue, @uidGenerator) ->
ins: (value, cb) ->
key = undef
insCb = (err) =>
if err then return cb(err, null)
cb(null, key)
job = (next) =>
key = @PI:KEY:<KEY>END_PI(@id)
@setJob(key, value, next)
if cb then @queue.add(insCb, job)
else @queue.add(null, job)
set: (key, value, cb) ->
job = (next) => @setJob(key, value, next)
@queue.add(cb, job)
del: (key, cb) ->
job = (next) => @delJob(key, next)
@queue.add(cb, job)
find: -> throw new Error('not implemented')
setJob: -> throw new Error('not implemented')
delJob: -> throw new Error('not implemented')
class CursorBase extends Emitter
constructor: (@queue, @query) ->
super()
@closed = false
@started = false
@err = null
@nextNodeCb = null
@thenCb = null
count: -> throw new Error('not implemented')
all: (cb) ->
rv =
total: 0
rows: []
rowCb = (row) =>
rv.rows.push(row)
if @hasNext() then @next()
endCb = (err) =>
if err then return cb(err, null)
rv.total = @count()
cb(null, rv)
@each(rowCb).then(endCb)
one: (cb) ->
rv = null
rowCb = (row) =>
rv = row
@close()
endCb = (err) =>
if err then return cb(err, null)
cb(null, rv)
@each(rowCb).then(endCb)
each: (cb) ->
jobCb = null
job = (cb) =>
jobCb = cb
@once('end', endCb)
@find(visitCb)
visitCb = (err, next, key, val) =>
@nextNodeCb = next
if err or not next then return @emit('end', err)
@fetchValue(key, val, fetchValueCb)
fetchValueCb = (err, row) =>
if err then return @emit('end', err)
cb.call(this, row)
endCb = (err) =>
if err then @err = err
# if (@hasNext()) @nextNodeCb(true)
@nextNodeCb = null
if @thenCb
@thenCb(err)
@thenCb = null
if jobCb
jobCb(err)
jobCb = null
if @closed
throw new CursorError('Cursor already closed')
if @started
throw new CursorError('Cursor already started')
@started = true
@queue.add(null, job)
return this
then: (cb) -> @thenCb = cb
hasNext: -> !!@nextNodeCb
next: ->
if not @hasNext()
throw new CursorError('No more rows')
@nextNodeCb()
close: ->
if @closed
return
@closed = true
@emit('end')
find: (cb) ->
if @query
if @query.$eq then return @findEq(cb)
if @query.$like then return @findLike(cb)
@findRange(cb)
findEq: (cb) ->
getCb = (err, obj) =>
if err then return cb(err, null, null, null)
cb(null, nextCb, @query.$eq, obj)
nextCb = => cb(null, null, null, null)
@fetchKey(@query.$eq, getCb)
findLike: (cb) ->
# 'like' queries are nothing but range queries where we derive
# the upper key from the '$like' parameter. That is, we find an upper
# key so that all keys within the resulting range 'start' with the
# '$like' parameter. It only makes sense for strings and arrays, eg:
# [1, 2, 3] is starts with [1, 2]
# 'ab' starts with 'abc'
gte = new BitArray(@query.$like); lte = gte.clone()
if (type = typeOf(@query.$like)) == ObjectType.Array
# to properly create the 'upper bound key' for array, we must
# insert the '1' before its terminator
lte.rewind(4)
lte.write(1, 1)
lte.write(0, 4)
else if (type == ObjectType.String)
lte.write(1, 1)
else
throw new Error('invalid object type for $like parameter')
if @query.$rev
return @findRangeDesc(gte, null, lte, null, cb)
@findRangeAsc(gte, null, lte, null, cb)
findRange: (cb) ->
if @query
gte = if @query.$gte then new BitArray(@query.$gte) else null
gt = if @query.$gt then new BitArray(@query.$gt) else null
lte = if @query.$lte then new BitArray(@query.$lte) else null
lt = if @query.$lt then new BitArray(@query.$lt) else null
if @query.$rev then return @findRangeDesc(gte, gt, lte, lt, cb)
@findRangeAsc(gte, gt, lte, lt, cb)
findRangeAsc: (gte, gt, lte, lt, cb) -> throw new Error('not implemented')
findRangeDesc: (gte, gt, lte, lt, cb) -> throw new Error('not implemented')
fetchKey: (ref, cb) -> throw new Error('not implemented')
fetchValue: (ref, cb) -> throw new Error('not implemented')
class DomainRow
constructor: (@key, @value, @ref) ->
exports.DomainBase = DomainBase
exports.CursorBase = CursorBase
exports.DomainRow = DomainRow
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999145269393921,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/profile-page/extra-tab.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 { span } from 'react-dom-factories'
el = React.createElement
export class ExtraTab extends React.PureComponent
render: =>
className = 'page-mode-link page-mode-link--profile-page'
if @props.page == @props.currentPage
className += ' page-mode-link--is-active'
span
className: className
span
className: 'fake-bold'
'data-content': osu.trans("users.show.extra.#{@props.page}.title")
osu.trans("users.show.extra.#{@props.page}.title")
span className: 'page-mode-link__stripe'
| 126243 | # 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 { span } from 'react-dom-factories'
el = React.createElement
export class ExtraTab extends React.PureComponent
render: =>
className = 'page-mode-link page-mode-link--profile-page'
if @props.page == @props.currentPage
className += ' page-mode-link--is-active'
span
className: className
span
className: 'fake-bold'
'data-content': osu.trans("users.show.extra.#{@props.page}.title")
osu.trans("users.show.extra.#{@props.page}.title")
span className: 'page-mode-link__stripe'
| 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 { span } from 'react-dom-factories'
el = React.createElement
export class ExtraTab extends React.PureComponent
render: =>
className = 'page-mode-link page-mode-link--profile-page'
if @props.page == @props.currentPage
className += ' page-mode-link--is-active'
span
className: className
span
className: 'fake-bold'
'data-content': osu.trans("users.show.extra.#{@props.page}.title")
osu.trans("users.show.extra.#{@props.page}.title")
span className: 'page-mode-link__stripe'
|
[
{
"context": " email: {prompt: 'Email'}\n password: {prompt: 'Password', hidden: true}\n .then (data) =>\n client = @c",
"end": 286,
"score": 0.9888911247253418,
"start": 278,
"tag": "PASSWORD",
"value": "Password"
}
] | lib/app/commands/auth.coffee | awesomebox/awesomebox | 1 | login_attempt_messages = [
"That doesn't seem right. Care to try again?"
"Hmmmm, still not right..."
"Why don't you go look up that password and come back later."
]
exports.login = ->
@_login_count ?= 0
@prompt
email: {prompt: 'Email'}
password: {prompt: 'Password', hidden: true}
.then (data) =>
client = @client(data)
client.me.get()
.then (user) =>
@login(user)
@log('')
@log "Welcome back! It's been way too long."
.catch (err) =>
if err.status_code is 401
if ++@_login_count is 3
@log('')
@error login_attempt_messages[@_login_count - 1]
return
@log('')
@error login_attempt_messages[@_login_count - 1]
@log('')
return exports.login.call(@)
throw err
exports.logout = ->
@logout()
@log "We're really sad to see you go. =-("
| 4971 | login_attempt_messages = [
"That doesn't seem right. Care to try again?"
"Hmmmm, still not right..."
"Why don't you go look up that password and come back later."
]
exports.login = ->
@_login_count ?= 0
@prompt
email: {prompt: 'Email'}
password: {prompt: '<PASSWORD>', hidden: true}
.then (data) =>
client = @client(data)
client.me.get()
.then (user) =>
@login(user)
@log('')
@log "Welcome back! It's been way too long."
.catch (err) =>
if err.status_code is 401
if ++@_login_count is 3
@log('')
@error login_attempt_messages[@_login_count - 1]
return
@log('')
@error login_attempt_messages[@_login_count - 1]
@log('')
return exports.login.call(@)
throw err
exports.logout = ->
@logout()
@log "We're really sad to see you go. =-("
| true | login_attempt_messages = [
"That doesn't seem right. Care to try again?"
"Hmmmm, still not right..."
"Why don't you go look up that password and come back later."
]
exports.login = ->
@_login_count ?= 0
@prompt
email: {prompt: 'Email'}
password: {prompt: 'PI:PASSWORD:<PASSWORD>END_PI', hidden: true}
.then (data) =>
client = @client(data)
client.me.get()
.then (user) =>
@login(user)
@log('')
@log "Welcome back! It's been way too long."
.catch (err) =>
if err.status_code is 401
if ++@_login_count is 3
@log('')
@error login_attempt_messages[@_login_count - 1]
return
@log('')
@error login_attempt_messages[@_login_count - 1]
@log('')
return exports.login.call(@)
throw err
exports.logout = ->
@logout()
@log "We're really sad to see you go. =-("
|
[
{
"context": " 'Niconico for Atom 0.0.0 / https://github.com/raccy/niconico'\n @liveHeartbeat = null\n\n destroy: -",
"end": 1206,
"score": 0.9993302822113037,
"start": 1201,
"tag": "USERNAME",
"value": "raccy"
},
{
"context": " formData =\n mail_tel: mail\n passwo... | lib/niconico-api.coffee | raccy/niconico | 0 | fs = require 'fs'
request = require 'request'
FileCookieStore = require 'tough-cookie-filestore'
cheerio = require 'cheerio'
# ニコニコ動画関係のAPI
module.exports =
class NiconicoApi
@URI:
top: 'http://www.nicovideo.jp/'
login: 'https://secure.nicovideo.jp/secure/login?site=niconico'
logout: 'https://secure.nicovideo.jp/secure/logout'
my:
top: 'http://www.nicovideo.jp/my/top'
community: 'http://www.nicovideo.jp/my/community'
channel: 'http://www.nicovideo.jp/my/channel'
live: 'http://www.nicovideo.jp/my/live'
mylist: 'http://www.nicovideo.jp/my/mylist'
live:
status: 'http://live.nicovideo.jp/api/getplayerstatus/{id}'
heartbeat: 'http://live.nicovideo.jp/api/heartbeat?v={id}'
constructor: (@cookieStoreFile) ->
# すでに存在しないとエラーになるらしい。けど、修正バージョンのブランチ使う。
# unless fs.existsSync(cookieStoreFile)
# fs.closeSync(fs.openSync(cookieStoreFile, 'w'))
console.log @cookieStoreFile
@requestJar = request.jar(new FileCookieStore(@cookieStoreFile))
@request = request.defaults
jar: @requestJar
followRedirect: false
headers:
'User-Agent':
'Niconico for Atom 0.0.0 / https://github.com/raccy/niconico'
@liveHeartbeat = null
destroy: ->
# なんかは破棄する物ある?
setCookieStoreFile: (@cookieStoreFile) ->
# TODO: 今は無理
# callback(err, response, body)
requestGet: (url, callback) ->
console.log ['Getリクエスト', url]
@request.get url, (err, response, body) ->
console.log ['Getレスポンス', err, response, body]
callback(err, response, body)
requestPost: (url, formData, callback) ->
console.log ['Postリクエスト', url, formData]
@request.post url, {form: formData}, (err, response, body) ->
console.log ['Postレスポンス', err, response, body]
callback err, response, body
# ログインする。
# ログインした情報をcallbackになげる。
# callback(err, data)
login: (mail, password, callback) ->
formData =
mail_tel: mail
password: password
@requestPost NiconicoApi.URI.login, formData, (err, response, body) ->
if err
callback err, null
else if response.statusCode == 302
if response.headers.location == 'http://www.nicovideo.jp/'
callback null, true
else
callback 'メールアドレスまたはパスワードが間違っています。', null
else
callback '不明なレスポンスが返されました。', null
# ログアウトする。
logout: (callback) ->
@request.get NiconicoApi.URI.logout, ->
callback()
# TODO
# トップをとる
# classback(err, {userId, userName})
getMyTop: (callback) ->
@request.get NiconicoApi.URI.my.top, (err, response, body) ->
if !err
data = {}
if response.statusCode == 200
myTop = cheerio.load body
data.userName = myTop('.profile h2').contents().text().
replace(/さんの$/, '')
data.userId = myTop('.accountNumber span').text()
callback(null, data)
else
callback(err, null)
# 登録しているチャンネル/コミュニティで放送中の番組一覧を出す。
getFavoritLiveList: ->
# 生放送番組の情報を取得する
getLiveStatus: (lv, callback) ->
url = NiconicoApi.URI.live.status.slice(0).replace('{id}', lv)
@request.get url, (err, response, body) =>
if err
callback(err, null)
else
liveStatus = cheerio.load(body)
if liveStatus('getplayerstatus').attr('status') == 'ok'
data = {}
data.stream = {}
data.stream.id = liveStatus('stream id').text()
data.stream.title = liveStatus('stream title').text()
data.stream.description = liveStatus('stream description').text()
data.stream.owner_id = liveStatus('stream owner_id').text()
data.stream.owner_name = liveStatus('stream owner_name').text()
data.stream.thumb_url = liveStatus('stream thumb_url').text()
# コメントサーバの情報
data.comment = {}
data.comment.addr = liveStatus('ms addr').text()
data.comment.port = liveStatus('ms port').text()
data.comment.thread = liveStatus('ms thread').text()
# RTMPサーバの情報
data.rtmp = {}
data.rtmp.url = liveStatus('rtmp url').text()
data.rtmp.ticket = liveStatus('rtmp ticket').text()
data.rtmp.contents = liveStatus('contents#main').text().
replace(/^rtmp:rtmp:\/\//, 'rtmp://')
@startLiveHeartbeat(data.stream.id)
callback(err, data)
else
callback(liveStatus('error code').text(), liveStatus)
getLiveHeratbeat: (lv, callback) ->
url = NiconicoApi.URI.live.heartbeat.slice(0).replace('{id}', lv)
@request.get url, (err, response, body) ->
if err
callback(err, null)
else
heartBeat = cheerio.load(body)
if heartBeat('heartbeat').attr('status') == 'ok'
data = {}
data.ticket = heartBeat('ticket').text()
data.watchCount = heartBeat('watchCount').text()
data.commentCount = heartBeat('commentCount').text()
data.waitTime = heartBeat('waitTime').text()
callback(null, data)
else
callback(heartBeat('error code'), null)
startLiveHeartbeat: (lv) ->
if lv
@liveHeartbeat = lv
@getLiveHeratbeat @liveHeartbeat, (err, data) =>
console.log 'ハートビートが叩かれたっす'
console.log data
if !err
setTimeout =>
@startLiveHeartbeat(@liveHeartbeat)
, 60 * 1000
stopLiveHeartbeat: ->
@liveHeartbeat = null
| 133158 | fs = require 'fs'
request = require 'request'
FileCookieStore = require 'tough-cookie-filestore'
cheerio = require 'cheerio'
# ニコニコ動画関係のAPI
module.exports =
class NiconicoApi
@URI:
top: 'http://www.nicovideo.jp/'
login: 'https://secure.nicovideo.jp/secure/login?site=niconico'
logout: 'https://secure.nicovideo.jp/secure/logout'
my:
top: 'http://www.nicovideo.jp/my/top'
community: 'http://www.nicovideo.jp/my/community'
channel: 'http://www.nicovideo.jp/my/channel'
live: 'http://www.nicovideo.jp/my/live'
mylist: 'http://www.nicovideo.jp/my/mylist'
live:
status: 'http://live.nicovideo.jp/api/getplayerstatus/{id}'
heartbeat: 'http://live.nicovideo.jp/api/heartbeat?v={id}'
constructor: (@cookieStoreFile) ->
# すでに存在しないとエラーになるらしい。けど、修正バージョンのブランチ使う。
# unless fs.existsSync(cookieStoreFile)
# fs.closeSync(fs.openSync(cookieStoreFile, 'w'))
console.log @cookieStoreFile
@requestJar = request.jar(new FileCookieStore(@cookieStoreFile))
@request = request.defaults
jar: @requestJar
followRedirect: false
headers:
'User-Agent':
'Niconico for Atom 0.0.0 / https://github.com/raccy/niconico'
@liveHeartbeat = null
destroy: ->
# なんかは破棄する物ある?
setCookieStoreFile: (@cookieStoreFile) ->
# TODO: 今は無理
# callback(err, response, body)
requestGet: (url, callback) ->
console.log ['Getリクエスト', url]
@request.get url, (err, response, body) ->
console.log ['Getレスポンス', err, response, body]
callback(err, response, body)
requestPost: (url, formData, callback) ->
console.log ['Postリクエスト', url, formData]
@request.post url, {form: formData}, (err, response, body) ->
console.log ['Postレスポンス', err, response, body]
callback err, response, body
# ログインする。
# ログインした情報をcallbackになげる。
# callback(err, data)
login: (mail, password, callback) ->
formData =
mail_tel: mail
password: <PASSWORD>
@requestPost NiconicoApi.URI.login, formData, (err, response, body) ->
if err
callback err, null
else if response.statusCode == 302
if response.headers.location == 'http://www.nicovideo.jp/'
callback null, true
else
callback 'メールアドレスまたはパスワードが間違っています。', null
else
callback '不明なレスポンスが返されました。', null
# ログアウトする。
logout: (callback) ->
@request.get NiconicoApi.URI.logout, ->
callback()
# TODO
# トップをとる
# classback(err, {userId, userName})
getMyTop: (callback) ->
@request.get NiconicoApi.URI.my.top, (err, response, body) ->
if !err
data = {}
if response.statusCode == 200
myTop = cheerio.load body
data.userName = myTop('.profile h2').contents().text().
replace(/さんの$/, '')
data.userId = myTop('.accountNumber span').text()
callback(null, data)
else
callback(err, null)
# 登録しているチャンネル/コミュニティで放送中の番組一覧を出す。
getFavoritLiveList: ->
# 生放送番組の情報を取得する
getLiveStatus: (lv, callback) ->
url = NiconicoApi.URI.live.status.slice(0).replace('{id}', lv)
@request.get url, (err, response, body) =>
if err
callback(err, null)
else
liveStatus = cheerio.load(body)
if liveStatus('getplayerstatus').attr('status') == 'ok'
data = {}
data.stream = {}
data.stream.id = liveStatus('stream id').text()
data.stream.title = liveStatus('stream title').text()
data.stream.description = liveStatus('stream description').text()
data.stream.owner_id = liveStatus('stream owner_id').text()
data.stream.owner_name = liveStatus('stream owner_name').text()
data.stream.thumb_url = liveStatus('stream thumb_url').text()
# コメントサーバの情報
data.comment = {}
data.comment.addr = liveStatus('ms addr').text()
data.comment.port = liveStatus('ms port').text()
data.comment.thread = liveStatus('ms thread').text()
# RTMPサーバの情報
data.rtmp = {}
data.rtmp.url = liveStatus('rtmp url').text()
data.rtmp.ticket = liveStatus('rtmp ticket').text()
data.rtmp.contents = liveStatus('contents#main').text().
replace(/^rtmp:rtmp:\/\//, 'rtmp://')
@startLiveHeartbeat(data.stream.id)
callback(err, data)
else
callback(liveStatus('error code').text(), liveStatus)
getLiveHeratbeat: (lv, callback) ->
url = NiconicoApi.URI.live.heartbeat.slice(0).replace('{id}', lv)
@request.get url, (err, response, body) ->
if err
callback(err, null)
else
heartBeat = cheerio.load(body)
if heartBeat('heartbeat').attr('status') == 'ok'
data = {}
data.ticket = heartBeat('ticket').text()
data.watchCount = heartBeat('watchCount').text()
data.commentCount = heartBeat('commentCount').text()
data.waitTime = heartBeat('waitTime').text()
callback(null, data)
else
callback(heartBeat('error code'), null)
startLiveHeartbeat: (lv) ->
if lv
@liveHeartbeat = lv
@getLiveHeratbeat @liveHeartbeat, (err, data) =>
console.log 'ハートビートが叩かれたっす'
console.log data
if !err
setTimeout =>
@startLiveHeartbeat(@liveHeartbeat)
, 60 * 1000
stopLiveHeartbeat: ->
@liveHeartbeat = null
| true | fs = require 'fs'
request = require 'request'
FileCookieStore = require 'tough-cookie-filestore'
cheerio = require 'cheerio'
# ニコニコ動画関係のAPI
module.exports =
class NiconicoApi
@URI:
top: 'http://www.nicovideo.jp/'
login: 'https://secure.nicovideo.jp/secure/login?site=niconico'
logout: 'https://secure.nicovideo.jp/secure/logout'
my:
top: 'http://www.nicovideo.jp/my/top'
community: 'http://www.nicovideo.jp/my/community'
channel: 'http://www.nicovideo.jp/my/channel'
live: 'http://www.nicovideo.jp/my/live'
mylist: 'http://www.nicovideo.jp/my/mylist'
live:
status: 'http://live.nicovideo.jp/api/getplayerstatus/{id}'
heartbeat: 'http://live.nicovideo.jp/api/heartbeat?v={id}'
constructor: (@cookieStoreFile) ->
# すでに存在しないとエラーになるらしい。けど、修正バージョンのブランチ使う。
# unless fs.existsSync(cookieStoreFile)
# fs.closeSync(fs.openSync(cookieStoreFile, 'w'))
console.log @cookieStoreFile
@requestJar = request.jar(new FileCookieStore(@cookieStoreFile))
@request = request.defaults
jar: @requestJar
followRedirect: false
headers:
'User-Agent':
'Niconico for Atom 0.0.0 / https://github.com/raccy/niconico'
@liveHeartbeat = null
destroy: ->
# なんかは破棄する物ある?
setCookieStoreFile: (@cookieStoreFile) ->
# TODO: 今は無理
# callback(err, response, body)
requestGet: (url, callback) ->
console.log ['Getリクエスト', url]
@request.get url, (err, response, body) ->
console.log ['Getレスポンス', err, response, body]
callback(err, response, body)
requestPost: (url, formData, callback) ->
console.log ['Postリクエスト', url, formData]
@request.post url, {form: formData}, (err, response, body) ->
console.log ['Postレスポンス', err, response, body]
callback err, response, body
# ログインする。
# ログインした情報をcallbackになげる。
# callback(err, data)
login: (mail, password, callback) ->
formData =
mail_tel: mail
password: PI:PASSWORD:<PASSWORD>END_PI
@requestPost NiconicoApi.URI.login, formData, (err, response, body) ->
if err
callback err, null
else if response.statusCode == 302
if response.headers.location == 'http://www.nicovideo.jp/'
callback null, true
else
callback 'メールアドレスまたはパスワードが間違っています。', null
else
callback '不明なレスポンスが返されました。', null
# ログアウトする。
logout: (callback) ->
@request.get NiconicoApi.URI.logout, ->
callback()
# TODO
# トップをとる
# classback(err, {userId, userName})
getMyTop: (callback) ->
@request.get NiconicoApi.URI.my.top, (err, response, body) ->
if !err
data = {}
if response.statusCode == 200
myTop = cheerio.load body
data.userName = myTop('.profile h2').contents().text().
replace(/さんの$/, '')
data.userId = myTop('.accountNumber span').text()
callback(null, data)
else
callback(err, null)
# 登録しているチャンネル/コミュニティで放送中の番組一覧を出す。
getFavoritLiveList: ->
# 生放送番組の情報を取得する
getLiveStatus: (lv, callback) ->
url = NiconicoApi.URI.live.status.slice(0).replace('{id}', lv)
@request.get url, (err, response, body) =>
if err
callback(err, null)
else
liveStatus = cheerio.load(body)
if liveStatus('getplayerstatus').attr('status') == 'ok'
data = {}
data.stream = {}
data.stream.id = liveStatus('stream id').text()
data.stream.title = liveStatus('stream title').text()
data.stream.description = liveStatus('stream description').text()
data.stream.owner_id = liveStatus('stream owner_id').text()
data.stream.owner_name = liveStatus('stream owner_name').text()
data.stream.thumb_url = liveStatus('stream thumb_url').text()
# コメントサーバの情報
data.comment = {}
data.comment.addr = liveStatus('ms addr').text()
data.comment.port = liveStatus('ms port').text()
data.comment.thread = liveStatus('ms thread').text()
# RTMPサーバの情報
data.rtmp = {}
data.rtmp.url = liveStatus('rtmp url').text()
data.rtmp.ticket = liveStatus('rtmp ticket').text()
data.rtmp.contents = liveStatus('contents#main').text().
replace(/^rtmp:rtmp:\/\//, 'rtmp://')
@startLiveHeartbeat(data.stream.id)
callback(err, data)
else
callback(liveStatus('error code').text(), liveStatus)
getLiveHeratbeat: (lv, callback) ->
url = NiconicoApi.URI.live.heartbeat.slice(0).replace('{id}', lv)
@request.get url, (err, response, body) ->
if err
callback(err, null)
else
heartBeat = cheerio.load(body)
if heartBeat('heartbeat').attr('status') == 'ok'
data = {}
data.ticket = heartBeat('ticket').text()
data.watchCount = heartBeat('watchCount').text()
data.commentCount = heartBeat('commentCount').text()
data.waitTime = heartBeat('waitTime').text()
callback(null, data)
else
callback(heartBeat('error code'), null)
startLiveHeartbeat: (lv) ->
if lv
@liveHeartbeat = lv
@getLiveHeratbeat @liveHeartbeat, (err, data) =>
console.log 'ハートビートが叩かれたっす'
console.log data
if !err
setTimeout =>
@startLiveHeartbeat(@liveHeartbeat)
, 60 * 1000
stopLiveHeartbeat: ->
@liveHeartbeat = null
|
[
{
"context": " an object that can be in a collection\n*\n* @author David Jegat <david.jegat@gmail.com>\n###\nclass BaseCollector\n\n",
"end": 78,
"score": 0.9998852014541626,
"start": 67,
"tag": "NAME",
"value": "David Jegat"
},
{
"context": "t can be in a collection\n*\n* @author Da... | src/Collection/BaseCollector.coffee | Djeg/MicroRacing | 1 | ###*
* Represent an object that can be in a collection
*
* @author David Jegat <david.jegat@gmail.com>
###
class BaseCollector
###*
* @consructor
* @param {string} name = null
###
constructor: (name) ->
if name
@name = name
else
@name = @constructor.name
| 206539 | ###*
* Represent an object that can be in a collection
*
* @author <NAME> <<EMAIL>>
###
class BaseCollector
###*
* @consructor
* @param {string} name = null
###
constructor: (name) ->
if name
@name = name
else
@name = @constructor.name
| true | ###*
* Represent an object that can be in a collection
*
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
class BaseCollector
###*
* @consructor
* @param {string} name = null
###
constructor: (name) ->
if name
@name = name
else
@name = @constructor.name
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9868794679641724,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/metricWidget.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# A component for indicating the presence or displaying the value of a metric.
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
ReactDOMServer = win.ReactDOMServer
{FaIcon, renderLineBreaks, showWhen} = require('./utils').load(win)
MetricWidget = React.createFactory React.createClass
displayName: 'MetricWidget'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
componentDidMount: ->
tooltipContent = R.div({className: 'tooltipContent'},
renderLineBreaks @props.definition
)
$(@refs.name).tooltip {
html: true
placement: 'auto top'
title: ReactDOMServer.renderToString tooltipContent
viewport: {
selector: @props.tooltipViewport or 'body'
padding: 0
}
}
render: ->
# Here we calculate the width needed for the widget's input and set inline below
# Note: the added space directly correlates to the padding on .innerValue
if @props.value?
inputWidth = (@props.value.length * 10) + 10
return R.div({
className: [
'metricWidget'
@props.styleClass or ''
].join ' '
},
(if @props.value?
R.div({className: 'value circle'},
(if @props.isEditable
R.input({
className: 'innerValue'
style: {width: "#{inputWidth}px"}
onFocus: @props.onFocus
value: @props.value
onChange: @_onChange
placeholder: '__'
maxLength: 20
})
else
R.div({className: 'innerValue'},
@props.value or '--'
)
)
)
else
R.div({className: 'icon circle'},
FaIcon 'line-chart'
)
)
R.div({className: 'name', ref: 'name'},
@props.name
)
(if @props.allowDeleting and not @props.isReadOnly
R.div({className: 'delete', onClick: @props.onDelete},
FaIcon 'times'
)
)
)
_onChange: (event) ->
if @props.onChange
@props.onChange event.target.value
return MetricWidget
module.exports = {load}
| 10269 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# A component for indicating the presence or displaying the value of a metric.
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
ReactDOMServer = win.ReactDOMServer
{FaIcon, renderLineBreaks, showWhen} = require('./utils').load(win)
MetricWidget = React.createFactory React.createClass
displayName: 'MetricWidget'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
componentDidMount: ->
tooltipContent = R.div({className: 'tooltipContent'},
renderLineBreaks @props.definition
)
$(@refs.name).tooltip {
html: true
placement: 'auto top'
title: ReactDOMServer.renderToString tooltipContent
viewport: {
selector: @props.tooltipViewport or 'body'
padding: 0
}
}
render: ->
# Here we calculate the width needed for the widget's input and set inline below
# Note: the added space directly correlates to the padding on .innerValue
if @props.value?
inputWidth = (@props.value.length * 10) + 10
return R.div({
className: [
'metricWidget'
@props.styleClass or ''
].join ' '
},
(if @props.value?
R.div({className: 'value circle'},
(if @props.isEditable
R.input({
className: 'innerValue'
style: {width: "#{inputWidth}px"}
onFocus: @props.onFocus
value: @props.value
onChange: @_onChange
placeholder: '__'
maxLength: 20
})
else
R.div({className: 'innerValue'},
@props.value or '--'
)
)
)
else
R.div({className: 'icon circle'},
FaIcon 'line-chart'
)
)
R.div({className: 'name', ref: 'name'},
@props.name
)
(if @props.allowDeleting and not @props.isReadOnly
R.div({className: 'delete', onClick: @props.onDelete},
FaIcon 'times'
)
)
)
_onChange: (event) ->
if @props.onChange
@props.onChange event.target.value
return MetricWidget
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# A component for indicating the presence or displaying the value of a metric.
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
ReactDOMServer = win.ReactDOMServer
{FaIcon, renderLineBreaks, showWhen} = require('./utils').load(win)
MetricWidget = React.createFactory React.createClass
displayName: 'MetricWidget'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
componentDidMount: ->
tooltipContent = R.div({className: 'tooltipContent'},
renderLineBreaks @props.definition
)
$(@refs.name).tooltip {
html: true
placement: 'auto top'
title: ReactDOMServer.renderToString tooltipContent
viewport: {
selector: @props.tooltipViewport or 'body'
padding: 0
}
}
render: ->
# Here we calculate the width needed for the widget's input and set inline below
# Note: the added space directly correlates to the padding on .innerValue
if @props.value?
inputWidth = (@props.value.length * 10) + 10
return R.div({
className: [
'metricWidget'
@props.styleClass or ''
].join ' '
},
(if @props.value?
R.div({className: 'value circle'},
(if @props.isEditable
R.input({
className: 'innerValue'
style: {width: "#{inputWidth}px"}
onFocus: @props.onFocus
value: @props.value
onChange: @_onChange
placeholder: '__'
maxLength: 20
})
else
R.div({className: 'innerValue'},
@props.value or '--'
)
)
)
else
R.div({className: 'icon circle'},
FaIcon 'line-chart'
)
)
R.div({className: 'name', ref: 'name'},
@props.name
)
(if @props.allowDeleting and not @props.isReadOnly
R.div({className: 'delete', onClick: @props.onDelete},
FaIcon 'times'
)
)
)
_onChange: (event) ->
if @props.onChange
@props.onChange event.target.value
return MetricWidget
module.exports = {load}
|
[
{
"context": "* grunt-akamai-rest-purge\n *\n * Copyright (c) 2014 Bastian Behrens\n * Licensed under the MIT license.\n *\n###\nmodule.",
"end": 72,
"score": 0.9998467564582825,
"start": 57,
"tag": "NAME",
"value": "Bastian Behrens"
},
{
"context": "ge:\n options:\n auth... | Gruntfile.coffee | gruntjs-updater/grunt-akamai-rest-purge | 0 | ###*
* grunt-akamai-rest-purge
*
* Copyright (c) 2014 Bastian Behrens
* Licensed under the MIT license.
*
###
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
jshint:
options:
jshintrc: ".jshintrc"
all: ["tasks/*.js"]
akamai_rest_purge:
options:
auth:
user: 'username'
pass: 'password'
all:
objects: ['http://www.your-domain.com/*']
download:
options:
action: 'invalidate'
proxy: 'http://some-proxy.com'
objects: ['http://www.your-domain.com/downloads/*']
# Actually load this plugin's task(s).
grunt.loadTasks "tasks"
# These plugins provide necessary tasks.
grunt.loadNpmTasks "grunt-contrib-jshint"
grunt.registerTask "default", ["jshint"]
| 64312 | ###*
* grunt-akamai-rest-purge
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
*
###
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
jshint:
options:
jshintrc: ".jshintrc"
all: ["tasks/*.js"]
akamai_rest_purge:
options:
auth:
user: 'username'
pass: '<PASSWORD>'
all:
objects: ['http://www.your-domain.com/*']
download:
options:
action: 'invalidate'
proxy: 'http://some-proxy.com'
objects: ['http://www.your-domain.com/downloads/*']
# Actually load this plugin's task(s).
grunt.loadTasks "tasks"
# These plugins provide necessary tasks.
grunt.loadNpmTasks "grunt-contrib-jshint"
grunt.registerTask "default", ["jshint"]
| true | ###*
* grunt-akamai-rest-purge
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
*
###
module.exports = (grunt) ->
# Project configuration.
grunt.initConfig
jshint:
options:
jshintrc: ".jshintrc"
all: ["tasks/*.js"]
akamai_rest_purge:
options:
auth:
user: 'username'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
all:
objects: ['http://www.your-domain.com/*']
download:
options:
action: 'invalidate'
proxy: 'http://some-proxy.com'
objects: ['http://www.your-domain.com/downloads/*']
# Actually load this plugin's task(s).
grunt.loadTasks "tasks"
# These plugins provide necessary tasks.
grunt.loadNpmTasks "grunt-contrib-jshint"
grunt.registerTask "default", ["jshint"]
|
[
{
"context": "oth children and dangerouslySetInnerHTML\n# @author David Petersen\n###\n'use strict'\n\n# -----------------------------",
"end": 122,
"score": 0.9998414516448975,
"start": 108,
"tag": "NAME",
"value": "David Petersen"
}
] | src/tests/rules/no-danger-with-children.coffee | danielbayley/eslint-plugin-coffee | 0 | ###*
# @fileoverview Report when a DOM element is using both children and dangerouslySetInnerHTML
# @author David Petersen
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-danger-with-children'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-danger-with-children', rule,
valid: [
code: '<div>Children</div>'
,
code: '<div {...props} />'
globals:
props: yes
,
code: '<div dangerouslySetInnerHTML={{ __html: "HTML" }} />'
,
code: '<div children="Children" />'
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props} />
'''
,
code: '''
moreProps = { className: "eslint" }
props = { children: "Children", ...moreProps }
<div {...props} />
'''
,
code: '''
otherProps = { children: "Children" }
{ a, b, ...props } = otherProps
<div {...props} />
'''
,
code: '<Hello>Children</Hello>'
,
code: '<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} />'
,
code: '''
<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
</Hello>
'''
,
code:
'React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } })'
,
code: 'React.createElement("div", {}, "Children")'
,
code:
'React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } })'
,
code: 'React.createElement("Hello", {}, "Children")'
,
# ,
# code: '<Hello {...undefined}>Children</Hello>'
code: 'React.createElement("Hello", undefined, "Children")'
,
code: '''
props = {...props, scratch: {mode: 'edit'}}
component = shallow(<TaskEditableTitle {...props} />)
'''
]
invalid: [
code: '''
<div dangerouslySetInnerHTML={{ __html: "HTML" }}>
Children
</div>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code:
'<div dangerouslySetInnerHTML={{ __html: "HTML" }} children="Children" />'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props}>Children</div>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { children: "Children", dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props} />
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
Children
</Hello>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code:
'<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} children="Children" />'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}> </Hello>'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"div",
{ dangerouslySetInnerHTML: { __html: "HTML" } },
"Children"
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"div",
{
dangerouslySetInnerHTML: { __html: "HTML" },
children: "Children",
}
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"Hello",
{ dangerouslySetInnerHTML: { __html: "HTML" } },
"Children"
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"Hello",
{
dangerouslySetInnerHTML: { __html: "HTML" },
children: "Children",
}
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props, "Children")
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { children: "Children", dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
moreProps = { children: "Children" }
otherProps = { ...moreProps }
props = { ...otherProps, dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
]
| 52494 | ###*
# @fileoverview Report when a DOM element is using both children and dangerouslySetInnerHTML
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-danger-with-children'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-danger-with-children', rule,
valid: [
code: '<div>Children</div>'
,
code: '<div {...props} />'
globals:
props: yes
,
code: '<div dangerouslySetInnerHTML={{ __html: "HTML" }} />'
,
code: '<div children="Children" />'
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props} />
'''
,
code: '''
moreProps = { className: "eslint" }
props = { children: "Children", ...moreProps }
<div {...props} />
'''
,
code: '''
otherProps = { children: "Children" }
{ a, b, ...props } = otherProps
<div {...props} />
'''
,
code: '<Hello>Children</Hello>'
,
code: '<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} />'
,
code: '''
<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
</Hello>
'''
,
code:
'React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } })'
,
code: 'React.createElement("div", {}, "Children")'
,
code:
'React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } })'
,
code: 'React.createElement("Hello", {}, "Children")'
,
# ,
# code: '<Hello {...undefined}>Children</Hello>'
code: 'React.createElement("Hello", undefined, "Children")'
,
code: '''
props = {...props, scratch: {mode: 'edit'}}
component = shallow(<TaskEditableTitle {...props} />)
'''
]
invalid: [
code: '''
<div dangerouslySetInnerHTML={{ __html: "HTML" }}>
Children
</div>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code:
'<div dangerouslySetInnerHTML={{ __html: "HTML" }} children="Children" />'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props}>Children</div>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { children: "Children", dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props} />
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
Children
</Hello>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code:
'<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} children="Children" />'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}> </Hello>'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"div",
{ dangerouslySetInnerHTML: { __html: "HTML" } },
"Children"
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"div",
{
dangerouslySetInnerHTML: { __html: "HTML" },
children: "Children",
}
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"Hello",
{ dangerouslySetInnerHTML: { __html: "HTML" } },
"Children"
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"Hello",
{
dangerouslySetInnerHTML: { __html: "HTML" },
children: "Children",
}
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props, "Children")
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { children: "Children", dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
moreProps = { children: "Children" }
otherProps = { ...moreProps }
props = { ...otherProps, dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
]
| true | ###*
# @fileoverview Report when a DOM element is using both children and dangerouslySetInnerHTML
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-danger-with-children'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-danger-with-children', rule,
valid: [
code: '<div>Children</div>'
,
code: '<div {...props} />'
globals:
props: yes
,
code: '<div dangerouslySetInnerHTML={{ __html: "HTML" }} />'
,
code: '<div children="Children" />'
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props} />
'''
,
code: '''
moreProps = { className: "eslint" }
props = { children: "Children", ...moreProps }
<div {...props} />
'''
,
code: '''
otherProps = { children: "Children" }
{ a, b, ...props } = otherProps
<div {...props} />
'''
,
code: '<Hello>Children</Hello>'
,
code: '<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} />'
,
code: '''
<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
</Hello>
'''
,
code:
'React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } })'
,
code: 'React.createElement("div", {}, "Children")'
,
code:
'React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } })'
,
code: 'React.createElement("Hello", {}, "Children")'
,
# ,
# code: '<Hello {...undefined}>Children</Hello>'
code: 'React.createElement("Hello", undefined, "Children")'
,
code: '''
props = {...props, scratch: {mode: 'edit'}}
component = shallow(<TaskEditableTitle {...props} />)
'''
]
invalid: [
code: '''
<div dangerouslySetInnerHTML={{ __html: "HTML" }}>
Children
</div>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code:
'<div dangerouslySetInnerHTML={{ __html: "HTML" }} children="Children" />'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props}>Children</div>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { children: "Children", dangerouslySetInnerHTML: { __html: "HTML" } }
<div {...props} />
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
Children
</Hello>
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code:
'<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} children="Children" />'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}> </Hello>'
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"div",
{ dangerouslySetInnerHTML: { __html: "HTML" } },
"Children"
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"div",
{
dangerouslySetInnerHTML: { __html: "HTML" },
children: "Children",
}
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"Hello",
{ dangerouslySetInnerHTML: { __html: "HTML" } },
"Children"
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
React.createElement(
"Hello",
{
dangerouslySetInnerHTML: { __html: "HTML" },
children: "Children",
}
)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props, "Children")
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
props = { children: "Children", dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
,
code: '''
moreProps = { children: "Children" }
otherProps = { ...moreProps }
props = { ...otherProps, dangerouslySetInnerHTML: { __html: "HTML" } }
React.createElement("div", props)
'''
errors: [
message: 'Only set one of `children` or `props.dangerouslySetInnerHTML`'
]
]
|
[
{
"context": "\n url: url\n data:\n private_token: gon.api_token\n per_page: 3\n dataType: \"jso",
"end": 2047,
"score": 0.6963809728622437,
"start": 2044,
"tag": "PASSWORD",
"value": "gon"
},
{
"context": "\n url: url\n data:\n private_t... | app/assets/javascripts/shared/api.js.coffee | dfraser74/sofreakingboring | 17 | @Api =
users_path: "/api/:version/users.json"
user_path: "/api/:version/users/:id.json"
projects_path: "/api/:version/projects.json"
recent_projects_path: "/api/:version/projects/recents.json"
project_members_path: "/api/:version/projects/:project_id/members.json"
project_snapshots_path: "/api/:version/projects/:project_id/snapshots.json"
tasks_path: "/api/:version/projects/:project_id/tasks.json"
task_path: "/api/:version/projects/:project_id/tasks/:id.json"
work_log_update_path: "/api/:version/projects/:project_id/tasks/:id/work_logs/:day.json"
remaining_update_path: "/api/:version/projects/:project_id/tasks/:id/remaining.json"
timesheet_path: "/api/:version/projects/:project_id/timesheets/:start.json"
timesheet_tasks_path: "/api/:version/projects/:project_id/timesheets/:start/tasks.json"
user: (user_id, callback) ->
url = Api.buildUrl(Api.user_path)
url = url.replace(':id', user_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (user) ->
callback(user)
# Return users list. Filtered by query
# Only active users retrieved
users: (query, per_page, callback) ->
url = Api.buildUrl(Api.users_path)
$.ajax(
url: url
data:
private_token: gon.api_token
search: query
per_page: per_page
active: true
dataType: "json"
).done (users) ->
callback(users)
# Return user projects list or all projects for admin.
projects: (admin, per_page, callback) ->
url = Api.buildUrl(Api.projects_path)
$.ajax(
url: url
data:
private_token: gon.api_token
admin: admin
per_page: per_page
dataType: "json"
).done (projects) ->
callback(projects)
# Return user recent projects list.
recent_projects: (callback) ->
url = Api.buildUrl(Api.recent_projects_path)
$.ajax(
url: url
data:
private_token: gon.api_token
per_page: 3
dataType: "json"
).done (projects) ->
callback(projects)
project_members: (project_id, callback) ->
url = Api.buildUrl(Api.project_members_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (tasks) ->
callback(tasks)
project_snapshots: (project_id, callback) ->
url = Api.buildUrl(Api.project_snapshots_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
per_page: 2000
private_token: gon.api_token
dataType: "json"
).done (shots) ->
callback(shots)
tasks: (project_id, callback) ->
url = Api.buildUrl(Api.tasks_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
per_page: 2000
private_token: gon.api_token
dataType: "json"
).done (tasks) ->
callback(tasks)
task: (project_id, task_id, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (task) ->
callback(task)
create_task: (project_id, data, callback) ->
url = Api.buildUrl(Api.tasks_path)
url = url.replace(':project_id', project_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "post"
data: data
dataType: "json"
).done (task) ->
callback(task)
update_task: (project_id, task_id, data, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (task) ->
callback(task)
delete_task: (project_id, task_id, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.ajax(
url: url
type: "delete"
data:
private_token: gon.api_token
dataType: "json"
).done (task) ->
callback(task)
timesheet: (project_id, start, callback) ->
url = Api.buildUrl(Api.timesheet_path)
url = url.replace(':project_id', project_id)
url = url.replace(':start', start)
$.ajax(
url: url
data:
private_token: gon.api_token
type: "get"
dataType: "json"
).done (timesheet) ->
callback(timesheet)
timesheet_tasks: (project_id, user_id, start, callback) ->
url = Api.buildUrl(Api.timesheet_tasks_path)
url = url.replace(':project_id', project_id)
url = url.replace(':start', start)
$.ajax(
url: url
data:
private_token: gon.api_token
user_id: user_id
type: "get"
dataType: "json"
).done (tasks) ->
callback(tasks)
update_work_log: (project_id, task_id, date, data, callback) ->
url = Api.buildUrl(Api.work_log_update_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
url = url.replace(':day', date)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (log) ->
callback(log)
update_remaining: (project_id, task_id, data, callback) ->
url = Api.buildUrl(Api.remaining_update_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (task) ->
callback(task)
buildUrl: (url) ->
return url.replace(':version', gon.api_version) | 139337 | @Api =
users_path: "/api/:version/users.json"
user_path: "/api/:version/users/:id.json"
projects_path: "/api/:version/projects.json"
recent_projects_path: "/api/:version/projects/recents.json"
project_members_path: "/api/:version/projects/:project_id/members.json"
project_snapshots_path: "/api/:version/projects/:project_id/snapshots.json"
tasks_path: "/api/:version/projects/:project_id/tasks.json"
task_path: "/api/:version/projects/:project_id/tasks/:id.json"
work_log_update_path: "/api/:version/projects/:project_id/tasks/:id/work_logs/:day.json"
remaining_update_path: "/api/:version/projects/:project_id/tasks/:id/remaining.json"
timesheet_path: "/api/:version/projects/:project_id/timesheets/:start.json"
timesheet_tasks_path: "/api/:version/projects/:project_id/timesheets/:start/tasks.json"
user: (user_id, callback) ->
url = Api.buildUrl(Api.user_path)
url = url.replace(':id', user_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (user) ->
callback(user)
# Return users list. Filtered by query
# Only active users retrieved
users: (query, per_page, callback) ->
url = Api.buildUrl(Api.users_path)
$.ajax(
url: url
data:
private_token: gon.api_token
search: query
per_page: per_page
active: true
dataType: "json"
).done (users) ->
callback(users)
# Return user projects list or all projects for admin.
projects: (admin, per_page, callback) ->
url = Api.buildUrl(Api.projects_path)
$.ajax(
url: url
data:
private_token: gon.api_token
admin: admin
per_page: per_page
dataType: "json"
).done (projects) ->
callback(projects)
# Return user recent projects list.
recent_projects: (callback) ->
url = Api.buildUrl(Api.recent_projects_path)
$.ajax(
url: url
data:
private_token: <PASSWORD>.api_token
per_page: 3
dataType: "json"
).done (projects) ->
callback(projects)
project_members: (project_id, callback) ->
url = Api.buildUrl(Api.project_members_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
private_token: <PASSWORD>.api_token
dataType: "json"
).done (tasks) ->
callback(tasks)
project_snapshots: (project_id, callback) ->
url = Api.buildUrl(Api.project_snapshots_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
per_page: 2000
private_token: gon.api_token
dataType: "json"
).done (shots) ->
callback(shots)
tasks: (project_id, callback) ->
url = Api.buildUrl(Api.tasks_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
per_page: 2000
private_token: gon.api_token
dataType: "json"
).done (tasks) ->
callback(tasks)
task: (project_id, task_id, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (task) ->
callback(task)
create_task: (project_id, data, callback) ->
url = Api.buildUrl(Api.tasks_path)
url = url.replace(':project_id', project_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "post"
data: data
dataType: "json"
).done (task) ->
callback(task)
update_task: (project_id, task_id, data, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (task) ->
callback(task)
delete_task: (project_id, task_id, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.ajax(
url: url
type: "delete"
data:
private_token: gon.api_token
dataType: "json"
).done (task) ->
callback(task)
timesheet: (project_id, start, callback) ->
url = Api.buildUrl(Api.timesheet_path)
url = url.replace(':project_id', project_id)
url = url.replace(':start', start)
$.ajax(
url: url
data:
private_token: gon.api_token
type: "get"
dataType: "json"
).done (timesheet) ->
callback(timesheet)
timesheet_tasks: (project_id, user_id, start, callback) ->
url = Api.buildUrl(Api.timesheet_tasks_path)
url = url.replace(':project_id', project_id)
url = url.replace(':start', start)
$.ajax(
url: url
data:
private_token: gon.api_token
user_id: user_id
type: "get"
dataType: "json"
).done (tasks) ->
callback(tasks)
update_work_log: (project_id, task_id, date, data, callback) ->
url = Api.buildUrl(Api.work_log_update_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
url = url.replace(':day', date)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (log) ->
callback(log)
update_remaining: (project_id, task_id, data, callback) ->
url = Api.buildUrl(Api.remaining_update_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (task) ->
callback(task)
buildUrl: (url) ->
return url.replace(':version', gon.api_version) | true | @Api =
users_path: "/api/:version/users.json"
user_path: "/api/:version/users/:id.json"
projects_path: "/api/:version/projects.json"
recent_projects_path: "/api/:version/projects/recents.json"
project_members_path: "/api/:version/projects/:project_id/members.json"
project_snapshots_path: "/api/:version/projects/:project_id/snapshots.json"
tasks_path: "/api/:version/projects/:project_id/tasks.json"
task_path: "/api/:version/projects/:project_id/tasks/:id.json"
work_log_update_path: "/api/:version/projects/:project_id/tasks/:id/work_logs/:day.json"
remaining_update_path: "/api/:version/projects/:project_id/tasks/:id/remaining.json"
timesheet_path: "/api/:version/projects/:project_id/timesheets/:start.json"
timesheet_tasks_path: "/api/:version/projects/:project_id/timesheets/:start/tasks.json"
user: (user_id, callback) ->
url = Api.buildUrl(Api.user_path)
url = url.replace(':id', user_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (user) ->
callback(user)
# Return users list. Filtered by query
# Only active users retrieved
users: (query, per_page, callback) ->
url = Api.buildUrl(Api.users_path)
$.ajax(
url: url
data:
private_token: gon.api_token
search: query
per_page: per_page
active: true
dataType: "json"
).done (users) ->
callback(users)
# Return user projects list or all projects for admin.
projects: (admin, per_page, callback) ->
url = Api.buildUrl(Api.projects_path)
$.ajax(
url: url
data:
private_token: gon.api_token
admin: admin
per_page: per_page
dataType: "json"
).done (projects) ->
callback(projects)
# Return user recent projects list.
recent_projects: (callback) ->
url = Api.buildUrl(Api.recent_projects_path)
$.ajax(
url: url
data:
private_token: PI:PASSWORD:<PASSWORD>END_PI.api_token
per_page: 3
dataType: "json"
).done (projects) ->
callback(projects)
project_members: (project_id, callback) ->
url = Api.buildUrl(Api.project_members_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
private_token: PI:PASSWORD:<PASSWORD>END_PI.api_token
dataType: "json"
).done (tasks) ->
callback(tasks)
project_snapshots: (project_id, callback) ->
url = Api.buildUrl(Api.project_snapshots_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
per_page: 2000
private_token: gon.api_token
dataType: "json"
).done (shots) ->
callback(shots)
tasks: (project_id, callback) ->
url = Api.buildUrl(Api.tasks_path)
url = url.replace(':project_id', project_id)
$.ajax(
url: url
data:
per_page: 2000
private_token: gon.api_token
dataType: "json"
).done (tasks) ->
callback(tasks)
task: (project_id, task_id, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.ajax(
url: url
data:
private_token: gon.api_token
dataType: "json"
).done (task) ->
callback(task)
create_task: (project_id, data, callback) ->
url = Api.buildUrl(Api.tasks_path)
url = url.replace(':project_id', project_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "post"
data: data
dataType: "json"
).done (task) ->
callback(task)
update_task: (project_id, task_id, data, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (task) ->
callback(task)
delete_task: (project_id, task_id, callback) ->
url = Api.buildUrl(Api.task_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.ajax(
url: url
type: "delete"
data:
private_token: gon.api_token
dataType: "json"
).done (task) ->
callback(task)
timesheet: (project_id, start, callback) ->
url = Api.buildUrl(Api.timesheet_path)
url = url.replace(':project_id', project_id)
url = url.replace(':start', start)
$.ajax(
url: url
data:
private_token: gon.api_token
type: "get"
dataType: "json"
).done (timesheet) ->
callback(timesheet)
timesheet_tasks: (project_id, user_id, start, callback) ->
url = Api.buildUrl(Api.timesheet_tasks_path)
url = url.replace(':project_id', project_id)
url = url.replace(':start', start)
$.ajax(
url: url
data:
private_token: gon.api_token
user_id: user_id
type: "get"
dataType: "json"
).done (tasks) ->
callback(tasks)
update_work_log: (project_id, task_id, date, data, callback) ->
url = Api.buildUrl(Api.work_log_update_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
url = url.replace(':day', date)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (log) ->
callback(log)
update_remaining: (project_id, task_id, data, callback) ->
url = Api.buildUrl(Api.remaining_update_path)
url = url.replace(':project_id', project_id)
url = url.replace(':id', task_id)
$.extend(data, {private_token: gon.api_token})
$.ajax(
url: url
type: "put"
data: data
dataType: "json"
).done (task) ->
callback(task)
buildUrl: (url) ->
return url.replace(':version', gon.api_version) |
[
{
"context": "rFeralu\"\n\t@type:\"ModifierFeralu\"\n\n\t@modifierName:\"Feralu\"\n\t@description:\"\"\n\n\t_filterPotentialCardInAura: (",
"end": 305,
"score": 0.9933627247810364,
"start": 299,
"tag": "NAME",
"value": "Feralu"
}
] | app/sdk/modifiers/modifierFeralu.coffee | willroberts/duelyst | 5 | CONFIG = require 'app/common/config'
Modifier = require './modifier'
Races = require 'app/sdk/cards/racesLookup'
ModifierBelongsToAllRaces = require 'app/sdk/modifiers/modifierBelongsToAllRaces'
class ModifierFeralu extends Modifier
type:"ModifierFeralu"
@type:"ModifierFeralu"
@modifierName:"Feralu"
@description:""
_filterPotentialCardInAura: (card) ->
return (card.getRaceId() isnt Races.Neutral or card.hasModifierClass(ModifierBelongsToAllRaces)) and super(card)
module.exports = ModifierFeralu
| 83372 | CONFIG = require 'app/common/config'
Modifier = require './modifier'
Races = require 'app/sdk/cards/racesLookup'
ModifierBelongsToAllRaces = require 'app/sdk/modifiers/modifierBelongsToAllRaces'
class ModifierFeralu extends Modifier
type:"ModifierFeralu"
@type:"ModifierFeralu"
@modifierName:"<NAME>"
@description:""
_filterPotentialCardInAura: (card) ->
return (card.getRaceId() isnt Races.Neutral or card.hasModifierClass(ModifierBelongsToAllRaces)) and super(card)
module.exports = ModifierFeralu
| true | CONFIG = require 'app/common/config'
Modifier = require './modifier'
Races = require 'app/sdk/cards/racesLookup'
ModifierBelongsToAllRaces = require 'app/sdk/modifiers/modifierBelongsToAllRaces'
class ModifierFeralu extends Modifier
type:"ModifierFeralu"
@type:"ModifierFeralu"
@modifierName:"PI:NAME:<NAME>END_PI"
@description:""
_filterPotentialCardInAura: (card) ->
return (card.getRaceId() isnt Races.Neutral or card.hasModifierClass(ModifierBelongsToAllRaces)) and super(card)
module.exports = ModifierFeralu
|
[
{
"context": " term.echo \"\"\n return\n ),\n greetings: \"Tikkuterminaali!\"\n name: \"tikku\"\n height: 600\n width: \"1",
"end": 3126,
"score": 0.9710062146186829,
"start": 3111,
"tag": "NAME",
"value": "Tikkuterminaali"
},
{
"context": " ),\n greetings: \"... | views/coffee/node-mqtt-gw.coffee | arisi/node-mqtt-gw | 0 | term=null
pause=false
init={}
stamp = () ->
(new Date).getTime();
ajax_data = (data) ->
console.log "ajax:",data
$(".adata").html(data.now)
@ajax = (obj) ->
console.log "doin ajax"
$.ajax
url: "/ajax"
type: "GET"
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj
success: (data) ->
ajax_data(data)
return
error: (xhr, ajaxOptions, thrownError) ->
alert thrownError
return
delta = (s) ->
if s
((stamp()-s)/1000).toFixed(1)
else
100000000
buf=""
buf2term = () ->
while true
p=buf.indexOf("\n")
if p!=-1
term.echo "[[b;yellow;black]#{buf[0..p-1]}]"
buf=buf[p+1..-1]
else
break
@ajax_form = (fn) ->
console.log "formi!"
data={}
$("##{fn} :input").each () ->
fn=[this.name]
if fn and fn>""
val=$(this).val();
data[fn]=val
console.log "#{fn}: #{val}"
console.log ">",data
ajax
act: "options"
data: data
update_form = () ->
console.log "init",init
dust.render "form_template", init.options, (err, out) ->
if err
console.log "dust:",err,out
$("#form").html out
sse_data = (obj) ->
if obj.type =="init"
init=obj
update_form()
else if obj.type =="options"
init.options=obj.options
update_form()
else if obj.type =="plist_all"
l=[]
for dev,data of obj.data
data.dev=dev
if delta(data.lastp3)>10
data.class="danger"
else
data.class="success"
if data.id
data.id=data.id[-6..-1]
l.push data
dust.render "devs_template", { data: l,randomi: Math.random()}, (err, out) ->
if err
console.log "dust:",err,out
$("#devs").html out
else if obj.type =="debug"
#$(".log").append obj.txt
#$(".log").scrollTop($("#loki")[0].scrollHeight);
#term.echo "[[raw]#{obj.txt}]"
buf+=obj.txt
if not pause
buf2term()
else
console.log obj
console.log "strange packet"
dust.helpers.age = (chunk, context, bodies, params) ->
if t=params.t
age=((stamp()-t)/1000).toFixed(1)
else
age=""
return chunk.write age
jQuery ($, undefined_) ->
source = new EventSource("/log.sse")
source.addEventListener "message", ((e) -> # note: 'newcontent'
obj=$.parseJSON(e.data)
sse_data obj
return
), false
ajax
send: "\nauth 1682\n"
term=$("#term").terminal ((command, term) ->
if command isnt ""
try
if command=="rs"
command="rbuf stat"
else if command=="ds"
command="devs stat"
else if command=="ps"
command="tasks stat"
if command=="cls"
term.clear()
else if command=="pause"
pause=not pause
if pause
term.echo "paused!"
else
term.echo "unpaused!"
buf2term()
else
ajax
act: "send"
data: "#{command}\n"
#term.echo new String(result) if result isnt `undefined`
catch e
term.error new String(e)
else
term.echo ""
return
),
greetings: "Tikkuterminaali!"
name: "tikku"
height: 600
width: "100%"
prompt: "] "
$("script[type='text/template']").each (index) ->
console.log index + ": " + $(this).attr("id")
dust.loadSource(dust.compile($("#"+$(this).attr("id")).html(),$(this).attr("id")))
return
| 11012 | term=null
pause=false
init={}
stamp = () ->
(new Date).getTime();
ajax_data = (data) ->
console.log "ajax:",data
$(".adata").html(data.now)
@ajax = (obj) ->
console.log "doin ajax"
$.ajax
url: "/ajax"
type: "GET"
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj
success: (data) ->
ajax_data(data)
return
error: (xhr, ajaxOptions, thrownError) ->
alert thrownError
return
delta = (s) ->
if s
((stamp()-s)/1000).toFixed(1)
else
100000000
buf=""
buf2term = () ->
while true
p=buf.indexOf("\n")
if p!=-1
term.echo "[[b;yellow;black]#{buf[0..p-1]}]"
buf=buf[p+1..-1]
else
break
@ajax_form = (fn) ->
console.log "formi!"
data={}
$("##{fn} :input").each () ->
fn=[this.name]
if fn and fn>""
val=$(this).val();
data[fn]=val
console.log "#{fn}: #{val}"
console.log ">",data
ajax
act: "options"
data: data
update_form = () ->
console.log "init",init
dust.render "form_template", init.options, (err, out) ->
if err
console.log "dust:",err,out
$("#form").html out
sse_data = (obj) ->
if obj.type =="init"
init=obj
update_form()
else if obj.type =="options"
init.options=obj.options
update_form()
else if obj.type =="plist_all"
l=[]
for dev,data of obj.data
data.dev=dev
if delta(data.lastp3)>10
data.class="danger"
else
data.class="success"
if data.id
data.id=data.id[-6..-1]
l.push data
dust.render "devs_template", { data: l,randomi: Math.random()}, (err, out) ->
if err
console.log "dust:",err,out
$("#devs").html out
else if obj.type =="debug"
#$(".log").append obj.txt
#$(".log").scrollTop($("#loki")[0].scrollHeight);
#term.echo "[[raw]#{obj.txt}]"
buf+=obj.txt
if not pause
buf2term()
else
console.log obj
console.log "strange packet"
dust.helpers.age = (chunk, context, bodies, params) ->
if t=params.t
age=((stamp()-t)/1000).toFixed(1)
else
age=""
return chunk.write age
jQuery ($, undefined_) ->
source = new EventSource("/log.sse")
source.addEventListener "message", ((e) -> # note: 'newcontent'
obj=$.parseJSON(e.data)
sse_data obj
return
), false
ajax
send: "\nauth 1682\n"
term=$("#term").terminal ((command, term) ->
if command isnt ""
try
if command=="rs"
command="rbuf stat"
else if command=="ds"
command="devs stat"
else if command=="ps"
command="tasks stat"
if command=="cls"
term.clear()
else if command=="pause"
pause=not pause
if pause
term.echo "paused!"
else
term.echo "unpaused!"
buf2term()
else
ajax
act: "send"
data: "#{command}\n"
#term.echo new String(result) if result isnt `undefined`
catch e
term.error new String(e)
else
term.echo ""
return
),
greetings: "<NAME>!"
name: "tikku"
height: 600
width: "100%"
prompt: "] "
$("script[type='text/template']").each (index) ->
console.log index + ": " + $(this).attr("id")
dust.loadSource(dust.compile($("#"+$(this).attr("id")).html(),$(this).attr("id")))
return
| true | term=null
pause=false
init={}
stamp = () ->
(new Date).getTime();
ajax_data = (data) ->
console.log "ajax:",data
$(".adata").html(data.now)
@ajax = (obj) ->
console.log "doin ajax"
$.ajax
url: "/ajax"
type: "GET"
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj
success: (data) ->
ajax_data(data)
return
error: (xhr, ajaxOptions, thrownError) ->
alert thrownError
return
delta = (s) ->
if s
((stamp()-s)/1000).toFixed(1)
else
100000000
buf=""
buf2term = () ->
while true
p=buf.indexOf("\n")
if p!=-1
term.echo "[[b;yellow;black]#{buf[0..p-1]}]"
buf=buf[p+1..-1]
else
break
@ajax_form = (fn) ->
console.log "formi!"
data={}
$("##{fn} :input").each () ->
fn=[this.name]
if fn and fn>""
val=$(this).val();
data[fn]=val
console.log "#{fn}: #{val}"
console.log ">",data
ajax
act: "options"
data: data
update_form = () ->
console.log "init",init
dust.render "form_template", init.options, (err, out) ->
if err
console.log "dust:",err,out
$("#form").html out
sse_data = (obj) ->
if obj.type =="init"
init=obj
update_form()
else if obj.type =="options"
init.options=obj.options
update_form()
else if obj.type =="plist_all"
l=[]
for dev,data of obj.data
data.dev=dev
if delta(data.lastp3)>10
data.class="danger"
else
data.class="success"
if data.id
data.id=data.id[-6..-1]
l.push data
dust.render "devs_template", { data: l,randomi: Math.random()}, (err, out) ->
if err
console.log "dust:",err,out
$("#devs").html out
else if obj.type =="debug"
#$(".log").append obj.txt
#$(".log").scrollTop($("#loki")[0].scrollHeight);
#term.echo "[[raw]#{obj.txt}]"
buf+=obj.txt
if not pause
buf2term()
else
console.log obj
console.log "strange packet"
dust.helpers.age = (chunk, context, bodies, params) ->
if t=params.t
age=((stamp()-t)/1000).toFixed(1)
else
age=""
return chunk.write age
jQuery ($, undefined_) ->
source = new EventSource("/log.sse")
source.addEventListener "message", ((e) -> # note: 'newcontent'
obj=$.parseJSON(e.data)
sse_data obj
return
), false
ajax
send: "\nauth 1682\n"
term=$("#term").terminal ((command, term) ->
if command isnt ""
try
if command=="rs"
command="rbuf stat"
else if command=="ds"
command="devs stat"
else if command=="ps"
command="tasks stat"
if command=="cls"
term.clear()
else if command=="pause"
pause=not pause
if pause
term.echo "paused!"
else
term.echo "unpaused!"
buf2term()
else
ajax
act: "send"
data: "#{command}\n"
#term.echo new String(result) if result isnt `undefined`
catch e
term.error new String(e)
else
term.echo ""
return
),
greetings: "PI:NAME:<NAME>END_PI!"
name: "tikku"
height: 600
width: "100%"
prompt: "] "
$("script[type='text/template']").each (index) ->
console.log index + ": " + $(this).attr("id")
dust.loadSource(dust.compile($("#"+$(this).attr("id")).html(),$(this).attr("id")))
return
|
[
{
"context": "m_sets'\n approved_team_sets: ember.computed 'team_sets.@each.state', -> @get('team_sets').filter (team_set) -> team_",
"end": 386,
"score": 0.7919335961341858,
"start": 370,
"tag": "EMAIL",
"value": "sets.@each.state"
},
{
"context": "d'\n neutral_team_sets: ember.c... | src/thinkspace/client/thinkspace-model/app/models/thinkspace/peer_assessment/progress_report.coffee | sixthedge/cellar | 6 | import ember from 'ember'
import ta from 'totem/ds/associations'
import base from '../common/componentable'
export default base.extend ta.add(),
# ### Attributes
assessment_id: ta.attr('string_id')
value: ta.attr()
# ### Computed Properties
team_sets: ember.computed.reads 'value.team_sets'
approved_team_sets: ember.computed 'team_sets.@each.state', -> @get('team_sets').filter (team_set) -> team_set.state == 'approved'
neutral_team_sets: ember.computed 'team_sets.@each.state', -> @get('team_sets').filter (team_set) -> team_set.state == 'neutral'
students_complete: ember.computed.reads 'value.complete.review_sets'
teams_complete: ember.computed.reads 'value.complete.team_sets'
students_total: ember.computed.reads 'value.total.review_sets'
teams_total: ember.computed.reads 'value.total.team_sets'
all_teams_sent: ember.computed 'team_sets.@each.state', -> @get('team_sets').every (team_set) -> team_set.state == 'sent'
all_teams_approved: ember.computed 'team_sets.@each.state', -> @get('team_sets').every (team_set) -> team_set.state == 'approved'
# ### Methods
process_team_sets: (records) ->
records = ember.makeArray(records) unless ember.isArray(records)
records.forEach (record) =>
team_set = @get('team_sets').findBy 'id', parseInt(record.get('id'))
ember.set team_set, 'state', record.get('state')
process_review_sets: (team_set, review_sets) ->
review_sets = ember.makeArray(review_sets) unless ember.isArray(review_sets)
team_set_data = @get('team_sets').findBy 'id', parseInt(team_set.get('id'))
review_sets.forEach (review_set) =>
review_set_data = team_set_data.review_sets.findBy 'ownerable_id', parseInt(review_set.get('ownerable_id'))
ember.set review_set_data, 'id', review_set.get('id')
ember.set review_set_data, 'state', review_set.get('state')
ember.set review_set_data, 'status', review_set.get('status')
get_incomplete_review_sets_for_team_set: (team_set) -> team_set.review_sets.filter (review_set) -> review_set.status != 'complete'
| 48861 | import ember from 'ember'
import ta from 'totem/ds/associations'
import base from '../common/componentable'
export default base.extend ta.add(),
# ### Attributes
assessment_id: ta.attr('string_id')
value: ta.attr()
# ### Computed Properties
team_sets: ember.computed.reads 'value.team_sets'
approved_team_sets: ember.computed 'team_<EMAIL>', -> @get('team_sets').filter (team_set) -> team_set.state == 'approved'
neutral_team_sets: ember.computed 'team_sets.<EMAIL>', -> @get('team_sets').filter (team_set) -> team_set.state == 'neutral'
students_complete: ember.computed.reads 'value.complete.review_sets'
teams_complete: ember.computed.reads 'value.complete.team_sets'
students_total: ember.computed.reads 'value.total.review_sets'
teams_total: ember.computed.reads 'value.total.team_sets'
all_teams_sent: ember.computed 'team_sets.@each.state', -> @get('team_sets').every (team_set) -> team_set.state == 'sent'
all_teams_approved: ember.computed 'team_<EMAIL>', -> @get('team_sets').every (team_set) -> team_set.state == 'approved'
# ### Methods
process_team_sets: (records) ->
records = ember.makeArray(records) unless ember.isArray(records)
records.forEach (record) =>
team_set = @get('team_sets').findBy 'id', parseInt(record.get('id'))
ember.set team_set, 'state', record.get('state')
process_review_sets: (team_set, review_sets) ->
review_sets = ember.makeArray(review_sets) unless ember.isArray(review_sets)
team_set_data = @get('team_sets').findBy 'id', parseInt(team_set.get('id'))
review_sets.forEach (review_set) =>
review_set_data = team_set_data.review_sets.findBy 'ownerable_id', parseInt(review_set.get('ownerable_id'))
ember.set review_set_data, 'id', review_set.get('id')
ember.set review_set_data, 'state', review_set.get('state')
ember.set review_set_data, 'status', review_set.get('status')
get_incomplete_review_sets_for_team_set: (team_set) -> team_set.review_sets.filter (review_set) -> review_set.status != 'complete'
| true | import ember from 'ember'
import ta from 'totem/ds/associations'
import base from '../common/componentable'
export default base.extend ta.add(),
# ### Attributes
assessment_id: ta.attr('string_id')
value: ta.attr()
# ### Computed Properties
team_sets: ember.computed.reads 'value.team_sets'
approved_team_sets: ember.computed 'team_PI:EMAIL:<EMAIL>END_PI', -> @get('team_sets').filter (team_set) -> team_set.state == 'approved'
neutral_team_sets: ember.computed 'team_sets.PI:EMAIL:<EMAIL>END_PI', -> @get('team_sets').filter (team_set) -> team_set.state == 'neutral'
students_complete: ember.computed.reads 'value.complete.review_sets'
teams_complete: ember.computed.reads 'value.complete.team_sets'
students_total: ember.computed.reads 'value.total.review_sets'
teams_total: ember.computed.reads 'value.total.team_sets'
all_teams_sent: ember.computed 'team_sets.@each.state', -> @get('team_sets').every (team_set) -> team_set.state == 'sent'
all_teams_approved: ember.computed 'team_PI:EMAIL:<EMAIL>END_PI', -> @get('team_sets').every (team_set) -> team_set.state == 'approved'
# ### Methods
process_team_sets: (records) ->
records = ember.makeArray(records) unless ember.isArray(records)
records.forEach (record) =>
team_set = @get('team_sets').findBy 'id', parseInt(record.get('id'))
ember.set team_set, 'state', record.get('state')
process_review_sets: (team_set, review_sets) ->
review_sets = ember.makeArray(review_sets) unless ember.isArray(review_sets)
team_set_data = @get('team_sets').findBy 'id', parseInt(team_set.get('id'))
review_sets.forEach (review_set) =>
review_set_data = team_set_data.review_sets.findBy 'ownerable_id', parseInt(review_set.get('ownerable_id'))
ember.set review_set_data, 'id', review_set.get('id')
ember.set review_set_data, 'state', review_set.get('state')
ember.set review_set_data, 'status', review_set.get('status')
get_incomplete_review_sets_for_team_set: (team_set) -> team_set.review_sets.filter (review_set) -> review_set.status != 'complete'
|
[
{
"context": "melizeKeys = yes\nApp.OtherFamily.collectionKey = 'other_families'\nApp.OtherFamily.url = '/api/v1/other_families'\nA",
"end": 260,
"score": 0.9474451541900635,
"start": 246,
"tag": "KEY",
"value": "other_families"
}
] | app/models/other-family.coffee | robinandeer/scout | 4 | NewRESTAdapter = require 'adapters/new-rest'
App.OtherFamily = Ember.Model.extend
pk: Em.attr()
family: Em.attr()
id: (->
return @get 'family'
).property 'family'
App.OtherFamily.camelizeKeys = yes
App.OtherFamily.collectionKey = 'other_families'
App.OtherFamily.url = '/api/v1/other_families'
App.OtherFamily.adapter = NewRESTAdapter.create()
module.exports = App.OtherFamily
| 109355 | NewRESTAdapter = require 'adapters/new-rest'
App.OtherFamily = Ember.Model.extend
pk: Em.attr()
family: Em.attr()
id: (->
return @get 'family'
).property 'family'
App.OtherFamily.camelizeKeys = yes
App.OtherFamily.collectionKey = '<KEY>'
App.OtherFamily.url = '/api/v1/other_families'
App.OtherFamily.adapter = NewRESTAdapter.create()
module.exports = App.OtherFamily
| true | NewRESTAdapter = require 'adapters/new-rest'
App.OtherFamily = Ember.Model.extend
pk: Em.attr()
family: Em.attr()
id: (->
return @get 'family'
).property 'family'
App.OtherFamily.camelizeKeys = yes
App.OtherFamily.collectionKey = 'PI:KEY:<KEY>END_PI'
App.OtherFamily.url = '/api/v1/other_families'
App.OtherFamily.adapter = NewRESTAdapter.create()
module.exports = App.OtherFamily
|
[
{
"context": "log, EventsHelper, MarkerOptions) ->\n keys = ['coords', 'icon', 'options', 'fit']\n class MarkerChildModel extends ModelKey\n ",
"end": 303,
"score": 0.9647278189659119,
"start": 269,
"tag": "KEY",
"value": "coords', 'icon', 'options', 'fit']"
},
{
"context":... | platforms/ios/www/lib/bower_components/angular-google-maps/src/coffee/directives/api/models/child/marker-child-model.coffee | FirstDateApp/FirstDateApp.github.io | 2 | angular.module("google-maps.directives.api.models.child".ns())
.factory "MarkerChildModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(),
"Logger".ns(), "EventsHelper".ns(),
"MarkerOptions".ns(),
(ModelKey, GmapUtil, $log, EventsHelper, MarkerOptions) ->
keys = ['coords', 'icon', 'options', 'fit']
class MarkerChildModel extends ModelKey
@include GmapUtil
@include EventsHelper
@include MarkerOptions
destroy = (child) ->
if child?.gMarker?
child.removeEvents child.externalListeners
child.removeEvents child.internalListeners
if child?.gMarker
child?.gMarkerManager.remove child?.gMarker, true
delete child.gMarker
constructor: (scope, @model, @keys, @gMap, @defaults, @doClick, @gMarkerManager, @doDrawSelf = true,
@trackModel = true)->
_.each @keys, (v, k) =>
@[k + 'Key'] = if _.isFunction @keys[k] then @keys[k]() else @keys[k]
@idKey = @idKeyKey or "id"
@id = @model[@idKey] if @model[@idKey]?
@needRedraw = false
@deferred = Promise.defer()
super(scope)
@setMyScope(@model, undefined, true)
@createMarker(@model)
if @trackModel
@scope.model = @model
@scope.$watch 'model', (newValue, oldValue) =>
if (newValue != oldValue)
@setMyScope newValue, oldValue
@needRedraw = true
, true
else
_.each @keys, (v, k) =>
@scope.$watch k, =>
@setMyScope @scope
#hiding destroy functionality as it should only be called via scope.$destroy()
@scope.$on "$destroy", =>
destroy @
$log.info @
destroy: =>
@scope.$destroy()
setMyScope: (model, oldModel = undefined, isInit = false) =>
@maybeSetScopeValue('icon', model, oldModel, @iconKey, @evalModelHandle, isInit, @setIcon)
@maybeSetScopeValue('coords', model, oldModel, @coordsKey, @evalModelHandle, isInit, @setCoords)
if _.isFunction(@clickKey)
@scope.click = () =>
@clickKey(@gMarker, "click", @model, undefined)
else
@maybeSetScopeValue('click', model, oldModel, @clickKey, @evalModelHandle, isInit)
@createMarker(model, oldModel, isInit)
createMarker: (model, oldModel = undefined, isInit = false)=>
@maybeSetScopeValue 'options', model, oldModel, @optionsKey, @evalModelHandle, isInit, @setOptions
maybeSetScopeValue: (scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter = undefined) =>
if oldModel == undefined
@scope[scopePropName] = evaluate(model, modelKey)
unless isInit
gSetter(@scope) if gSetter?
return
oldVal = evaluate(oldModel, modelKey)
newValue = evaluate(model, modelKey)
if newValue != oldVal
@scope[scopePropName] = newValue
unless isInit
gSetter(@scope) if gSetter?
@gMarkerManager.draw() if @doDrawSelf
setCoords: (scope) =>
if scope.$id != @scope.$id or @gMarker == undefined
return
if scope.coords?
if !@validateCoords(@scope.coords)
$log.debug "MarkerChild does not have coords yet. They may be defined later."
return
@gMarker.setPosition @getCoords(scope.coords)
@gMarker.setVisible @validateCoords(scope.coords)
@gMarkerManager.add @gMarker
else
@gMarkerManager.remove @gMarker
setIcon: (scope) =>
if scope.$id != @scope.$id or @gMarker == undefined
return
@gMarkerManager.remove @gMarker
@gMarker.setIcon scope.icon
@gMarkerManager.add @gMarker
@gMarker.setPosition @getCoords(scope.coords)
@gMarker.setVisible @validateCoords(scope.coords)
setOptions: (scope) =>
if scope.$id != @scope.$id
return
if @gMarker?
@gMarkerManager.remove(@gMarker)
delete @gMarker
unless scope.coords ? scope.icon? scope.options?
return
@opts = @createOptions(scope.coords, scope.icon, scope.options)
delete @gMarker
if @isLabel @opts
@gMarker = new MarkerWithLabel @setLabelOptions @opts
else
@gMarker = new google.maps.Marker(@opts)
if @gMarker
@deferred.resolve @gMarker
else
@deferred.reject "gMarker is null"
if @model["fitKey"]
@gMarkerManager.fit()
#hook external event handlers for events
@removeEvents @externalListeners if @externalListeners
@removeEvents @internalListeners if @internalListeners
@externalListeners = @setEvents @gMarker, @scope, @model, ['dragend']
#must pass fake $apply see events-helper
@internalListeners = @setEvents @gMarker, {events: @internalEvents(), $apply: () ->}, @model
@gMarker.key = @id if @id?
@gMarkerManager.add @gMarker
setLabelOptions: (opts) =>
opts.labelAnchor = @getLabelPositionPoint opts.labelAnchor
opts
internalEvents: =>
dragend: (marker, eventName, model, mousearg) =>
modelToSet = if @trackModel then @scope.model else @model
newCoords = @setCoordsFromEvent @modelOrKey(modelToSet, @coordsKey), @gMarker.getPosition()
modelToSet = @setVal(model, @coordsKey, newCoords)
#since we ignored dragend for scope above, if @scope.events has it then we should fire it
@scope.events.dragend(marker, eventName, modelToSet, mousearg) if @scope.events?.dragend?
@scope.$apply()
click: (marker, eventName, model, mousearg) =>
if @doClick and @scope.click?
@scope.$apply @scope.click(marker, eventName, @model, mousearg)
MarkerChildModel
]
| 110024 | angular.module("google-maps.directives.api.models.child".ns())
.factory "MarkerChildModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(),
"Logger".ns(), "EventsHelper".ns(),
"MarkerOptions".ns(),
(ModelKey, GmapUtil, $log, EventsHelper, MarkerOptions) ->
keys = ['<KEY>
class MarkerChildModel extends ModelKey
@include GmapUtil
@include EventsHelper
@include MarkerOptions
destroy = (child) ->
if child?.gMarker?
child.removeEvents child.externalListeners
child.removeEvents child.internalListeners
if child?.gMarker
child?.gMarkerManager.remove child?.gMarker, true
delete child.gMarker
constructor: (scope, @model, @keys, @gMap, @defaults, @doClick, @gMarkerManager, @doDrawSelf = true,
@trackModel = true)->
_.each @keys, (v, k) =>
@[k + 'Key'] = if _.isFunction @keys[k] then @keys[k]() else @keys[k]
@idKey = @idKeyKey or "id"
@id = @model[@idKey] if @model[@idKey]?
@needRedraw = false
@deferred = Promise.defer()
super(scope)
@setMyScope(@model, undefined, true)
@createMarker(@model)
if @trackModel
@scope.model = @model
@scope.$watch 'model', (newValue, oldValue) =>
if (newValue != oldValue)
@setMyScope newValue, oldValue
@needRedraw = true
, true
else
_.each @keys, (v, k) =>
@scope.$watch k, =>
@setMyScope @scope
#hiding destroy functionality as it should only be called via scope.$destroy()
@scope.$on "$destroy", =>
destroy @
$log.info @
destroy: =>
@scope.$destroy()
setMyScope: (model, oldModel = undefined, isInit = false) =>
@maybeSetScopeValue('icon', model, oldModel, @iconKey, @evalModelHandle, isInit, @setIcon)
@maybeSetScopeValue('coords', model, oldModel, @coordsKey, @evalModelHandle, isInit, @setCoords)
if _.isFunction(@clickKey)
@scope.click = () =>
@clickKey(@gMarker, "click", @model, undefined)
else
@maybeSetScopeValue('click', model, oldModel, @clickKey, @evalModelHandle, isInit)
@createMarker(model, oldModel, isInit)
createMarker: (model, oldModel = undefined, isInit = false)=>
@maybeSetScopeValue 'options', model, oldModel, @optionsKey, @evalModelHandle, isInit, @setOptions
maybeSetScopeValue: (scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter = undefined) =>
if oldModel == undefined
@scope[scopePropName] = evaluate(model, modelKey)
unless isInit
gSetter(@scope) if gSetter?
return
oldVal = evaluate(oldModel, modelKey)
newValue = evaluate(model, modelKey)
if newValue != oldVal
@scope[scopePropName] = newValue
unless isInit
gSetter(@scope) if gSetter?
@gMarkerManager.draw() if @doDrawSelf
setCoords: (scope) =>
if scope.$id != @scope.$id or @gMarker == undefined
return
if scope.coords?
if !@validateCoords(@scope.coords)
$log.debug "MarkerChild does not have coords yet. They may be defined later."
return
@gMarker.setPosition @getCoords(scope.coords)
@gMarker.setVisible @validateCoords(scope.coords)
@gMarkerManager.add @gMarker
else
@gMarkerManager.remove @gMarker
setIcon: (scope) =>
if scope.$id != @scope.$id or @gMarker == undefined
return
@gMarkerManager.remove @gMarker
@gMarker.setIcon scope.icon
@gMarkerManager.add @gMarker
@gMarker.setPosition @getCoords(scope.coords)
@gMarker.setVisible @validateCoords(scope.coords)
setOptions: (scope) =>
if scope.$id != @scope.$id
return
if @gMarker?
@gMarkerManager.remove(@gMarker)
delete @gMarker
unless scope.coords ? scope.icon? scope.options?
return
@opts = @createOptions(scope.coords, scope.icon, scope.options)
delete @gMarker
if @isLabel @opts
@gMarker = new MarkerWithLabel @setLabelOptions @opts
else
@gMarker = new google.maps.Marker(@opts)
if @gMarker
@deferred.resolve @gMarker
else
@deferred.reject "gMarker is null"
if @model["fitKey"]
@gMarkerManager.fit()
#hook external event handlers for events
@removeEvents @externalListeners if @externalListeners
@removeEvents @internalListeners if @internalListeners
@externalListeners = @setEvents @gMarker, @scope, @model, ['dragend']
#must pass fake $apply see events-helper
@internalListeners = @setEvents @gMarker, {events: @internalEvents(), $apply: () ->}, @model
@gMarker.key = @<KEY> if @id?
@gMarkerManager.add @gMarker
setLabelOptions: (opts) =>
opts.labelAnchor = @getLabelPositionPoint opts.labelAnchor
opts
internalEvents: =>
dragend: (marker, eventName, model, mousearg) =>
modelToSet = if @trackModel then @scope.model else @model
newCoords = @setCoordsFromEvent @modelOrKey(modelToSet, @coordsKey), @gMarker.getPosition()
modelToSet = @setVal(model, @coordsKey, newCoords)
#since we ignored dragend for scope above, if @scope.events has it then we should fire it
@scope.events.dragend(marker, eventName, modelToSet, mousearg) if @scope.events?.dragend?
@scope.$apply()
click: (marker, eventName, model, mousearg) =>
if @doClick and @scope.click?
@scope.$apply @scope.click(marker, eventName, @model, mousearg)
MarkerChildModel
]
| true | angular.module("google-maps.directives.api.models.child".ns())
.factory "MarkerChildModel".ns(), [ "ModelKey".ns(), "GmapUtil".ns(),
"Logger".ns(), "EventsHelper".ns(),
"MarkerOptions".ns(),
(ModelKey, GmapUtil, $log, EventsHelper, MarkerOptions) ->
keys = ['PI:KEY:<KEY>END_PI
class MarkerChildModel extends ModelKey
@include GmapUtil
@include EventsHelper
@include MarkerOptions
destroy = (child) ->
if child?.gMarker?
child.removeEvents child.externalListeners
child.removeEvents child.internalListeners
if child?.gMarker
child?.gMarkerManager.remove child?.gMarker, true
delete child.gMarker
constructor: (scope, @model, @keys, @gMap, @defaults, @doClick, @gMarkerManager, @doDrawSelf = true,
@trackModel = true)->
_.each @keys, (v, k) =>
@[k + 'Key'] = if _.isFunction @keys[k] then @keys[k]() else @keys[k]
@idKey = @idKeyKey or "id"
@id = @model[@idKey] if @model[@idKey]?
@needRedraw = false
@deferred = Promise.defer()
super(scope)
@setMyScope(@model, undefined, true)
@createMarker(@model)
if @trackModel
@scope.model = @model
@scope.$watch 'model', (newValue, oldValue) =>
if (newValue != oldValue)
@setMyScope newValue, oldValue
@needRedraw = true
, true
else
_.each @keys, (v, k) =>
@scope.$watch k, =>
@setMyScope @scope
#hiding destroy functionality as it should only be called via scope.$destroy()
@scope.$on "$destroy", =>
destroy @
$log.info @
destroy: =>
@scope.$destroy()
setMyScope: (model, oldModel = undefined, isInit = false) =>
@maybeSetScopeValue('icon', model, oldModel, @iconKey, @evalModelHandle, isInit, @setIcon)
@maybeSetScopeValue('coords', model, oldModel, @coordsKey, @evalModelHandle, isInit, @setCoords)
if _.isFunction(@clickKey)
@scope.click = () =>
@clickKey(@gMarker, "click", @model, undefined)
else
@maybeSetScopeValue('click', model, oldModel, @clickKey, @evalModelHandle, isInit)
@createMarker(model, oldModel, isInit)
createMarker: (model, oldModel = undefined, isInit = false)=>
@maybeSetScopeValue 'options', model, oldModel, @optionsKey, @evalModelHandle, isInit, @setOptions
maybeSetScopeValue: (scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter = undefined) =>
if oldModel == undefined
@scope[scopePropName] = evaluate(model, modelKey)
unless isInit
gSetter(@scope) if gSetter?
return
oldVal = evaluate(oldModel, modelKey)
newValue = evaluate(model, modelKey)
if newValue != oldVal
@scope[scopePropName] = newValue
unless isInit
gSetter(@scope) if gSetter?
@gMarkerManager.draw() if @doDrawSelf
setCoords: (scope) =>
if scope.$id != @scope.$id or @gMarker == undefined
return
if scope.coords?
if !@validateCoords(@scope.coords)
$log.debug "MarkerChild does not have coords yet. They may be defined later."
return
@gMarker.setPosition @getCoords(scope.coords)
@gMarker.setVisible @validateCoords(scope.coords)
@gMarkerManager.add @gMarker
else
@gMarkerManager.remove @gMarker
setIcon: (scope) =>
if scope.$id != @scope.$id or @gMarker == undefined
return
@gMarkerManager.remove @gMarker
@gMarker.setIcon scope.icon
@gMarkerManager.add @gMarker
@gMarker.setPosition @getCoords(scope.coords)
@gMarker.setVisible @validateCoords(scope.coords)
setOptions: (scope) =>
if scope.$id != @scope.$id
return
if @gMarker?
@gMarkerManager.remove(@gMarker)
delete @gMarker
unless scope.coords ? scope.icon? scope.options?
return
@opts = @createOptions(scope.coords, scope.icon, scope.options)
delete @gMarker
if @isLabel @opts
@gMarker = new MarkerWithLabel @setLabelOptions @opts
else
@gMarker = new google.maps.Marker(@opts)
if @gMarker
@deferred.resolve @gMarker
else
@deferred.reject "gMarker is null"
if @model["fitKey"]
@gMarkerManager.fit()
#hook external event handlers for events
@removeEvents @externalListeners if @externalListeners
@removeEvents @internalListeners if @internalListeners
@externalListeners = @setEvents @gMarker, @scope, @model, ['dragend']
#must pass fake $apply see events-helper
@internalListeners = @setEvents @gMarker, {events: @internalEvents(), $apply: () ->}, @model
@gMarker.key = @PI:KEY:<KEY>END_PI if @id?
@gMarkerManager.add @gMarker
setLabelOptions: (opts) =>
opts.labelAnchor = @getLabelPositionPoint opts.labelAnchor
opts
internalEvents: =>
dragend: (marker, eventName, model, mousearg) =>
modelToSet = if @trackModel then @scope.model else @model
newCoords = @setCoordsFromEvent @modelOrKey(modelToSet, @coordsKey), @gMarker.getPosition()
modelToSet = @setVal(model, @coordsKey, newCoords)
#since we ignored dragend for scope above, if @scope.events has it then we should fire it
@scope.events.dragend(marker, eventName, modelToSet, mousearg) if @scope.events?.dragend?
@scope.$apply()
click: (marker, eventName, model, mousearg) =>
if @doClick and @scope.click?
@scope.$apply @scope.click(marker, eventName, @model, mousearg)
MarkerChildModel
]
|
[
{
"context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apach",
"end": 35,
"score": 0.9998233914375305,
"start": 24,
"tag": "NAME",
"value": "Dan Elliott"
},
{
"context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed ... | clients/www/src/coffee/handler/DataManager.coffee | bluthen/isadore_server | 0 | # Copyright 2010-2019 Dan Elliott, Russell Valentine
#
# 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.
class window.DataManager
@_CHECK_EVENT_INTERVAL: 10000
@_reset: () ->
@_data = {}
@_subscriptionId = null
@_serverSubs = {'subscriptions': []}
@_jsSubs = {}
@_subInterval = null
@_getFillLock = false
@_getFillQueue = []
@_startInterval: () ->
if not @_subInterval?
@_subInterval = setInterval(
() =>
@_checkEvents()
@_CHECK_EVENT_INTERVAL)
@_checkEvents: () ->
###
Checks with the server to see if there are new events.
###
if @_subscriptionId?
#Ajax call to get subscription events
$.ajax({
url: "../resources/subscription_event/#{@_subscriptionId}"
type: 'DELETE'
dataType: 'json'
success: (data) =>
#for each event
for e in data.events
@_processEvent(JSON.parse(e.event))
error: (jqXHR) =>
#Reset
if jqXHR.statusCode == 404
@_reset()
})
@_serverSubscribe: (sub, cb) ->
if not @_subscriptionId
$.ajax({
url: '../resources/subscription'
type: 'POST'
dataType: 'json'
success: (data) =>
@_subscriptionId = data.subscriber_id
@_serverSubscribe2(sub, cb)
error: (jqXHR, textStatus, errorThrown) =>
console?.error?("#{textStatus} - #{errorThrown}")
cb?()
})
else
@_serverSubscribe2(sub, cb)
@_serverSubscribe2: (sub, cb) ->
@_serverSubs.subscriptions.push(sub)
$.ajax({
url: "../resources/subscription/#{@_subscriptionId}"
type: 'PUT'
dataType: 'text'
data: {subscribed: JSON.stringify(@_serverSubs)}
success: () ->
cb?()
error: (jqXHR, textStatus, errorThrown) =>
console?.trace?()
console?.error?("#{textStatus} - #{errorThrown}")
cb?()
})
@_getFill: (year, cb) ->
# If we don't have this years fill year
if @_getFillLock
@_getFillQueue.push(() =>
@_getFill(year, cb)
)
return
if not @_data.fill?[year]
# Subscribe to changes for this year's fill
@_getFillLock = true
fetchFills = () =>
# Fetch entire years fill using fill-fast
startYear = new Date(year, 0, 1, 0, 0, 0, 0)
endYear = new Date(year, 11, 31, 23, 59, 59, 999);
$.ajax({
url: '../resources/data/fills-fast'
type: 'GET'
dataType: 'json'
data: {
'begin_span1' : HTMLHelper.dateToParamString(startYear),
'begin_span2' : HTMLHelper.dateToParamString(endYear)
}
success: (data) =>
if not @_data.fill?
@_data.fill = {}
@_data.fill[year] = data.fills
try
cb?(@_data.fill[year])
finally
@_getFillLock = false
while @_getFillQueue.length > 0
f = @_getFillQueue.splice(0, 1)[0]
f?()
error: (jqXHR, textStatus, errorThrown) =>
console?.error?("#{textStatus} - #{errorThrown}")
@_getFillLock = false
while @_getFillQueue.length > 0
f = @_getFillQueue.splice(0, 1)[0]
f?()
})
@_serverSubscribe({key: 'fill', type: ['edit', 'add', 'delete'], year: year, self_events: false},
fetchFills
)
else
cb?(@_data.fill[year])
@_removeExistingFills: (year, fill_ids) ->
###
@param year The year to look for ids to remove.
@params fill_ids ids to remove if exist.
###
_.remove(@_data.fill[year], (f) ->
return f.id in fill_ids
)
@_processEvent: (event) ->
###
Process event from a publish or REST found event
@params event.key
@params event.type {string} one of 'edit', 'delete', 'add'
@params event.ids {array of numbers}
@params event.year {number} (required if type='fill')
@params event.when {ISO8601 datestring} (optional)
@params event.data (optional) Updated object to hold in manager, for fill key event it should be {fills: [{fill}, ...]}.
###
# if event.key == 'fill' and if we have fill year's data
if event.key? and event.key == 'fill' and @_data.fill?[event.year]
if event.type in ['delete', 'edit']
@_removeExistingFills(event.year, event.ids)
if event.type in ['add', 'edit']
if event.data?.fills?
# If event.data copy event.data add that to our data
for fill in event.data.fills
@_data.fill[event.year].push(_.cloneDeep(fill))
@_processEventCallbacks(event)
else
finished = {}
for fillId in event.ids
finished[fillId] = false
for fillId in event.ids
$.ajax({
url: "../resources/data/fills/#{fillId}"
type: 'GET'
dataType: 'json'
success: (data) =>
@_removeExistingFills(event.year, [data.id])
@_data.fill[event.year].push(data)
finished[data.id] = data
if _.every(finished)
event.data = {fills: _.toArray(finished)}
@_processEventCallbacks(event)
})
else
@_processEventCallbacks(event)
else
console?.warn?('_processEvent, unsupported event.key')
@_processEventCallbacks: (event) ->
###
Goes through js subscriptions and calls the callback of any subscriptions matching event.
@param event the event to do callbacks for.
###
#Currently only fill key is supported
for sid, sub of @_jsSubs
#Go through subscriptions
if (
sub.key == 'fill' and event.key == sub.key and event.year == sub.year and
(event.type == sub.type or (_.isArray(sub.type) and event.type in sub.type))
)
#If subscription matches event
if sub.ids? and _.intersection(event.ids, sub.ids).length() > 0
#Call subscriptions callback with copy of event
e = _.cloneDeep(event)
e.data.fills = _.filter(e.data.fills, (f) -> f.id in sub.ids)
sub.callback?(e)
else
sub.callback?(_.cloneDeep(event))
@getFills: (args) ->
###
Get request fills ids from year, if no ids will give entire year. This will fetch it from server if not cached,
otherwise returns cached data. This attempts to keep cache updated.
@param args.year {number} The year of fills to get
@param args.ids {array of numbers} (optional) ids you want from that year.
@param args.callback {function} function(data) The callback to call with own copy of the data.
Example data
{'fills': [{filldata}, {filldata}, ...}]}
###
# Get data requested
args.year = parseInt(args.year, 10)
if args.ids?
for i in [0...args.ids.length]
args.ids[i] = parseInt(args.ids[i], 10)
@_getFill(
args.year,
(fills) =>
f = {'fills': []}
if args.ids?
#Take out fills with id that we want
for fill in fills
if fill.id in args.ids
f.fills.push(fill)
# Callback with copy of data
args.callback?(_.cloneDeep(f))
else
# Callback with copy of data
args.callback?({fills: _.cloneDeep(fills)})
)
@dataSub: (args) ->
###
Subscribe to data change events.
@param args.key {string} Only value for this currently support is 'fill'
@param args.type {array of strings} valid strings are 'edit', 'add', 'delete'
@params args.ids {array of numbers} (optional) valid with 'edit'/'delete' type, which key ids should trigger the event.
@params args.year {number} (required for key='fill') Which year we are listening for.
@param args.callback {function} function(data) data is of format {key: args.key, type: type, ids: [id1, .., idn], year: year, data: newdata}
@returns subscription id to use with @dataUnSub
###
if args.key == 'fill'
@_getFill(args.year)
# add subscription to subscribers list
id = _.uniqueId('dataSub_')
@_jsSubs[id] = args
else
throw "Unsuported key type."
#Return subscription id
return id
@dataUnSub: (id) ->
###
Unsubscribes from data event.
@param id The id returned by @dataSub
###
delete @_jsSubs[id]
@dataPub: (event) ->
###
Publish a data change event.
@param event.key {string} Only value for this currently support is 'fill'
@param event.type {string} Valid values are 'edit', 'add', 'delete'
@param event.year {number} (required for key='fill') Which year event is for
@param event.data {object} replacement object if type = 'edit', 'add', null if type='delete'
###
@_processEvent(_.cloneDeep(event))
@getRestSubscriberId: () ->
###
Get the subscription id assigned to this client.
@return uuid of subscription id that is used in rest api.
###
return @_subscriptionId;
$(document).ready( () ->
DataManager._reset()
DataManager._startInterval()
)
| 148582 | # Copyright 2010-2019 <NAME>, <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.
class window.DataManager
@_CHECK_EVENT_INTERVAL: 10000
@_reset: () ->
@_data = {}
@_subscriptionId = null
@_serverSubs = {'subscriptions': []}
@_jsSubs = {}
@_subInterval = null
@_getFillLock = false
@_getFillQueue = []
@_startInterval: () ->
if not @_subInterval?
@_subInterval = setInterval(
() =>
@_checkEvents()
@_CHECK_EVENT_INTERVAL)
@_checkEvents: () ->
###
Checks with the server to see if there are new events.
###
if @_subscriptionId?
#Ajax call to get subscription events
$.ajax({
url: "../resources/subscription_event/#{@_subscriptionId}"
type: 'DELETE'
dataType: 'json'
success: (data) =>
#for each event
for e in data.events
@_processEvent(JSON.parse(e.event))
error: (jqXHR) =>
#Reset
if jqXHR.statusCode == 404
@_reset()
})
@_serverSubscribe: (sub, cb) ->
if not @_subscriptionId
$.ajax({
url: '../resources/subscription'
type: 'POST'
dataType: 'json'
success: (data) =>
@_subscriptionId = data.subscriber_id
@_serverSubscribe2(sub, cb)
error: (jqXHR, textStatus, errorThrown) =>
console?.error?("#{textStatus} - #{errorThrown}")
cb?()
})
else
@_serverSubscribe2(sub, cb)
@_serverSubscribe2: (sub, cb) ->
@_serverSubs.subscriptions.push(sub)
$.ajax({
url: "../resources/subscription/#{@_subscriptionId}"
type: 'PUT'
dataType: 'text'
data: {subscribed: JSON.stringify(@_serverSubs)}
success: () ->
cb?()
error: (jqXHR, textStatus, errorThrown) =>
console?.trace?()
console?.error?("#{textStatus} - #{errorThrown}")
cb?()
})
@_getFill: (year, cb) ->
# If we don't have this years fill year
if @_getFillLock
@_getFillQueue.push(() =>
@_getFill(year, cb)
)
return
if not @_data.fill?[year]
# Subscribe to changes for this year's fill
@_getFillLock = true
fetchFills = () =>
# Fetch entire years fill using fill-fast
startYear = new Date(year, 0, 1, 0, 0, 0, 0)
endYear = new Date(year, 11, 31, 23, 59, 59, 999);
$.ajax({
url: '../resources/data/fills-fast'
type: 'GET'
dataType: 'json'
data: {
'begin_span1' : HTMLHelper.dateToParamString(startYear),
'begin_span2' : HTMLHelper.dateToParamString(endYear)
}
success: (data) =>
if not @_data.fill?
@_data.fill = {}
@_data.fill[year] = data.fills
try
cb?(@_data.fill[year])
finally
@_getFillLock = false
while @_getFillQueue.length > 0
f = @_getFillQueue.splice(0, 1)[0]
f?()
error: (jqXHR, textStatus, errorThrown) =>
console?.error?("#{textStatus} - #{errorThrown}")
@_getFillLock = false
while @_getFillQueue.length > 0
f = @_getFillQueue.splice(0, 1)[0]
f?()
})
@_serverSubscribe({key: 'fill', type: ['edit', 'add', 'delete'], year: year, self_events: false},
fetchFills
)
else
cb?(@_data.fill[year])
@_removeExistingFills: (year, fill_ids) ->
###
@param year The year to look for ids to remove.
@params fill_ids ids to remove if exist.
###
_.remove(@_data.fill[year], (f) ->
return f.id in fill_ids
)
@_processEvent: (event) ->
###
Process event from a publish or REST found event
@params event.key
@params event.type {string} one of 'edit', 'delete', 'add'
@params event.ids {array of numbers}
@params event.year {number} (required if type='fill')
@params event.when {ISO8601 datestring} (optional)
@params event.data (optional) Updated object to hold in manager, for fill key event it should be {fills: [{fill}, ...]}.
###
# if event.key == 'fill' and if we have fill year's data
if event.key? and event.key == 'fill' and @_data.fill?[event.year]
if event.type in ['delete', 'edit']
@_removeExistingFills(event.year, event.ids)
if event.type in ['add', 'edit']
if event.data?.fills?
# If event.data copy event.data add that to our data
for fill in event.data.fills
@_data.fill[event.year].push(_.cloneDeep(fill))
@_processEventCallbacks(event)
else
finished = {}
for fillId in event.ids
finished[fillId] = false
for fillId in event.ids
$.ajax({
url: "../resources/data/fills/#{fillId}"
type: 'GET'
dataType: 'json'
success: (data) =>
@_removeExistingFills(event.year, [data.id])
@_data.fill[event.year].push(data)
finished[data.id] = data
if _.every(finished)
event.data = {fills: _.toArray(finished)}
@_processEventCallbacks(event)
})
else
@_processEventCallbacks(event)
else
console?.warn?('_processEvent, unsupported event.key')
@_processEventCallbacks: (event) ->
###
Goes through js subscriptions and calls the callback of any subscriptions matching event.
@param event the event to do callbacks for.
###
#Currently only fill key is supported
for sid, sub of @_jsSubs
#Go through subscriptions
if (
sub.key == 'fill' and event.key == sub.key and event.year == sub.year and
(event.type == sub.type or (_.isArray(sub.type) and event.type in sub.type))
)
#If subscription matches event
if sub.ids? and _.intersection(event.ids, sub.ids).length() > 0
#Call subscriptions callback with copy of event
e = _.cloneDeep(event)
e.data.fills = _.filter(e.data.fills, (f) -> f.id in sub.ids)
sub.callback?(e)
else
sub.callback?(_.cloneDeep(event))
@getFills: (args) ->
###
Get request fills ids from year, if no ids will give entire year. This will fetch it from server if not cached,
otherwise returns cached data. This attempts to keep cache updated.
@param args.year {number} The year of fills to get
@param args.ids {array of numbers} (optional) ids you want from that year.
@param args.callback {function} function(data) The callback to call with own copy of the data.
Example data
{'fills': [{filldata}, {filldata}, ...}]}
###
# Get data requested
args.year = parseInt(args.year, 10)
if args.ids?
for i in [0...args.ids.length]
args.ids[i] = parseInt(args.ids[i], 10)
@_getFill(
args.year,
(fills) =>
f = {'fills': []}
if args.ids?
#Take out fills with id that we want
for fill in fills
if fill.id in args.ids
f.fills.push(fill)
# Callback with copy of data
args.callback?(_.cloneDeep(f))
else
# Callback with copy of data
args.callback?({fills: _.cloneDeep(fills)})
)
@dataSub: (args) ->
###
Subscribe to data change events.
@param args.key {string} Only value for this currently support is 'fill'
@param args.type {array of strings} valid strings are 'edit', 'add', 'delete'
@params args.ids {array of numbers} (optional) valid with 'edit'/'delete' type, which key ids should trigger the event.
@params args.year {number} (required for key='fill') Which year we are listening for.
@param args.callback {function} function(data) data is of format {key: args.key, type: type, ids: [id1, .., idn], year: year, data: newdata}
@returns subscription id to use with @dataUnSub
###
if args.key == 'fill'
@_getFill(args.year)
# add subscription to subscribers list
id = _.uniqueId('dataSub_')
@_jsSubs[id] = args
else
throw "Unsuported key type."
#Return subscription id
return id
@dataUnSub: (id) ->
###
Unsubscribes from data event.
@param id The id returned by @dataSub
###
delete @_jsSubs[id]
@dataPub: (event) ->
###
Publish a data change event.
@param event.key {string} Only value for this currently support is 'fill'
@param event.type {string} Valid values are 'edit', 'add', 'delete'
@param event.year {number} (required for key='fill') Which year event is for
@param event.data {object} replacement object if type = 'edit', 'add', null if type='delete'
###
@_processEvent(_.cloneDeep(event))
@getRestSubscriberId: () ->
###
Get the subscription id assigned to this client.
@return uuid of subscription id that is used in rest api.
###
return @_subscriptionId;
$(document).ready( () ->
DataManager._reset()
DataManager._startInterval()
)
| true | # Copyright 2010-2019 PI:NAME:<NAME>END_PI, 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.
class window.DataManager
@_CHECK_EVENT_INTERVAL: 10000
@_reset: () ->
@_data = {}
@_subscriptionId = null
@_serverSubs = {'subscriptions': []}
@_jsSubs = {}
@_subInterval = null
@_getFillLock = false
@_getFillQueue = []
@_startInterval: () ->
if not @_subInterval?
@_subInterval = setInterval(
() =>
@_checkEvents()
@_CHECK_EVENT_INTERVAL)
@_checkEvents: () ->
###
Checks with the server to see if there are new events.
###
if @_subscriptionId?
#Ajax call to get subscription events
$.ajax({
url: "../resources/subscription_event/#{@_subscriptionId}"
type: 'DELETE'
dataType: 'json'
success: (data) =>
#for each event
for e in data.events
@_processEvent(JSON.parse(e.event))
error: (jqXHR) =>
#Reset
if jqXHR.statusCode == 404
@_reset()
})
@_serverSubscribe: (sub, cb) ->
if not @_subscriptionId
$.ajax({
url: '../resources/subscription'
type: 'POST'
dataType: 'json'
success: (data) =>
@_subscriptionId = data.subscriber_id
@_serverSubscribe2(sub, cb)
error: (jqXHR, textStatus, errorThrown) =>
console?.error?("#{textStatus} - #{errorThrown}")
cb?()
})
else
@_serverSubscribe2(sub, cb)
@_serverSubscribe2: (sub, cb) ->
@_serverSubs.subscriptions.push(sub)
$.ajax({
url: "../resources/subscription/#{@_subscriptionId}"
type: 'PUT'
dataType: 'text'
data: {subscribed: JSON.stringify(@_serverSubs)}
success: () ->
cb?()
error: (jqXHR, textStatus, errorThrown) =>
console?.trace?()
console?.error?("#{textStatus} - #{errorThrown}")
cb?()
})
@_getFill: (year, cb) ->
# If we don't have this years fill year
if @_getFillLock
@_getFillQueue.push(() =>
@_getFill(year, cb)
)
return
if not @_data.fill?[year]
# Subscribe to changes for this year's fill
@_getFillLock = true
fetchFills = () =>
# Fetch entire years fill using fill-fast
startYear = new Date(year, 0, 1, 0, 0, 0, 0)
endYear = new Date(year, 11, 31, 23, 59, 59, 999);
$.ajax({
url: '../resources/data/fills-fast'
type: 'GET'
dataType: 'json'
data: {
'begin_span1' : HTMLHelper.dateToParamString(startYear),
'begin_span2' : HTMLHelper.dateToParamString(endYear)
}
success: (data) =>
if not @_data.fill?
@_data.fill = {}
@_data.fill[year] = data.fills
try
cb?(@_data.fill[year])
finally
@_getFillLock = false
while @_getFillQueue.length > 0
f = @_getFillQueue.splice(0, 1)[0]
f?()
error: (jqXHR, textStatus, errorThrown) =>
console?.error?("#{textStatus} - #{errorThrown}")
@_getFillLock = false
while @_getFillQueue.length > 0
f = @_getFillQueue.splice(0, 1)[0]
f?()
})
@_serverSubscribe({key: 'fill', type: ['edit', 'add', 'delete'], year: year, self_events: false},
fetchFills
)
else
cb?(@_data.fill[year])
@_removeExistingFills: (year, fill_ids) ->
###
@param year The year to look for ids to remove.
@params fill_ids ids to remove if exist.
###
_.remove(@_data.fill[year], (f) ->
return f.id in fill_ids
)
@_processEvent: (event) ->
###
Process event from a publish or REST found event
@params event.key
@params event.type {string} one of 'edit', 'delete', 'add'
@params event.ids {array of numbers}
@params event.year {number} (required if type='fill')
@params event.when {ISO8601 datestring} (optional)
@params event.data (optional) Updated object to hold in manager, for fill key event it should be {fills: [{fill}, ...]}.
###
# if event.key == 'fill' and if we have fill year's data
if event.key? and event.key == 'fill' and @_data.fill?[event.year]
if event.type in ['delete', 'edit']
@_removeExistingFills(event.year, event.ids)
if event.type in ['add', 'edit']
if event.data?.fills?
# If event.data copy event.data add that to our data
for fill in event.data.fills
@_data.fill[event.year].push(_.cloneDeep(fill))
@_processEventCallbacks(event)
else
finished = {}
for fillId in event.ids
finished[fillId] = false
for fillId in event.ids
$.ajax({
url: "../resources/data/fills/#{fillId}"
type: 'GET'
dataType: 'json'
success: (data) =>
@_removeExistingFills(event.year, [data.id])
@_data.fill[event.year].push(data)
finished[data.id] = data
if _.every(finished)
event.data = {fills: _.toArray(finished)}
@_processEventCallbacks(event)
})
else
@_processEventCallbacks(event)
else
console?.warn?('_processEvent, unsupported event.key')
@_processEventCallbacks: (event) ->
###
Goes through js subscriptions and calls the callback of any subscriptions matching event.
@param event the event to do callbacks for.
###
#Currently only fill key is supported
for sid, sub of @_jsSubs
#Go through subscriptions
if (
sub.key == 'fill' and event.key == sub.key and event.year == sub.year and
(event.type == sub.type or (_.isArray(sub.type) and event.type in sub.type))
)
#If subscription matches event
if sub.ids? and _.intersection(event.ids, sub.ids).length() > 0
#Call subscriptions callback with copy of event
e = _.cloneDeep(event)
e.data.fills = _.filter(e.data.fills, (f) -> f.id in sub.ids)
sub.callback?(e)
else
sub.callback?(_.cloneDeep(event))
@getFills: (args) ->
###
Get request fills ids from year, if no ids will give entire year. This will fetch it from server if not cached,
otherwise returns cached data. This attempts to keep cache updated.
@param args.year {number} The year of fills to get
@param args.ids {array of numbers} (optional) ids you want from that year.
@param args.callback {function} function(data) The callback to call with own copy of the data.
Example data
{'fills': [{filldata}, {filldata}, ...}]}
###
# Get data requested
args.year = parseInt(args.year, 10)
if args.ids?
for i in [0...args.ids.length]
args.ids[i] = parseInt(args.ids[i], 10)
@_getFill(
args.year,
(fills) =>
f = {'fills': []}
if args.ids?
#Take out fills with id that we want
for fill in fills
if fill.id in args.ids
f.fills.push(fill)
# Callback with copy of data
args.callback?(_.cloneDeep(f))
else
# Callback with copy of data
args.callback?({fills: _.cloneDeep(fills)})
)
@dataSub: (args) ->
###
Subscribe to data change events.
@param args.key {string} Only value for this currently support is 'fill'
@param args.type {array of strings} valid strings are 'edit', 'add', 'delete'
@params args.ids {array of numbers} (optional) valid with 'edit'/'delete' type, which key ids should trigger the event.
@params args.year {number} (required for key='fill') Which year we are listening for.
@param args.callback {function} function(data) data is of format {key: args.key, type: type, ids: [id1, .., idn], year: year, data: newdata}
@returns subscription id to use with @dataUnSub
###
if args.key == 'fill'
@_getFill(args.year)
# add subscription to subscribers list
id = _.uniqueId('dataSub_')
@_jsSubs[id] = args
else
throw "Unsuported key type."
#Return subscription id
return id
@dataUnSub: (id) ->
###
Unsubscribes from data event.
@param id The id returned by @dataSub
###
delete @_jsSubs[id]
@dataPub: (event) ->
###
Publish a data change event.
@param event.key {string} Only value for this currently support is 'fill'
@param event.type {string} Valid values are 'edit', 'add', 'delete'
@param event.year {number} (required for key='fill') Which year event is for
@param event.data {object} replacement object if type = 'edit', 'add', null if type='delete'
###
@_processEvent(_.cloneDeep(event))
@getRestSubscriberId: () ->
###
Get the subscription id assigned to this client.
@return uuid of subscription id that is used in rest api.
###
return @_subscriptionId;
$(document).ready( () ->
DataManager._reset()
DataManager._startInterval()
)
|
[
{
"context": "elp - cherwell commands\n#\n# Notes:\n#\n# Author:\n# gfjohnson\n\ncher = require 'cheroapjs'\n\nmoduledesc = 'Cherwe",
"end": 429,
"score": 0.9996587634086609,
"start": 420,
"tag": "USERNAME",
"value": "gfjohnson"
},
{
"context": "ost: 'localhost'\n userId: 'example... | src/cherwell.coffee | gsfjohnson/hubot-cherwell | 0 | # coffeelint: disable=max_line_length
#
# Description:
# Interact with Cherwell API.
#
# Dependencies:
# cheroapjs
#
# Configuration:
# HUBOT_CHERWELL_HOST [required] - url (e.g. cher.example.com)
# HUBOT_CHERWELL_USER [required] - api user
# HUBOT_CHERWELL_PASS [required] - api pass
# HUBOT_CHERWELL_SSL [optional] - use ssl
#
# Commands:
# hubot cher help - cherwell commands
#
# Notes:
#
# Author:
# gfjohnson
cher = require 'cheroapjs'
moduledesc = 'Cherwell'
modulename = 'cher'
config =
host: 'localhost'
userId: 'example'
password: 'example'
ssl: true
config.ssl = true if process.env.HUBOT_CHERWELL_SSL
config.host = process.env.HUBOT_CHERWELL_HOST if process.env.HUBOT_CHERWELL_HOST
config.userId = process.env.HUBOT_CHERWELL_USERID if process.env.HUBOT_CHERWELL_USERID
config.password = process.env.HUBOT_CHERWELL_PASS if process.env.HUBOT_CHERWELL_PASS
unless config.userId == "example"
cher.connect config
GetBusinessObjectByPublicId = (robot, msg, args) ->
# robot.logger.info "searchByObjectTypes: sending request for #{keyword}"
cher.GetBusinessObjectByPublicId args, (err, res) ->
if err
msgout = "#{moduledesc}: error"
robot.logger.info "#{msgout} (#{err}) [#{msg.envelope.user.name}]"
return robot.send {room: msg.envelope.user.name}, "#{msgout}, check hubot log for details"
if res is null or !res.ShortDescription
msgout = "#{moduledesc}: no result for `#{JSON.stringify(args)}`"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
r = []
r.push "ShortDesc: #{res.ShortDescription.substring 0, 300}"
r.push "Created: #{res.CreatedDateTime}"
r.push "LastModified: #{res.LastModifiedDateTime}"
r.push "Closed: #{res.ClosedDateTime}"
r.push "Service: #{res.Service}"
r.push "Category: #{res.Category} -> #{res.Subcategory}"
r.push "Owned by: #{res.OwnedBy} (#{res.OwnedByTeam})"
r.push ""
r.push "#{res.Description.substring 0, 2000}"
out = r.join "\n"
msgout = "#{moduledesc}: ```#{out}```"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
module.exports = (robot) ->
robot.respond /cher help$/, (msg) ->
cmds = []
arr = [
"#{modulename} incident <id> - show incident"
]
for str in arr
cmd = str.split " - "
cmds.push "`#{cmd[0]}` - #{cmd[1]}"
robot.send {room: msg.message?.user?.name}, cmds.join "\n"
robot.respond /cher i(?:ncident)? (\d+)$/i, (msg) ->
id = msg.match[1]
robot.logger.info "#{moduledesc}: incident search: #{id} [#{msg.envelope.user.name}]"
args =
busObPublicId: id
return GetBusinessObjectByPublicId robot, msg, args
| 200654 | # coffeelint: disable=max_line_length
#
# Description:
# Interact with Cherwell API.
#
# Dependencies:
# cheroapjs
#
# Configuration:
# HUBOT_CHERWELL_HOST [required] - url (e.g. cher.example.com)
# HUBOT_CHERWELL_USER [required] - api user
# HUBOT_CHERWELL_PASS [required] - api pass
# HUBOT_CHERWELL_SSL [optional] - use ssl
#
# Commands:
# hubot cher help - cherwell commands
#
# Notes:
#
# Author:
# gfjohnson
cher = require 'cheroapjs'
moduledesc = 'Cherwell'
modulename = 'cher'
config =
host: 'localhost'
userId: 'example'
password: '<PASSWORD>'
ssl: true
config.ssl = true if process.env.HUBOT_CHERWELL_SSL
config.host = process.env.HUBOT_CHERWELL_HOST if process.env.HUBOT_CHERWELL_HOST
config.userId = process.env.HUBOT_CHERWELL_USERID if process.env.HUBOT_CHERWELL_USERID
config.password = process.env.HUBOT_CHERWELL_PASS if process.env.HUBOT_CHERWELL_PASS
unless config.userId == "example"
cher.connect config
GetBusinessObjectByPublicId = (robot, msg, args) ->
# robot.logger.info "searchByObjectTypes: sending request for #{keyword}"
cher.GetBusinessObjectByPublicId args, (err, res) ->
if err
msgout = "#{moduledesc}: error"
robot.logger.info "#{msgout} (#{err}) [#{msg.envelope.user.name}]"
return robot.send {room: msg.envelope.user.name}, "#{msgout}, check hubot log for details"
if res is null or !res.ShortDescription
msgout = "#{moduledesc}: no result for `#{JSON.stringify(args)}`"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
r = []
r.push "ShortDesc: #{res.ShortDescription.substring 0, 300}"
r.push "Created: #{res.CreatedDateTime}"
r.push "LastModified: #{res.LastModifiedDateTime}"
r.push "Closed: #{res.ClosedDateTime}"
r.push "Service: #{res.Service}"
r.push "Category: #{res.Category} -> #{res.Subcategory}"
r.push "Owned by: #{res.OwnedBy} (#{res.OwnedByTeam})"
r.push ""
r.push "#{res.Description.substring 0, 2000}"
out = r.join "\n"
msgout = "#{moduledesc}: ```#{out}```"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
module.exports = (robot) ->
robot.respond /cher help$/, (msg) ->
cmds = []
arr = [
"#{modulename} incident <id> - show incident"
]
for str in arr
cmd = str.split " - "
cmds.push "`#{cmd[0]}` - #{cmd[1]}"
robot.send {room: msg.message?.user?.name}, cmds.join "\n"
robot.respond /cher i(?:ncident)? (\d+)$/i, (msg) ->
id = msg.match[1]
robot.logger.info "#{moduledesc}: incident search: #{id} [#{msg.envelope.user.name}]"
args =
busObPublicId: id
return GetBusinessObjectByPublicId robot, msg, args
| true | # coffeelint: disable=max_line_length
#
# Description:
# Interact with Cherwell API.
#
# Dependencies:
# cheroapjs
#
# Configuration:
# HUBOT_CHERWELL_HOST [required] - url (e.g. cher.example.com)
# HUBOT_CHERWELL_USER [required] - api user
# HUBOT_CHERWELL_PASS [required] - api pass
# HUBOT_CHERWELL_SSL [optional] - use ssl
#
# Commands:
# hubot cher help - cherwell commands
#
# Notes:
#
# Author:
# gfjohnson
cher = require 'cheroapjs'
moduledesc = 'Cherwell'
modulename = 'cher'
config =
host: 'localhost'
userId: 'example'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
ssl: true
config.ssl = true if process.env.HUBOT_CHERWELL_SSL
config.host = process.env.HUBOT_CHERWELL_HOST if process.env.HUBOT_CHERWELL_HOST
config.userId = process.env.HUBOT_CHERWELL_USERID if process.env.HUBOT_CHERWELL_USERID
config.password = process.env.HUBOT_CHERWELL_PASS if process.env.HUBOT_CHERWELL_PASS
unless config.userId == "example"
cher.connect config
GetBusinessObjectByPublicId = (robot, msg, args) ->
# robot.logger.info "searchByObjectTypes: sending request for #{keyword}"
cher.GetBusinessObjectByPublicId args, (err, res) ->
if err
msgout = "#{moduledesc}: error"
robot.logger.info "#{msgout} (#{err}) [#{msg.envelope.user.name}]"
return robot.send {room: msg.envelope.user.name}, "#{msgout}, check hubot log for details"
if res is null or !res.ShortDescription
msgout = "#{moduledesc}: no result for `#{JSON.stringify(args)}`"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
r = []
r.push "ShortDesc: #{res.ShortDescription.substring 0, 300}"
r.push "Created: #{res.CreatedDateTime}"
r.push "LastModified: #{res.LastModifiedDateTime}"
r.push "Closed: #{res.ClosedDateTime}"
r.push "Service: #{res.Service}"
r.push "Category: #{res.Category} -> #{res.Subcategory}"
r.push "Owned by: #{res.OwnedBy} (#{res.OwnedByTeam})"
r.push ""
r.push "#{res.Description.substring 0, 2000}"
out = r.join "\n"
msgout = "#{moduledesc}: ```#{out}```"
robot.logger.info "#{msgout} [#{msg.envelope.user.name}]"
return msg.reply msgout
module.exports = (robot) ->
robot.respond /cher help$/, (msg) ->
cmds = []
arr = [
"#{modulename} incident <id> - show incident"
]
for str in arr
cmd = str.split " - "
cmds.push "`#{cmd[0]}` - #{cmd[1]}"
robot.send {room: msg.message?.user?.name}, cmds.join "\n"
robot.respond /cher i(?:ncident)? (\d+)$/i, (msg) ->
id = msg.match[1]
robot.logger.info "#{moduledesc}: incident search: #{id} [#{msg.envelope.user.name}]"
args =
busObPublicId: id
return GetBusinessObjectByPublicId robot, msg, args
|
[
{
"context": "d_key = process.env.CAMO_KEY || '0x24FEEDFACEDEADBEEFCAFE'\nmax_redirects = process.env.CAMO_MAX_REDIRECTS",
"end": 344,
"score": 0.9987437129020691,
"start": 320,
"tag": "KEY",
"value": "0x24FEEDFACEDEADBEEFCAFE"
}
] | server.coffee | zeke/camo | 1 | Fs = require 'fs'
Dns = require 'dns'
Url = require 'url'
Http = require 'http'
Crypto = require 'crypto'
QueryString = require 'querystring'
port = parseInt process.env.PORT || 8081
version = "1.3.0"
shared_key = process.env.CAMO_KEY || '0x24FEEDFACEDEADBEEFCAFE'
max_redirects = process.env.CAMO_MAX_REDIRECTS || 4
camo_hostname = process.env.CAMO_HOSTNAME || "unknown"
socket_timeout = process.env.CAMO_SOCKET_TIMEOUT || 10
logging_enabled = process.env.CAMO_LOGGING_ENABLED || "disabled"
content_length_limit = parseInt(process.env.CAMO_LENGTH_LIMIT || 5242880, 10)
debug_log = (msg) ->
if logging_enabled == "debug"
console.log("--------------------------------------------")
console.log(msg)
console.log("--------------------------------------------")
error_log = (msg) ->
unless logging_enabled == "disabled"
console.error("[#{new Date().toISOString()}] #{msg}")
RESTRICTED_IPS = /^((10\.)|(127\.)|(169\.254)|(192\.168)|(172\.((1[6-9])|(2[0-9])|(3[0-1]))))/
total_connections = 0
current_connections = 0
started_at = new Date
four_oh_four = (resp, msg, url) ->
error_log "#{msg}: #{url?.format() or 'unknown'}"
resp.writeHead 404
finish resp, "Not Found"
finish = (resp, str) ->
current_connections -= 1
current_connections = 0 if current_connections < 1
resp.connection && resp.end str
# A Transform Stream that limits the piped data to the specified length
Stream = require('stream')
class LimitStream extends Stream.Transform
constructor: (length) ->
super()
@remaining = length
_transform: (chunk, encoding, cb) ->
if @remaining > 0
if @remaining < chunk.length
chunk = chunk.slice(0, @remaining)
@push(chunk)
@remaining -= chunk.length
if @remaining <= 0
@emit('length_limited')
@end()
cb()
write: (chunk, encoding, cb) ->
if @remaining > 0
super
else
false
process_url = (url, transferred_headers, resp, remaining_redirects) ->
if !url.host?
return four_oh_four(resp, "Invalid host", url)
if url.protocol == 'https:'
error_log("Redirecting https URL to origin: #{url.format()}")
resp.writeHead 301, {'Location': url.format()}
finish resp
return
else if url.protocol != 'http:'
four_oh_four(resp, "Unknown protocol", url)
return
Dns.lookup url.hostname, (err, address, family) ->
if err
return four_oh_four(resp, "No host found: #{err}", url)
if address.match(RESTRICTED_IPS)
return four_oh_four(resp, "Hitting excluded IP", url)
fetch_url address, url, transferred_headers, resp, remaining_redirects
fetch_url = (ip_address, url, transferred_headers, resp, remaining_redirects) ->
src = Http.createClient url.port || 80, url.hostname
src.on 'error', (error) ->
four_oh_four(resp, "Client Request error #{error.stack}", url)
query_path = url.pathname
if url.query?
query_path += "?#{url.query}"
transferred_headers.host = url.host
debug_log transferred_headers
srcReq = src.request 'GET', query_path, transferred_headers
srcReq.setTimeout (socket_timeout * 1000), ()->
srcReq.abort()
four_oh_four resp, "Socket timeout", url
srcReq.on 'response', (srcResp) ->
is_finished = true
debug_log srcResp.headers
content_length = srcResp.headers['content-length']
if content_length > content_length_limit
srcResp.destroy()
four_oh_four(resp, "Content-Length exceeded", url)
else
newHeaders =
'content-type' : srcResp.headers['content-type']
'cache-control' : srcResp.headers['cache-control'] || 'public, max-age=31536000'
'Camo-Host' : camo_hostname
'X-Content-Type-Options' : 'nosniff'
# Handle chunked responses properly
if content_length?
newHeaders['content-length'] = content_length
if srcResp.headers['transfer-encoding']
newHeaders['transfer-encoding'] = srcResp.headers['transfer-encoding']
if srcResp.headers['content-encoding']
newHeaders['content-encoding'] = srcResp.headers['content-encoding']
srcResp.on 'end', ->
if is_finished
finish resp
srcResp.on 'error', ->
if is_finished
finish resp
switch srcResp.statusCode
when 200
if newHeaders['content-type'] && newHeaders['content-type'].slice(0, 5) != 'image'
srcResp.destroy()
four_oh_four(resp, "Non-Image content-type returned", url)
return
debug_log newHeaders
resp.writeHead srcResp.statusCode, newHeaders
limit = new LimitStream(content_length_limit)
srcResp.pipe(limit)
limit.pipe(resp)
limit.on 'length_limited', ->
srcResp.destroy()
error_log("Killed connection at content_length_limit: #{url.format()}")
when 301, 302, 303, 307
srcResp.destroy()
if remaining_redirects <= 0
four_oh_four(resp, "Exceeded max depth", url)
else if !srcResp.headers['location']
four_oh_four(resp, "Redirect with no location", url)
else
is_finished = false
newUrl = Url.parse srcResp.headers['location']
unless newUrl.host? and newUrl.hostname?
newUrl.host = newUrl.hostname = url.hostname
newUrl.protocol = url.protocol
debug_log "Redirected to #{newUrl.format()}"
process_url newUrl, transferred_headers, resp, remaining_redirects - 1
when 304
srcResp.destroy()
resp.writeHead srcResp.statusCode, newHeaders
else
srcResp.destroy()
four_oh_four(resp, "Origin responded with #{srcResp.statusCode}", url)
srcReq.on 'error', ->
finish resp
srcReq.end()
resp.on 'close', ->
error_log("Request aborted")
srcReq.abort()
resp.on 'error', (e) ->
error_log("Request error: #{e}")
srcReq.abort()
# decode a string of two char hex digits
hexdec = (str) ->
if str and str.length > 0 and str.length % 2 == 0 and not str.match(/[^0-9a-f]/)
buf = new Buffer(str.length / 2)
for i in [0...str.length] by 2
buf[i/2] = parseInt(str[i..i+1], 16)
buf.toString()
server = Http.createServer (req, resp) ->
if req.method != 'GET' || req.url == '/'
resp.writeHead 200
resp.end 'hwhat'
else if req.url == '/favicon.ico'
resp.writeHead 200
resp.end 'ok'
else if req.url == '/status'
resp.writeHead 200
resp.end "ok #{current_connections}/#{total_connections} since #{started_at.toString()}"
else
total_connections += 1
current_connections += 1
url = Url.parse req.url
user_agent = process.env.CAMO_HEADER_VIA or= "Camo Asset Proxy #{version}"
transferred_headers =
'Via' : user_agent
'User-Agent' : user_agent
'Accept' : req.headers.accept ? 'image/*'
'Accept-Encoding' : req.headers['accept-encoding']
'x-content-type-options' : 'nosniff'
delete(req.headers.cookie)
[query_digest, encoded_url] = url.pathname.replace(/^\//, '').split("/", 2)
if encoded_url = hexdec(encoded_url)
url_type = 'path'
dest_url = encoded_url
else
url_type = 'query'
dest_url = QueryString.parse(url.query).url
debug_log({
type: url_type
url: req.url
headers: req.headers
dest: dest_url
digest: query_digest
})
if req.headers['via'] && req.headers['via'].indexOf(user_agent) != -1
return four_oh_four(resp, "Requesting from self")
if url.pathname? && dest_url
hmac = Crypto.createHmac("sha1", shared_key)
hmac.update(dest_url, 'utf8')
hmac_digest = hmac.digest('hex')
if hmac_digest == query_digest
url = Url.parse dest_url
process_url url, transferred_headers, resp, max_redirects
else
four_oh_four(resp, "checksum mismatch #{hmac_digest}:#{query_digest}")
else
four_oh_four(resp, "No pathname provided on the server")
console.log "SSL-Proxy running on #{port} with pid:#{process.pid}."
console.log "Using the secret key #{shared_key}"
server.listen port
| 23302 | Fs = require 'fs'
Dns = require 'dns'
Url = require 'url'
Http = require 'http'
Crypto = require 'crypto'
QueryString = require 'querystring'
port = parseInt process.env.PORT || 8081
version = "1.3.0"
shared_key = process.env.CAMO_KEY || '<KEY>'
max_redirects = process.env.CAMO_MAX_REDIRECTS || 4
camo_hostname = process.env.CAMO_HOSTNAME || "unknown"
socket_timeout = process.env.CAMO_SOCKET_TIMEOUT || 10
logging_enabled = process.env.CAMO_LOGGING_ENABLED || "disabled"
content_length_limit = parseInt(process.env.CAMO_LENGTH_LIMIT || 5242880, 10)
debug_log = (msg) ->
if logging_enabled == "debug"
console.log("--------------------------------------------")
console.log(msg)
console.log("--------------------------------------------")
error_log = (msg) ->
unless logging_enabled == "disabled"
console.error("[#{new Date().toISOString()}] #{msg}")
RESTRICTED_IPS = /^((10\.)|(127\.)|(169\.254)|(192\.168)|(172\.((1[6-9])|(2[0-9])|(3[0-1]))))/
total_connections = 0
current_connections = 0
started_at = new Date
four_oh_four = (resp, msg, url) ->
error_log "#{msg}: #{url?.format() or 'unknown'}"
resp.writeHead 404
finish resp, "Not Found"
finish = (resp, str) ->
current_connections -= 1
current_connections = 0 if current_connections < 1
resp.connection && resp.end str
# A Transform Stream that limits the piped data to the specified length
Stream = require('stream')
class LimitStream extends Stream.Transform
constructor: (length) ->
super()
@remaining = length
_transform: (chunk, encoding, cb) ->
if @remaining > 0
if @remaining < chunk.length
chunk = chunk.slice(0, @remaining)
@push(chunk)
@remaining -= chunk.length
if @remaining <= 0
@emit('length_limited')
@end()
cb()
write: (chunk, encoding, cb) ->
if @remaining > 0
super
else
false
process_url = (url, transferred_headers, resp, remaining_redirects) ->
if !url.host?
return four_oh_four(resp, "Invalid host", url)
if url.protocol == 'https:'
error_log("Redirecting https URL to origin: #{url.format()}")
resp.writeHead 301, {'Location': url.format()}
finish resp
return
else if url.protocol != 'http:'
four_oh_four(resp, "Unknown protocol", url)
return
Dns.lookup url.hostname, (err, address, family) ->
if err
return four_oh_four(resp, "No host found: #{err}", url)
if address.match(RESTRICTED_IPS)
return four_oh_four(resp, "Hitting excluded IP", url)
fetch_url address, url, transferred_headers, resp, remaining_redirects
fetch_url = (ip_address, url, transferred_headers, resp, remaining_redirects) ->
src = Http.createClient url.port || 80, url.hostname
src.on 'error', (error) ->
four_oh_four(resp, "Client Request error #{error.stack}", url)
query_path = url.pathname
if url.query?
query_path += "?#{url.query}"
transferred_headers.host = url.host
debug_log transferred_headers
srcReq = src.request 'GET', query_path, transferred_headers
srcReq.setTimeout (socket_timeout * 1000), ()->
srcReq.abort()
four_oh_four resp, "Socket timeout", url
srcReq.on 'response', (srcResp) ->
is_finished = true
debug_log srcResp.headers
content_length = srcResp.headers['content-length']
if content_length > content_length_limit
srcResp.destroy()
four_oh_four(resp, "Content-Length exceeded", url)
else
newHeaders =
'content-type' : srcResp.headers['content-type']
'cache-control' : srcResp.headers['cache-control'] || 'public, max-age=31536000'
'Camo-Host' : camo_hostname
'X-Content-Type-Options' : 'nosniff'
# Handle chunked responses properly
if content_length?
newHeaders['content-length'] = content_length
if srcResp.headers['transfer-encoding']
newHeaders['transfer-encoding'] = srcResp.headers['transfer-encoding']
if srcResp.headers['content-encoding']
newHeaders['content-encoding'] = srcResp.headers['content-encoding']
srcResp.on 'end', ->
if is_finished
finish resp
srcResp.on 'error', ->
if is_finished
finish resp
switch srcResp.statusCode
when 200
if newHeaders['content-type'] && newHeaders['content-type'].slice(0, 5) != 'image'
srcResp.destroy()
four_oh_four(resp, "Non-Image content-type returned", url)
return
debug_log newHeaders
resp.writeHead srcResp.statusCode, newHeaders
limit = new LimitStream(content_length_limit)
srcResp.pipe(limit)
limit.pipe(resp)
limit.on 'length_limited', ->
srcResp.destroy()
error_log("Killed connection at content_length_limit: #{url.format()}")
when 301, 302, 303, 307
srcResp.destroy()
if remaining_redirects <= 0
four_oh_four(resp, "Exceeded max depth", url)
else if !srcResp.headers['location']
four_oh_four(resp, "Redirect with no location", url)
else
is_finished = false
newUrl = Url.parse srcResp.headers['location']
unless newUrl.host? and newUrl.hostname?
newUrl.host = newUrl.hostname = url.hostname
newUrl.protocol = url.protocol
debug_log "Redirected to #{newUrl.format()}"
process_url newUrl, transferred_headers, resp, remaining_redirects - 1
when 304
srcResp.destroy()
resp.writeHead srcResp.statusCode, newHeaders
else
srcResp.destroy()
four_oh_four(resp, "Origin responded with #{srcResp.statusCode}", url)
srcReq.on 'error', ->
finish resp
srcReq.end()
resp.on 'close', ->
error_log("Request aborted")
srcReq.abort()
resp.on 'error', (e) ->
error_log("Request error: #{e}")
srcReq.abort()
# decode a string of two char hex digits
hexdec = (str) ->
if str and str.length > 0 and str.length % 2 == 0 and not str.match(/[^0-9a-f]/)
buf = new Buffer(str.length / 2)
for i in [0...str.length] by 2
buf[i/2] = parseInt(str[i..i+1], 16)
buf.toString()
server = Http.createServer (req, resp) ->
if req.method != 'GET' || req.url == '/'
resp.writeHead 200
resp.end 'hwhat'
else if req.url == '/favicon.ico'
resp.writeHead 200
resp.end 'ok'
else if req.url == '/status'
resp.writeHead 200
resp.end "ok #{current_connections}/#{total_connections} since #{started_at.toString()}"
else
total_connections += 1
current_connections += 1
url = Url.parse req.url
user_agent = process.env.CAMO_HEADER_VIA or= "Camo Asset Proxy #{version}"
transferred_headers =
'Via' : user_agent
'User-Agent' : user_agent
'Accept' : req.headers.accept ? 'image/*'
'Accept-Encoding' : req.headers['accept-encoding']
'x-content-type-options' : 'nosniff'
delete(req.headers.cookie)
[query_digest, encoded_url] = url.pathname.replace(/^\//, '').split("/", 2)
if encoded_url = hexdec(encoded_url)
url_type = 'path'
dest_url = encoded_url
else
url_type = 'query'
dest_url = QueryString.parse(url.query).url
debug_log({
type: url_type
url: req.url
headers: req.headers
dest: dest_url
digest: query_digest
})
if req.headers['via'] && req.headers['via'].indexOf(user_agent) != -1
return four_oh_four(resp, "Requesting from self")
if url.pathname? && dest_url
hmac = Crypto.createHmac("sha1", shared_key)
hmac.update(dest_url, 'utf8')
hmac_digest = hmac.digest('hex')
if hmac_digest == query_digest
url = Url.parse dest_url
process_url url, transferred_headers, resp, max_redirects
else
four_oh_four(resp, "checksum mismatch #{hmac_digest}:#{query_digest}")
else
four_oh_four(resp, "No pathname provided on the server")
console.log "SSL-Proxy running on #{port} with pid:#{process.pid}."
console.log "Using the secret key #{shared_key}"
server.listen port
| true | Fs = require 'fs'
Dns = require 'dns'
Url = require 'url'
Http = require 'http'
Crypto = require 'crypto'
QueryString = require 'querystring'
port = parseInt process.env.PORT || 8081
version = "1.3.0"
shared_key = process.env.CAMO_KEY || 'PI:KEY:<KEY>END_PI'
max_redirects = process.env.CAMO_MAX_REDIRECTS || 4
camo_hostname = process.env.CAMO_HOSTNAME || "unknown"
socket_timeout = process.env.CAMO_SOCKET_TIMEOUT || 10
logging_enabled = process.env.CAMO_LOGGING_ENABLED || "disabled"
content_length_limit = parseInt(process.env.CAMO_LENGTH_LIMIT || 5242880, 10)
debug_log = (msg) ->
if logging_enabled == "debug"
console.log("--------------------------------------------")
console.log(msg)
console.log("--------------------------------------------")
error_log = (msg) ->
unless logging_enabled == "disabled"
console.error("[#{new Date().toISOString()}] #{msg}")
RESTRICTED_IPS = /^((10\.)|(127\.)|(169\.254)|(192\.168)|(172\.((1[6-9])|(2[0-9])|(3[0-1]))))/
total_connections = 0
current_connections = 0
started_at = new Date
four_oh_four = (resp, msg, url) ->
error_log "#{msg}: #{url?.format() or 'unknown'}"
resp.writeHead 404
finish resp, "Not Found"
finish = (resp, str) ->
current_connections -= 1
current_connections = 0 if current_connections < 1
resp.connection && resp.end str
# A Transform Stream that limits the piped data to the specified length
Stream = require('stream')
class LimitStream extends Stream.Transform
constructor: (length) ->
super()
@remaining = length
_transform: (chunk, encoding, cb) ->
if @remaining > 0
if @remaining < chunk.length
chunk = chunk.slice(0, @remaining)
@push(chunk)
@remaining -= chunk.length
if @remaining <= 0
@emit('length_limited')
@end()
cb()
write: (chunk, encoding, cb) ->
if @remaining > 0
super
else
false
process_url = (url, transferred_headers, resp, remaining_redirects) ->
if !url.host?
return four_oh_four(resp, "Invalid host", url)
if url.protocol == 'https:'
error_log("Redirecting https URL to origin: #{url.format()}")
resp.writeHead 301, {'Location': url.format()}
finish resp
return
else if url.protocol != 'http:'
four_oh_four(resp, "Unknown protocol", url)
return
Dns.lookup url.hostname, (err, address, family) ->
if err
return four_oh_four(resp, "No host found: #{err}", url)
if address.match(RESTRICTED_IPS)
return four_oh_four(resp, "Hitting excluded IP", url)
fetch_url address, url, transferred_headers, resp, remaining_redirects
fetch_url = (ip_address, url, transferred_headers, resp, remaining_redirects) ->
src = Http.createClient url.port || 80, url.hostname
src.on 'error', (error) ->
four_oh_four(resp, "Client Request error #{error.stack}", url)
query_path = url.pathname
if url.query?
query_path += "?#{url.query}"
transferred_headers.host = url.host
debug_log transferred_headers
srcReq = src.request 'GET', query_path, transferred_headers
srcReq.setTimeout (socket_timeout * 1000), ()->
srcReq.abort()
four_oh_four resp, "Socket timeout", url
srcReq.on 'response', (srcResp) ->
is_finished = true
debug_log srcResp.headers
content_length = srcResp.headers['content-length']
if content_length > content_length_limit
srcResp.destroy()
four_oh_four(resp, "Content-Length exceeded", url)
else
newHeaders =
'content-type' : srcResp.headers['content-type']
'cache-control' : srcResp.headers['cache-control'] || 'public, max-age=31536000'
'Camo-Host' : camo_hostname
'X-Content-Type-Options' : 'nosniff'
# Handle chunked responses properly
if content_length?
newHeaders['content-length'] = content_length
if srcResp.headers['transfer-encoding']
newHeaders['transfer-encoding'] = srcResp.headers['transfer-encoding']
if srcResp.headers['content-encoding']
newHeaders['content-encoding'] = srcResp.headers['content-encoding']
srcResp.on 'end', ->
if is_finished
finish resp
srcResp.on 'error', ->
if is_finished
finish resp
switch srcResp.statusCode
when 200
if newHeaders['content-type'] && newHeaders['content-type'].slice(0, 5) != 'image'
srcResp.destroy()
four_oh_four(resp, "Non-Image content-type returned", url)
return
debug_log newHeaders
resp.writeHead srcResp.statusCode, newHeaders
limit = new LimitStream(content_length_limit)
srcResp.pipe(limit)
limit.pipe(resp)
limit.on 'length_limited', ->
srcResp.destroy()
error_log("Killed connection at content_length_limit: #{url.format()}")
when 301, 302, 303, 307
srcResp.destroy()
if remaining_redirects <= 0
four_oh_four(resp, "Exceeded max depth", url)
else if !srcResp.headers['location']
four_oh_four(resp, "Redirect with no location", url)
else
is_finished = false
newUrl = Url.parse srcResp.headers['location']
unless newUrl.host? and newUrl.hostname?
newUrl.host = newUrl.hostname = url.hostname
newUrl.protocol = url.protocol
debug_log "Redirected to #{newUrl.format()}"
process_url newUrl, transferred_headers, resp, remaining_redirects - 1
when 304
srcResp.destroy()
resp.writeHead srcResp.statusCode, newHeaders
else
srcResp.destroy()
four_oh_four(resp, "Origin responded with #{srcResp.statusCode}", url)
srcReq.on 'error', ->
finish resp
srcReq.end()
resp.on 'close', ->
error_log("Request aborted")
srcReq.abort()
resp.on 'error', (e) ->
error_log("Request error: #{e}")
srcReq.abort()
# decode a string of two char hex digits
hexdec = (str) ->
if str and str.length > 0 and str.length % 2 == 0 and not str.match(/[^0-9a-f]/)
buf = new Buffer(str.length / 2)
for i in [0...str.length] by 2
buf[i/2] = parseInt(str[i..i+1], 16)
buf.toString()
server = Http.createServer (req, resp) ->
if req.method != 'GET' || req.url == '/'
resp.writeHead 200
resp.end 'hwhat'
else if req.url == '/favicon.ico'
resp.writeHead 200
resp.end 'ok'
else if req.url == '/status'
resp.writeHead 200
resp.end "ok #{current_connections}/#{total_connections} since #{started_at.toString()}"
else
total_connections += 1
current_connections += 1
url = Url.parse req.url
user_agent = process.env.CAMO_HEADER_VIA or= "Camo Asset Proxy #{version}"
transferred_headers =
'Via' : user_agent
'User-Agent' : user_agent
'Accept' : req.headers.accept ? 'image/*'
'Accept-Encoding' : req.headers['accept-encoding']
'x-content-type-options' : 'nosniff'
delete(req.headers.cookie)
[query_digest, encoded_url] = url.pathname.replace(/^\//, '').split("/", 2)
if encoded_url = hexdec(encoded_url)
url_type = 'path'
dest_url = encoded_url
else
url_type = 'query'
dest_url = QueryString.parse(url.query).url
debug_log({
type: url_type
url: req.url
headers: req.headers
dest: dest_url
digest: query_digest
})
if req.headers['via'] && req.headers['via'].indexOf(user_agent) != -1
return four_oh_four(resp, "Requesting from self")
if url.pathname? && dest_url
hmac = Crypto.createHmac("sha1", shared_key)
hmac.update(dest_url, 'utf8')
hmac_digest = hmac.digest('hex')
if hmac_digest == query_digest
url = Url.parse dest_url
process_url url, transferred_headers, resp, max_redirects
else
four_oh_four(resp, "checksum mismatch #{hmac_digest}:#{query_digest}")
else
four_oh_four(resp, "No pathname provided on the server")
console.log "SSL-Proxy running on #{port} with pid:#{process.pid}."
console.log "Using the secret key #{shared_key}"
server.listen port
|
[
{
"context": "e key', ()->\n expect(property.key).to.equal('foo.bar')\n \n it 'should parse the value', ()->\n ",
"end": 396,
"score": 0.8693715929985046,
"start": 389,
"tag": "KEY",
"value": "foo.bar"
}
] | test/property-test.coffee | samolsen/node-filter-java-properties | 0 | _ = require('underscore')
expect = require('chai').expect
errors = require('common-errors')
ArgumentError = errors.ArgumentError
Property = require('../src/property')
describe 'Property', ()->
property = null
beforeEach ()->
property = new Property('foo.bar=Hello World')
describe 'constructor', ()->
it 'should parse the key', ()->
expect(property.key).to.equal('foo.bar')
it 'should parse the value', ()->
expect(property.value).to.equal('Hello World')
it 'should trim the key', ()->
property = new Property(' foo =Hello World')
expect(property.key).to.equal('foo')
it 'should trim the value', ()->
property = new Property('foo= Hello World ')
expect(property.value).to.equal('Hello World')
it 'should throw an error if it could not be split', ()->
fn = ()-> new Property('abc')
expect(fn).to.throw(ArgumentError)
describe 'toRegExp', ()->
it 'should throw an error if a string is not passed', ()->
fn = ()-> property.toRegExp()
expect(fn).to.throw(ArgumentError)
it 'should throw an error if an empty string is passed', ()->
fn = ()-> property.toRegExp('')
expect(fn).to.throw(ArgumentError)
it 'should throw an error if its arguments containts mulptiple "*" characters', ()->
fn = ()-> property.toRegExp('${*|*}')
expect(fn).to.throw(ArgumentError)
describe 'arguments with a "*" token', ()->
token = '${*}'
regex = null
beforeEach ()->
regex = property.toRegExp(token)
it 'should return a regex', ()->
isRegex = _.isRegExp(regex)
expect(isRegex).to.be.true
it 'should return a regex matching bracketed tokens', ()->
expect(regex.toString()).to.equal('/\\$\\{foo\\.bar\\}/g')
it 'should return a regex with the global flag set', ()->
expect(regex.toString()).to.match(/\/([imy]+)?g([imy]+)?$/)
describe 'arguments without a "*" token', ()->
token = '@'
regex = null
beforeEach ()->
regex = property.toRegExp(token)
it 'should return a regex', ()->
isRegex = _.isRegExp(regex)
expect(isRegex).to.be.true
it 'should return a regex matching bracketed tokens', ()->
expect(regex.toString()).to.equal('/'+ token + 'foo\\.bar' + token + '/' + 'g')
it 'should return a regex with the global flag set', ()->
expect(regex.toString()).to.match(/\/([imy]+)?g([imy]+)?$/)
describe 'filterString with a "*" token', ()->
token = '${*}'
string = '${foo.bar}'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'filterString with a "*" token', ()->
token = '${*}'
string = '${foo.bar}'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'filterString without a "*" token', ()->
token = '@'
string = '@foo.bar@'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'static methods', ()->
describe 'isParseableString', ()->
it 'should return false if no "=" is present', ()->
expect(Property.isParseableString('wge3g')).to.be.false
it 'should return true if 1 "=" is present', ()->
expect(Property.isParseableString('foo.bar=Booyah!')).to.be.true
it 'should return true if more than 1 "=" is present', ()->
expect(Property.isParseableString('foo.bar=Booyah = Grandma')).to.be.true
| 118600 | _ = require('underscore')
expect = require('chai').expect
errors = require('common-errors')
ArgumentError = errors.ArgumentError
Property = require('../src/property')
describe 'Property', ()->
property = null
beforeEach ()->
property = new Property('foo.bar=Hello World')
describe 'constructor', ()->
it 'should parse the key', ()->
expect(property.key).to.equal('<KEY>')
it 'should parse the value', ()->
expect(property.value).to.equal('Hello World')
it 'should trim the key', ()->
property = new Property(' foo =Hello World')
expect(property.key).to.equal('foo')
it 'should trim the value', ()->
property = new Property('foo= Hello World ')
expect(property.value).to.equal('Hello World')
it 'should throw an error if it could not be split', ()->
fn = ()-> new Property('abc')
expect(fn).to.throw(ArgumentError)
describe 'toRegExp', ()->
it 'should throw an error if a string is not passed', ()->
fn = ()-> property.toRegExp()
expect(fn).to.throw(ArgumentError)
it 'should throw an error if an empty string is passed', ()->
fn = ()-> property.toRegExp('')
expect(fn).to.throw(ArgumentError)
it 'should throw an error if its arguments containts mulptiple "*" characters', ()->
fn = ()-> property.toRegExp('${*|*}')
expect(fn).to.throw(ArgumentError)
describe 'arguments with a "*" token', ()->
token = '${*}'
regex = null
beforeEach ()->
regex = property.toRegExp(token)
it 'should return a regex', ()->
isRegex = _.isRegExp(regex)
expect(isRegex).to.be.true
it 'should return a regex matching bracketed tokens', ()->
expect(regex.toString()).to.equal('/\\$\\{foo\\.bar\\}/g')
it 'should return a regex with the global flag set', ()->
expect(regex.toString()).to.match(/\/([imy]+)?g([imy]+)?$/)
describe 'arguments without a "*" token', ()->
token = '@'
regex = null
beforeEach ()->
regex = property.toRegExp(token)
it 'should return a regex', ()->
isRegex = _.isRegExp(regex)
expect(isRegex).to.be.true
it 'should return a regex matching bracketed tokens', ()->
expect(regex.toString()).to.equal('/'+ token + 'foo\\.bar' + token + '/' + 'g')
it 'should return a regex with the global flag set', ()->
expect(regex.toString()).to.match(/\/([imy]+)?g([imy]+)?$/)
describe 'filterString with a "*" token', ()->
token = '${*}'
string = '${foo.bar}'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'filterString with a "*" token', ()->
token = '${*}'
string = '${foo.bar}'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'filterString without a "*" token', ()->
token = '@'
string = '@foo.bar@'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'static methods', ()->
describe 'isParseableString', ()->
it 'should return false if no "=" is present', ()->
expect(Property.isParseableString('wge3g')).to.be.false
it 'should return true if 1 "=" is present', ()->
expect(Property.isParseableString('foo.bar=Booyah!')).to.be.true
it 'should return true if more than 1 "=" is present', ()->
expect(Property.isParseableString('foo.bar=Booyah = Grandma')).to.be.true
| true | _ = require('underscore')
expect = require('chai').expect
errors = require('common-errors')
ArgumentError = errors.ArgumentError
Property = require('../src/property')
describe 'Property', ()->
property = null
beforeEach ()->
property = new Property('foo.bar=Hello World')
describe 'constructor', ()->
it 'should parse the key', ()->
expect(property.key).to.equal('PI:KEY:<KEY>END_PI')
it 'should parse the value', ()->
expect(property.value).to.equal('Hello World')
it 'should trim the key', ()->
property = new Property(' foo =Hello World')
expect(property.key).to.equal('foo')
it 'should trim the value', ()->
property = new Property('foo= Hello World ')
expect(property.value).to.equal('Hello World')
it 'should throw an error if it could not be split', ()->
fn = ()-> new Property('abc')
expect(fn).to.throw(ArgumentError)
describe 'toRegExp', ()->
it 'should throw an error if a string is not passed', ()->
fn = ()-> property.toRegExp()
expect(fn).to.throw(ArgumentError)
it 'should throw an error if an empty string is passed', ()->
fn = ()-> property.toRegExp('')
expect(fn).to.throw(ArgumentError)
it 'should throw an error if its arguments containts mulptiple "*" characters', ()->
fn = ()-> property.toRegExp('${*|*}')
expect(fn).to.throw(ArgumentError)
describe 'arguments with a "*" token', ()->
token = '${*}'
regex = null
beforeEach ()->
regex = property.toRegExp(token)
it 'should return a regex', ()->
isRegex = _.isRegExp(regex)
expect(isRegex).to.be.true
it 'should return a regex matching bracketed tokens', ()->
expect(regex.toString()).to.equal('/\\$\\{foo\\.bar\\}/g')
it 'should return a regex with the global flag set', ()->
expect(regex.toString()).to.match(/\/([imy]+)?g([imy]+)?$/)
describe 'arguments without a "*" token', ()->
token = '@'
regex = null
beforeEach ()->
regex = property.toRegExp(token)
it 'should return a regex', ()->
isRegex = _.isRegExp(regex)
expect(isRegex).to.be.true
it 'should return a regex matching bracketed tokens', ()->
expect(regex.toString()).to.equal('/'+ token + 'foo\\.bar' + token + '/' + 'g')
it 'should return a regex with the global flag set', ()->
expect(regex.toString()).to.match(/\/([imy]+)?g([imy]+)?$/)
describe 'filterString with a "*" token', ()->
token = '${*}'
string = '${foo.bar}'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'filterString with a "*" token', ()->
token = '${*}'
string = '${foo.bar}'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'filterString without a "*" token', ()->
token = '@'
string = '@foo.bar@'
it 'should replace the bracketed token', ()->
filtered = property.filterString(string, token)
expect(filtered).to.equal('Hello World')
describe 'static methods', ()->
describe 'isParseableString', ()->
it 'should return false if no "=" is present', ()->
expect(Property.isParseableString('wge3g')).to.be.false
it 'should return true if 1 "=" is present', ()->
expect(Property.isParseableString('foo.bar=Booyah!')).to.be.true
it 'should return true if more than 1 "=" is present', ()->
expect(Property.isParseableString('foo.bar=Booyah = Grandma')).to.be.true
|
[
{
"context": "success_query = new ChartSerie(gquery_key: \"policy_goal_#{key}_reached\")\n @value_query = new C",
"end": 871,
"score": 0.6362707018852234,
"start": 871,
"tag": "KEY",
"value": ""
},
{
"context": "ss_query = new ChartSerie(gquery_key: \"policy_goal_#{key}_reache... | app/assets/javascripts/d3/target_bar.coffee | Abeer-AlHasan/Abu-Dhabi-Model | 21 | D3.target_bar =
data:
# The key must match the chart key
renewability_targets: [
{key: 'co2_emissions', unit: 'MTon'},
{key: 'renewable_percentage', unit: '%', min: 0, max: 100}
],
dependence_targets: [
{key: 'net_energy_import', unit: '%', min: 0, max: 100},
{key: 'net_electricity_import', unit: '%', min: 0, max: 100}
],
cost_targets: [
{key: 'total_energy_costs', unit: 'Bln euro'},
{key: 'electricity_costs', unit: 'Euro/MWh'}
],
area_targets: [
{key: 'onshore_land', unit: 'km2'},
{key: 'onshore_coast', unit: 'km'},
{key: 'offshore', unit: 'km2'}
]
Target: class extends Backbone.Model
initialize: =>
key = @get 'key'
@view = @get 'view'
@success_query = new ChartSerie(gquery_key: "policy_goal_#{key}_reached")
@value_query = new ChartSerie(gquery_key: "policy_goal_#{key}_value")
@target_query = new ChartSerie(gquery_key: "policy_goal_#{key}_target_value")
@view.series.push @success_query, @value_query, @target_query
@scale = d3.scale.linear()
@axis = d3.svg.axis().tickSize(2, 0).ticks(4).orient('bottom')
max_value: =>
return m if m = @get('max')
max = 0
for query in [@success_query, @value_query, @target_query]
max = x if (x = query.future_value()) > max
max = x if (x = query.present_value()) > max
max = 0 if max < 0
# Let's add some padding
max * 1.05
min_value: => if (m = @get('min')) then m else 0
update_scale: => @scale.domain([@min_value(), @max_value()])
axis_builder: => @axis.scale(@scale)
successful: => @success_query.future_value()
is_set: => _.isNumber @target_query.future_value()
# negative values aren't allowed
#
format_value: (x) =>
v = switch @get 'key'
when 'net_electricity_import', 'renewable_percentage', 'net_energy_import'
x * 100
else x
if v < 0 then v = 0
v
present_value: => @format_value @value_query.present_value()
future_value: => @format_value @value_query.future_value()
target_value: => @format_value @target_query.future_value()
View: class extends D3ChartView
initialize: ->
@key = @model.get 'key'
@series = @model.series
@targets = []
for item in D3.target_bar.data[@key]
item.view = this
t = new D3.target_bar.Target(item)
@targets.push t
@initialize_defaults()
margins:
top: 25
bottom: 10
left: 20
right: 18
label_width: 100
# margin between label and horizontal bars
label_margin: 5
draw: =>
[@width, @height] = @available_size()
for t in @targets
t.scale.range([0, @width - @label_width - @label_margin])
@svg = @create_svg_container @width, @height, @margins
# Every target belongs to a group which is translated altogether
@items = @svg.selectAll("g.target")
.data(@targets, ((d) -> d.get 'key'))
.enter()
.append('svg:g')
.attr('class', 'target')
.attr('transform', (d, i) -> "translate(0, #{i * 60})")
# labels first
@items.append("svg:text")
.text((d) -> I18n.t "targets.#{d.get 'key'}")
.attr('class', 'target_label')
.attr('text-anchor', 'end')
.attr('x', @label_width)
.attr('y', 1)
@items.append("svg:text")
.text((d) -> d.get 'unit')
.attr('class', 'target_unit')
.attr('text-anchor', 'end')
.attr('x', @label_width)
.attr('y', 15)
# now bars and axis
# This group contains bars, target lines and x-axis
@blocks = @items.append("svg:g")
.attr("transform", "translate(#{@label_width + @label_margin})")
current_values = @blocks.append("svg:rect")
.attr('class', 'current_value')
.attr('y', -10)
.attr('height', 15)
.attr('width', 0)
.attr('fill', '#66ccff')
@blocks.append("svg:text")
.text(App.settings.get("start_year"))
.attr('class', 'year_label')
.attr('y', 2)
.attr('x', 2)
future_values = @blocks.append("svg:rect")
.attr('class', 'future_value')
.attr('y', 6)
.attr('height', 15)
.attr('width', 0)
.attr('fill', '#0080ff')
@blocks.append("svg:text")
.text(App.settings.get("end_year"))
.attr('class', 'year_label')
.attr('y', 17)
.attr('x', 2)
user_targets = @blocks.append("svg:rect")
.attr('class', 'target_value')
.attr('y', -15)
.attr('width', 2)
.attr('height', 38)
.attr('fill', '#ff0000')
.style("opacity", 0.7)
@axis = @blocks.append('svg:g')
.attr("class", 'x_axis')
.attr('transform', 'translate(0.5, 22.5)')
refresh: =>
t.update_scale() for t in @targets
targets = @svg.selectAll("g.target")
.data(@targets, ((d) -> d.get 'key'))
targets.selectAll('g.x_axis')
.transition()
.duration(500)
.each((d) ->
d3.select(this).call(d.axis_builder())
)
targets.selectAll('rect.current_value')
.transition()
.attr('width', (d) -> d.scale(d.present_value()) )
targets.selectAll('rect.future_value')
.transition()
.attr('width', (d) -> d.scale(d.future_value()) )
targets.selectAll('text.target_label')
.transition()
.style('fill', (d) ->
if !d.is_set()
'#000000'
else if d.successful()
'#008040'
else
'#800040')
.text((d) ->
t = I18n.t "targets.#{d.get 'key'}"
if !d.is_set()
t
else if d.successful()
"#{t} +"
else
"#{t} -"
)
targets.selectAll('rect.target_value')
.transition()
.attr('x', (d) -> d.scale(d.target_value()) - 1)
.attr('fill', (d) -> if d.successful() then '#008040' else '#ff0000')
.style('opacity', (d) -> if d.is_set() then 0.7 else 0.0)
| 211291 | D3.target_bar =
data:
# The key must match the chart key
renewability_targets: [
{key: 'co2_emissions', unit: 'MTon'},
{key: 'renewable_percentage', unit: '%', min: 0, max: 100}
],
dependence_targets: [
{key: 'net_energy_import', unit: '%', min: 0, max: 100},
{key: 'net_electricity_import', unit: '%', min: 0, max: 100}
],
cost_targets: [
{key: 'total_energy_costs', unit: 'Bln euro'},
{key: 'electricity_costs', unit: 'Euro/MWh'}
],
area_targets: [
{key: 'onshore_land', unit: 'km2'},
{key: 'onshore_coast', unit: 'km'},
{key: 'offshore', unit: 'km2'}
]
Target: class extends Backbone.Model
initialize: =>
key = @get 'key'
@view = @get 'view'
@success_query = new ChartSerie(gquery_key: "policy<KEY>_goal<KEY>_#{key<KEY>}_reached")
@value_query = new ChartSerie(gquery_key: "policy<KEY>_goal_<KEY>key<KEY>}_value")
@target_query = new ChartSerie(gquery_key: "policy<KEY>_goal_<KEY>key<KEY>}_target_value")
@view.series.push @success_query, @value_query, @target_query
@scale = d3.scale.linear()
@axis = d3.svg.axis().tickSize(2, 0).ticks(4).orient('bottom')
max_value: =>
return m if m = @get('max')
max = 0
for query in [@success_query, @value_query, @target_query]
max = x if (x = query.future_value()) > max
max = x if (x = query.present_value()) > max
max = 0 if max < 0
# Let's add some padding
max * 1.05
min_value: => if (m = @get('min')) then m else 0
update_scale: => @scale.domain([@min_value(), @max_value()])
axis_builder: => @axis.scale(@scale)
successful: => @success_query.future_value()
is_set: => _.isNumber @target_query.future_value()
# negative values aren't allowed
#
format_value: (x) =>
v = switch @get 'key'
when 'net_electricity_import', 'renewable_percentage', 'net_energy_import'
x * 100
else x
if v < 0 then v = 0
v
present_value: => @format_value @value_query.present_value()
future_value: => @format_value @value_query.future_value()
target_value: => @format_value @target_query.future_value()
View: class extends D3ChartView
initialize: ->
@key = @model.get 'key'
@series = @model.series
@targets = []
for item in D3.target_bar.data[@key]
item.view = this
t = new D3.target_bar.Target(item)
@targets.push t
@initialize_defaults()
margins:
top: 25
bottom: 10
left: 20
right: 18
label_width: 100
# margin between label and horizontal bars
label_margin: 5
draw: =>
[@width, @height] = @available_size()
for t in @targets
t.scale.range([0, @width - @label_width - @label_margin])
@svg = @create_svg_container @width, @height, @margins
# Every target belongs to a group which is translated altogether
@items = @svg.selectAll("g.target")
.data(@targets, ((d) -> d.get 'key'))
.enter()
.append('svg:g')
.attr('class', 'target')
.attr('transform', (d, i) -> "translate(0, #{i * 60})")
# labels first
@items.append("svg:text")
.text((d) -> I18n.t "targets.#{d.get 'key'}")
.attr('class', 'target_label')
.attr('text-anchor', 'end')
.attr('x', @label_width)
.attr('y', 1)
@items.append("svg:text")
.text((d) -> d.get 'unit')
.attr('class', 'target_unit')
.attr('text-anchor', 'end')
.attr('x', @label_width)
.attr('y', 15)
# now bars and axis
# This group contains bars, target lines and x-axis
@blocks = @items.append("svg:g")
.attr("transform", "translate(#{@label_width + @label_margin})")
current_values = @blocks.append("svg:rect")
.attr('class', 'current_value')
.attr('y', -10)
.attr('height', 15)
.attr('width', 0)
.attr('fill', '#66ccff')
@blocks.append("svg:text")
.text(App.settings.get("start_year"))
.attr('class', 'year_label')
.attr('y', 2)
.attr('x', 2)
future_values = @blocks.append("svg:rect")
.attr('class', 'future_value')
.attr('y', 6)
.attr('height', 15)
.attr('width', 0)
.attr('fill', '#0080ff')
@blocks.append("svg:text")
.text(App.settings.get("end_year"))
.attr('class', 'year_label')
.attr('y', 17)
.attr('x', 2)
user_targets = @blocks.append("svg:rect")
.attr('class', 'target_value')
.attr('y', -15)
.attr('width', 2)
.attr('height', 38)
.attr('fill', '#ff0000')
.style("opacity", 0.7)
@axis = @blocks.append('svg:g')
.attr("class", 'x_axis')
.attr('transform', 'translate(0.5, 22.5)')
refresh: =>
t.update_scale() for t in @targets
targets = @svg.selectAll("g.target")
.data(@targets, ((d) -> d.get 'key'))
targets.selectAll('g.x_axis')
.transition()
.duration(500)
.each((d) ->
d3.select(this).call(d.axis_builder())
)
targets.selectAll('rect.current_value')
.transition()
.attr('width', (d) -> d.scale(d.present_value()) )
targets.selectAll('rect.future_value')
.transition()
.attr('width', (d) -> d.scale(d.future_value()) )
targets.selectAll('text.target_label')
.transition()
.style('fill', (d) ->
if !d.is_set()
'#000000'
else if d.successful()
'#008040'
else
'#800040')
.text((d) ->
t = I18n.t "targets.#{d.get 'key'}"
if !d.is_set()
t
else if d.successful()
"#{t} +"
else
"#{t} -"
)
targets.selectAll('rect.target_value')
.transition()
.attr('x', (d) -> d.scale(d.target_value()) - 1)
.attr('fill', (d) -> if d.successful() then '#008040' else '#ff0000')
.style('opacity', (d) -> if d.is_set() then 0.7 else 0.0)
| true | D3.target_bar =
data:
# The key must match the chart key
renewability_targets: [
{key: 'co2_emissions', unit: 'MTon'},
{key: 'renewable_percentage', unit: '%', min: 0, max: 100}
],
dependence_targets: [
{key: 'net_energy_import', unit: '%', min: 0, max: 100},
{key: 'net_electricity_import', unit: '%', min: 0, max: 100}
],
cost_targets: [
{key: 'total_energy_costs', unit: 'Bln euro'},
{key: 'electricity_costs', unit: 'Euro/MWh'}
],
area_targets: [
{key: 'onshore_land', unit: 'km2'},
{key: 'onshore_coast', unit: 'km'},
{key: 'offshore', unit: 'km2'}
]
Target: class extends Backbone.Model
initialize: =>
key = @get 'key'
@view = @get 'view'
@success_query = new ChartSerie(gquery_key: "policyPI:KEY:<KEY>END_PI_goalPI:KEY:<KEY>END_PI_#{keyPI:KEY:<KEY>END_PI}_reached")
@value_query = new ChartSerie(gquery_key: "policyPI:KEY:<KEY>END_PI_goal_PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}_value")
@target_query = new ChartSerie(gquery_key: "policyPI:KEY:<KEY>END_PI_goal_PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}_target_value")
@view.series.push @success_query, @value_query, @target_query
@scale = d3.scale.linear()
@axis = d3.svg.axis().tickSize(2, 0).ticks(4).orient('bottom')
max_value: =>
return m if m = @get('max')
max = 0
for query in [@success_query, @value_query, @target_query]
max = x if (x = query.future_value()) > max
max = x if (x = query.present_value()) > max
max = 0 if max < 0
# Let's add some padding
max * 1.05
min_value: => if (m = @get('min')) then m else 0
update_scale: => @scale.domain([@min_value(), @max_value()])
axis_builder: => @axis.scale(@scale)
successful: => @success_query.future_value()
is_set: => _.isNumber @target_query.future_value()
# negative values aren't allowed
#
format_value: (x) =>
v = switch @get 'key'
when 'net_electricity_import', 'renewable_percentage', 'net_energy_import'
x * 100
else x
if v < 0 then v = 0
v
present_value: => @format_value @value_query.present_value()
future_value: => @format_value @value_query.future_value()
target_value: => @format_value @target_query.future_value()
View: class extends D3ChartView
initialize: ->
@key = @model.get 'key'
@series = @model.series
@targets = []
for item in D3.target_bar.data[@key]
item.view = this
t = new D3.target_bar.Target(item)
@targets.push t
@initialize_defaults()
margins:
top: 25
bottom: 10
left: 20
right: 18
label_width: 100
# margin between label and horizontal bars
label_margin: 5
draw: =>
[@width, @height] = @available_size()
for t in @targets
t.scale.range([0, @width - @label_width - @label_margin])
@svg = @create_svg_container @width, @height, @margins
# Every target belongs to a group which is translated altogether
@items = @svg.selectAll("g.target")
.data(@targets, ((d) -> d.get 'key'))
.enter()
.append('svg:g')
.attr('class', 'target')
.attr('transform', (d, i) -> "translate(0, #{i * 60})")
# labels first
@items.append("svg:text")
.text((d) -> I18n.t "targets.#{d.get 'key'}")
.attr('class', 'target_label')
.attr('text-anchor', 'end')
.attr('x', @label_width)
.attr('y', 1)
@items.append("svg:text")
.text((d) -> d.get 'unit')
.attr('class', 'target_unit')
.attr('text-anchor', 'end')
.attr('x', @label_width)
.attr('y', 15)
# now bars and axis
# This group contains bars, target lines and x-axis
@blocks = @items.append("svg:g")
.attr("transform", "translate(#{@label_width + @label_margin})")
current_values = @blocks.append("svg:rect")
.attr('class', 'current_value')
.attr('y', -10)
.attr('height', 15)
.attr('width', 0)
.attr('fill', '#66ccff')
@blocks.append("svg:text")
.text(App.settings.get("start_year"))
.attr('class', 'year_label')
.attr('y', 2)
.attr('x', 2)
future_values = @blocks.append("svg:rect")
.attr('class', 'future_value')
.attr('y', 6)
.attr('height', 15)
.attr('width', 0)
.attr('fill', '#0080ff')
@blocks.append("svg:text")
.text(App.settings.get("end_year"))
.attr('class', 'year_label')
.attr('y', 17)
.attr('x', 2)
user_targets = @blocks.append("svg:rect")
.attr('class', 'target_value')
.attr('y', -15)
.attr('width', 2)
.attr('height', 38)
.attr('fill', '#ff0000')
.style("opacity", 0.7)
@axis = @blocks.append('svg:g')
.attr("class", 'x_axis')
.attr('transform', 'translate(0.5, 22.5)')
refresh: =>
t.update_scale() for t in @targets
targets = @svg.selectAll("g.target")
.data(@targets, ((d) -> d.get 'key'))
targets.selectAll('g.x_axis')
.transition()
.duration(500)
.each((d) ->
d3.select(this).call(d.axis_builder())
)
targets.selectAll('rect.current_value')
.transition()
.attr('width', (d) -> d.scale(d.present_value()) )
targets.selectAll('rect.future_value')
.transition()
.attr('width', (d) -> d.scale(d.future_value()) )
targets.selectAll('text.target_label')
.transition()
.style('fill', (d) ->
if !d.is_set()
'#000000'
else if d.successful()
'#008040'
else
'#800040')
.text((d) ->
t = I18n.t "targets.#{d.get 'key'}"
if !d.is_set()
t
else if d.successful()
"#{t} +"
else
"#{t} -"
)
targets.selectAll('rect.target_value')
.transition()
.attr('x', (d) -> d.scale(d.target_value()) - 1)
.attr('fill', (d) -> if d.successful() then '#008040' else '#ff0000')
.style('opacity', (d) -> if d.is_set() then 0.7 else 0.0)
|
[
{
"context": "###\nWiggle Module for FramerJS\nCreated by Lucien Lee (@luciendeer), Feb. 17th, 2016\nhttps://github.com",
"end": 52,
"score": 0.9998781085014343,
"start": 42,
"tag": "NAME",
"value": "Lucien Lee"
},
{
"context": "#\nWiggle Module for FramerJS\nCreated by Lucien Lee (@... | Wiggle.coffee | LucienLee/framer-Wiggle | 2 | ###
Wiggle Module for FramerJS
Created by Lucien Lee (@luciendeer), Feb. 17th, 2016
https://github.com/LucienLee/framer-Wiggle
Wiggle Module help you creating wiggle effect in FramerJS.
Add the following line to your project in Framer Studio.
require 'Wiggle'
[Configure wiggle]
layer.wiggle =
freq: 6 //wiggle frequence (per sec)
amp: 1 // wiggle amplitude
variance: 2 // wiggle amplitude variance
wiggleWhenDragging: false // keep wiggling when dragging or not
[Wiggle!]
layer.wiggle.start()
layer.wiggle.stop()
[Check wiggle state]
layer.wiggle.isWiggling //return true or false
###
class Wiggle extends Framer.BaseClass
# wiggle frequence (per sec)
@define "freq",
get: -> @_freq,
set: (value)->
if _.isNumber(value) and value > 0
@_freq = value
@_updateWiggleAniamtion()
# wiggle amplitude
@define "amp",
get: -> @_amp,
set: (value)->
if _.isNumber(value)
@_amp = value
@_updateWiggleAniamtion()
# wiggle amplitude variance
@define "variance",
get: -> @_variance,
set: (value)->
if _.isNumber(value)
@_variance = value
@_updateWiggleAniamtion()
# keep wiggling when dragging
@define "wiggleWhenDragging",
get: -> @_keepWiggling
set: (value)-> @_keepWiggling = value if _.isBoolean value
@define "isWiggling", get: -> @_isWiggling or false
constructor: (@layer)->
super
@freq = 6
@amp = 2
@variance = 1
@_keepWiggling = false
@oringinalRotate = @layer.rotation
@layer.on Events.DragSessionStart, =>
if not @_keepWiggling then @stop()
@layer.on Events.DragSessionEnd, =>
if not @_keepWiggling then @start()
_updateWiggleAniamtion: ->
@Animations = []
length = 4
halfDuration = 1/@freq/2
originShift = 0.25
for i in [0...length]
rotationShift = Utils.randomNumber(-@variance, @variance)
@Animations[2*i] = new Animation
layer: @layer
properties:
rotation: @amp+rotationShift
originX: 0.5-originShift
time: halfDuration
@Animations[2*i+1] = new Animation
layer: @layer
properties:
rotation: -(@amp+rotationShift)
originX: 0.5+originShift
time: halfDuration
for animation, index in @Animations
if index is @Animations.length-1
animation.on(Events.AnimationEnd, @Animations[0].start )
else
animation.on( Events.AnimationEnd, ((index)->
@Animations[index+1].start()
).bind(this, index))
_resetFrame: ->
@layer.rotation = @oringinalRotate
@layer.originX = .5
start: ->
Utils.randomChoice(@Animations).start()
@_isWiggling = true
stop: ->
for animation in @Animations
animation.stop()
@_resetFrame()
@_isWiggling = false
# Add extension method to Layer
Layer.define "wiggle",
get: -> @_wiggle ?= new Wiggle(@)
set: (options) ->
@wiggle.freq = options.freq if options.freq
@wiggle.amp = options.amp if options.amp
@wiggle.wiggleWhenDragging = options.wiggleWhenDragging if options.wiggleWhenDragging | 86762 | ###
Wiggle Module for FramerJS
Created by <NAME> (@luciendeer), Feb. 17th, 2016
https://github.com/LucienLee/framer-Wiggle
Wiggle Module help you creating wiggle effect in FramerJS.
Add the following line to your project in Framer Studio.
require 'Wiggle'
[Configure wiggle]
layer.wiggle =
freq: 6 //wiggle frequence (per sec)
amp: 1 // wiggle amplitude
variance: 2 // wiggle amplitude variance
wiggleWhenDragging: false // keep wiggling when dragging or not
[Wiggle!]
layer.wiggle.start()
layer.wiggle.stop()
[Check wiggle state]
layer.wiggle.isWiggling //return true or false
###
class Wiggle extends Framer.BaseClass
# wiggle frequence (per sec)
@define "freq",
get: -> @_freq,
set: (value)->
if _.isNumber(value) and value > 0
@_freq = value
@_updateWiggleAniamtion()
# wiggle amplitude
@define "amp",
get: -> @_amp,
set: (value)->
if _.isNumber(value)
@_amp = value
@_updateWiggleAniamtion()
# wiggle amplitude variance
@define "variance",
get: -> @_variance,
set: (value)->
if _.isNumber(value)
@_variance = value
@_updateWiggleAniamtion()
# keep wiggling when dragging
@define "wiggleWhenDragging",
get: -> @_keepWiggling
set: (value)-> @_keepWiggling = value if _.isBoolean value
@define "isWiggling", get: -> @_isWiggling or false
constructor: (@layer)->
super
@freq = 6
@amp = 2
@variance = 1
@_keepWiggling = false
@oringinalRotate = @layer.rotation
@layer.on Events.DragSessionStart, =>
if not @_keepWiggling then @stop()
@layer.on Events.DragSessionEnd, =>
if not @_keepWiggling then @start()
_updateWiggleAniamtion: ->
@Animations = []
length = 4
halfDuration = 1/@freq/2
originShift = 0.25
for i in [0...length]
rotationShift = Utils.randomNumber(-@variance, @variance)
@Animations[2*i] = new Animation
layer: @layer
properties:
rotation: @amp+rotationShift
originX: 0.5-originShift
time: halfDuration
@Animations[2*i+1] = new Animation
layer: @layer
properties:
rotation: -(@amp+rotationShift)
originX: 0.5+originShift
time: halfDuration
for animation, index in @Animations
if index is @Animations.length-1
animation.on(Events.AnimationEnd, @Animations[0].start )
else
animation.on( Events.AnimationEnd, ((index)->
@Animations[index+1].start()
).bind(this, index))
_resetFrame: ->
@layer.rotation = @oringinalRotate
@layer.originX = .5
start: ->
Utils.randomChoice(@Animations).start()
@_isWiggling = true
stop: ->
for animation in @Animations
animation.stop()
@_resetFrame()
@_isWiggling = false
# Add extension method to Layer
Layer.define "wiggle",
get: -> @_wiggle ?= new Wiggle(@)
set: (options) ->
@wiggle.freq = options.freq if options.freq
@wiggle.amp = options.amp if options.amp
@wiggle.wiggleWhenDragging = options.wiggleWhenDragging if options.wiggleWhenDragging | true | ###
Wiggle Module for FramerJS
Created by PI:NAME:<NAME>END_PI (@luciendeer), Feb. 17th, 2016
https://github.com/LucienLee/framer-Wiggle
Wiggle Module help you creating wiggle effect in FramerJS.
Add the following line to your project in Framer Studio.
require 'Wiggle'
[Configure wiggle]
layer.wiggle =
freq: 6 //wiggle frequence (per sec)
amp: 1 // wiggle amplitude
variance: 2 // wiggle amplitude variance
wiggleWhenDragging: false // keep wiggling when dragging or not
[Wiggle!]
layer.wiggle.start()
layer.wiggle.stop()
[Check wiggle state]
layer.wiggle.isWiggling //return true or false
###
class Wiggle extends Framer.BaseClass
# wiggle frequence (per sec)
@define "freq",
get: -> @_freq,
set: (value)->
if _.isNumber(value) and value > 0
@_freq = value
@_updateWiggleAniamtion()
# wiggle amplitude
@define "amp",
get: -> @_amp,
set: (value)->
if _.isNumber(value)
@_amp = value
@_updateWiggleAniamtion()
# wiggle amplitude variance
@define "variance",
get: -> @_variance,
set: (value)->
if _.isNumber(value)
@_variance = value
@_updateWiggleAniamtion()
# keep wiggling when dragging
@define "wiggleWhenDragging",
get: -> @_keepWiggling
set: (value)-> @_keepWiggling = value if _.isBoolean value
@define "isWiggling", get: -> @_isWiggling or false
constructor: (@layer)->
super
@freq = 6
@amp = 2
@variance = 1
@_keepWiggling = false
@oringinalRotate = @layer.rotation
@layer.on Events.DragSessionStart, =>
if not @_keepWiggling then @stop()
@layer.on Events.DragSessionEnd, =>
if not @_keepWiggling then @start()
_updateWiggleAniamtion: ->
@Animations = []
length = 4
halfDuration = 1/@freq/2
originShift = 0.25
for i in [0...length]
rotationShift = Utils.randomNumber(-@variance, @variance)
@Animations[2*i] = new Animation
layer: @layer
properties:
rotation: @amp+rotationShift
originX: 0.5-originShift
time: halfDuration
@Animations[2*i+1] = new Animation
layer: @layer
properties:
rotation: -(@amp+rotationShift)
originX: 0.5+originShift
time: halfDuration
for animation, index in @Animations
if index is @Animations.length-1
animation.on(Events.AnimationEnd, @Animations[0].start )
else
animation.on( Events.AnimationEnd, ((index)->
@Animations[index+1].start()
).bind(this, index))
_resetFrame: ->
@layer.rotation = @oringinalRotate
@layer.originX = .5
start: ->
Utils.randomChoice(@Animations).start()
@_isWiggling = true
stop: ->
for animation in @Animations
animation.stop()
@_resetFrame()
@_isWiggling = false
# Add extension method to Layer
Layer.define "wiggle",
get: -> @_wiggle ?= new Wiggle(@)
set: (options) ->
@wiggle.freq = options.freq if options.freq
@wiggle.amp = options.amp if options.amp
@wiggle.wiggleWhenDragging = options.wiggleWhenDragging if options.wiggleWhenDragging |
[
{
"context": "on extends SyncKey Chaplin.Collection\n syncKey: 'someItems'\n url: '/test'\n\ndescribe 'SyncKey mixin', ->\n s",
"end": 148,
"score": 0.8931474685668945,
"start": 139,
"tag": "KEY",
"value": "someItems"
},
{
"context": "a function', ->\n before ->\n syncKey ... | mixins/models/sync-key.spec.coffee | kpunith8/gringotts | 0 | import Chaplin from 'chaplin'
import SyncKey from './sync-key'
class MockSyncKeyCollection extends SyncKey Chaplin.Collection
syncKey: 'someItems'
url: '/test'
describe 'SyncKey mixin', ->
sandbox = null
collection = null
syncKey = null
beforeEach ->
sandbox = sinon.createSandbox useFakeServer: yes
sandbox.server.respondWith [200, {}, JSON.stringify {
someItems: [{}, {}, {}]
}]
collection = new MockSyncKeyCollection()
collection.syncKey = syncKey if syncKey
collection.fetch()
afterEach ->
sandbox.restore()
collection.dispose()
it 'should be instantiated', ->
expect(collection).to.be.instanceOf MockSyncKeyCollection
it 'should parse response correctly', ->
expect(collection.length).to.equal 3
context 'when syncKey is a function', ->
before ->
syncKey = -> 'someItems'
it 'should parse response correctly', ->
expect(collection.length).to.equal 3
| 85484 | import Chaplin from 'chaplin'
import SyncKey from './sync-key'
class MockSyncKeyCollection extends SyncKey Chaplin.Collection
syncKey: '<KEY>'
url: '/test'
describe 'SyncKey mixin', ->
sandbox = null
collection = null
syncKey = null
beforeEach ->
sandbox = sinon.createSandbox useFakeServer: yes
sandbox.server.respondWith [200, {}, JSON.stringify {
someItems: [{}, {}, {}]
}]
collection = new MockSyncKeyCollection()
collection.syncKey = syncKey if syncKey
collection.fetch()
afterEach ->
sandbox.restore()
collection.dispose()
it 'should be instantiated', ->
expect(collection).to.be.instanceOf MockSyncKeyCollection
it 'should parse response correctly', ->
expect(collection.length).to.equal 3
context 'when syncKey is a function', ->
before ->
syncKey = -> '<KEY>'
it 'should parse response correctly', ->
expect(collection.length).to.equal 3
| true | import Chaplin from 'chaplin'
import SyncKey from './sync-key'
class MockSyncKeyCollection extends SyncKey Chaplin.Collection
syncKey: 'PI:KEY:<KEY>END_PI'
url: '/test'
describe 'SyncKey mixin', ->
sandbox = null
collection = null
syncKey = null
beforeEach ->
sandbox = sinon.createSandbox useFakeServer: yes
sandbox.server.respondWith [200, {}, JSON.stringify {
someItems: [{}, {}, {}]
}]
collection = new MockSyncKeyCollection()
collection.syncKey = syncKey if syncKey
collection.fetch()
afterEach ->
sandbox.restore()
collection.dispose()
it 'should be instantiated', ->
expect(collection).to.be.instanceOf MockSyncKeyCollection
it 'should parse response correctly', ->
expect(collection.length).to.equal 3
context 'when syncKey is a function', ->
before ->
syncKey = -> 'PI:KEY:<KEY>END_PI'
it 'should parse response correctly', ->
expect(collection.length).to.equal 3
|
[
{
"context": "app_name}\\' do\\n repository \\'${2:git@github.com/whoami/project}\\'\\n reference \\'${3:master}\\'\\n action",
"end": 4877,
"score": 0.9969079494476318,
"start": 4871,
"tag": "USERNAME",
"value": "whoami"
},
{
"context": " 'prefix': 'ifconfig'\n 'body': 'ifconf... | snippets/recipes.cson | pschaumburg/language-chef | 3 | '.source.chef.recipes':
'apt_package':
'prefix': 'apt_package'
'body': 'apt_package \'${1:name}\' do\n action :${2:install}\n source \'${3:/path/to/file.deb}\'\nend'
'apt_preference':
'prefix': 'apt_preference'
'body': 'apt_preference \'${1:name}\' do\n pin \'${2:version 5.1.49-3}\'\n action :${3:add}\nend'
'apt_repository':
'prefix': 'apt_repository'
'body': 'apt_repository \'${1:nginx}\' do\n uri \'${2:http://nginx.org/packages/ubuntu/}\'\n components [${3:\'nginx\'}]\n action :${4:add}\nend'
'apt_update':
'prefix': 'apt_update'
'body': 'apt_update \'${1:name}\' do\n frequency ${2:86400}\n action :${3:periodic}\nend'
'bash':
'prefix': 'bash'
'body': 'bash \'${1:a bash script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:wget http://www.example.com/tarball.tar.bz\n tar -zxf tarball.tar.gz\n cd tarball\n ./configure\n make\n make install}\n EOH\n action :${4:run}\nend'
'batch':
'prefix': 'batch'
'body': 'batch \'${1:a batch script}\' do\n user \'${2:Administrator}\'\n cwd \'${3:C:\\\\temp}\'\n code <<-EOH\n ${4: 7z.exe x C:\\\\temp\\ruby-1.8.7-p352-i386-mingw32.7z\n -oC:\\source -r -y\n xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y}\n EOH\n action :${3:run}\nend'
'bff_package':
'prefix': 'bff_package'
'body': 'bff_package \'${1:name}\' do\n source \'${2:/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0}\'\n action :${3:install}\nend'
'breakpoint':
'prefix': 'breakpoint' #check
'body': 'breakpoint \'${1:name}\' do\n action :${2:break}\nend'
'cab_package':
'prefix': 'cab_package'
'body': 'cab_package \'${1:name}\' do\n source \'${2:C:\\\\example.cab\}\'\n action :${3:install}\nend'
'chef_gem':
'prefix': 'chef_gem'
'body': 'chef_gem \'${1:name}\' do\n compile_time ${2:false} \n action :${3:install}\nend'
'chef_handler':
'prefix': 'chef_handler'
'body': 'chef_handler \'${1:name_of_handler}\' do\n source \'${2:path to source}\'\n arguments [${3:argument1, argument2}]\n action :${4:enable}\nend'
'chocolatey_package':
'prefix': 'chocolatey_package'
'body': 'chocolatey_package \'${1:name}\' do\n action :${3:install}\nend'
'cookbook_file':
'prefix': 'cookbook_file'
'body': 'cookbook_file \'${1:/tmp/filename.md}\' do\n source \'${2:filename.md}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0644}\'\n action :${6:create}\nend'
'cron':
'prefix': 'cron'
'body': 'cron \'${1:name}\' do\n hour \'${2:5}\'\n minute \'${3:5}\'\n command \'${4:/bin/true}\'\n action :${5:create}\nend'
'csh':
'prefix': 'csh'
'body': 'csh \'${1:a csh script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:foreach i ( 10 15 20 40 )\n echo $i\n end}\n EOH\n action :${5:run}\nend'
'directory':
'prefix': 'directory'
'body': 'directory \'${1:/tmp/something}\' do\n owner \'${2:root}\'\n group \'${3:root}\'\n mode \'${4:0755}\'\n recursive ${5:true}\n action :${6:create}\nend'
'dmg_package':
'prefix': 'dmg_package'
'body': 'dmg_package \'${1:name}\' do\n source \'${2:https://packages.chef.io/files/stable/chefdk/2.5.3/mac_os_x/10.13/chefdk-2.5.3-1.dmg}\'\n action :${3:install}\nend'
'dnf_package':
'prefix': 'dnf_package'
'body': 'dnf_package \'${1:only-in-custom-repo}\' do\n action :${2:install}\nend'
'dpkg_package':
'prefix': 'dpkg_package'
'body': 'dpkg_package \'${1:name}\' do\n source \'${2:/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb}\'\n action :${3:install}\nend'
'dsc_resource':
'prefix': 'dsc_resource'
'body': 'dsc_resource \'${1:name}\' do\n resource :${2:archive}\n property :${3:ensure}, \'${4:Present}\'\n property :${5:path} \"${6:C:\\\\Users\\\\Public\\\\Documents\\\\example.zip\}"\n property :${7:destination} \"${8:C:\\\\Users\\\\Public\\\\Documents\\\\ExtractionPath\}"\n action :${9:nothing}\nend'
'dsc_script':
'prefix': 'dsc_script'
'body': 'dsc_script \'${1:name}\' do\n code <<-EOH\n ${2:}\n EOH\n action :${3:run}\nend'
'execute':
'prefix': 'execute'
'body': 'execute \'${1:name}\' do\n command \'${2:command}\'\n action :${3:run}\nend'
'file':
'prefix': 'file'
'body': 'file \'${1:/tmp/something}\' do\n content \'${2:This is a placeholder}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'freebsd_package':
'prefix': 'freebsd_package'
'body': 'freebsd_package \'${1:name}\' do\n action :${2:install}\nend'
'gem_package':
'prefix': 'gem_package'
'body': 'gem_package \'${1:gem}\' do\n gem_binary \'${2:/opt/chef/embedded/bin/gem}\'\n action :${3:install}\nend'
'git':
'prefix': 'git'
'body': 'git \'${1:/tmp/app_name}\' do\n repository \'${2:git@github.com/whoami/project}\'\n reference \'${3:master}\'\n action :${4:sync}\nend'
'group':
'prefix': 'group'
'body': 'group \'${1:www-data}\' do\n members [\'${2:maintenance}\', \'${3:clicron}\']\n append ${4:false}\n action :${5:create}\nend'
'homebrew_cask':
'prefix': 'homebrew_cask'
'body': 'homebrew_cask \'${1:name}\' do\n action :${2:install}\nend'
'homebrew_package':
'prefix': 'homebrew_package'
'body': 'homebrew_package \'${1:name}\' do\n action :${2:install}\nend'
'homebrew_tap':
'prefix': 'homebrew_tap'
'body': 'homebrew_tap \'${1:name}\' do\n action :${2:install}\nend'
'hostname':
'prefix': 'hostname'
'body': 'hostname \'${1:name}\' do\n action :${2:set}\nend'
'http_request':
'prefix': 'http_request'
'body': 'http_request \'${1:some_message}\' do\n url \'${2:http://example.com/check_in}\'\n message ${3:{:some => \'data\'}.to_json}\n action :${5:post}\nend'
'ifconfig':
'prefix': 'ifconfig'
'body': 'ifconfig \'${1:192.168.0.1}\' do\n device \'${2:eth1}\'\n action :${3:add}\nend'
'ips_package':
'prefix': 'ips_package'
'body': 'ips_package \'${1:name}\' do\n action :${2:install}\nend'
'ksh':
'prefix': 'ksh'
'body': 'ksh \'${1:name}\' do\n code <<-EOH\n ${2:code}\n EOH\n action :${3:run}\nend'
'launchd':
'prefix': 'launchd'
'body': 'launchd \'${1:com.chef.every15}\' do\n source \'${2:com.chef.every15.plist}\'\n action :${3:create}\nend'
'link':
'prefix': 'link'
'body': 'link \'${1:/tmp/passwd}\' do\n to \'${2:/etc/passwd}\'\n action :${3:create}\nend'
'log':
'prefix': 'log'
'body': 'log \'${1:name}\' do\n message \'${2:This is the message that will be added to the log.}\'\n action :${3:write}\nend'
'macos_userdefaults':
'prefix': 'macos_userdefaults'
'body': 'macos_userdefaults \'${1:name}\' do\n domain \'${2:AppleKeyboardUIMode}\'\n global ${3:true}\n value \'${4:2}\'\n action :${5:write}\nend'
'macports_package':
'prefix': 'macports_package'
'body': 'macports_package \'${1:name}\' do\n action :${2:install}\nend'
'mdadm':
'prefix': 'mdadm'
'body': 'mdadm \'${1:/dev/md0}\' do\n devices [ ${2:\'/dev/sda\', \'/dev/sdb\'} ]\n level ${3:0}\n action :${4:create} ]\nend'
'mount':
'prefix': 'mount'
'body': 'mount \'${1:/mnt/volume1}\' do\n device \'${2:volume1}\'\n device_type :${3:label}\n fstype \'${4:xfs}\'\n options \'${5:rw}\'\n action :${6:mount}\nend'
'msu_package':
'prefix': 'msu_package'
'body': 'msu_package \'${1:name}\' do\n source \'${2:C:\\\\example.msu}\'\n action :${3:install}\nend'
'ohai_hint':
'prefix': 'ohai_hint'
'body': 'ohai_hint \'${1:name}\' do\n hint_name \'${2:custom}\'\n content \'${3:test_content}\'\n action :${4:create}\nend'
'ohai':
'prefix': 'ohai'
'body': 'ohai \'${1:reload_passwd}\' do\n plugin \'${2:etc}\'\n action :${3:reload}\nend'
'openbsd_package':
'prefix': 'openbsd_package'
'body': 'openbsd_package \'${1:name}\' do\n action :${2:install}\nend'
'openssl_dhparam':
'prefix': 'openssl_dhparam'
'body': 'openssl_dhparam \'${1:/etc/httpd/ssl/dhparam.pem}\' do\n key_length ${2:4096}\n action :${3:create}\nend'
'openssl_rsa_private_key_file':
'prefix': 'openssl_rsa_private_key_file'
'body': 'openssl_rsa_private_key_file \'${1:name}\' do\n action :${2:create}\nend'
'openssl_rsa_public_key':
'prefix': 'openssl_rsa_public_key'
'body': 'openssl_rsa_public_key \'${1:/etc/example/key.pub}\' do\n private_key_path \'${2:/etc/example/key.pem}\'\n action :${3:install}\nend'
'osx_profile':
'prefix': 'osx_profile'
'body': 'osx_profile \'${1:name}\' do\n profile \'${2:screensaver/com.company.screensaver.mobileconfig}\'\n action :${3:install}\nend'
'package':
'prefix': 'package'
'body': 'package \'${1:tar}\' do\n version \'${2:1.16.1-1}\'\n action :${3:install}\nend'
'pacman_package':
'prefix': 'pacman_package'
'body': 'pacman_package \'${1:name}\' do\n action :${2:install}\nend'
'paludis_package':
'prefix': 'paludis_package'
'body': 'paludis_package \'${1:name}\' do\n action :${2:install}\nend'
'perl':
'prefix': 'perl'
'body': 'perl \'${1:a perl script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:# hello.pl\n # - Displays a warm greeting\n print \"Hello, World!\\n\";}\n EOH\n action :${5:run}\nend'
'portage_package':
'prefix': 'portage_package'
'body': 'portage_package \'${1:name}\' do\n action :${2:install}\nend'
'powershell_package':
'prefix': 'powershell_package'
'body': 'powershell_package \'${1:xCertificate}\' do\n version \'${2:1.1.0.0}\'\n action :${3:install}\nend'
'powershell_script':
'prefix': 'powershell_script'
'body': 'powershell_script \'${1:read-env-var}\' do\n cwd ${2:C:\\\\temp}\n code <<-EOH \n ${3:$stream = [System.IO.StreamWriter] \"./test-read-env-var.txt\"\n $stream.WriteLine(\"FOO is $env:foo\")\n $stream.close()}\n EOH\n action :${3:run}\nend'
'python':
'prefix': 'python'
'body': 'python \'${1:a python script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:print \"Hello world! From Chef and Python.\"}\n EOH\n action :${5:run}\nend'
'reboot':
'prefix': 'reboot'
'body': 'reboot \'${1:now}\' do\n action :${2:nothing}\n reason \'${3:Need to reboot when the run completes successfully.}\'\n delay_mins ${4:5}\nend'
'registry_key':
'prefix': 'registry_key'
'body': 'registry_key \'${1:HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\name_of_registry_key}\' do\n values [{:name => \'${2:NewRegistryKeyValue}\', :type => :${3:string}, :data => ${4:\'C:\\\\Windows\\\\System32\\\\file_name.bmp\'}}]\n action :${5:create}\nend'
'remote_directory':
'prefix': 'remote_directory'
'body': 'remote_directory \'${1:/etc/apache2}\' do\n source \'${2:apache2}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'remote_file':
'prefix': 'remote_file'
'body': 'remote_file \'${1:var/www/customers/public_html/index.html}\' do\n source \'${2:http://somesite.com/index.html}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'rhsm_errata_level':
'prefix': 'rhsm_errata_level'
'body': 'rhsm_errata_level \'${1:example_install_moderate}\' do\n errata_level \'${2:moderate}\'\n action :${3:install}\nend'
'rhsm_errata':
'prefix': 'rhsm_errata'
'body': 'rhsm_errata \'${1:errata-install}\' do\n errata_id \'${2:RHSA:2018-1234}\'\n action :${3:install}\nend'
'rhsm_register':
'prefix': 'rhsm_register'
'body': 'rhsm_register \'${1:name}\' do\n satellite_host \'${2:satellite.mycompany.com}\'\n activation_key [ ${3:\'key1\', \'key2\'} ]\n action :${4:register}\nend'
'rhsm_repo':
'prefix': 'rhsm_repo'
'body': 'rhsm_repo \'${1:rhel-7-server-extras-rpms}\' do\n action :${5:disable}\nend'
'rhsm_subscription':
'prefix': 'rhsm_subscription'
'body': 'rhsm_subscription \'${1:name}\' do\n action :${2:attach}\nend'
'route':
'prefix': 'route'
'body': 'route \'${1:10.0.1.10/32}\' do\n gateway \'${2:10.0.0.20}\'\n device \'${3:eth1}\'\n action :${4:add}\nend'
'rpm_package':
'prefix': 'rpm_package'
'body': 'rpm_package \'${1:name}\' do\n action :${2:install}\nend'
'ruby':
'prefix': 'ruby'
'body': 'ruby \'${1:desc}\' do\n cwd \'${2:/tmp}\'\n code <<-EOH\n ${3:mkdir -p #{extract_path\\}\n tar xzf #{src_filename\\} -C #{extract_path\\}\n mv #{extract_path\\}/*/* #{extract_path\\}/}\n EOH\n action :${4:run}\nend'
'ruby_block':
'prefix': 'ruby_block'
'body': 'ruby_block \'${1:desc}\' do\n block do\n ${2:Chef::Config.from_file(\"/etc/chef/client.rb\")}\n end\n action :${3:run}\nend'
'script':
'prefix': 'script'
'body': 'script \'${1:name}\' do\n interpreter \'${2:bash}\'\n user \'${3:root}\'\n cwd \'${4:/tmp}\'\n code <<-EOF\n ${5: mkdir -p /var/www/html}\n EOF\n action :${6:run}\nend'
'service':
'prefix': 'service'
'body': 'service \'${1:tomcat}\' do\n supports :${2:status} => true\n action [:${3:enable}, :${3:start}]\nend'
'smartos_package':
'prefix': 'smartos_package'
'body': 'smartos_package \'${1:name}\' do\n action :${2:install}\nend'
'solaris_package':
'prefix': 'solaris_package'
'body': 'solaris_package \'${1:name}\' do\n source \'${2:/packages_directory}\'\n action :${3:install}\nend'
'subversion':
'prefix': 'subversion'
'body': 'subversion \'${1:CouchDB Edge}\' do\n repository \'${2:http://svn.apache.org/repos/asf/couchdb/trunk}\'\n revision \'${3:HEAD}\'\n destination \'${4:/opt/mysources/couch}\'\n action :${5:sync}\nend'
'sudo':
'prefix': 'sudo'
'body': 'sudo \'${1:passwordless-access}\' do\n commands %{2:[\'systemctl restart httpd\', \'systemctl restart mysql\']}\n nopasswd false\n action :${3:create}\nend'
'swap_file':
'prefix': 'swap_file'
'body': 'swap_file \'${1:/dev/sda1}\' do\n size ${2:1024}\n action :${3:create}\nend'
'sysctl':
'prefix': 'sysctl'
'body': 'sysctl \'${1:name}\' do\n value ${2:1024}\n action :${3:apply}\nend'
'systemd_unit':
'prefix': 'systemd_unit'
'body': 'systemd_unit \'${1:etcd.service}\' do\n content(${2:Unit: {\n Description: \'Etcd\',\n Documentation: \'https://coreos.com/etcd\',\n After: \'network.target\',\n \\},\n Service: {\n Type: \'notify\',\n ExecStart: \'/usr/local/etcd\',\n Restart: \'always\',\n \\},\n Install: {\n WantedBy: \'multi-user.target\',\n \\}})\n action :${3:create}\nend'
'template':
'prefix': 'template'
'body': 'template \'${1:/tmp/config.conf}\' do\n source \'${2:config.conf.erb}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0744}\'\n action :${6:create}\nend'
'user':
'prefix': 'user'
'body': 'user \'${1:random}\' do\n comment \'${2:Random User}\'\n uid \'${3:1000}\'\n gid \'${4:users}\'\n shell \'${5:/bin/bash}\'\n action :${6:create}\nend'
'windows_ad_join':
'prefix': 'windows_ad_join'
'body': 'windows_ad_join \'${1:ad.example.org}\' do\n domain_user ${2:\'nick\'}\n password \'${3:p@ssw0rd1}\'\n action :${4:join}\nend'
'windows_auto_run':
'prefix': 'windows_auto_run'
'body': 'windows_auto_run \'${1:BGINFO}\' do\n program \'${2:C:/Sysinternals/bginfo.exe}\'\n args \'${3:\'C:/Sysinternals/Config.bgi\' /NOLICPROMPT /TIMER:0}\'\n action :${4:create}\nend'
'windows_env':
'prefix': 'windows_env'
'body': 'windows_env \'${1:ComSpec}\' do\n value \'${2:C:\\\\Windows\\\\system32\\\\cmd.exe}\'\n action :${3:create}\nend'
'windows_feature':
'prefix': 'windows_feature'
'body': 'windows_feature \'${1:DHCPServer}\' do\n action :${2:install}\nend'
'windows_feature_dism':
'prefix': 'windows_feature_dism'
'body': 'windows_feature_dism \'${1:name}\' do\n all ${2:false}\n source \'${3:localrepository}\'\n action :${4:install}\nend'
'windows_feature_powershell':
'prefix': 'windows_feature_powershell'
'body': 'windows_feature_powershell \'${1:name}\' do\n all ${2:false}\n source \'${3:localrepository}\'\n action :${4:install}\nend'
'windows_font':
'prefix': 'windows_font'
'body': 'windows_font \'${1:name}\' do\n source \'${2:https://example.com/Custom.otf}\'\n action :${3:install}\nend'
'windows_package':
'prefix': 'windows_package'
'body': 'windows_package \'${1:name}\' do\n action :${2:install}\nend'
'windows_path':
'prefix': 'windows_path'
'body': 'windows_path \'${1:C:\\Sysinternals}\' do\n action :${2:add}\nend'
'windows_printer':
'prefix': 'windows_printer'
'body': 'windows_printer \'${1:HP LaserJet 5th Floor}\' do\n driver_name \'${2:HP LaserJet 4100 Series PCL6}\'\n ipv4_address \'${3:10.4.64.38}\'\n action :${4:create}\nend'
'windows_printer_port':
'prefix': 'windows_printer_port'
'body': 'windows_printer_port \'${1:10.4.64.37}\' do\n action :${2:create}\nend'
'windows_service':
'prefix': 'windows_service'
'body': 'windows_service \'${1:BITS}\' do\n action :${2:configure_startup}\n startup_type :${3:manual}\nend'
'windows_shortcut':
'prefix': 'windows_shortcut'
'body': 'windows_shortcut \'${1:Notepad.lnk}\' do\n description \'${2:Launch Notepad}\'\n target \'${3:C:\\Windows\\notepad.exe}\'\n iconlocation \'${4:C:\\Windows\\notepad.exe,0}\'\n action :${5:create}\nend'
'windows_task':
'prefix': 'windows_task'
'body': 'windows_task \'${1:chef-client}\' do\n command \'${2:chef-client}\'\n run_level :${3:highest}\n frequency \'${4:weekly}\'\n frequency_modifier ${5:2}\n day ${6:Mon, Fri}\n action :${7:create}\nend'
'yum_package':
'prefix': 'yum_package'
'body': 'yum_package \'${1:wget}\' do\n source \'${2:/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb}\'\n action :${3:install}\nend'
'yum_repository':
'prefix': 'yum_repository'
'body': 'yum_repository \'${1:name}\' do\n description \'Zenoss Stable repo\'\n baseurl \'http://dev.zenoss.com/yum/stable/\'\n gpgkey \'http://dev.zenoss.com/yum/RPM-GPG-KEY-zenoss\'\n action :${2:create}\nend'
'zypper_package':
'prefix': 'zypper_package'
'body': 'zypper_package \'${1:name}\' do\n action :${3:install}\nend'
'zypper_repository':
'prefix': 'zypper_repository'
'body': 'zypper_repository \'${1:Packman}\' do\n baseurl \'http://packman.inode.at\'\n path \'/suse/openSUSE_Leap_42.3\'\n action :${3:add}\nend'
| 110002 | '.source.chef.recipes':
'apt_package':
'prefix': 'apt_package'
'body': 'apt_package \'${1:name}\' do\n action :${2:install}\n source \'${3:/path/to/file.deb}\'\nend'
'apt_preference':
'prefix': 'apt_preference'
'body': 'apt_preference \'${1:name}\' do\n pin \'${2:version 5.1.49-3}\'\n action :${3:add}\nend'
'apt_repository':
'prefix': 'apt_repository'
'body': 'apt_repository \'${1:nginx}\' do\n uri \'${2:http://nginx.org/packages/ubuntu/}\'\n components [${3:\'nginx\'}]\n action :${4:add}\nend'
'apt_update':
'prefix': 'apt_update'
'body': 'apt_update \'${1:name}\' do\n frequency ${2:86400}\n action :${3:periodic}\nend'
'bash':
'prefix': 'bash'
'body': 'bash \'${1:a bash script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:wget http://www.example.com/tarball.tar.bz\n tar -zxf tarball.tar.gz\n cd tarball\n ./configure\n make\n make install}\n EOH\n action :${4:run}\nend'
'batch':
'prefix': 'batch'
'body': 'batch \'${1:a batch script}\' do\n user \'${2:Administrator}\'\n cwd \'${3:C:\\\\temp}\'\n code <<-EOH\n ${4: 7z.exe x C:\\\\temp\\ruby-1.8.7-p352-i386-mingw32.7z\n -oC:\\source -r -y\n xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y}\n EOH\n action :${3:run}\nend'
'bff_package':
'prefix': 'bff_package'
'body': 'bff_package \'${1:name}\' do\n source \'${2:/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0}\'\n action :${3:install}\nend'
'breakpoint':
'prefix': 'breakpoint' #check
'body': 'breakpoint \'${1:name}\' do\n action :${2:break}\nend'
'cab_package':
'prefix': 'cab_package'
'body': 'cab_package \'${1:name}\' do\n source \'${2:C:\\\\example.cab\}\'\n action :${3:install}\nend'
'chef_gem':
'prefix': 'chef_gem'
'body': 'chef_gem \'${1:name}\' do\n compile_time ${2:false} \n action :${3:install}\nend'
'chef_handler':
'prefix': 'chef_handler'
'body': 'chef_handler \'${1:name_of_handler}\' do\n source \'${2:path to source}\'\n arguments [${3:argument1, argument2}]\n action :${4:enable}\nend'
'chocolatey_package':
'prefix': 'chocolatey_package'
'body': 'chocolatey_package \'${1:name}\' do\n action :${3:install}\nend'
'cookbook_file':
'prefix': 'cookbook_file'
'body': 'cookbook_file \'${1:/tmp/filename.md}\' do\n source \'${2:filename.md}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0644}\'\n action :${6:create}\nend'
'cron':
'prefix': 'cron'
'body': 'cron \'${1:name}\' do\n hour \'${2:5}\'\n minute \'${3:5}\'\n command \'${4:/bin/true}\'\n action :${5:create}\nend'
'csh':
'prefix': 'csh'
'body': 'csh \'${1:a csh script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:foreach i ( 10 15 20 40 )\n echo $i\n end}\n EOH\n action :${5:run}\nend'
'directory':
'prefix': 'directory'
'body': 'directory \'${1:/tmp/something}\' do\n owner \'${2:root}\'\n group \'${3:root}\'\n mode \'${4:0755}\'\n recursive ${5:true}\n action :${6:create}\nend'
'dmg_package':
'prefix': 'dmg_package'
'body': 'dmg_package \'${1:name}\' do\n source \'${2:https://packages.chef.io/files/stable/chefdk/2.5.3/mac_os_x/10.13/chefdk-2.5.3-1.dmg}\'\n action :${3:install}\nend'
'dnf_package':
'prefix': 'dnf_package'
'body': 'dnf_package \'${1:only-in-custom-repo}\' do\n action :${2:install}\nend'
'dpkg_package':
'prefix': 'dpkg_package'
'body': 'dpkg_package \'${1:name}\' do\n source \'${2:/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb}\'\n action :${3:install}\nend'
'dsc_resource':
'prefix': 'dsc_resource'
'body': 'dsc_resource \'${1:name}\' do\n resource :${2:archive}\n property :${3:ensure}, \'${4:Present}\'\n property :${5:path} \"${6:C:\\\\Users\\\\Public\\\\Documents\\\\example.zip\}"\n property :${7:destination} \"${8:C:\\\\Users\\\\Public\\\\Documents\\\\ExtractionPath\}"\n action :${9:nothing}\nend'
'dsc_script':
'prefix': 'dsc_script'
'body': 'dsc_script \'${1:name}\' do\n code <<-EOH\n ${2:}\n EOH\n action :${3:run}\nend'
'execute':
'prefix': 'execute'
'body': 'execute \'${1:name}\' do\n command \'${2:command}\'\n action :${3:run}\nend'
'file':
'prefix': 'file'
'body': 'file \'${1:/tmp/something}\' do\n content \'${2:This is a placeholder}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'freebsd_package':
'prefix': 'freebsd_package'
'body': 'freebsd_package \'${1:name}\' do\n action :${2:install}\nend'
'gem_package':
'prefix': 'gem_package'
'body': 'gem_package \'${1:gem}\' do\n gem_binary \'${2:/opt/chef/embedded/bin/gem}\'\n action :${3:install}\nend'
'git':
'prefix': 'git'
'body': 'git \'${1:/tmp/app_name}\' do\n repository \'${2:git@github.com/whoami/project}\'\n reference \'${3:master}\'\n action :${4:sync}\nend'
'group':
'prefix': 'group'
'body': 'group \'${1:www-data}\' do\n members [\'${2:maintenance}\', \'${3:clicron}\']\n append ${4:false}\n action :${5:create}\nend'
'homebrew_cask':
'prefix': 'homebrew_cask'
'body': 'homebrew_cask \'${1:name}\' do\n action :${2:install}\nend'
'homebrew_package':
'prefix': 'homebrew_package'
'body': 'homebrew_package \'${1:name}\' do\n action :${2:install}\nend'
'homebrew_tap':
'prefix': 'homebrew_tap'
'body': 'homebrew_tap \'${1:name}\' do\n action :${2:install}\nend'
'hostname':
'prefix': 'hostname'
'body': 'hostname \'${1:name}\' do\n action :${2:set}\nend'
'http_request':
'prefix': 'http_request'
'body': 'http_request \'${1:some_message}\' do\n url \'${2:http://example.com/check_in}\'\n message ${3:{:some => \'data\'}.to_json}\n action :${5:post}\nend'
'ifconfig':
'prefix': 'ifconfig'
'body': 'ifconfig \'${1:192.168.0.1}\' do\n device \'${2:eth1}\'\n action :${3:add}\nend'
'ips_package':
'prefix': 'ips_package'
'body': 'ips_package \'${1:name}\' do\n action :${2:install}\nend'
'ksh':
'prefix': 'ksh'
'body': 'ksh \'${1:name}\' do\n code <<-EOH\n ${2:code}\n EOH\n action :${3:run}\nend'
'launchd':
'prefix': 'launchd'
'body': 'launchd \'${1:com.chef.every15}\' do\n source \'${2:com.chef.every15.plist}\'\n action :${3:create}\nend'
'link':
'prefix': 'link'
'body': 'link \'${1:/tmp/passwd}\' do\n to \'${2:/etc/passwd}\'\n action :${3:create}\nend'
'log':
'prefix': 'log'
'body': 'log \'${1:name}\' do\n message \'${2:This is the message that will be added to the log.}\'\n action :${3:write}\nend'
'macos_userdefaults':
'prefix': 'macos_userdefaults'
'body': 'macos_userdefaults \'${1:name}\' do\n domain \'${2:AppleKeyboardUIMode}\'\n global ${3:true}\n value \'${4:2}\'\n action :${5:write}\nend'
'macports_package':
'prefix': 'macports_package'
'body': 'macports_package \'${1:name}\' do\n action :${2:install}\nend'
'mdadm':
'prefix': 'mdadm'
'body': 'mdadm \'${1:/dev/md0}\' do\n devices [ ${2:\'/dev/sda\', \'/dev/sdb\'} ]\n level ${3:0}\n action :${4:create} ]\nend'
'mount':
'prefix': 'mount'
'body': 'mount \'${1:/mnt/volume1}\' do\n device \'${2:volume1}\'\n device_type :${3:label}\n fstype \'${4:xfs}\'\n options \'${5:rw}\'\n action :${6:mount}\nend'
'msu_package':
'prefix': 'msu_package'
'body': 'msu_package \'${1:name}\' do\n source \'${2:C:\\\\example.msu}\'\n action :${3:install}\nend'
'ohai_hint':
'prefix': 'ohai_hint'
'body': 'ohai_hint \'${1:name}\' do\n hint_name \'${2:custom}\'\n content \'${3:test_content}\'\n action :${4:create}\nend'
'ohai':
'prefix': 'ohai'
'body': 'ohai \'${1:reload_passwd}\' do\n plugin \'${2:etc}\'\n action :${3:reload}\nend'
'openbsd_package':
'prefix': 'openbsd_package'
'body': 'openbsd_package \'${1:name}\' do\n action :${2:install}\nend'
'openssl_dhparam':
'prefix': 'openssl_dhparam'
'body': 'openssl_dhparam \'${1:/etc/httpd/ssl/dhparam.pem}\' do\n key_length ${2:4096}\n action :${3:create}\nend'
'openssl_rsa_private_key_file':
'prefix': 'openssl_rsa_private_key_file'
'body': 'openssl_rsa_private_key_file \'${1:name}\' do\n action :${2:create}\nend'
'openssl_rsa_public_key':
'prefix': 'openssl_rsa_public_key'
'body': 'openssl_rsa_public_key \'${1:/etc/example/key.pub}\' do\n private_key_path \'${2:/etc/example/key.pem}\'\n action :${3:install}\nend'
'osx_profile':
'prefix': 'osx_profile'
'body': 'osx_profile \'${1:name}\' do\n profile \'${2:screensaver/com.company.screensaver.mobileconfig}\'\n action :${3:install}\nend'
'package':
'prefix': 'package'
'body': 'package \'${1:tar}\' do\n version \'${2:1.16.1-1}\'\n action :${3:install}\nend'
'pacman_package':
'prefix': 'pacman_package'
'body': 'pacman_package \'${1:name}\' do\n action :${2:install}\nend'
'paludis_package':
'prefix': 'paludis_package'
'body': 'paludis_package \'${1:name}\' do\n action :${2:install}\nend'
'perl':
'prefix': 'perl'
'body': 'perl \'${1:a perl script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:# hello.pl\n # - Displays a warm greeting\n print \"Hello, World!\\n\";}\n EOH\n action :${5:run}\nend'
'portage_package':
'prefix': 'portage_package'
'body': 'portage_package \'${1:name}\' do\n action :${2:install}\nend'
'powershell_package':
'prefix': 'powershell_package'
'body': 'powershell_package \'${1:xCertificate}\' do\n version \'${2:1.1.0.0}\'\n action :${3:install}\nend'
'powershell_script':
'prefix': 'powershell_script'
'body': 'powershell_script \'${1:read-env-var}\' do\n cwd ${2:C:\\\\temp}\n code <<-EOH \n ${3:$stream = [System.IO.StreamWriter] \"./test-read-env-var.txt\"\n $stream.WriteLine(\"FOO is $env:foo\")\n $stream.close()}\n EOH\n action :${3:run}\nend'
'python':
'prefix': 'python'
'body': 'python \'${1:a python script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:print \"Hello world! From Chef and Python.\"}\n EOH\n action :${5:run}\nend'
'reboot':
'prefix': 'reboot'
'body': 'reboot \'${1:now}\' do\n action :${2:nothing}\n reason \'${3:Need to reboot when the run completes successfully.}\'\n delay_mins ${4:5}\nend'
'registry_key':
'prefix': 'registry_key'
'body': 'registry_key \'${1:HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\name_of_registry_key}\' do\n values [{:name => \'${2:NewRegistryKeyValue}\', :type => :${3:string}, :data => ${4:\'C:\\\\Windows\\\\System32\\\\file_name.bmp\'}}]\n action :${5:create}\nend'
'remote_directory':
'prefix': 'remote_directory'
'body': 'remote_directory \'${1:/etc/apache2}\' do\n source \'${2:apache2}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'remote_file':
'prefix': 'remote_file'
'body': 'remote_file \'${1:var/www/customers/public_html/index.html}\' do\n source \'${2:http://somesite.com/index.html}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'rhsm_errata_level':
'prefix': 'rhsm_errata_level'
'body': 'rhsm_errata_level \'${1:example_install_moderate}\' do\n errata_level \'${2:moderate}\'\n action :${3:install}\nend'
'rhsm_errata':
'prefix': 'rhsm_errata'
'body': 'rhsm_errata \'${1:errata-install}\' do\n errata_id \'${2:RHSA:2018-1234}\'\n action :${3:install}\nend'
'rhsm_register':
'prefix': 'rhsm_register'
'body': 'rhsm_register \'${1:name}\' do\n satellite_host \'${2:satellite.my<EMAIL>}\'\n activation_key [ ${3:\'key1\', \'key2\'} ]\n action :${4:register}\nend'
'rhsm_repo':
'prefix': 'rhsm_repo'
'body': 'rhsm_repo \'${1:rhel-7-server-extras-rpms}\' do\n action :${5:disable}\nend'
'rhsm_subscription':
'prefix': 'rhsm_subscription'
'body': 'rhsm_subscription \'${1:name}\' do\n action :${2:attach}\nend'
'route':
'prefix': 'route'
'body': 'route \'${1:10.0.1.10/32}\' do\n gateway \'${2:10.0.0.20}\'\n device \'${3:eth1}\'\n action :${4:add}\nend'
'rpm_package':
'prefix': 'rpm_package'
'body': 'rpm_package \'${1:name}\' do\n action :${2:install}\nend'
'ruby':
'prefix': 'ruby'
'body': 'ruby \'${1:desc}\' do\n cwd \'${2:/tmp}\'\n code <<-EOH\n ${3:mkdir -p #{extract_path\\}\n tar xzf #{src_filename\\} -C #{extract_path\\}\n mv #{extract_path\\}/*/* #{extract_path\\}/}\n EOH\n action :${4:run}\nend'
'ruby_block':
'prefix': 'ruby_block'
'body': 'ruby_block \'${1:desc}\' do\n block do\n ${2:Chef::Config.from_file(\"/etc/chef/client.rb\")}\n end\n action :${3:run}\nend'
'script':
'prefix': 'script'
'body': 'script \'${1:name}\' do\n interpreter \'${2:bash}\'\n user \'${3:root}\'\n cwd \'${4:/tmp}\'\n code <<-EOF\n ${5: mkdir -p /var/www/html}\n EOF\n action :${6:run}\nend'
'service':
'prefix': 'service'
'body': 'service \'${1:tomcat}\' do\n supports :${2:status} => true\n action [:${3:enable}, :${3:start}]\nend'
'smartos_package':
'prefix': 'smartos_package'
'body': 'smartos_package \'${1:name}\' do\n action :${2:install}\nend'
'solaris_package':
'prefix': 'solaris_package'
'body': 'solaris_package \'${1:name}\' do\n source \'${2:/packages_directory}\'\n action :${3:install}\nend'
'subversion':
'prefix': 'subversion'
'body': 'subversion \'${1:CouchDB Edge}\' do\n repository \'${2:http://svn.apache.org/repos/asf/couchdb/trunk}\'\n revision \'${3:HEAD}\'\n destination \'${4:/opt/mysources/couch}\'\n action :${5:sync}\nend'
'sudo':
'prefix': 'sudo'
'body': 'sudo \'${1:passwordless-access}\' do\n commands %{2:[\'systemctl restart httpd\', \'systemctl restart mysql\']}\n nopasswd false\n action :${3:create}\nend'
'swap_file':
'prefix': 'swap_file'
'body': 'swap_file \'${1:/dev/sda1}\' do\n size ${2:1024}\n action :${3:create}\nend'
'sysctl':
'prefix': 'sysctl'
'body': 'sysctl \'${1:name}\' do\n value ${2:1024}\n action :${3:apply}\nend'
'systemd_unit':
'prefix': 'systemd_unit'
'body': 'systemd_unit \'${1:etcd.service}\' do\n content(${2:Unit: {\n Description: \'Etcd\',\n Documentation: \'https://coreos.com/etcd\',\n After: \'network.target\',\n \\},\n Service: {\n Type: \'notify\',\n ExecStart: \'/usr/local/etcd\',\n Restart: \'always\',\n \\},\n Install: {\n WantedBy: \'multi-user.target\',\n \\}})\n action :${3:create}\nend'
'template':
'prefix': 'template'
'body': 'template \'${1:/tmp/config.conf}\' do\n source \'${2:config.conf.erb}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0744}\'\n action :${6:create}\nend'
'user':
'prefix': 'user'
'body': 'user \'${1:random}\' do\n comment \'${2:Random User}\'\n uid \'${3:1000}\'\n gid \'${4:users}\'\n shell \'${5:/bin/bash}\'\n action :${6:create}\nend'
'windows_ad_join':
'prefix': 'windows_ad_join'
'body': 'windows_ad_join \'${1:ad.example.org}\' do\n domain_user ${2:\'nick\'}\n password \'<PASSWORD>}\'\n action :${4:join}\nend'
'windows_auto_run':
'prefix': 'windows_auto_run'
'body': 'windows_auto_run \'${1:BGINFO}\' do\n program \'${2:C:/Sysinternals/bginfo.exe}\'\n args \'${3:\'C:/Sysinternals/Config.bgi\' /NOLICPROMPT /TIMER:0}\'\n action :${4:create}\nend'
'windows_env':
'prefix': 'windows_env'
'body': 'windows_env \'${1:ComSpec}\' do\n value \'${2:C:\\\\Windows\\\\system32\\\\cmd.exe}\'\n action :${3:create}\nend'
'windows_feature':
'prefix': 'windows_feature'
'body': 'windows_feature \'${1:DHCPServer}\' do\n action :${2:install}\nend'
'windows_feature_dism':
'prefix': 'windows_feature_dism'
'body': 'windows_feature_dism \'${1:name}\' do\n all ${2:false}\n source \'${3:localrepository}\'\n action :${4:install}\nend'
'windows_feature_powershell':
'prefix': 'windows_feature_powershell'
'body': 'windows_feature_powershell \'${1:name}\' do\n all ${2:false}\n source \'${3:localrepository}\'\n action :${4:install}\nend'
'windows_font':
'prefix': 'windows_font'
'body': 'windows_font \'${1:name}\' do\n source \'${2:https://example.com/Custom.otf}\'\n action :${3:install}\nend'
'windows_package':
'prefix': 'windows_package'
'body': 'windows_package \'${1:name}\' do\n action :${2:install}\nend'
'windows_path':
'prefix': 'windows_path'
'body': 'windows_path \'${1:C:\\Sysinternals}\' do\n action :${2:add}\nend'
'windows_printer':
'prefix': 'windows_printer'
'body': 'windows_printer \'${1:HP LaserJet 5th Floor}\' do\n driver_name \'${2:HP LaserJet 4100 Series PCL6}\'\n ipv4_address \'${3:10.4.64.38}\'\n action :${4:create}\nend'
'windows_printer_port':
'prefix': 'windows_printer_port'
'body': 'windows_printer_port \'${1:10.4.64.37}\' do\n action :${2:create}\nend'
'windows_service':
'prefix': 'windows_service'
'body': 'windows_service \'${1:BITS}\' do\n action :${2:configure_startup}\n startup_type :${3:manual}\nend'
'windows_shortcut':
'prefix': 'windows_shortcut'
'body': 'windows_shortcut \'${1:Notepad.lnk}\' do\n description \'${2:Launch Notepad}\'\n target \'${3:C:\\Windows\\notepad.exe}\'\n iconlocation \'${4:C:\\Windows\\notepad.exe,0}\'\n action :${5:create}\nend'
'windows_task':
'prefix': 'windows_task'
'body': 'windows_task \'${1:chef-client}\' do\n command \'${2:chef-client}\'\n run_level :${3:highest}\n frequency \'${4:weekly}\'\n frequency_modifier ${5:2}\n day ${6:Mon, Fri}\n action :${7:create}\nend'
'yum_package':
'prefix': 'yum_package'
'body': 'yum_package \'${1:wget}\' do\n source \'${2:/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb}\'\n action :${3:install}\nend'
'yum_repository':
'prefix': 'yum_repository'
'body': 'yum_repository \'${1:name}\' do\n description \'Zenoss Stable repo\'\n baseurl \'http://dev.zenoss.com/yum/stable/\'\n gpgkey \'http://dev.zenoss.com/yum/RPM-GPG-KEY-zenoss\'\n action :${2:create}\nend'
'zypper_package':
'prefix': 'zypper_package'
'body': 'zypper_package \'${1:name}\' do\n action :${3:install}\nend'
'zypper_repository':
'prefix': 'zypper_repository'
'body': 'zypper_repository \'${1:Packman}\' do\n baseurl \'http://packman.inode.at\'\n path \'/suse/openSUSE_Leap_42.3\'\n action :${3:add}\nend'
| true | '.source.chef.recipes':
'apt_package':
'prefix': 'apt_package'
'body': 'apt_package \'${1:name}\' do\n action :${2:install}\n source \'${3:/path/to/file.deb}\'\nend'
'apt_preference':
'prefix': 'apt_preference'
'body': 'apt_preference \'${1:name}\' do\n pin \'${2:version 5.1.49-3}\'\n action :${3:add}\nend'
'apt_repository':
'prefix': 'apt_repository'
'body': 'apt_repository \'${1:nginx}\' do\n uri \'${2:http://nginx.org/packages/ubuntu/}\'\n components [${3:\'nginx\'}]\n action :${4:add}\nend'
'apt_update':
'prefix': 'apt_update'
'body': 'apt_update \'${1:name}\' do\n frequency ${2:86400}\n action :${3:periodic}\nend'
'bash':
'prefix': 'bash'
'body': 'bash \'${1:a bash script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:wget http://www.example.com/tarball.tar.bz\n tar -zxf tarball.tar.gz\n cd tarball\n ./configure\n make\n make install}\n EOH\n action :${4:run}\nend'
'batch':
'prefix': 'batch'
'body': 'batch \'${1:a batch script}\' do\n user \'${2:Administrator}\'\n cwd \'${3:C:\\\\temp}\'\n code <<-EOH\n ${4: 7z.exe x C:\\\\temp\\ruby-1.8.7-p352-i386-mingw32.7z\n -oC:\\source -r -y\n xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y}\n EOH\n action :${3:run}\nend'
'bff_package':
'prefix': 'bff_package'
'body': 'bff_package \'${1:name}\' do\n source \'${2:/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0}\'\n action :${3:install}\nend'
'breakpoint':
'prefix': 'breakpoint' #check
'body': 'breakpoint \'${1:name}\' do\n action :${2:break}\nend'
'cab_package':
'prefix': 'cab_package'
'body': 'cab_package \'${1:name}\' do\n source \'${2:C:\\\\example.cab\}\'\n action :${3:install}\nend'
'chef_gem':
'prefix': 'chef_gem'
'body': 'chef_gem \'${1:name}\' do\n compile_time ${2:false} \n action :${3:install}\nend'
'chef_handler':
'prefix': 'chef_handler'
'body': 'chef_handler \'${1:name_of_handler}\' do\n source \'${2:path to source}\'\n arguments [${3:argument1, argument2}]\n action :${4:enable}\nend'
'chocolatey_package':
'prefix': 'chocolatey_package'
'body': 'chocolatey_package \'${1:name}\' do\n action :${3:install}\nend'
'cookbook_file':
'prefix': 'cookbook_file'
'body': 'cookbook_file \'${1:/tmp/filename.md}\' do\n source \'${2:filename.md}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0644}\'\n action :${6:create}\nend'
'cron':
'prefix': 'cron'
'body': 'cron \'${1:name}\' do\n hour \'${2:5}\'\n minute \'${3:5}\'\n command \'${4:/bin/true}\'\n action :${5:create}\nend'
'csh':
'prefix': 'csh'
'body': 'csh \'${1:a csh script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:foreach i ( 10 15 20 40 )\n echo $i\n end}\n EOH\n action :${5:run}\nend'
'directory':
'prefix': 'directory'
'body': 'directory \'${1:/tmp/something}\' do\n owner \'${2:root}\'\n group \'${3:root}\'\n mode \'${4:0755}\'\n recursive ${5:true}\n action :${6:create}\nend'
'dmg_package':
'prefix': 'dmg_package'
'body': 'dmg_package \'${1:name}\' do\n source \'${2:https://packages.chef.io/files/stable/chefdk/2.5.3/mac_os_x/10.13/chefdk-2.5.3-1.dmg}\'\n action :${3:install}\nend'
'dnf_package':
'prefix': 'dnf_package'
'body': 'dnf_package \'${1:only-in-custom-repo}\' do\n action :${2:install}\nend'
'dpkg_package':
'prefix': 'dpkg_package'
'body': 'dpkg_package \'${1:name}\' do\n source \'${2:/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb}\'\n action :${3:install}\nend'
'dsc_resource':
'prefix': 'dsc_resource'
'body': 'dsc_resource \'${1:name}\' do\n resource :${2:archive}\n property :${3:ensure}, \'${4:Present}\'\n property :${5:path} \"${6:C:\\\\Users\\\\Public\\\\Documents\\\\example.zip\}"\n property :${7:destination} \"${8:C:\\\\Users\\\\Public\\\\Documents\\\\ExtractionPath\}"\n action :${9:nothing}\nend'
'dsc_script':
'prefix': 'dsc_script'
'body': 'dsc_script \'${1:name}\' do\n code <<-EOH\n ${2:}\n EOH\n action :${3:run}\nend'
'execute':
'prefix': 'execute'
'body': 'execute \'${1:name}\' do\n command \'${2:command}\'\n action :${3:run}\nend'
'file':
'prefix': 'file'
'body': 'file \'${1:/tmp/something}\' do\n content \'${2:This is a placeholder}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'freebsd_package':
'prefix': 'freebsd_package'
'body': 'freebsd_package \'${1:name}\' do\n action :${2:install}\nend'
'gem_package':
'prefix': 'gem_package'
'body': 'gem_package \'${1:gem}\' do\n gem_binary \'${2:/opt/chef/embedded/bin/gem}\'\n action :${3:install}\nend'
'git':
'prefix': 'git'
'body': 'git \'${1:/tmp/app_name}\' do\n repository \'${2:git@github.com/whoami/project}\'\n reference \'${3:master}\'\n action :${4:sync}\nend'
'group':
'prefix': 'group'
'body': 'group \'${1:www-data}\' do\n members [\'${2:maintenance}\', \'${3:clicron}\']\n append ${4:false}\n action :${5:create}\nend'
'homebrew_cask':
'prefix': 'homebrew_cask'
'body': 'homebrew_cask \'${1:name}\' do\n action :${2:install}\nend'
'homebrew_package':
'prefix': 'homebrew_package'
'body': 'homebrew_package \'${1:name}\' do\n action :${2:install}\nend'
'homebrew_tap':
'prefix': 'homebrew_tap'
'body': 'homebrew_tap \'${1:name}\' do\n action :${2:install}\nend'
'hostname':
'prefix': 'hostname'
'body': 'hostname \'${1:name}\' do\n action :${2:set}\nend'
'http_request':
'prefix': 'http_request'
'body': 'http_request \'${1:some_message}\' do\n url \'${2:http://example.com/check_in}\'\n message ${3:{:some => \'data\'}.to_json}\n action :${5:post}\nend'
'ifconfig':
'prefix': 'ifconfig'
'body': 'ifconfig \'${1:192.168.0.1}\' do\n device \'${2:eth1}\'\n action :${3:add}\nend'
'ips_package':
'prefix': 'ips_package'
'body': 'ips_package \'${1:name}\' do\n action :${2:install}\nend'
'ksh':
'prefix': 'ksh'
'body': 'ksh \'${1:name}\' do\n code <<-EOH\n ${2:code}\n EOH\n action :${3:run}\nend'
'launchd':
'prefix': 'launchd'
'body': 'launchd \'${1:com.chef.every15}\' do\n source \'${2:com.chef.every15.plist}\'\n action :${3:create}\nend'
'link':
'prefix': 'link'
'body': 'link \'${1:/tmp/passwd}\' do\n to \'${2:/etc/passwd}\'\n action :${3:create}\nend'
'log':
'prefix': 'log'
'body': 'log \'${1:name}\' do\n message \'${2:This is the message that will be added to the log.}\'\n action :${3:write}\nend'
'macos_userdefaults':
'prefix': 'macos_userdefaults'
'body': 'macos_userdefaults \'${1:name}\' do\n domain \'${2:AppleKeyboardUIMode}\'\n global ${3:true}\n value \'${4:2}\'\n action :${5:write}\nend'
'macports_package':
'prefix': 'macports_package'
'body': 'macports_package \'${1:name}\' do\n action :${2:install}\nend'
'mdadm':
'prefix': 'mdadm'
'body': 'mdadm \'${1:/dev/md0}\' do\n devices [ ${2:\'/dev/sda\', \'/dev/sdb\'} ]\n level ${3:0}\n action :${4:create} ]\nend'
'mount':
'prefix': 'mount'
'body': 'mount \'${1:/mnt/volume1}\' do\n device \'${2:volume1}\'\n device_type :${3:label}\n fstype \'${4:xfs}\'\n options \'${5:rw}\'\n action :${6:mount}\nend'
'msu_package':
'prefix': 'msu_package'
'body': 'msu_package \'${1:name}\' do\n source \'${2:C:\\\\example.msu}\'\n action :${3:install}\nend'
'ohai_hint':
'prefix': 'ohai_hint'
'body': 'ohai_hint \'${1:name}\' do\n hint_name \'${2:custom}\'\n content \'${3:test_content}\'\n action :${4:create}\nend'
'ohai':
'prefix': 'ohai'
'body': 'ohai \'${1:reload_passwd}\' do\n plugin \'${2:etc}\'\n action :${3:reload}\nend'
'openbsd_package':
'prefix': 'openbsd_package'
'body': 'openbsd_package \'${1:name}\' do\n action :${2:install}\nend'
'openssl_dhparam':
'prefix': 'openssl_dhparam'
'body': 'openssl_dhparam \'${1:/etc/httpd/ssl/dhparam.pem}\' do\n key_length ${2:4096}\n action :${3:create}\nend'
'openssl_rsa_private_key_file':
'prefix': 'openssl_rsa_private_key_file'
'body': 'openssl_rsa_private_key_file \'${1:name}\' do\n action :${2:create}\nend'
'openssl_rsa_public_key':
'prefix': 'openssl_rsa_public_key'
'body': 'openssl_rsa_public_key \'${1:/etc/example/key.pub}\' do\n private_key_path \'${2:/etc/example/key.pem}\'\n action :${3:install}\nend'
'osx_profile':
'prefix': 'osx_profile'
'body': 'osx_profile \'${1:name}\' do\n profile \'${2:screensaver/com.company.screensaver.mobileconfig}\'\n action :${3:install}\nend'
'package':
'prefix': 'package'
'body': 'package \'${1:tar}\' do\n version \'${2:1.16.1-1}\'\n action :${3:install}\nend'
'pacman_package':
'prefix': 'pacman_package'
'body': 'pacman_package \'${1:name}\' do\n action :${2:install}\nend'
'paludis_package':
'prefix': 'paludis_package'
'body': 'paludis_package \'${1:name}\' do\n action :${2:install}\nend'
'perl':
'prefix': 'perl'
'body': 'perl \'${1:a perl script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:# hello.pl\n # - Displays a warm greeting\n print \"Hello, World!\\n\";}\n EOH\n action :${5:run}\nend'
'portage_package':
'prefix': 'portage_package'
'body': 'portage_package \'${1:name}\' do\n action :${2:install}\nend'
'powershell_package':
'prefix': 'powershell_package'
'body': 'powershell_package \'${1:xCertificate}\' do\n version \'${2:1.1.0.0}\'\n action :${3:install}\nend'
'powershell_script':
'prefix': 'powershell_script'
'body': 'powershell_script \'${1:read-env-var}\' do\n cwd ${2:C:\\\\temp}\n code <<-EOH \n ${3:$stream = [System.IO.StreamWriter] \"./test-read-env-var.txt\"\n $stream.WriteLine(\"FOO is $env:foo\")\n $stream.close()}\n EOH\n action :${3:run}\nend'
'python':
'prefix': 'python'
'body': 'python \'${1:a python script}\' do\n user \'${2:root}\'\n cwd \'${3:/tmp}\'\n code <<-EOH\n ${4:print \"Hello world! From Chef and Python.\"}\n EOH\n action :${5:run}\nend'
'reboot':
'prefix': 'reboot'
'body': 'reboot \'${1:now}\' do\n action :${2:nothing}\n reason \'${3:Need to reboot when the run completes successfully.}\'\n delay_mins ${4:5}\nend'
'registry_key':
'prefix': 'registry_key'
'body': 'registry_key \'${1:HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\name_of_registry_key}\' do\n values [{:name => \'${2:NewRegistryKeyValue}\', :type => :${3:string}, :data => ${4:\'C:\\\\Windows\\\\System32\\\\file_name.bmp\'}}]\n action :${5:create}\nend'
'remote_directory':
'prefix': 'remote_directory'
'body': 'remote_directory \'${1:/etc/apache2}\' do\n source \'${2:apache2}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'remote_file':
'prefix': 'remote_file'
'body': 'remote_file \'${1:var/www/customers/public_html/index.html}\' do\n source \'${2:http://somesite.com/index.html}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0755}\'\n action :${6:create}\nend'
'rhsm_errata_level':
'prefix': 'rhsm_errata_level'
'body': 'rhsm_errata_level \'${1:example_install_moderate}\' do\n errata_level \'${2:moderate}\'\n action :${3:install}\nend'
'rhsm_errata':
'prefix': 'rhsm_errata'
'body': 'rhsm_errata \'${1:errata-install}\' do\n errata_id \'${2:RHSA:2018-1234}\'\n action :${3:install}\nend'
'rhsm_register':
'prefix': 'rhsm_register'
'body': 'rhsm_register \'${1:name}\' do\n satellite_host \'${2:satellite.myPI:EMAIL:<EMAIL>END_PI}\'\n activation_key [ ${3:\'key1\', \'key2\'} ]\n action :${4:register}\nend'
'rhsm_repo':
'prefix': 'rhsm_repo'
'body': 'rhsm_repo \'${1:rhel-7-server-extras-rpms}\' do\n action :${5:disable}\nend'
'rhsm_subscription':
'prefix': 'rhsm_subscription'
'body': 'rhsm_subscription \'${1:name}\' do\n action :${2:attach}\nend'
'route':
'prefix': 'route'
'body': 'route \'${1:10.0.1.10/32}\' do\n gateway \'${2:10.0.0.20}\'\n device \'${3:eth1}\'\n action :${4:add}\nend'
'rpm_package':
'prefix': 'rpm_package'
'body': 'rpm_package \'${1:name}\' do\n action :${2:install}\nend'
'ruby':
'prefix': 'ruby'
'body': 'ruby \'${1:desc}\' do\n cwd \'${2:/tmp}\'\n code <<-EOH\n ${3:mkdir -p #{extract_path\\}\n tar xzf #{src_filename\\} -C #{extract_path\\}\n mv #{extract_path\\}/*/* #{extract_path\\}/}\n EOH\n action :${4:run}\nend'
'ruby_block':
'prefix': 'ruby_block'
'body': 'ruby_block \'${1:desc}\' do\n block do\n ${2:Chef::Config.from_file(\"/etc/chef/client.rb\")}\n end\n action :${3:run}\nend'
'script':
'prefix': 'script'
'body': 'script \'${1:name}\' do\n interpreter \'${2:bash}\'\n user \'${3:root}\'\n cwd \'${4:/tmp}\'\n code <<-EOF\n ${5: mkdir -p /var/www/html}\n EOF\n action :${6:run}\nend'
'service':
'prefix': 'service'
'body': 'service \'${1:tomcat}\' do\n supports :${2:status} => true\n action [:${3:enable}, :${3:start}]\nend'
'smartos_package':
'prefix': 'smartos_package'
'body': 'smartos_package \'${1:name}\' do\n action :${2:install}\nend'
'solaris_package':
'prefix': 'solaris_package'
'body': 'solaris_package \'${1:name}\' do\n source \'${2:/packages_directory}\'\n action :${3:install}\nend'
'subversion':
'prefix': 'subversion'
'body': 'subversion \'${1:CouchDB Edge}\' do\n repository \'${2:http://svn.apache.org/repos/asf/couchdb/trunk}\'\n revision \'${3:HEAD}\'\n destination \'${4:/opt/mysources/couch}\'\n action :${5:sync}\nend'
'sudo':
'prefix': 'sudo'
'body': 'sudo \'${1:passwordless-access}\' do\n commands %{2:[\'systemctl restart httpd\', \'systemctl restart mysql\']}\n nopasswd false\n action :${3:create}\nend'
'swap_file':
'prefix': 'swap_file'
'body': 'swap_file \'${1:/dev/sda1}\' do\n size ${2:1024}\n action :${3:create}\nend'
'sysctl':
'prefix': 'sysctl'
'body': 'sysctl \'${1:name}\' do\n value ${2:1024}\n action :${3:apply}\nend'
'systemd_unit':
'prefix': 'systemd_unit'
'body': 'systemd_unit \'${1:etcd.service}\' do\n content(${2:Unit: {\n Description: \'Etcd\',\n Documentation: \'https://coreos.com/etcd\',\n After: \'network.target\',\n \\},\n Service: {\n Type: \'notify\',\n ExecStart: \'/usr/local/etcd\',\n Restart: \'always\',\n \\},\n Install: {\n WantedBy: \'multi-user.target\',\n \\}})\n action :${3:create}\nend'
'template':
'prefix': 'template'
'body': 'template \'${1:/tmp/config.conf}\' do\n source \'${2:config.conf.erb}\'\n owner \'${3:root}\'\n group \'${4:root}\'\n mode \'${5:0744}\'\n action :${6:create}\nend'
'user':
'prefix': 'user'
'body': 'user \'${1:random}\' do\n comment \'${2:Random User}\'\n uid \'${3:1000}\'\n gid \'${4:users}\'\n shell \'${5:/bin/bash}\'\n action :${6:create}\nend'
'windows_ad_join':
'prefix': 'windows_ad_join'
'body': 'windows_ad_join \'${1:ad.example.org}\' do\n domain_user ${2:\'nick\'}\n password \'PI:PASSWORD:<PASSWORD>END_PI}\'\n action :${4:join}\nend'
'windows_auto_run':
'prefix': 'windows_auto_run'
'body': 'windows_auto_run \'${1:BGINFO}\' do\n program \'${2:C:/Sysinternals/bginfo.exe}\'\n args \'${3:\'C:/Sysinternals/Config.bgi\' /NOLICPROMPT /TIMER:0}\'\n action :${4:create}\nend'
'windows_env':
'prefix': 'windows_env'
'body': 'windows_env \'${1:ComSpec}\' do\n value \'${2:C:\\\\Windows\\\\system32\\\\cmd.exe}\'\n action :${3:create}\nend'
'windows_feature':
'prefix': 'windows_feature'
'body': 'windows_feature \'${1:DHCPServer}\' do\n action :${2:install}\nend'
'windows_feature_dism':
'prefix': 'windows_feature_dism'
'body': 'windows_feature_dism \'${1:name}\' do\n all ${2:false}\n source \'${3:localrepository}\'\n action :${4:install}\nend'
'windows_feature_powershell':
'prefix': 'windows_feature_powershell'
'body': 'windows_feature_powershell \'${1:name}\' do\n all ${2:false}\n source \'${3:localrepository}\'\n action :${4:install}\nend'
'windows_font':
'prefix': 'windows_font'
'body': 'windows_font \'${1:name}\' do\n source \'${2:https://example.com/Custom.otf}\'\n action :${3:install}\nend'
'windows_package':
'prefix': 'windows_package'
'body': 'windows_package \'${1:name}\' do\n action :${2:install}\nend'
'windows_path':
'prefix': 'windows_path'
'body': 'windows_path \'${1:C:\\Sysinternals}\' do\n action :${2:add}\nend'
'windows_printer':
'prefix': 'windows_printer'
'body': 'windows_printer \'${1:HP LaserJet 5th Floor}\' do\n driver_name \'${2:HP LaserJet 4100 Series PCL6}\'\n ipv4_address \'${3:10.4.64.38}\'\n action :${4:create}\nend'
'windows_printer_port':
'prefix': 'windows_printer_port'
'body': 'windows_printer_port \'${1:10.4.64.37}\' do\n action :${2:create}\nend'
'windows_service':
'prefix': 'windows_service'
'body': 'windows_service \'${1:BITS}\' do\n action :${2:configure_startup}\n startup_type :${3:manual}\nend'
'windows_shortcut':
'prefix': 'windows_shortcut'
'body': 'windows_shortcut \'${1:Notepad.lnk}\' do\n description \'${2:Launch Notepad}\'\n target \'${3:C:\\Windows\\notepad.exe}\'\n iconlocation \'${4:C:\\Windows\\notepad.exe,0}\'\n action :${5:create}\nend'
'windows_task':
'prefix': 'windows_task'
'body': 'windows_task \'${1:chef-client}\' do\n command \'${2:chef-client}\'\n run_level :${3:highest}\n frequency \'${4:weekly}\'\n frequency_modifier ${5:2}\n day ${6:Mon, Fri}\n action :${7:create}\nend'
'yum_package':
'prefix': 'yum_package'
'body': 'yum_package \'${1:wget}\' do\n source \'${2:/foo/bar/wget_1.13.4-2ubuntu1.4_amd64.deb}\'\n action :${3:install}\nend'
'yum_repository':
'prefix': 'yum_repository'
'body': 'yum_repository \'${1:name}\' do\n description \'Zenoss Stable repo\'\n baseurl \'http://dev.zenoss.com/yum/stable/\'\n gpgkey \'http://dev.zenoss.com/yum/RPM-GPG-KEY-zenoss\'\n action :${2:create}\nend'
'zypper_package':
'prefix': 'zypper_package'
'body': 'zypper_package \'${1:name}\' do\n action :${3:install}\nend'
'zypper_repository':
'prefix': 'zypper_repository'
'body': 'zypper_repository \'${1:Packman}\' do\n baseurl \'http://packman.inode.at\'\n path \'/suse/openSUSE_Leap_42.3\'\n action :${3:add}\nend'
|
[
{
"context": "###\n Copyright(c) 2016- Jigme Ko <jigme1968@gmail.com>\n MIT Licensed\n###\n### 目的\n ",
"end": 32,
"score": 0.9998197555541992,
"start": 24,
"tag": "NAME",
"value": "Jigme Ko"
},
{
"context": "###\n Copyright(c) 2016- Jigme Ko <jigme1968@gmail.com>\n MIT Licensed\n###... | src/tsdata.coffee | emptist/setushare | 0 | ###
Copyright(c) 2016- Jigme Ko <jigme1968@gmail.com>
MIT Licensed
###
### 目的
Python資源眾多, Pandas有用.
如何交互收發信息 [參閱](https://github.com/extrabacon/python-shell/issues/16)
經過測試, tushare 庫 有一個 _write_head() _write_tips() 和 _write_console()
會污染stdout, 文件為: tushare/stock/cons.py, 須將這些function 全部 加 pass 註釋掉代碼
###
Pysh = require 'python-shell'
# will repeatedly return 3 times, don't know why
class Tushare
constructor: ->
options =
mode:'json'
pythonOptions:['-u']
scriptPath: __dirname
@pysh = new Pysh '../getjson.py', options
#所有的on什麼都放這裡
done: ()->
@pysh.end (err)->
throw err if err
console.info 'done.'
data: (command, callback)->
# 用完退出只需 pysh.done()
@pysh.on 'message', (json)-> callback json
@pysh.send command
module.exports = Tushare
| 17476 | ###
Copyright(c) 2016- <NAME> <<EMAIL>>
MIT Licensed
###
### 目的
Python資源眾多, Pandas有用.
如何交互收發信息 [參閱](https://github.com/extrabacon/python-shell/issues/16)
經過測試, tushare 庫 有一個 _write_head() _write_tips() 和 _write_console()
會污染stdout, 文件為: tushare/stock/cons.py, 須將這些function 全部 加 pass 註釋掉代碼
###
Pysh = require 'python-shell'
# will repeatedly return 3 times, don't know why
class Tushare
constructor: ->
options =
mode:'json'
pythonOptions:['-u']
scriptPath: __dirname
@pysh = new Pysh '../getjson.py', options
#所有的on什麼都放這裡
done: ()->
@pysh.end (err)->
throw err if err
console.info 'done.'
data: (command, callback)->
# 用完退出只需 pysh.done()
@pysh.on 'message', (json)-> callback json
@pysh.send command
module.exports = Tushare
| true | ###
Copyright(c) 2016- PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
MIT Licensed
###
### 目的
Python資源眾多, Pandas有用.
如何交互收發信息 [參閱](https://github.com/extrabacon/python-shell/issues/16)
經過測試, tushare 庫 有一個 _write_head() _write_tips() 和 _write_console()
會污染stdout, 文件為: tushare/stock/cons.py, 須將這些function 全部 加 pass 註釋掉代碼
###
Pysh = require 'python-shell'
# will repeatedly return 3 times, don't know why
class Tushare
constructor: ->
options =
mode:'json'
pythonOptions:['-u']
scriptPath: __dirname
@pysh = new Pysh '../getjson.py', options
#所有的on什麼都放這裡
done: ()->
@pysh.end (err)->
throw err if err
console.info 'done.'
data: (command, callback)->
# 用完退出只需 pysh.done()
@pysh.on 'message', (json)-> callback json
@pysh.send command
module.exports = Tushare
|
[
{
"context": " apiRoot: testApiRoot\n apiKey: \"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa\"\n experiments: []\n",
"end": 190,
"score": 0.9996029734611511,
"start": 154,
"tag": "KEY",
"value": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
}
] | src/test/client-spec.coffee | plyfe/myna-js | 2 | describe "Client.constructor", ->
it "should accept custom options", ->
actual = new Myna.Client
apiRoot: testApiRoot
apiKey: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
experiments: []
| 61228 | describe "Client.constructor", ->
it "should accept custom options", ->
actual = new Myna.Client
apiRoot: testApiRoot
apiKey: "<KEY>"
experiments: []
| true | describe "Client.constructor", ->
it "should accept custom options", ->
actual = new Myna.Client
apiRoot: testApiRoot
apiKey: "PI:KEY:<KEY>END_PI"
experiments: []
|
[
{
"context": "changed', utils.wrap (done) ->\n data = {name: 'whatever'}\n [res, body] = yield request.putAsync { uri:",
"end": 4278,
"score": 0.7976254820823669,
"start": 4270,
"tag": "NAME",
"value": "whatever"
}
] | spec/server/functional/campaign.spec.coffee | johanvl/codecombat | 2 | require '../common'
campaignURL = getURL('/db/campaign')
campaignSchema = require '../../../app/schemas/models/campaign.schema'
campaignLevelProperties = _.keys(campaignSchema.properties.levels.additionalProperties.properties)
Achievement = require '../../../server/models/Achievement'
Campaign = require '../../../server/models/Campaign'
Level = require '../../../server/models/Level'
User = require '../../../server/models/User'
request = require '../request'
utils = require '../utils'
slack = require '../../../server/slack'
Promise = require 'bluebird'
describe 'GET /db/campaign', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([Campaign])
@heroCampaign1 = yield new Campaign({name: 'Hero Campaign 1', type: 'hero'}).save()
@heroCampaign2 = yield new Campaign({name: 'Hero Campaign 2', type: 'hero'}).save()
@courseCampaign1 = yield new Campaign({name: 'Course Campaign 1', type: 'course'}).save()
@courseCampaign2 = yield new Campaign({name: 'Course Campaign 2', type: 'course'}).save()
done()
it 'returns all campaigns', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign'), { json: true }
expect(res.statusCode).toBe(200)
expect(body.length).toBe(4)
done()
it 'accepts project parameter with [] notation', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign?project[]=name&project[]=type'), { json: true }
expect(res.statusCode).toBe(200)
expect(res.body[0].slug).toBeUndefined()
done()
describe 'with GET query param type', ->
it 'returns campaigns of that type', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign?type=course'), { json: true }
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBe('course')
done()
describe 'POST /db/campaign', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@levels = (level.toObject() for level in [yield utils.makeLevel(), yield utils.makeLevel()])
done()
it 'can create campaigns', utils.wrap (done) ->
campaign = {
levels: {}
}
for level in @levels.reverse()
campaign.levels[level.original.valueOf()] = _.pick level, campaignLevelProperties
[res, body] = yield request.postAsync {uri: campaignURL, json: campaign}
expect(res.statusCode).toBe(201)
campaign = body
done()
describe 'PUT /db/campaign/:handle', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@campaign = yield utils.makeCampaign()
@levelsUpdated = @campaign.get('levelsUpdated').toISOString()
done()
it 'saves changes to campaigns', utils.wrap (done) ->
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(body.name).toBe('A new name')
c = yield Campaign.findById(body._id)
expect(c.get('name')).toBe('A new name')
done()
it 'does not allow normal users to make changes', utils.wrap (done) ->
user = yield utils.initUser()
yield utils.loginUser(user)
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(res.statusCode).toBe(403)
done()
it 'allows normal users to put translation changes', utils.wrap (done) ->
user = yield utils.initUser()
yield utils.logout()
yield utils.loginUser(user)
json = _.clone @campaign.toObject()
json.i18n = { de: { name: 'A new name' } }
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: json }
expect(res.statusCode).toBe(200)
done()
it 'sends a slack message', utils.wrap (done) ->
spyOn(slack, 'sendSlackMessage')
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(slack.sendSlackMessage).toHaveBeenCalled()
done()
it 'sets campaign.levelsUpdated to now iff levels are changed', utils.wrap (done) ->
data = {name: 'whatever'}
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: data }
expect(body.levelsUpdated).toBe(@levelsUpdated)
yield new Promise((resolve) -> setTimeout(resolve, 10))
data = {levels: {'a': {original: 'a'}}}
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: data }
expect(body.levelsUpdated).not.toBe(@levelsUpdated)
done()
describe 'GET, POST /db/campaign/names', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@campaignA = yield utils.makeCampaign()
@campaignB = yield utils.makeCampaign()
done()
it 'returns names of campaigns by for given ids', utils.wrap (done) ->
[res, body] = yield request.getAsync({url: getURL("/db/campaign/names?ids=#{@campaignA.id},#{@campaignB.id}"), json: true})
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
[res, body] = yield request.postAsync({url: getURL('/db/campaign/names'), json: { ids: [@campaignA.id, @campaignB.id] }})
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
done()
describe 'GET /db/campaign/:handle/levels', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@level1 = yield utils.makeLevel()
@level2 = yield utils.makeLevel()
@campaign = yield utils.makeCampaign({}, {levels: [@level1, @level2]})
done()
it 'fetches the levels in a campaign', utils.wrap (done) ->
url = getURL("/db/campaign/#{@campaign._id}/levels")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
expect(_.difference([@level1.get('slug'), @level2.get('slug')], _.pluck(body, 'slug')).length).toBe(0)
done()
describe 'GET /db/campaign/:handle/achievements', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
level = yield utils.makeLevel()
@achievement = yield utils.makeAchievement({}, {related: level})
@campaign = yield utils.makeCampaign({}, {levels: [level]})
done()
it 'fetches the achievements in the levels in a campaign', utils.wrap (done) ->
url = getURL("/db/campaign/#{@campaign.id}/achievements")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(1)
done()
describe 'GET /db/campaign/-/overworld', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
level = yield utils.makeLevel()
@campaignA = yield utils.makeCampaign({type: 'hero', hidesHUD: true})
@campaignB = yield utils.makeCampaign({type: 'hero'}, {
levels: [level]
adjacentCampaigns: [@campaignA]
})
@campaignC = yield utils.makeCampaign({type: 'course'})
done()
it 'fetches campaigns of type "hero", returning projected level and adjacentCampaign children', utils.wrap (done) ->
url = getURL("/db/campaign/-/overworld")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBe('hero')
campaign = _.findWhere(body, {_id: @campaignB.id})
expect(_.size(campaign.levels)).toBeGreaterThan(0)
for level in _.values(campaign.levels)
expect(level.slug).toBeDefined()
expect(_.size(campaign.adjacentCampaigns)).toBeGreaterThan(0)
for campaign in _.values(campaign.adjacentCampaigns)
expect(campaign.name).toBeDefined()
done()
it 'takes a project query param', utils.wrap (done) ->
url = getURL("/db/campaign/-/overworld?project=name")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBeUndefined()
expect(campaign.name).toBeDefined()
done()
| 83098 | require '../common'
campaignURL = getURL('/db/campaign')
campaignSchema = require '../../../app/schemas/models/campaign.schema'
campaignLevelProperties = _.keys(campaignSchema.properties.levels.additionalProperties.properties)
Achievement = require '../../../server/models/Achievement'
Campaign = require '../../../server/models/Campaign'
Level = require '../../../server/models/Level'
User = require '../../../server/models/User'
request = require '../request'
utils = require '../utils'
slack = require '../../../server/slack'
Promise = require 'bluebird'
describe 'GET /db/campaign', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([Campaign])
@heroCampaign1 = yield new Campaign({name: 'Hero Campaign 1', type: 'hero'}).save()
@heroCampaign2 = yield new Campaign({name: 'Hero Campaign 2', type: 'hero'}).save()
@courseCampaign1 = yield new Campaign({name: 'Course Campaign 1', type: 'course'}).save()
@courseCampaign2 = yield new Campaign({name: 'Course Campaign 2', type: 'course'}).save()
done()
it 'returns all campaigns', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign'), { json: true }
expect(res.statusCode).toBe(200)
expect(body.length).toBe(4)
done()
it 'accepts project parameter with [] notation', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign?project[]=name&project[]=type'), { json: true }
expect(res.statusCode).toBe(200)
expect(res.body[0].slug).toBeUndefined()
done()
describe 'with GET query param type', ->
it 'returns campaigns of that type', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign?type=course'), { json: true }
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBe('course')
done()
describe 'POST /db/campaign', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@levels = (level.toObject() for level in [yield utils.makeLevel(), yield utils.makeLevel()])
done()
it 'can create campaigns', utils.wrap (done) ->
campaign = {
levels: {}
}
for level in @levels.reverse()
campaign.levels[level.original.valueOf()] = _.pick level, campaignLevelProperties
[res, body] = yield request.postAsync {uri: campaignURL, json: campaign}
expect(res.statusCode).toBe(201)
campaign = body
done()
describe 'PUT /db/campaign/:handle', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@campaign = yield utils.makeCampaign()
@levelsUpdated = @campaign.get('levelsUpdated').toISOString()
done()
it 'saves changes to campaigns', utils.wrap (done) ->
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(body.name).toBe('A new name')
c = yield Campaign.findById(body._id)
expect(c.get('name')).toBe('A new name')
done()
it 'does not allow normal users to make changes', utils.wrap (done) ->
user = yield utils.initUser()
yield utils.loginUser(user)
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(res.statusCode).toBe(403)
done()
it 'allows normal users to put translation changes', utils.wrap (done) ->
user = yield utils.initUser()
yield utils.logout()
yield utils.loginUser(user)
json = _.clone @campaign.toObject()
json.i18n = { de: { name: 'A new name' } }
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: json }
expect(res.statusCode).toBe(200)
done()
it 'sends a slack message', utils.wrap (done) ->
spyOn(slack, 'sendSlackMessage')
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(slack.sendSlackMessage).toHaveBeenCalled()
done()
it 'sets campaign.levelsUpdated to now iff levels are changed', utils.wrap (done) ->
data = {name: '<NAME>'}
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: data }
expect(body.levelsUpdated).toBe(@levelsUpdated)
yield new Promise((resolve) -> setTimeout(resolve, 10))
data = {levels: {'a': {original: 'a'}}}
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: data }
expect(body.levelsUpdated).not.toBe(@levelsUpdated)
done()
describe 'GET, POST /db/campaign/names', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@campaignA = yield utils.makeCampaign()
@campaignB = yield utils.makeCampaign()
done()
it 'returns names of campaigns by for given ids', utils.wrap (done) ->
[res, body] = yield request.getAsync({url: getURL("/db/campaign/names?ids=#{@campaignA.id},#{@campaignB.id}"), json: true})
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
[res, body] = yield request.postAsync({url: getURL('/db/campaign/names'), json: { ids: [@campaignA.id, @campaignB.id] }})
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
done()
describe 'GET /db/campaign/:handle/levels', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@level1 = yield utils.makeLevel()
@level2 = yield utils.makeLevel()
@campaign = yield utils.makeCampaign({}, {levels: [@level1, @level2]})
done()
it 'fetches the levels in a campaign', utils.wrap (done) ->
url = getURL("/db/campaign/#{@campaign._id}/levels")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
expect(_.difference([@level1.get('slug'), @level2.get('slug')], _.pluck(body, 'slug')).length).toBe(0)
done()
describe 'GET /db/campaign/:handle/achievements', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
level = yield utils.makeLevel()
@achievement = yield utils.makeAchievement({}, {related: level})
@campaign = yield utils.makeCampaign({}, {levels: [level]})
done()
it 'fetches the achievements in the levels in a campaign', utils.wrap (done) ->
url = getURL("/db/campaign/#{@campaign.id}/achievements")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(1)
done()
describe 'GET /db/campaign/-/overworld', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
level = yield utils.makeLevel()
@campaignA = yield utils.makeCampaign({type: 'hero', hidesHUD: true})
@campaignB = yield utils.makeCampaign({type: 'hero'}, {
levels: [level]
adjacentCampaigns: [@campaignA]
})
@campaignC = yield utils.makeCampaign({type: 'course'})
done()
it 'fetches campaigns of type "hero", returning projected level and adjacentCampaign children', utils.wrap (done) ->
url = getURL("/db/campaign/-/overworld")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBe('hero')
campaign = _.findWhere(body, {_id: @campaignB.id})
expect(_.size(campaign.levels)).toBeGreaterThan(0)
for level in _.values(campaign.levels)
expect(level.slug).toBeDefined()
expect(_.size(campaign.adjacentCampaigns)).toBeGreaterThan(0)
for campaign in _.values(campaign.adjacentCampaigns)
expect(campaign.name).toBeDefined()
done()
it 'takes a project query param', utils.wrap (done) ->
url = getURL("/db/campaign/-/overworld?project=name")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBeUndefined()
expect(campaign.name).toBeDefined()
done()
| true | require '../common'
campaignURL = getURL('/db/campaign')
campaignSchema = require '../../../app/schemas/models/campaign.schema'
campaignLevelProperties = _.keys(campaignSchema.properties.levels.additionalProperties.properties)
Achievement = require '../../../server/models/Achievement'
Campaign = require '../../../server/models/Campaign'
Level = require '../../../server/models/Level'
User = require '../../../server/models/User'
request = require '../request'
utils = require '../utils'
slack = require '../../../server/slack'
Promise = require 'bluebird'
describe 'GET /db/campaign', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([Campaign])
@heroCampaign1 = yield new Campaign({name: 'Hero Campaign 1', type: 'hero'}).save()
@heroCampaign2 = yield new Campaign({name: 'Hero Campaign 2', type: 'hero'}).save()
@courseCampaign1 = yield new Campaign({name: 'Course Campaign 1', type: 'course'}).save()
@courseCampaign2 = yield new Campaign({name: 'Course Campaign 2', type: 'course'}).save()
done()
it 'returns all campaigns', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign'), { json: true }
expect(res.statusCode).toBe(200)
expect(body.length).toBe(4)
done()
it 'accepts project parameter with [] notation', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign?project[]=name&project[]=type'), { json: true }
expect(res.statusCode).toBe(200)
expect(res.body[0].slug).toBeUndefined()
done()
describe 'with GET query param type', ->
it 'returns campaigns of that type', utils.wrap (done) ->
[res, body] = yield request.getAsync getURL('/db/campaign?type=course'), { json: true }
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBe('course')
done()
describe 'POST /db/campaign', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@levels = (level.toObject() for level in [yield utils.makeLevel(), yield utils.makeLevel()])
done()
it 'can create campaigns', utils.wrap (done) ->
campaign = {
levels: {}
}
for level in @levels.reverse()
campaign.levels[level.original.valueOf()] = _.pick level, campaignLevelProperties
[res, body] = yield request.postAsync {uri: campaignURL, json: campaign}
expect(res.statusCode).toBe(201)
campaign = body
done()
describe 'PUT /db/campaign/:handle', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@campaign = yield utils.makeCampaign()
@levelsUpdated = @campaign.get('levelsUpdated').toISOString()
done()
it 'saves changes to campaigns', utils.wrap (done) ->
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(body.name).toBe('A new name')
c = yield Campaign.findById(body._id)
expect(c.get('name')).toBe('A new name')
done()
it 'does not allow normal users to make changes', utils.wrap (done) ->
user = yield utils.initUser()
yield utils.loginUser(user)
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(res.statusCode).toBe(403)
done()
it 'allows normal users to put translation changes', utils.wrap (done) ->
user = yield utils.initUser()
yield utils.logout()
yield utils.loginUser(user)
json = _.clone @campaign.toObject()
json.i18n = { de: { name: 'A new name' } }
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: json }
expect(res.statusCode).toBe(200)
done()
it 'sends a slack message', utils.wrap (done) ->
spyOn(slack, 'sendSlackMessage')
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: { name: 'A new name' } }
expect(slack.sendSlackMessage).toHaveBeenCalled()
done()
it 'sets campaign.levelsUpdated to now iff levels are changed', utils.wrap (done) ->
data = {name: 'PI:NAME:<NAME>END_PI'}
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: data }
expect(body.levelsUpdated).toBe(@levelsUpdated)
yield new Promise((resolve) -> setTimeout(resolve, 10))
data = {levels: {'a': {original: 'a'}}}
[res, body] = yield request.putAsync { uri: campaignURL+'/'+@campaign.id, json: data }
expect(body.levelsUpdated).not.toBe(@levelsUpdated)
done()
describe 'GET, POST /db/campaign/names', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@campaignA = yield utils.makeCampaign()
@campaignB = yield utils.makeCampaign()
done()
it 'returns names of campaigns by for given ids', utils.wrap (done) ->
[res, body] = yield request.getAsync({url: getURL("/db/campaign/names?ids=#{@campaignA.id},#{@campaignB.id}"), json: true})
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
[res, body] = yield request.postAsync({url: getURL('/db/campaign/names'), json: { ids: [@campaignA.id, @campaignB.id] }})
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
done()
describe 'GET /db/campaign/:handle/levels', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
@level1 = yield utils.makeLevel()
@level2 = yield utils.makeLevel()
@campaign = yield utils.makeCampaign({}, {levels: [@level1, @level2]})
done()
it 'fetches the levels in a campaign', utils.wrap (done) ->
url = getURL("/db/campaign/#{@campaign._id}/levels")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
expect(_.difference([@level1.get('slug'), @level2.get('slug')], _.pluck(body, 'slug')).length).toBe(0)
done()
describe 'GET /db/campaign/:handle/achievements', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Achievement, Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
level = yield utils.makeLevel()
@achievement = yield utils.makeAchievement({}, {related: level})
@campaign = yield utils.makeCampaign({}, {levels: [level]})
done()
it 'fetches the achievements in the levels in a campaign', utils.wrap (done) ->
url = getURL("/db/campaign/#{@campaign.id}/achievements")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(1)
done()
describe 'GET /db/campaign/-/overworld', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels [Campaign, Level, User]
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
level = yield utils.makeLevel()
@campaignA = yield utils.makeCampaign({type: 'hero', hidesHUD: true})
@campaignB = yield utils.makeCampaign({type: 'hero'}, {
levels: [level]
adjacentCampaigns: [@campaignA]
})
@campaignC = yield utils.makeCampaign({type: 'course'})
done()
it 'fetches campaigns of type "hero", returning projected level and adjacentCampaign children', utils.wrap (done) ->
url = getURL("/db/campaign/-/overworld")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBe('hero')
campaign = _.findWhere(body, {_id: @campaignB.id})
expect(_.size(campaign.levels)).toBeGreaterThan(0)
for level in _.values(campaign.levels)
expect(level.slug).toBeDefined()
expect(_.size(campaign.adjacentCampaigns)).toBeGreaterThan(0)
for campaign in _.values(campaign.adjacentCampaigns)
expect(campaign.name).toBeDefined()
done()
it 'takes a project query param', utils.wrap (done) ->
url = getURL("/db/campaign/-/overworld?project=name")
[res, body] = yield request.getAsync {uri: url, json: true}
expect(res.statusCode).toBe(200)
expect(body.length).toBe(2)
for campaign in body
expect(campaign.type).toBeUndefined()
expect(campaign.name).toBeDefined()
done()
|
[
{
"context": "e. `eden -o phase`) whitelist.\n keys = [\"AS\", \"MC\"]\n for num, val of group\n ",
"end": 2081,
"score": 0.9958133101463318,
"start": 2079,
"tag": "KEY",
"value": "AS"
},
{
"context": "en -o phase`) whitelist.\n keys = [\"AS\", \"MC... | lib/points.coffee | astrolet/archai | 1 | _ = require 'underscore'
Backbone = require 'backbone'
coordinates = require('upon').coordinates
ensemble = new (require './ensemble')
class Point extends Backbone.Model
# Note: 0 should perhaps be the default for degrees?
atCoordinates: (lon = 0, lat) ->
@at = coordinates.of @get("lon") ? lon, @get("lat") ? lat
@at.ecliptical 'dec'
initialize: (a) ->
[a.lon, a.lat] = @atCoordinates a.lon, a.lat
a.re ?= '' # regarding reason
a.ts ?= '' # timeshift - more, related moments
@set a
# TODO: with a newer Backbone,
# `@on "change:lon change:lat", @atCoordinates` instead.
@bind "change:lon", @atCoordinates
@bind "change:lat", @atCoordinates
class Points extends Backbone.Collection
model: Point
initialize: (models = [], options = {}) ->
models = @precious options if _.isEmpty models
@reset models
precious: (options) ->
json = options.data
return [] unless json?
[objs, idx] = [[], 0]
for i, group of json
switch i
when '1', '2'
keys =
0: "lon"
1: "lat"
2: "dau"
3: "day_lon"
4: "day_lat"
5: "day_dau"
for id, it of group
sid = if i is "2" then "#{10000 + new Number(id)}" else id
item = ensemble.sid sid
its = item.get('id')
objs.push
id: if its is '?' then sid else its
sid: sid
for key, val of it
objs[idx][keys[key]] = val
idx++
when '3'
# Adding the frontal so many.
# TODO: check if all of these are on the ecliptic (i.e. lon values)
# Also see if all of them are to be used and if in order - whitelist?
# For example we may just want the Vertex from the following:
# `"ARMC", "VX", "EQAS"`. Furthermore, we may want some angles
# for calculations / inference, but not to show - in which case
# it would be Eden's (i.e. `eden -o phase`) whitelist.
keys = ["AS", "MC"]
for num, val of group
if keys[num]?
objs.push
id: "#{[keys[num]]}"
sid: null
lon: val
day_lon: null
idx++
when '4'
for count in [1..12]
# Whole-sign houses start with 'T' for topics, all others with 'H'.
objs.push
id: "#{if group[12] is 'W' then 'T' else 'H'}#{count}"
sid: null
lon: group[count-1]
day_lon: null
re: @houses[group[12]]
idx++
objs
# Minimal lowercase tags, a reason.
houses: { "P": "placidus"
, "K": "koch"
, "O": "porphyrius"
, "R": "regiomontanus"
, "C": "campanus"
, "A": "ascendant"
, "E": "equal"
, "V": "vehlow-equal"
, "W": "whole-sign"
, "X": "axial-rotation"
, "H": "horizontal"
, "T": "topocentric"
, "B": "alcabitus"
, "M": "morinus"
, "U": "krusinski-pisa"
, "G": "gauquelin-sectors"
}
# The first point or the @getNone id of Ensemble.
a: -> @at(0) ? new Point id: '-'
module.exports = Points
| 37670 | _ = require 'underscore'
Backbone = require 'backbone'
coordinates = require('upon').coordinates
ensemble = new (require './ensemble')
class Point extends Backbone.Model
# Note: 0 should perhaps be the default for degrees?
atCoordinates: (lon = 0, lat) ->
@at = coordinates.of @get("lon") ? lon, @get("lat") ? lat
@at.ecliptical 'dec'
initialize: (a) ->
[a.lon, a.lat] = @atCoordinates a.lon, a.lat
a.re ?= '' # regarding reason
a.ts ?= '' # timeshift - more, related moments
@set a
# TODO: with a newer Backbone,
# `@on "change:lon change:lat", @atCoordinates` instead.
@bind "change:lon", @atCoordinates
@bind "change:lat", @atCoordinates
class Points extends Backbone.Collection
model: Point
initialize: (models = [], options = {}) ->
models = @precious options if _.isEmpty models
@reset models
precious: (options) ->
json = options.data
return [] unless json?
[objs, idx] = [[], 0]
for i, group of json
switch i
when '1', '2'
keys =
0: "lon"
1: "lat"
2: "dau"
3: "day_lon"
4: "day_lat"
5: "day_dau"
for id, it of group
sid = if i is "2" then "#{10000 + new Number(id)}" else id
item = ensemble.sid sid
its = item.get('id')
objs.push
id: if its is '?' then sid else its
sid: sid
for key, val of it
objs[idx][keys[key]] = val
idx++
when '3'
# Adding the frontal so many.
# TODO: check if all of these are on the ecliptic (i.e. lon values)
# Also see if all of them are to be used and if in order - whitelist?
# For example we may just want the Vertex from the following:
# `"ARMC", "VX", "EQAS"`. Furthermore, we may want some angles
# for calculations / inference, but not to show - in which case
# it would be Eden's (i.e. `eden -o phase`) whitelist.
keys = ["<KEY>", "<KEY>"]
for num, val of group
if keys[num]?
objs.push
id: "#{[keys[num]]}"
sid: null
lon: val
day_lon: null
idx++
when '4'
for count in [1..12]
# Whole-sign houses start with 'T' for topics, all others with 'H'.
objs.push
id: "#{if group[12] is 'W' then 'T' else 'H'}#{count}"
sid: null
lon: group[count-1]
day_lon: null
re: @houses[group[12]]
idx++
objs
# Minimal lowercase tags, a reason.
houses: { "P": "placidus"
, "K": "koch"
, "O": "porphyrius"
, "R": "regiomontanus"
, "C": "campanus"
, "A": "ascendant"
, "E": "equal"
, "V": "vehlow-equal"
, "W": "whole-sign"
, "X": "axial-rotation"
, "H": "horizontal"
, "T": "topocentric"
, "B": "alcabitus"
, "M": "morinus"
, "U": "krusinski-pisa"
, "G": "gauquelin-sectors"
}
# The first point or the @getNone id of Ensemble.
a: -> @at(0) ? new Point id: '-'
module.exports = Points
| true | _ = require 'underscore'
Backbone = require 'backbone'
coordinates = require('upon').coordinates
ensemble = new (require './ensemble')
class Point extends Backbone.Model
# Note: 0 should perhaps be the default for degrees?
atCoordinates: (lon = 0, lat) ->
@at = coordinates.of @get("lon") ? lon, @get("lat") ? lat
@at.ecliptical 'dec'
initialize: (a) ->
[a.lon, a.lat] = @atCoordinates a.lon, a.lat
a.re ?= '' # regarding reason
a.ts ?= '' # timeshift - more, related moments
@set a
# TODO: with a newer Backbone,
# `@on "change:lon change:lat", @atCoordinates` instead.
@bind "change:lon", @atCoordinates
@bind "change:lat", @atCoordinates
class Points extends Backbone.Collection
model: Point
initialize: (models = [], options = {}) ->
models = @precious options if _.isEmpty models
@reset models
precious: (options) ->
json = options.data
return [] unless json?
[objs, idx] = [[], 0]
for i, group of json
switch i
when '1', '2'
keys =
0: "lon"
1: "lat"
2: "dau"
3: "day_lon"
4: "day_lat"
5: "day_dau"
for id, it of group
sid = if i is "2" then "#{10000 + new Number(id)}" else id
item = ensemble.sid sid
its = item.get('id')
objs.push
id: if its is '?' then sid else its
sid: sid
for key, val of it
objs[idx][keys[key]] = val
idx++
when '3'
# Adding the frontal so many.
# TODO: check if all of these are on the ecliptic (i.e. lon values)
# Also see if all of them are to be used and if in order - whitelist?
# For example we may just want the Vertex from the following:
# `"ARMC", "VX", "EQAS"`. Furthermore, we may want some angles
# for calculations / inference, but not to show - in which case
# it would be Eden's (i.e. `eden -o phase`) whitelist.
keys = ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"]
for num, val of group
if keys[num]?
objs.push
id: "#{[keys[num]]}"
sid: null
lon: val
day_lon: null
idx++
when '4'
for count in [1..12]
# Whole-sign houses start with 'T' for topics, all others with 'H'.
objs.push
id: "#{if group[12] is 'W' then 'T' else 'H'}#{count}"
sid: null
lon: group[count-1]
day_lon: null
re: @houses[group[12]]
idx++
objs
# Minimal lowercase tags, a reason.
houses: { "P": "placidus"
, "K": "koch"
, "O": "porphyrius"
, "R": "regiomontanus"
, "C": "campanus"
, "A": "ascendant"
, "E": "equal"
, "V": "vehlow-equal"
, "W": "whole-sign"
, "X": "axial-rotation"
, "H": "horizontal"
, "T": "topocentric"
, "B": "alcabitus"
, "M": "morinus"
, "U": "krusinski-pisa"
, "G": "gauquelin-sectors"
}
# The first point or the @getNone id of Ensemble.
a: -> @at(0) ? new Point id: '-'
module.exports = Points
|
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o",
"end": 67,
"score": 0.8228392004966736,
"start": 62,
"tag": "NAME",
"value": "Hatio"
}
] | src/handle/HandleChecker.coffee | heartyoh/infopik | 0 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (
dou
kin
) ->
"use strict"
createView = (attributes) ->
fills = ['red', 'black', 'yellow', 'cyan']
fill = Math.floor(Math.random() * 10) % (fills.length)
new kin.Rect(dou.util.shallow_merge(attributes, {fill: fills[fill]}))
createHandle = (attributes) ->
new Kin.Rect(attributes)
{
type: 'handle-checker'
name: 'handle-checker'
description: 'Checker Handle Specification'
defaults: {
width: 10
height: 10
fill: 'red'
stroke: 'black'
strokeWidth: 2
}
view_factory_fn: createView
handle_factory_fn: createHandle
toolbox_image: 'images/toolbox_handle_checker.png'
}
| 167611 | # ==========================================
# Copyright 2014 <NAME>, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (
dou
kin
) ->
"use strict"
createView = (attributes) ->
fills = ['red', 'black', 'yellow', 'cyan']
fill = Math.floor(Math.random() * 10) % (fills.length)
new kin.Rect(dou.util.shallow_merge(attributes, {fill: fills[fill]}))
createHandle = (attributes) ->
new Kin.Rect(attributes)
{
type: 'handle-checker'
name: 'handle-checker'
description: 'Checker Handle Specification'
defaults: {
width: 10
height: 10
fill: 'red'
stroke: 'black'
strokeWidth: 2
}
view_factory_fn: createView
handle_factory_fn: createHandle
toolbox_image: 'images/toolbox_handle_checker.png'
}
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PI, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (
dou
kin
) ->
"use strict"
createView = (attributes) ->
fills = ['red', 'black', 'yellow', 'cyan']
fill = Math.floor(Math.random() * 10) % (fills.length)
new kin.Rect(dou.util.shallow_merge(attributes, {fill: fills[fill]}))
createHandle = (attributes) ->
new Kin.Rect(attributes)
{
type: 'handle-checker'
name: 'handle-checker'
description: 'Checker Handle Specification'
defaults: {
width: 10
height: 10
fill: 'red'
stroke: 'black'
strokeWidth: 2
}
view_factory_fn: createView
handle_factory_fn: createHandle
toolbox_image: 'images/toolbox_handle_checker.png'
}
|
[
{
"context": "ody.rank\n\n\tif not validator.matches(season_key,/^[0-9]{4}\\-[0-9]{2}/i)\n\t\treturn next(new Errors.BadRequ",
"end": 3444,
"score": 0.7297994494438171,
"start": 3441,
"tag": "KEY",
"value": "0-9"
},
{
"context": "nk\n\n\tif not validator.matches(season_key,/^[0-9]{4}... | server/routes/api/me/qa.coffee | willroberts/duelyst | 5 | express = require 'express'
_ = require 'underscore'
Promise = require 'bluebird'
FirebasePromises = require '../../../lib/firebase_promises.coffee'
DuelystFirebase = require '../../../lib/duelyst_firebase_module'
moment = require 'moment'
validator = require 'validator'
# lib Modules
UsersModule = require '../../../lib/data_access/users'
ReferralsModule = require '../../../lib/data_access/referrals'
RiftModule = require '../../../lib/data_access/rift'
InventoryModule = require '../../../lib/data_access/inventory'
QuestsModule = require '../../../lib/data_access/quests.coffee'
GauntletModule = require '../../../lib/data_access/gauntlet.coffee'
CosmeticChestsModule = require '../../../lib/data_access/cosmetic_chests.coffee'
AchievementsModule = require '../../../lib/data_access/achievements.coffee'
GiftCrateModule = require '../../../lib/data_access/gift_crate.coffee'
SyncModule = require '../../../lib/data_access/sync.coffee'
RankModule = require '../../../lib/data_access/rank.coffee'
SyncModule = require '../../../lib/data_access/sync.coffee'
ShopModule = require '../../../lib/data_access/shop.coffee'
TwitchModule = require '../../../lib/data_access/twitch.coffee'
knex = require '../../../lib/data_access/knex'
DataAccessHelpers = require '../../../lib/data_access/helpers'
Logger = require '../../../../app/common/logger.coffee'
Errors = require '../../../lib/custom_errors'
# sdk
SDK = require '../../../../app/sdk.coffee'
FactionFactory = require '../../../../app/sdk/cards/factionFactory'
RankFactory = require '../../../../app/sdk/rank/rankFactory.coffee'
GiftCrateLookup = require '../../../../app/sdk/giftCrates/giftCrateLookup.coffee'
CosmeticsLookup = require '../../../../app/sdk/cosmetics/cosmeticsLookup.coffee'
GameSession = require '../../../../app/sdk/gameSession.coffee'
Redis = require '../../../redis/'
{SRankManager} = require '../../../redis/'
t = require 'tcomb-validation'
util = require 'util'
# Daily challenges
zlib = require 'zlib'
config = require '../../../../config/config.js'
CONFIG = require('app/common/config');
UtilsEnv = require('app/common/utils/utils_env');
generatePushId = require '../../../../app/common/generate_push_id'
{Jobs} = require '../../../redis/'
# create a S3 API client
AWS = require "aws-sdk"
AWS.config.update
accessKeyId: config.get("s3_archive.key")
secretAccessKey: config.get("s3_archive.secret")
s3 = new AWS.S3()
# Promise.promisifyAll(s3)
rankedQueue = new Redis.PlayerQueue(Redis.Redis, {name:'ranked'})
router = express.Router()
Logger.module("EXPRESS").log "QA routes ACTIVE".green
router.delete '/rank/history/:season_key/rewards', (req,res,next)->
user_id = req.user.d.id
season_key = req.params.season_key
if not validator.matches(season_key,/^[0-9]{4}\-[0-9]{2}/i)
return next(new Errors.BadRequestError())
season_starting_at = moment(season_key + " +0000", "YYYY-MM Z").utc()
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).first().then (row)-> console.log "found: ",row
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).update(
rewards_claimed_at:null,
reward_ids:null
is_unread:true
).then (updateCount)->
res.status(200).json({})
router.put '/rank/history/:season_key/top_rank', (req,res,next)->
user_id = req.user.d.id
season_key = req.params.season_key
rank = req.body.rank
if not validator.matches(season_key,/^[0-9]{4}\-[0-9]{2}/i)
return next(new Errors.BadRequestError())
season_starting_at = moment(season_key + " +0000", "YYYY-MM Z").utc()
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).update(
top_rank:rank,
).then ()->
res.status(200).json({})
# Updates the users current rank (and top rank if appropriate)
router.put '/rank', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
user_id = req.user.d.id
rank = req.body.rank
knex("users").where({'id':user_id}).first()
.bind {}
.then (row)->
@.userRow = row
@.updateData = {
rank: rank
rank_stars: 0
}
if rank < row.rank_top_rank
@.updateData.rank_top_rank = rank
if rank < row.top_rank
@.updateData.top_rank = rank
knex("users").where({'id':user_id}).update(@.updateData)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
FirebasePromises.set(@.fbRootRef.child('user-ranking').child(user_id).child('current'),{
rank: parseInt(@.updateData.rank)
stars: @.updateData.rank_stars
stars_required: RankFactory.starsNeededToAdvanceRank(@.updateData.rank) || 0
updated_at: MOMENT_UTC_NOW.valueOf() || null
created_at: moment.utc(@.userRow.rank_created_at).valueOf()
starting_at: moment.utc(@.userRow.rank_starting_at).valueOf()
})
if @.updateData.top_rank?
FirebasePromises.set(@.fbRootRef.child('user-ranking').child(user_id).child('top'),{
rank: parseInt(@.updateData.top_rank)
updated_at: MOMENT_UTC_NOW.valueOf() || null
created_at: moment.utc(@.userRow.rank_created_at).valueOf()
starting_at: moment.utc(@.userRow.rank_starting_at).valueOf()
})
.then () ->
# TODO: Remove rating data from fb and database if rank is not 0
return Promise.resolve()
.then () ->
res.status(200).json({
rank:@.updateData.rank
top_rank: if @.updateData.rank_top_rank? then @.updateData.rank_top_rank else @.userRow.rank_top_rank
})
# Updates the users current s rank rating
router.put '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
rank_rating = req.body.rank_rating
userRatingRowData =
rating: rank_rating
updated_at: MOMENT_UTC_NOW.toDate()
newLadderPosition = null
txPromise = knex.transaction (tx)->
tx("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).first()
.then (userRankRatingRow) ->
# Update or insert
if userRankRatingRow?
userRatingRowData.ladder_rating = RankModule._ladderRatingForRatingAndWinCount(userRatingRowData.rating,userRankRatingRow.srank_win_count)
return tx("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).update(userRatingRowData)
else
return tx("user_rank_ratings").insert({
user_id: user_id
season_starting_at: seasonStartingAt
rating: rank_rating
ladder_rating: RankModule._ladderRatingForRatingAndWinCount(rank_rating,0)
top_rating: rank_rating
rating_deviation: 200
volatility: 0.06
created_at: MOMENT_UTC_NOW.toDate()
updated_at: MOMENT_UTC_NOW.toDate()
})
.then () ->
return RankModule.updateAndGetUserLadderPosition(txPromise,tx,user_id,startOfSeasonMonth,MOMENT_UTC_NOW)
.then (ladderPosition) ->
newLadderPosition = ladderPosition
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({ladder_position:newLadderPosition})
# Resets the users current s rank rating
router.delete '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
return Promise.all([
knex("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).delete(),
knex("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).delete()
]).then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.remove(fbRootRef.child('users').child(user_id).child('presence').child('ladder_position'))
.then () ->
res.status(200).json({})
# Retrieves the users current s rank rating data
router.get '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
user_rating_data = null
txPromise = knex.transaction (tx)->
RankModule.getUserRatingData(tx,user_id,MOMENT_UTC_NOW)
.then (userRatingRow) ->
user_rating_data = userRatingRow || {}
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({user_rating_data:user_rating_data})
# Retrieves the users current s rank ladder position (Does not update it anywhere)
router.get '/ladder_position', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
user_ladder_position = null
txPromise = knex.transaction (tx)->
RankModule.getUserLadderPosition(tx,user_id,startOfSeasonMonth,MOMENT_UTC_NOW)
.then (userLadderPosition) ->
user_ladder_position = userLadderPosition || null
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({user_ladder_position:user_ladder_position})
# Marks the current season as last season (so that it is ready to be cycled) and deletes last season from history if needed
router.delete '/rank/history/last', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
previous_season_key = moment().utc().subtract(1,'month').format("YYYY-MM")
previous_season_starting_at = moment(previous_season_key + " +0000", "YYYY-MM Z").utc()
current_season_key = moment().utc().format("YYYY-MM")
current_season_starting_at = moment(current_season_key + " +0000", "YYYY-MM Z").utc()
user_id = req.user.d.id
Promise.all([
knex("user_rank_history").where({'user_id':user_id,'starting_at':previous_season_starting_at.toDate()}).delete(),
knex("user_rank_ratings").where({'user_id':user_id,'season_starting_at':previous_season_starting_at.toDate()}).delete(),
])
.bind {}
.then ()->
@.updateUserData = {
rank_starting_at: previous_season_starting_at.toDate()
}
@.updateRankRatingData = {
season_starting_at: previous_season_starting_at.toDate()
}
return Promise.all([
knex("users").where({'id':user_id}).update(@.updateUserData),
knex("user_rank_ratings").where({'user_id':user_id,'season_starting_at':current_season_starting_at}).update(@.updateRankRatingData),
SRankManager._removeUserFromLadder(user_id,moment.utc(current_season_starting_at))
])
.then () ->
res.status(200).json({})
router.post '/inventory/spirit', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
InventoryModule.giveUserSpirit(txPromise,tx,user_id,amount,'QA gift')
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/gold', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
InventoryModule.giveUserGold(txPromise,tx,user_id,amount,'QA gift')
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/premium', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
if (amount > 0)
InventoryModule.giveUserPremium(txPromise,tx,user_id,amount,'QA gift')
else
InventoryModule.debitPremiumFromUser(txPromise,tx,user_id,-amount,'QA charge')
.then ()->
res.status(200).json({})
router.post '/inventory/rift_ticket', (req, res, next) ->
user_id = req.user.d.id
txPromise = knex.transaction (tx)->
# InventoryModule.giveUserGold(txPromise,tx,user_id,amount,'QA gift')
RiftModule.addRiftTicketToUser(txPromise,tx,user_id,"qa gift",generatePushId())
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/cards', (req, res, next) ->
user_id = req.user.d.id
cardIds = req.body.card_ids
if !cardIds or cardIds?.length <= 0
return res.status(400).json({})
txPromise = knex.transaction (tx)->
return InventoryModule.giveUserCards(txPromise,tx,user_id,cardIds,'QA','QA','QA gift')
.then ()->
res.status(200).json({})
router.post '/inventory/card_set_with_spirit', (req, res, next) ->
user_id = req.user.d.id
cardSetId = req.body.card_set_id
txPromise = knex.transaction (tx)->
return InventoryModule.buyRemainingSpiritOrbsWithSpirit(user_id,cardSetId)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.post '/inventory/fill_collection', (req, res, next) ->
user_id = req.user.d.id
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.then (cardCollectionRow) ->
missingCardIds = []
_.each(SDK.GameSession.getCardCaches().getIsCollectible(true).getIsUnlockable(false).getIsPrismatic(false).getCardIds(), (cardId) ->
if cardCollectionRow? and cardCollectionRow.cards?
cardData = cardCollectionRow.cards[cardId]
numMissing = 0
if (SDK.CardFactory.cardForIdentifier(cardId).getRarityId() == SDK.Rarity.Mythron)
if !cardData?
numMissing = 1
else if cardData?
numMissing = Math.max(0, 1 - cardData.count)
else
if !cardData?
numMissing = CONFIG.MAX_DECK_DUPLICATES
else if cardData?
numMissing = Math.max(0, CONFIG.MAX_DECK_DUPLICATES - cardData.count)
else
# If no card collection yet then they are missing all of this card
numMissing = CONFIG.MAX_DECK_DUPLICATES
if (SDK.CardFactory.cardForIdentifier(cardId).getRarityId() == SDK.Rarity.Mythron)
numMissing = 1
if numMissing > 0
for i in [0...numMissing]
missingCardIds.push(cardId)
)
if missingCardIds.length > 0
return InventoryModule.giveUserCards(txPromise,tx,user_id,missingCardIds,'QA','QA','QA gift')
else
return Promise.resolve()
return txPromise.then ()->
res.status(200).json({})
router.delete '/inventory/unused', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedUnusedCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (!sdkCard)
@.ownedUnusedCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedUnusedCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/inventory/bloodborn', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedBloodbornCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (sdkCard.getCardSetId() == SDK.CardSet.Bloodborn)
@.ownedBloodbornCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedBloodbornCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then () ->
return Promise.all([
tx("user_spirit_orbs_opened").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Bloodborn).delete(),
tx("user_spirit_orbs").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Bloodborn).delete(),
tx("users").where("id",user_id).update({
total_orb_count_set_3: 0
})
])
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/inventory/unity', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedUnityCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (sdkCard.getCardSetId() == SDK.CardSet.Unity)
@.ownedUnityCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedUnityCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then () ->
return Promise.all([
tx("user_spirit_orbs_opened").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Unity).delete(),
tx("user_spirit_orbs").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Unity).delete(),
tx("users").where("id",user_id).update({
total_orb_count_set_4: null
})
])
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/quests/current', (req, res, next) ->
user_id = req.user.d.id
twoDaysAgoMoment = moment.utc().subtract(2,"day")
knex("user_quests").where({'user_id':user_id}).delete()
.then ()->
return knex("users").where('id',user_id).update(
free_card_of_the_day_claimed_at: twoDaysAgoMoment.toDate()
)
.then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests'))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("catch-up").child("current").child('quests'))
FirebasePromises.set(@.fbRootRef.child("users").child(user_id).child("free_card_of_the_day_claimed_at"),twoDaysAgoMoment.valueOf())
])
.then ()->
QuestsModule.generateDailyQuests(user_id)
.then ()->
res.status(200).json({})
router.put '/quests/current', (req, res, next) ->
user_id = req.user.d.id
quest_ids = req.body.quest_ids
# wipe old quests and regenerate just to treat this like a fresh generation
knex("user_quests").where({'user_id':user_id}).delete()
.then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests'))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("catch-up").child("current").child('quests'))
])
.then ()->
QuestsModule.generateDailyQuests(user_id)
.then ()->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,null,quest_ids[0])
QuestsModule.mulliganDailyQuest(user_id,1,null,quest_ids[1])
])
.then ()->
return Promise.all([
knex("user_quests").where({'user_id':user_id}).update({mulliganed_at:null})
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests').child(0).child("mulliganed_at"))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests').child(1).child("mulliganed_at"))
])
.then ()->
res.status(200).json({})
router.put '/quests/current/progress', (req, res, next) ->
user_id = req.user.d.id
quest_slots = req.body.quest_slots
txPromise = knex.transaction (tx)->
return Promise.each(quest_slots, (quest_slot) ->
return tx("user_quests").first().where({'user_id':user_id,'quest_slot_index':quest_slot})
.then (questRow) ->
if questRow?
newProgress = questRow.progress || 0
newProgress += 1
return QuestsModule._setQuestProgress(txPromise,tx,questRow,newProgress)
else
return Promise.resolve()
)
return txPromise
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.put '/quests/generated_at', (req, res, next) ->
user_id = req.user.d.id
days_back = req.body.days_back
knex("users").where({'id':user_id}).first("daily_quests_generated_at")
.bind {}
.then (row)->
@.previousGeneratedAt = row.daily_quests_generated_at
@.newGeneratedAtMoment = moment.utc(row.daily_quests_generated_at).subtract(days_back,'days')
@.userRow = row
@.updateData = {
daily_quests_generated_at: @.newGeneratedAtMoment.toDate()
}
knex("users").where({'id':user_id}).update(@.updateData)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.set(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('updated_at'),@.newGeneratedAtMoment.valueOf())
FirebasePromises.set(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('generated_at'),@.newGeneratedAtMoment.valueOf())
])
.then () ->
res.status(200).json({
generated_at:@.newGeneratedAtMoment.valueOf()
})
router.post '/quests/setup_frostfire_2016', (req, res, next) ->
user_id = req.user.d.id
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",30001).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,moment.utc("2016-12-02"))
.then () ->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,moment.utc("2016-12-02"),101),
QuestsModule.mulliganDailyQuest(user_id,1,moment.utc("2016-12-02"),101)
])
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",0).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",1).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",QuestsModule.SEASONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: 13})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/quests/setup_seasonal_quest', (req, res, next) ->
user_id = req.user.d.id
generateQuestsAt = req.body.generate_quests_at
generateQuestsAtMoment = moment.utc(generateQuestsAt)
sdkQuestForGenerationTime = SDK.QuestFactory.seasonalQuestForMoment(generateQuestsAtMoment)
if not sdkQuestForGenerationTime?
res.status(403).json({message:"No seasonal quest for: " + generateQuestsAtMoment.toString()})
return
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",sdkQuestForGenerationTime.getId()).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,generateQuestsAtMoment)
.then () ->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,generateQuestsAtMoment,101),
QuestsModule.mulliganDailyQuest(user_id,1,generateQuestsAtMoment,1500)
])
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",0).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",1).andWhere("user_id",user_id).update({progress: 7})
knex("user_quests").where("quest_slot_index",QuestsModule.SEASONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: 13})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/quests/setup_promotional_quest', (req, res, next) ->
user_id = req.user.d.id
generateQuestsAt = req.body.generate_quests_at
generateQuestsAtMoment = moment.utc(generateQuestsAt)
sdkQuestForGenerationTime = SDK.QuestFactory.promotionalQuestForMoment(generateQuestsAtMoment)
progressToStartWith = sdkQuestForGenerationTime.params["completionProgress"] - 1
if not sdkQuestForGenerationTime?
res.status(403).json({message:"No promo quest for: " + generateQuestsAtMoment.toString()})
return
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",sdkQuestForGenerationTime.getId()).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,generateQuestsAtMoment)
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",QuestsModule.PROMOTIONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: progressToStartWith})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/matchmaking/time_series/:division/values', (req, res, next) ->
division = req.params.division
ms = req.body.ms
rankedQueue.matchMade(division,ms)
res.status(200).json({})
router.post '/faction_progression/set_all_win_counts_to_99', (req,res,next)->
user_id = req.user.d.id
knex("user_faction_progression").where('user_id',user_id)
.then (rows)->
all = []
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
Logger.module("QA").log "factionIds ", factionIds
for factionId in factionIds
row = _.find(rows, (r)-> return r.faction_id == factionId)
Logger.module("QA").log "faction #{factionId}", row?.user_id
if row?
all.push knex("user_faction_progression").where({
'user_id':user_id,
'faction_id':row.faction_id
}).update(
'win_count':99
)
return Promise.all(all)
.then ()->
res.status(200).json({})
router.post '/faction_progression/add_level', (req,res,next)->
user_id = req.user.d.id
factionId = req.body.faction_id
if factionId?
knex("user_faction_progression").where({'user_id': user_id, "faction_id": factionId}).first()
.then (factionProgressionRow)->
if !factionProgressionRow?
return UsersModule.createFactionProgressionRecord(user_id,factionId, generatePushId(), SDK.GameType.Ranked)
.then () ->
return knex("user_faction_progression").where({'user_id': user_id, "faction_id": factionId}).first()
.then (factionProgressionRow) ->
if !factionProgressionRow?
return Promise.reject("No row found for faction #{factionId}")
else
currentXP = factionProgressionRow.xp || 0
currentLevel = SDK.FactionProgression.levelForXP(currentXP)
nextLevel = currentLevel + 1
nextLevelXP = SDK.FactionProgression.totalXPForLevel(nextLevel)
deltaXP = nextLevelXP - currentXP
if deltaXP <= 0
return Promise.reject("Cannot increase level for faction #{factionId}, currently at #{currentLevel}")
else
winsNeeded = Math.ceil(deltaXP / SDK.FactionProgression.winXP)
promises = []
for i in [0...winsNeeded]
promises.push(UsersModule.updateUserFactionProgressionWithGameOutcome(user_id, factionId, true, generatePushId(), SDK.GameType.Ranked))
return Promise.all(promises)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.post '/faction_progression/set_all_levels_to_10', (req,res,next)->
user_id = req.user.d.id
knex("user_faction_progression").where('user_id',user_id)
.then (rows)->
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
allPromises = []
for factionId in factionIds
row = _.find(rows, (r)-> return r.faction_id == factionId)
if !row?
allPromises.push(UsersModule.createFactionProgressionRecord(user_id,factionId,generatePushId(),SDK.GameType.SinglePlayer))
return Promise.all(allPromises)
.then () ->
return knex("user_faction_progression").where('user_id',user_id)
.then (factionRows) ->
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
winsPerFaction = []
for factionId in factionIds
row = _.find(factionRows, (r)-> return r.faction_id == factionId)
if !row?
return Promise.reject("No row found for faction - #{factionId}")
else
factionXp = row.xp
xpForLevelTen = SDK.FactionProgression.levelXPTable[10]
neededXp = xpForLevelTen - factionXp
xpPerWin = SDK.FactionProgression.winXP
if neededXp > 0
neededWins = Math.ceil(neededXp / xpPerWin)
winsPerFaction = winsPerFaction.concat(Array(neededWins).fill(factionId))
return Promise.each(winsPerFaction, (factionId) ->
return UsersModule.updateUserFactionProgressionWithGameOutcome(user_id,factionId,true,generatePushId(),SDK.GameType.Ranked)
)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.delete '/gauntlet/current', (req,res,next)->
userId = req.user.d.id
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return Promise.all([
knex("user_gauntlet_run").where('user_id',userId).delete()
FirebasePromises.remove(fbRootRef.child("user-gauntlet-run").child(userId).child("current"))
])
.then () ->
res.status(200).json({})
.catch (error) ->
res.status(403).json({message:error.toString()})
router.delete '/gauntlet/current/general', (req,res,next)->
userId = req.user.d.id
# Get current gauntlet data
knex("user_gauntlet_run").first().where('user_id',userId)
.bind({})
.then (gauntletData) ->
this.gauntletData = gauntletData
if (not gauntletData?)
return Promise.reject(new Error("You are not currently in a Gauntlet Run"))
if (not gauntletData.is_complete)
return Promise.reject(new Error("Current Gauntlet deck is not complete"))
cardIdInGeneralSlot = gauntletData.deck[0]
sdkCard = GameSession.getCardCaches().getCardById(cardIdInGeneralSlot)
if (not sdkCard.getIsGeneral())
return Promise.reject(new Error("Current Gauntlet deck does not have general in expected slot"))
this.newDeck = gauntletData.deck.slice(1)
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
updateData =
deck: this.newDeck
general_id: null
return Promise.all([
knex("user_gauntlet_run").where('user_id',userId).update(updateData)
FirebasePromises.update(fbRootRef.child("user-gauntlet-run").child(userId).child("current"),updateData)
])
.then () ->
res.status(200).json(this.gauntletData)
.catch (error) ->
res.status(403).json({message:error.toString()})
router.post '/gauntlet/progress', (req,res,next)->
userId = req.user.d.id
isWinner = req.body.is_winner
Redis.GameManager.generateGameId()
.then (gameId) ->
GauntletModule.updateArenaRunWithGameOutcome(userId,isWinner,gameId,false)
.then (runData) ->
res.status(200).json(runData)
.catch (error) ->
res.status(403).json({message:error.toString()})
router.post '/gauntlet/fill_deck', (req,res,next)->
userId = req.user.d.id
# Get current gauntlet data
knex("user_gauntlet_run").first().where('user_id',userId)
.then (gauntletData) ->
recursiveSelect = (gauntletData) ->
if !gauntletData? || !gauntletData.card_choices? || !gauntletData.card_choices[0]?
# No more card choices
res.status(200).json(gauntletData)
else
cardIdChoice = null;
if (gauntletData.card_choices?)
cardIdChoice = gauntletData.card_choices[0]
else if (gauntletData.general_choices?)
cardIdChoice = gauntletData.general_choices[0]
GauntletModule.chooseCard(userId,cardIdChoice)
.then (newGauntletData) ->
recursiveSelect(newGauntletData)
recursiveSelect(gauntletData)
.catch (error) ->
res.status(403).json({message:error.message})
router.post '/gift_crate/winter2015', (req,res,next)->
userId = req.user.d.id
txPromise = knex.transaction (tx)->
Promise.all([
tx("user_emotes").where("user_id",userId).andWhere("emote_id",CosmeticsLookup.Emote.OtherSnowChaserHoliday2015).delete()
tx("user_rewards").where("user_id",userId).andWhere("source_id",GiftCrateLookup.WinterHoliday2015).delete()
tx("user_gift_crates").where("user_id",userId).andWhere("crate_type",GiftCrateLookup.WinterHoliday2015).delete()
])
.then ()->
return GiftCrateModule.addGiftCrateToUser(txPromise,tx,userId,GiftCrateLookup.WinterHoliday2015)
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/gift_crate/lag2016', (req,res,next)->
userId = req.user.d.id
txPromise = knex.transaction (tx)->
Promise.all([
tx("user_rewards").where("user_id",userId).andWhere("source_id",GiftCrateLookup.FebruaryLag2016).delete()
tx("user_gift_crates").where("user_id",userId).andWhere("crate_type",GiftCrateLookup.FebruaryLag2016).delete()
])
.then ()->
return GiftCrateModule.addGiftCrateToUser(txPromise,tx,userId,GiftCrateLookup.FebruaryLag2016)
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic_chest/:chest_type', (req,res,next)->
userId = req.user.d.id
chestType = req.params.chest_type
hoursBack = parseInt(req.body.hours_back)
if not hoursBack?
hoursBack = 0
bossId = null
eventId = null
if chestType == SDK.CosmeticsChestTypeLookup.Boss
bossId = SDK.Cards.Boss.Boss3
eventId = "QA-" + generatePushId()
txPromise = knex.transaction (tx)->
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,chestType,bossId,eventId,1,"soft",generatePushId(),moment.utc().subtract(hoursBack,"hours"))
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic_chest_key/:chest_type', (req,res,next)->
userId = req.user.d.id
chestType = req.params.chest_type
txPromise = knex.transaction (tx)->
return CosmeticChestsModule.giveUserChestKey(txPromise,tx,userId,chestType,1,"soft",generatePushId())
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic/:cosmetic_id', (req,res,next)->
userId = req.user.d.id
cosmetic_id = req.params.cosmetic_id
txPromise = knex.transaction (tx)->
return InventoryModule.giveUserCosmeticId(txPromise,tx,userId,cosmetic_id,"soft",generatePushId())
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/referrals/events', (req,res,next)->
userId = req.user.d.id
eventType = req.body.event_type
knex("users").where('id',userId).first('referred_by_user_id')
.then (userRow)->
ReferralsModule.processReferralEventForUser(userId,userRow.referred_by_user_id,eventType)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.post '/referrals/mark', (req,res,next)->
userId = req.user.d.id
username = req.body.username
knex("users").where('username',username).first('id')
.then (userRow)->
ReferralsModule.markUserAsReferredByFriend(userId,userRow.id)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.put '/account/reset', (req,res,next)->
userId = req.user.d.id
return SyncModule.wipeUserData(userId)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.post '/daily_challenge', (req,res,next)->
Logger.module("QA").log "Pushing Daily challenge"
challengeName = req.body.challenge_name
challengeDescription = req.body.challenge_description
challengeDifficulty = req.body.challenge_difficulty
challengeGold = 5
challengeJSON = req.body.challenge_json
challengeDate = req.body.challenge_date
challengeInstructions = req.body.challenge_instructions
challengeHint = req.body.challenge_hint
Promise.promisifyAll(zlib)
zlib.gzipAsync(challengeJSON)
.bind({})
.then (gzipGameSessionData) ->
@.gzipGameSessionData = gzipGameSessionData
env = null
if (UtilsEnv.getIsInLocal())
env = "local"
else if (UtilsEnv.getIsInStaging())
env = "staging"
else
return Promise.reject(new Error("Unknown/Invalid ENV for storing Daily Challenge"))
bucket = "duelyst-challenges"
filename = env + "/" + challengeDate + ".json"
@.url = "https://s3-us-west-2.amazonaws.com/" + bucket + "/" + filename
Logger.module("QA").log "Pushing Daily challenge with url #{@.url}"
params =
Bucket: bucket
Key: filename
Body: @.gzipGameSessionData
ACL: 'public-read'
ContentEncoding: "gzip"
ContentType: "text/json"
return s3.putObjectAsync(params)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.set(fbRootRef.child("daily-challenges").child(challengeDate),{
title: challengeName
description: challengeDescription
gold: challengeGold
difficulty: challengeDifficulty
instructions: challengeInstructions
url: @.url
challenge_id: generatePushId()
hint: challengeHint
})
.then () ->
Logger.module("QA").log "Success Pushing Daily challenge"
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed Pushing Daily challenge\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post "/daily_challenge/completed_at", (req, res, next) ->
user_id = req.user.d.id
completedAtTime = req.body.completed_at
lastCompletedData = {
daily_challenge_last_completed_at: completedAtTime
}
Promise.all([
knex("users").where('id',user_id).update(lastCompletedData),
knex("user_daily_challenges_completed").where('user_id',user_id).delete()
]).then () ->
lastCompletedData = DataAccessHelpers.restifyData(lastCompletedData)
res.status(200).json(lastCompletedData)
.catch (error) ->
Logger.module("QA").log "Failed updating daily challenge completed at\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post "/daily_challenge/passed_qa", (req, res, next) ->
dateKey = req.body.date_key
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return FirebasePromises.update(@.fbRootRef.child('daily-challenges').child(dateKey),{
isQAReady: true
})
.then () ->
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed marking daily challenge as passing QA\n #{error.toString()}"
res.status(403).json({message:error.toString()})
# Updates the users current s rank rating
router.delete '/user_progression/last_crate_awarded_at', (req,res,next)->
user_id = req.user.d.id
knex("user_progression").where("user_id",user_id).update({
last_crate_awarded_at:null,
last_crate_awarded_game_count:null,
last_crate_awarded_win_count:null,
}).then ()->
res.status(200).json({})
# Resets data for an achievement then marks it as complete
router.post '/achievement/reset_and_complete', (req, res, next) ->
user_id = req.user.d.id
achievement_id = req.body.achievement_id
return knex("user_achievements").where("user_id",user_id).andWhere("achievement_id",achievement_id).delete()
.then ()->
sdkAchievement = SDK.AchievementsFactory.achievementForIdentifier(achievement_id)
if (sdkAchievement == null)
return Promise.reject("No such achievement with id: #{achievement_id}")
achProgressMap = {}
achProgressMap[achievement_id] = sdkAchievement.progressRequired
return AchievementsModule._applyAchievementProgressMapToUser(user_id,achProgressMap)
.then ()->
Logger.module("QA").log "Completed resetting and completing achievement #{achievement_id}"
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed resetting and completing achievement\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post '/migration/prismatic_backfill', (req, res, next) ->
user_id = req.user.d.id
numOrbs = req.body.num_orbs
numOrbs = parseInt(numOrbs)
return knex("users").where('id',user_id).update(
last_session_version: "1.72.0"
).bind {}
.then () ->
timeBeforePrismaticFeatureAddedMoment = moment.utc("2016-07-20 20:00")
return Promise.each([1..numOrbs], (index) ->
return knex("user_spirit_orbs_opened").insert({
id: generatePushId()
user_id: user_id
card_set: SDK.CardSet.Core
transaction_type: "soft"
created_at: timeBeforePrismaticFeatureAddedMoment.toDate()
opened_at: timeBeforePrismaticFeatureAddedMoment.toDate()
cards: [1,1,1,1,1]
})
)
.then ()->
Logger.module("QA").log "Completed setting up prismatic backfill"
res.status(200).json({})
router.delete '/boss_event', (req, res, next) ->
bossEventId = "QA-Boss-Event"
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.remove(fbRootRef.child('boss-events').child(bossEventId))
.then ()->
Logger.module("QA").log "Completed setting up qa boss event"
res.status(200).json({})
router.delete '/boss_event/rewards', (req, res, next) ->
user_id = req.user.d.id
return Promise.all([
knex("user_bosses_defeated").where("user_id",user_id).delete(),
knex("user_cosmetic_chests").where("user_id",user_id).andWhere("chest_type",SDK.CosmeticsChestTypeLookup.Boss).delete(),
knex("user_cosmetic_chests_opened").where("user_id",user_id).andWhere("chest_type",SDK.CosmeticsChestTypeLookup.Boss).delete()
]).then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
Logger.module("QA").log "Completed removing user's boss rewards"
res.status(200).json({})
router.put '/boss_event', (req, res, next) ->
adjustedMs = req.body.adjusted_ms
bossId = parseInt(req.body.boss_id)
eventStartMoment = moment.utc().add(adjustedMs,"milliseconds")
bossEventId = "QA-Boss-Event"
bossEventData = {
event_id: bossEventId
boss_id: bossId
event_start: eventStartMoment.valueOf()
event_end: eventStartMoment.clone().add(1,"week").valueOf()
valid_end: eventStartMoment.clone().add(1,"week").add(1,"hour").valueOf()
}
return DuelystFirebase.connect().getRootRef()
.bind {}
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return FirebasePromises.remove(@.fbRootRef.child('boss-events').child(bossEventId))
.then () ->
return FirebasePromises.set(@.fbRootRef.child('boss-events').child(bossEventId),bossEventData)
.then ()->
Logger.module("QA").log "Completed setting up qa boss event"
res.status(200).json({})
router.put '/rift/duplicates', (req, res, next) ->
user_id = req.user.d.id
return knex("user_rift_runs").select().where('user_id', user_id)
.then (riftRuns) ->
return Promise.each(riftRuns, (riftRun) ->
if riftRun.card_choices?
return knex("user_rift_runs").where('ticket_id', riftRun.ticket_id).update({
card_choices: [11088, 20076, 11087, 11087, 20209, 11052]
})
else
return Promise.resolve()
)
.then ()->
res.status(200).json({})
# router.put '/premium_currency/amount', (req, res, next) ->
# user_id = req.user.d.id
# amount = parseInt(req.body.amount)
# amountPromise = null
# txPromise = knex.transaction (tx)->
# if (amount < 0)
# return ShopModule.debitUserPremiumCurrency(txPromise,tx,user_id,amount,generatePushId(),"qa tool gift")
# else
# return ShopModule.creditUserPremiumCurrency(txPromise,tx,user_id,amount,generatePushId(),"qa tool gift")
# .then ()->
# res.status(200).json({})
router.get '/shop/charge_log', (req, res, next) ->
user_id = req.user.d.id
return knex("user_charges").select().where('user_id',user_id)
.then (userChargeRows)->
res.status(200).json({userChargeRows:userChargeRows})
module.exports = router
| 167651 | express = require 'express'
_ = require 'underscore'
Promise = require 'bluebird'
FirebasePromises = require '../../../lib/firebase_promises.coffee'
DuelystFirebase = require '../../../lib/duelyst_firebase_module'
moment = require 'moment'
validator = require 'validator'
# lib Modules
UsersModule = require '../../../lib/data_access/users'
ReferralsModule = require '../../../lib/data_access/referrals'
RiftModule = require '../../../lib/data_access/rift'
InventoryModule = require '../../../lib/data_access/inventory'
QuestsModule = require '../../../lib/data_access/quests.coffee'
GauntletModule = require '../../../lib/data_access/gauntlet.coffee'
CosmeticChestsModule = require '../../../lib/data_access/cosmetic_chests.coffee'
AchievementsModule = require '../../../lib/data_access/achievements.coffee'
GiftCrateModule = require '../../../lib/data_access/gift_crate.coffee'
SyncModule = require '../../../lib/data_access/sync.coffee'
RankModule = require '../../../lib/data_access/rank.coffee'
SyncModule = require '../../../lib/data_access/sync.coffee'
ShopModule = require '../../../lib/data_access/shop.coffee'
TwitchModule = require '../../../lib/data_access/twitch.coffee'
knex = require '../../../lib/data_access/knex'
DataAccessHelpers = require '../../../lib/data_access/helpers'
Logger = require '../../../../app/common/logger.coffee'
Errors = require '../../../lib/custom_errors'
# sdk
SDK = require '../../../../app/sdk.coffee'
FactionFactory = require '../../../../app/sdk/cards/factionFactory'
RankFactory = require '../../../../app/sdk/rank/rankFactory.coffee'
GiftCrateLookup = require '../../../../app/sdk/giftCrates/giftCrateLookup.coffee'
CosmeticsLookup = require '../../../../app/sdk/cosmetics/cosmeticsLookup.coffee'
GameSession = require '../../../../app/sdk/gameSession.coffee'
Redis = require '../../../redis/'
{SRankManager} = require '../../../redis/'
t = require 'tcomb-validation'
util = require 'util'
# Daily challenges
zlib = require 'zlib'
config = require '../../../../config/config.js'
CONFIG = require('app/common/config');
UtilsEnv = require('app/common/utils/utils_env');
generatePushId = require '../../../../app/common/generate_push_id'
{Jobs} = require '../../../redis/'
# create a S3 API client
AWS = require "aws-sdk"
AWS.config.update
accessKeyId: config.get("s3_archive.key")
secretAccessKey: config.get("s3_archive.secret")
s3 = new AWS.S3()
# Promise.promisifyAll(s3)
rankedQueue = new Redis.PlayerQueue(Redis.Redis, {name:'ranked'})
router = express.Router()
Logger.module("EXPRESS").log "QA routes ACTIVE".green
router.delete '/rank/history/:season_key/rewards', (req,res,next)->
user_id = req.user.d.id
season_key = req.params.season_key
if not validator.matches(season_key,/^[0-9]{4}\-[0-9]{2}/i)
return next(new Errors.BadRequestError())
season_starting_at = moment(season_key + " +0000", "YYYY-MM Z").utc()
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).first().then (row)-> console.log "found: ",row
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).update(
rewards_claimed_at:null,
reward_ids:null
is_unread:true
).then (updateCount)->
res.status(200).json({})
router.put '/rank/history/:season_key/top_rank', (req,res,next)->
user_id = req.user.d.id
season_key = req.params.season_key
rank = req.body.rank
if not validator.matches(season_key,/^[<KEY>]{4<KEY>}\-[0-<KEY>]{<KEY>)
return next(new Errors.BadRequestError())
season_starting_at = moment(season_key + " +0000", "YYYY-MM Z").utc()
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).update(
top_rank:rank,
).then ()->
res.status(200).json({})
# Updates the users current rank (and top rank if appropriate)
router.put '/rank', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
user_id = req.user.d.id
rank = req.body.rank
knex("users").where({'id':user_id}).first()
.bind {}
.then (row)->
@.userRow = row
@.updateData = {
rank: rank
rank_stars: 0
}
if rank < row.rank_top_rank
@.updateData.rank_top_rank = rank
if rank < row.top_rank
@.updateData.top_rank = rank
knex("users").where({'id':user_id}).update(@.updateData)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
FirebasePromises.set(@.fbRootRef.child('user-ranking').child(user_id).child('current'),{
rank: parseInt(@.updateData.rank)
stars: @.updateData.rank_stars
stars_required: RankFactory.starsNeededToAdvanceRank(@.updateData.rank) || 0
updated_at: MOMENT_UTC_NOW.valueOf() || null
created_at: moment.utc(@.userRow.rank_created_at).valueOf()
starting_at: moment.utc(@.userRow.rank_starting_at).valueOf()
})
if @.updateData.top_rank?
FirebasePromises.set(@.fbRootRef.child('user-ranking').child(user_id).child('top'),{
rank: parseInt(@.updateData.top_rank)
updated_at: MOMENT_UTC_NOW.valueOf() || null
created_at: moment.utc(@.userRow.rank_created_at).valueOf()
starting_at: moment.utc(@.userRow.rank_starting_at).valueOf()
})
.then () ->
# TODO: Remove rating data from fb and database if rank is not 0
return Promise.resolve()
.then () ->
res.status(200).json({
rank:@.updateData.rank
top_rank: if @.updateData.rank_top_rank? then @.updateData.rank_top_rank else @.userRow.rank_top_rank
})
# Updates the users current s rank rating
router.put '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
rank_rating = req.body.rank_rating
userRatingRowData =
rating: rank_rating
updated_at: MOMENT_UTC_NOW.toDate()
newLadderPosition = null
txPromise = knex.transaction (tx)->
tx("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).first()
.then (userRankRatingRow) ->
# Update or insert
if userRankRatingRow?
userRatingRowData.ladder_rating = RankModule._ladderRatingForRatingAndWinCount(userRatingRowData.rating,userRankRatingRow.srank_win_count)
return tx("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).update(userRatingRowData)
else
return tx("user_rank_ratings").insert({
user_id: user_id
season_starting_at: seasonStartingAt
rating: rank_rating
ladder_rating: RankModule._ladderRatingForRatingAndWinCount(rank_rating,0)
top_rating: rank_rating
rating_deviation: 200
volatility: 0.06
created_at: MOMENT_UTC_NOW.toDate()
updated_at: MOMENT_UTC_NOW.toDate()
})
.then () ->
return RankModule.updateAndGetUserLadderPosition(txPromise,tx,user_id,startOfSeasonMonth,MOMENT_UTC_NOW)
.then (ladderPosition) ->
newLadderPosition = ladderPosition
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({ladder_position:newLadderPosition})
# Resets the users current s rank rating
router.delete '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
return Promise.all([
knex("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).delete(),
knex("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).delete()
]).then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.remove(fbRootRef.child('users').child(user_id).child('presence').child('ladder_position'))
.then () ->
res.status(200).json({})
# Retrieves the users current s rank rating data
router.get '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
user_rating_data = null
txPromise = knex.transaction (tx)->
RankModule.getUserRatingData(tx,user_id,MOMENT_UTC_NOW)
.then (userRatingRow) ->
user_rating_data = userRatingRow || {}
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({user_rating_data:user_rating_data})
# Retrieves the users current s rank ladder position (Does not update it anywhere)
router.get '/ladder_position', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
user_ladder_position = null
txPromise = knex.transaction (tx)->
RankModule.getUserLadderPosition(tx,user_id,startOfSeasonMonth,MOMENT_UTC_NOW)
.then (userLadderPosition) ->
user_ladder_position = userLadderPosition || null
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({user_ladder_position:user_ladder_position})
# Marks the current season as last season (so that it is ready to be cycled) and deletes last season from history if needed
router.delete '/rank/history/last', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
previous_season_key = moment().utc().subtract(1,'month').format("YYYY-<KEY>")
previous_season_starting_at = moment(previous_season_key + " +0000", "YYYY-MM Z").utc()
current_season_key = moment().utc().format("YYYY-<KEY>")
current_season_starting_at = moment(current_season_key + " +0000", "YYYY-MM Z").utc()
user_id = req.user.d.id
Promise.all([
knex("user_rank_history").where({'user_id':user_id,'starting_at':previous_season_starting_at.toDate()}).delete(),
knex("user_rank_ratings").where({'user_id':user_id,'season_starting_at':previous_season_starting_at.toDate()}).delete(),
])
.bind {}
.then ()->
@.updateUserData = {
rank_starting_at: previous_season_starting_at.toDate()
}
@.updateRankRatingData = {
season_starting_at: previous_season_starting_at.toDate()
}
return Promise.all([
knex("users").where({'id':user_id}).update(@.updateUserData),
knex("user_rank_ratings").where({'user_id':user_id,'season_starting_at':current_season_starting_at}).update(@.updateRankRatingData),
SRankManager._removeUserFromLadder(user_id,moment.utc(current_season_starting_at))
])
.then () ->
res.status(200).json({})
router.post '/inventory/spirit', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
InventoryModule.giveUserSpirit(txPromise,tx,user_id,amount,'QA gift')
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/gold', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
InventoryModule.giveUserGold(txPromise,tx,user_id,amount,'QA gift')
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/premium', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
if (amount > 0)
InventoryModule.giveUserPremium(txPromise,tx,user_id,amount,'QA gift')
else
InventoryModule.debitPremiumFromUser(txPromise,tx,user_id,-amount,'QA charge')
.then ()->
res.status(200).json({})
router.post '/inventory/rift_ticket', (req, res, next) ->
user_id = req.user.d.id
txPromise = knex.transaction (tx)->
# InventoryModule.giveUserGold(txPromise,tx,user_id,amount,'QA gift')
RiftModule.addRiftTicketToUser(txPromise,tx,user_id,"qa gift",generatePushId())
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/cards', (req, res, next) ->
user_id = req.user.d.id
cardIds = req.body.card_ids
if !cardIds or cardIds?.length <= 0
return res.status(400).json({})
txPromise = knex.transaction (tx)->
return InventoryModule.giveUserCards(txPromise,tx,user_id,cardIds,'QA','QA','QA gift')
.then ()->
res.status(200).json({})
router.post '/inventory/card_set_with_spirit', (req, res, next) ->
user_id = req.user.d.id
cardSetId = req.body.card_set_id
txPromise = knex.transaction (tx)->
return InventoryModule.buyRemainingSpiritOrbsWithSpirit(user_id,cardSetId)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.post '/inventory/fill_collection', (req, res, next) ->
user_id = req.user.d.id
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.then (cardCollectionRow) ->
missingCardIds = []
_.each(SDK.GameSession.getCardCaches().getIsCollectible(true).getIsUnlockable(false).getIsPrismatic(false).getCardIds(), (cardId) ->
if cardCollectionRow? and cardCollectionRow.cards?
cardData = cardCollectionRow.cards[cardId]
numMissing = 0
if (SDK.CardFactory.cardForIdentifier(cardId).getRarityId() == SDK.Rarity.Mythron)
if !cardData?
numMissing = 1
else if cardData?
numMissing = Math.max(0, 1 - cardData.count)
else
if !cardData?
numMissing = CONFIG.MAX_DECK_DUPLICATES
else if cardData?
numMissing = Math.max(0, CONFIG.MAX_DECK_DUPLICATES - cardData.count)
else
# If no card collection yet then they are missing all of this card
numMissing = CONFIG.MAX_DECK_DUPLICATES
if (SDK.CardFactory.cardForIdentifier(cardId).getRarityId() == SDK.Rarity.Mythron)
numMissing = 1
if numMissing > 0
for i in [0...numMissing]
missingCardIds.push(cardId)
)
if missingCardIds.length > 0
return InventoryModule.giveUserCards(txPromise,tx,user_id,missingCardIds,'QA','QA','QA gift')
else
return Promise.resolve()
return txPromise.then ()->
res.status(200).json({})
router.delete '/inventory/unused', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedUnusedCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (!sdkCard)
@.ownedUnusedCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedUnusedCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/inventory/bloodborn', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedBloodbornCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (sdkCard.getCardSetId() == SDK.CardSet.Bloodborn)
@.ownedBloodbornCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedBloodbornCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then () ->
return Promise.all([
tx("user_spirit_orbs_opened").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Bloodborn).delete(),
tx("user_spirit_orbs").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Bloodborn).delete(),
tx("users").where("id",user_id).update({
total_orb_count_set_3: 0
})
])
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/inventory/unity', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedUnityCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (sdkCard.getCardSetId() == SDK.CardSet.Unity)
@.ownedUnityCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedUnityCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then () ->
return Promise.all([
tx("user_spirit_orbs_opened").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Unity).delete(),
tx("user_spirit_orbs").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Unity).delete(),
tx("users").where("id",user_id).update({
total_orb_count_set_4: null
})
])
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/quests/current', (req, res, next) ->
user_id = req.user.d.id
twoDaysAgoMoment = moment.utc().subtract(2,"day")
knex("user_quests").where({'user_id':user_id}).delete()
.then ()->
return knex("users").where('id',user_id).update(
free_card_of_the_day_claimed_at: twoDaysAgoMoment.toDate()
)
.then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests'))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("catch-up").child("current").child('quests'))
FirebasePromises.set(@.fbRootRef.child("users").child(user_id).child("free_card_of_the_day_claimed_at"),twoDaysAgoMoment.valueOf())
])
.then ()->
QuestsModule.generateDailyQuests(user_id)
.then ()->
res.status(200).json({})
router.put '/quests/current', (req, res, next) ->
user_id = req.user.d.id
quest_ids = req.body.quest_ids
# wipe old quests and regenerate just to treat this like a fresh generation
knex("user_quests").where({'user_id':user_id}).delete()
.then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests'))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("catch-up").child("current").child('quests'))
])
.then ()->
QuestsModule.generateDailyQuests(user_id)
.then ()->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,null,quest_ids[0])
QuestsModule.mulliganDailyQuest(user_id,1,null,quest_ids[1])
])
.then ()->
return Promise.all([
knex("user_quests").where({'user_id':user_id}).update({mulliganed_at:null})
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests').child(0).child("mulliganed_at"))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests').child(1).child("mulliganed_at"))
])
.then ()->
res.status(200).json({})
router.put '/quests/current/progress', (req, res, next) ->
user_id = req.user.d.id
quest_slots = req.body.quest_slots
txPromise = knex.transaction (tx)->
return Promise.each(quest_slots, (quest_slot) ->
return tx("user_quests").first().where({'user_id':user_id,'quest_slot_index':quest_slot})
.then (questRow) ->
if questRow?
newProgress = questRow.progress || 0
newProgress += 1
return QuestsModule._setQuestProgress(txPromise,tx,questRow,newProgress)
else
return Promise.resolve()
)
return txPromise
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.put '/quests/generated_at', (req, res, next) ->
user_id = req.user.d.id
days_back = req.body.days_back
knex("users").where({'id':user_id}).first("daily_quests_generated_at")
.bind {}
.then (row)->
@.previousGeneratedAt = row.daily_quests_generated_at
@.newGeneratedAtMoment = moment.utc(row.daily_quests_generated_at).subtract(days_back,'days')
@.userRow = row
@.updateData = {
daily_quests_generated_at: @.newGeneratedAtMoment.toDate()
}
knex("users").where({'id':user_id}).update(@.updateData)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.set(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('updated_at'),@.newGeneratedAtMoment.valueOf())
FirebasePromises.set(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('generated_at'),@.newGeneratedAtMoment.valueOf())
])
.then () ->
res.status(200).json({
generated_at:@.newGeneratedAtMoment.valueOf()
})
router.post '/quests/setup_frostfire_2016', (req, res, next) ->
user_id = req.user.d.id
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",30001).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,moment.utc("2016-12-02"))
.then () ->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,moment.utc("2016-12-02"),101),
QuestsModule.mulliganDailyQuest(user_id,1,moment.utc("2016-12-02"),101)
])
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",0).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",1).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",QuestsModule.SEASONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: 13})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/quests/setup_seasonal_quest', (req, res, next) ->
user_id = req.user.d.id
generateQuestsAt = req.body.generate_quests_at
generateQuestsAtMoment = moment.utc(generateQuestsAt)
sdkQuestForGenerationTime = SDK.QuestFactory.seasonalQuestForMoment(generateQuestsAtMoment)
if not sdkQuestForGenerationTime?
res.status(403).json({message:"No seasonal quest for: " + generateQuestsAtMoment.toString()})
return
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",sdkQuestForGenerationTime.getId()).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,generateQuestsAtMoment)
.then () ->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,generateQuestsAtMoment,101),
QuestsModule.mulliganDailyQuest(user_id,1,generateQuestsAtMoment,1500)
])
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",0).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",1).andWhere("user_id",user_id).update({progress: 7})
knex("user_quests").where("quest_slot_index",QuestsModule.SEASONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: 13})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/quests/setup_promotional_quest', (req, res, next) ->
user_id = req.user.d.id
generateQuestsAt = req.body.generate_quests_at
generateQuestsAtMoment = moment.utc(generateQuestsAt)
sdkQuestForGenerationTime = SDK.QuestFactory.promotionalQuestForMoment(generateQuestsAtMoment)
progressToStartWith = sdkQuestForGenerationTime.params["completionProgress"] - 1
if not sdkQuestForGenerationTime?
res.status(403).json({message:"No promo quest for: " + generateQuestsAtMoment.toString()})
return
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",sdkQuestForGenerationTime.getId()).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,generateQuestsAtMoment)
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",QuestsModule.PROMOTIONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: progressToStartWith})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/matchmaking/time_series/:division/values', (req, res, next) ->
division = req.params.division
ms = req.body.ms
rankedQueue.matchMade(division,ms)
res.status(200).json({})
router.post '/faction_progression/set_all_win_counts_to_99', (req,res,next)->
user_id = req.user.d.id
knex("user_faction_progression").where('user_id',user_id)
.then (rows)->
all = []
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
Logger.module("QA").log "factionIds ", factionIds
for factionId in factionIds
row = _.find(rows, (r)-> return r.faction_id == factionId)
Logger.module("QA").log "faction #{factionId}", row?.user_id
if row?
all.push knex("user_faction_progression").where({
'user_id':user_id,
'faction_id':row.faction_id
}).update(
'win_count':99
)
return Promise.all(all)
.then ()->
res.status(200).json({})
router.post '/faction_progression/add_level', (req,res,next)->
user_id = req.user.d.id
factionId = req.body.faction_id
if factionId?
knex("user_faction_progression").where({'user_id': user_id, "faction_id": factionId}).first()
.then (factionProgressionRow)->
if !factionProgressionRow?
return UsersModule.createFactionProgressionRecord(user_id,factionId, generatePushId(), SDK.GameType.Ranked)
.then () ->
return knex("user_faction_progression").where({'user_id': user_id, "faction_id": factionId}).first()
.then (factionProgressionRow) ->
if !factionProgressionRow?
return Promise.reject("No row found for faction #{factionId}")
else
currentXP = factionProgressionRow.xp || 0
currentLevel = SDK.FactionProgression.levelForXP(currentXP)
nextLevel = currentLevel + 1
nextLevelXP = SDK.FactionProgression.totalXPForLevel(nextLevel)
deltaXP = nextLevelXP - currentXP
if deltaXP <= 0
return Promise.reject("Cannot increase level for faction #{factionId}, currently at #{currentLevel}")
else
winsNeeded = Math.ceil(deltaXP / SDK.FactionProgression.winXP)
promises = []
for i in [0...winsNeeded]
promises.push(UsersModule.updateUserFactionProgressionWithGameOutcome(user_id, factionId, true, generatePushId(), SDK.GameType.Ranked))
return Promise.all(promises)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.post '/faction_progression/set_all_levels_to_10', (req,res,next)->
user_id = req.user.d.id
knex("user_faction_progression").where('user_id',user_id)
.then (rows)->
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
allPromises = []
for factionId in factionIds
row = _.find(rows, (r)-> return r.faction_id == factionId)
if !row?
allPromises.push(UsersModule.createFactionProgressionRecord(user_id,factionId,generatePushId(),SDK.GameType.SinglePlayer))
return Promise.all(allPromises)
.then () ->
return knex("user_faction_progression").where('user_id',user_id)
.then (factionRows) ->
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
winsPerFaction = []
for factionId in factionIds
row = _.find(factionRows, (r)-> return r.faction_id == factionId)
if !row?
return Promise.reject("No row found for faction - #{factionId}")
else
factionXp = row.xp
xpForLevelTen = SDK.FactionProgression.levelXPTable[10]
neededXp = xpForLevelTen - factionXp
xpPerWin = SDK.FactionProgression.winXP
if neededXp > 0
neededWins = Math.ceil(neededXp / xpPerWin)
winsPerFaction = winsPerFaction.concat(Array(neededWins).fill(factionId))
return Promise.each(winsPerFaction, (factionId) ->
return UsersModule.updateUserFactionProgressionWithGameOutcome(user_id,factionId,true,generatePushId(),SDK.GameType.Ranked)
)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.delete '/gauntlet/current', (req,res,next)->
userId = req.user.d.id
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return Promise.all([
knex("user_gauntlet_run").where('user_id',userId).delete()
FirebasePromises.remove(fbRootRef.child("user-gauntlet-run").child(userId).child("current"))
])
.then () ->
res.status(200).json({})
.catch (error) ->
res.status(403).json({message:error.toString()})
router.delete '/gauntlet/current/general', (req,res,next)->
userId = req.user.d.id
# Get current gauntlet data
knex("user_gauntlet_run").first().where('user_id',userId)
.bind({})
.then (gauntletData) ->
this.gauntletData = gauntletData
if (not gauntletData?)
return Promise.reject(new Error("You are not currently in a Gauntlet Run"))
if (not gauntletData.is_complete)
return Promise.reject(new Error("Current Gauntlet deck is not complete"))
cardIdInGeneralSlot = gauntletData.deck[0]
sdkCard = GameSession.getCardCaches().getCardById(cardIdInGeneralSlot)
if (not sdkCard.getIsGeneral())
return Promise.reject(new Error("Current Gauntlet deck does not have general in expected slot"))
this.newDeck = gauntletData.deck.slice(1)
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
updateData =
deck: this.newDeck
general_id: null
return Promise.all([
knex("user_gauntlet_run").where('user_id',userId).update(updateData)
FirebasePromises.update(fbRootRef.child("user-gauntlet-run").child(userId).child("current"),updateData)
])
.then () ->
res.status(200).json(this.gauntletData)
.catch (error) ->
res.status(403).json({message:error.toString()})
router.post '/gauntlet/progress', (req,res,next)->
userId = req.user.d.id
isWinner = req.body.is_winner
Redis.GameManager.generateGameId()
.then (gameId) ->
GauntletModule.updateArenaRunWithGameOutcome(userId,isWinner,gameId,false)
.then (runData) ->
res.status(200).json(runData)
.catch (error) ->
res.status(403).json({message:error.toString()})
router.post '/gauntlet/fill_deck', (req,res,next)->
userId = req.user.d.id
# Get current gauntlet data
knex("user_gauntlet_run").first().where('user_id',userId)
.then (gauntletData) ->
recursiveSelect = (gauntletData) ->
if !gauntletData? || !gauntletData.card_choices? || !gauntletData.card_choices[0]?
# No more card choices
res.status(200).json(gauntletData)
else
cardIdChoice = null;
if (gauntletData.card_choices?)
cardIdChoice = gauntletData.card_choices[0]
else if (gauntletData.general_choices?)
cardIdChoice = gauntletData.general_choices[0]
GauntletModule.chooseCard(userId,cardIdChoice)
.then (newGauntletData) ->
recursiveSelect(newGauntletData)
recursiveSelect(gauntletData)
.catch (error) ->
res.status(403).json({message:error.message})
router.post '/gift_crate/winter2015', (req,res,next)->
userId = req.user.d.id
txPromise = knex.transaction (tx)->
Promise.all([
tx("user_emotes").where("user_id",userId).andWhere("emote_id",CosmeticsLookup.Emote.OtherSnowChaserHoliday2015).delete()
tx("user_rewards").where("user_id",userId).andWhere("source_id",GiftCrateLookup.WinterHoliday2015).delete()
tx("user_gift_crates").where("user_id",userId).andWhere("crate_type",GiftCrateLookup.WinterHoliday2015).delete()
])
.then ()->
return GiftCrateModule.addGiftCrateToUser(txPromise,tx,userId,GiftCrateLookup.WinterHoliday2015)
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/gift_crate/lag2016', (req,res,next)->
userId = req.user.d.id
txPromise = knex.transaction (tx)->
Promise.all([
tx("user_rewards").where("user_id",userId).andWhere("source_id",GiftCrateLookup.FebruaryLag2016).delete()
tx("user_gift_crates").where("user_id",userId).andWhere("crate_type",GiftCrateLookup.FebruaryLag2016).delete()
])
.then ()->
return GiftCrateModule.addGiftCrateToUser(txPromise,tx,userId,GiftCrateLookup.FebruaryLag2016)
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic_chest/:chest_type', (req,res,next)->
userId = req.user.d.id
chestType = req.params.chest_type
hoursBack = parseInt(req.body.hours_back)
if not hoursBack?
hoursBack = 0
bossId = null
eventId = null
if chestType == SDK.CosmeticsChestTypeLookup.Boss
bossId = SDK.Cards.Boss.Boss3
eventId = "QA-" + generatePushId()
txPromise = knex.transaction (tx)->
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,chestType,bossId,eventId,1,"soft",generatePushId(),moment.utc().subtract(hoursBack,"hours"))
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic_chest_key/:chest_type', (req,res,next)->
userId = req.user.d.id
chestType = req.params.chest_type
txPromise = knex.transaction (tx)->
return CosmeticChestsModule.giveUserChestKey(txPromise,tx,userId,chestType,1,"soft",generatePushId())
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic/:cosmetic_id', (req,res,next)->
userId = req.user.d.id
cosmetic_id = req.params.cosmetic_id
txPromise = knex.transaction (tx)->
return InventoryModule.giveUserCosmeticId(txPromise,tx,userId,cosmetic_id,"soft",generatePushId())
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/referrals/events', (req,res,next)->
userId = req.user.d.id
eventType = req.body.event_type
knex("users").where('id',userId).first('referred_by_user_id')
.then (userRow)->
ReferralsModule.processReferralEventForUser(userId,userRow.referred_by_user_id,eventType)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.post '/referrals/mark', (req,res,next)->
userId = req.user.d.id
username = req.body.username
knex("users").where('username',username).first('id')
.then (userRow)->
ReferralsModule.markUserAsReferredByFriend(userId,userRow.id)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.put '/account/reset', (req,res,next)->
userId = req.user.d.id
return SyncModule.wipeUserData(userId)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.post '/daily_challenge', (req,res,next)->
Logger.module("QA").log "Pushing Daily challenge"
challengeName = req.body.challenge_name
challengeDescription = req.body.challenge_description
challengeDifficulty = req.body.challenge_difficulty
challengeGold = 5
challengeJSON = req.body.challenge_json
challengeDate = req.body.challenge_date
challengeInstructions = req.body.challenge_instructions
challengeHint = req.body.challenge_hint
Promise.promisifyAll(zlib)
zlib.gzipAsync(challengeJSON)
.bind({})
.then (gzipGameSessionData) ->
@.gzipGameSessionData = gzipGameSessionData
env = null
if (UtilsEnv.getIsInLocal())
env = "local"
else if (UtilsEnv.getIsInStaging())
env = "staging"
else
return Promise.reject(new Error("Unknown/Invalid ENV for storing Daily Challenge"))
bucket = "duelyst-challenges"
filename = env + "/" + challengeDate + ".json"
@.url = "https://s3-us-west-2.amazonaws.com/" + bucket + "/" + filename
Logger.module("QA").log "Pushing Daily challenge with url #{@.url}"
params =
Bucket: bucket
Key: filename
Body: @.gzipGameSessionData
ACL: 'public-read'
ContentEncoding: "gzip"
ContentType: "text/json"
return s3.putObjectAsync(params)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.set(fbRootRef.child("daily-challenges").child(challengeDate),{
title: challengeName
description: challengeDescription
gold: challengeGold
difficulty: challengeDifficulty
instructions: challengeInstructions
url: @.url
challenge_id: generatePushId()
hint: challengeHint
})
.then () ->
Logger.module("QA").log "Success Pushing Daily challenge"
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed Pushing Daily challenge\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post "/daily_challenge/completed_at", (req, res, next) ->
user_id = req.user.d.id
completedAtTime = req.body.completed_at
lastCompletedData = {
daily_challenge_last_completed_at: completedAtTime
}
Promise.all([
knex("users").where('id',user_id).update(lastCompletedData),
knex("user_daily_challenges_completed").where('user_id',user_id).delete()
]).then () ->
lastCompletedData = DataAccessHelpers.restifyData(lastCompletedData)
res.status(200).json(lastCompletedData)
.catch (error) ->
Logger.module("QA").log "Failed updating daily challenge completed at\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post "/daily_challenge/passed_qa", (req, res, next) ->
dateKey = req.body.date_key
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return FirebasePromises.update(@.fbRootRef.child('daily-challenges').child(dateKey),{
isQAReady: true
})
.then () ->
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed marking daily challenge as passing QA\n #{error.toString()}"
res.status(403).json({message:error.toString()})
# Updates the users current s rank rating
router.delete '/user_progression/last_crate_awarded_at', (req,res,next)->
user_id = req.user.d.id
knex("user_progression").where("user_id",user_id).update({
last_crate_awarded_at:null,
last_crate_awarded_game_count:null,
last_crate_awarded_win_count:null,
}).then ()->
res.status(200).json({})
# Resets data for an achievement then marks it as complete
router.post '/achievement/reset_and_complete', (req, res, next) ->
user_id = req.user.d.id
achievement_id = req.body.achievement_id
return knex("user_achievements").where("user_id",user_id).andWhere("achievement_id",achievement_id).delete()
.then ()->
sdkAchievement = SDK.AchievementsFactory.achievementForIdentifier(achievement_id)
if (sdkAchievement == null)
return Promise.reject("No such achievement with id: #{achievement_id}")
achProgressMap = {}
achProgressMap[achievement_id] = sdkAchievement.progressRequired
return AchievementsModule._applyAchievementProgressMapToUser(user_id,achProgressMap)
.then ()->
Logger.module("QA").log "Completed resetting and completing achievement #{achievement_id}"
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed resetting and completing achievement\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post '/migration/prismatic_backfill', (req, res, next) ->
user_id = req.user.d.id
numOrbs = req.body.num_orbs
numOrbs = parseInt(numOrbs)
return knex("users").where('id',user_id).update(
last_session_version: "1.72.0"
).bind {}
.then () ->
timeBeforePrismaticFeatureAddedMoment = moment.utc("2016-07-20 20:00")
return Promise.each([1..numOrbs], (index) ->
return knex("user_spirit_orbs_opened").insert({
id: generatePushId()
user_id: user_id
card_set: SDK.CardSet.Core
transaction_type: "soft"
created_at: timeBeforePrismaticFeatureAddedMoment.toDate()
opened_at: timeBeforePrismaticFeatureAddedMoment.toDate()
cards: [1,1,1,1,1]
})
)
.then ()->
Logger.module("QA").log "Completed setting up prismatic backfill"
res.status(200).json({})
router.delete '/boss_event', (req, res, next) ->
bossEventId = "QA-Boss-Event"
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.remove(fbRootRef.child('boss-events').child(bossEventId))
.then ()->
Logger.module("QA").log "Completed setting up qa boss event"
res.status(200).json({})
router.delete '/boss_event/rewards', (req, res, next) ->
user_id = req.user.d.id
return Promise.all([
knex("user_bosses_defeated").where("user_id",user_id).delete(),
knex("user_cosmetic_chests").where("user_id",user_id).andWhere("chest_type",SDK.CosmeticsChestTypeLookup.Boss).delete(),
knex("user_cosmetic_chests_opened").where("user_id",user_id).andWhere("chest_type",SDK.CosmeticsChestTypeLookup.Boss).delete()
]).then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
Logger.module("QA").log "Completed removing user's boss rewards"
res.status(200).json({})
router.put '/boss_event', (req, res, next) ->
adjustedMs = req.body.adjusted_ms
bossId = parseInt(req.body.boss_id)
eventStartMoment = moment.utc().add(adjustedMs,"milliseconds")
bossEventId = "QA-Boss-Event"
bossEventData = {
event_id: bossEventId
boss_id: bossId
event_start: eventStartMoment.valueOf()
event_end: eventStartMoment.clone().add(1,"week").valueOf()
valid_end: eventStartMoment.clone().add(1,"week").add(1,"hour").valueOf()
}
return DuelystFirebase.connect().getRootRef()
.bind {}
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return FirebasePromises.remove(@.fbRootRef.child('boss-events').child(bossEventId))
.then () ->
return FirebasePromises.set(@.fbRootRef.child('boss-events').child(bossEventId),bossEventData)
.then ()->
Logger.module("QA").log "Completed setting up qa boss event"
res.status(200).json({})
router.put '/rift/duplicates', (req, res, next) ->
user_id = req.user.d.id
return knex("user_rift_runs").select().where('user_id', user_id)
.then (riftRuns) ->
return Promise.each(riftRuns, (riftRun) ->
if riftRun.card_choices?
return knex("user_rift_runs").where('ticket_id', riftRun.ticket_id).update({
card_choices: [11088, 20076, 11087, 11087, 20209, 11052]
})
else
return Promise.resolve()
)
.then ()->
res.status(200).json({})
# router.put '/premium_currency/amount', (req, res, next) ->
# user_id = req.user.d.id
# amount = parseInt(req.body.amount)
# amountPromise = null
# txPromise = knex.transaction (tx)->
# if (amount < 0)
# return ShopModule.debitUserPremiumCurrency(txPromise,tx,user_id,amount,generatePushId(),"qa tool gift")
# else
# return ShopModule.creditUserPremiumCurrency(txPromise,tx,user_id,amount,generatePushId(),"qa tool gift")
# .then ()->
# res.status(200).json({})
router.get '/shop/charge_log', (req, res, next) ->
user_id = req.user.d.id
return knex("user_charges").select().where('user_id',user_id)
.then (userChargeRows)->
res.status(200).json({userChargeRows:userChargeRows})
module.exports = router
| true | express = require 'express'
_ = require 'underscore'
Promise = require 'bluebird'
FirebasePromises = require '../../../lib/firebase_promises.coffee'
DuelystFirebase = require '../../../lib/duelyst_firebase_module'
moment = require 'moment'
validator = require 'validator'
# lib Modules
UsersModule = require '../../../lib/data_access/users'
ReferralsModule = require '../../../lib/data_access/referrals'
RiftModule = require '../../../lib/data_access/rift'
InventoryModule = require '../../../lib/data_access/inventory'
QuestsModule = require '../../../lib/data_access/quests.coffee'
GauntletModule = require '../../../lib/data_access/gauntlet.coffee'
CosmeticChestsModule = require '../../../lib/data_access/cosmetic_chests.coffee'
AchievementsModule = require '../../../lib/data_access/achievements.coffee'
GiftCrateModule = require '../../../lib/data_access/gift_crate.coffee'
SyncModule = require '../../../lib/data_access/sync.coffee'
RankModule = require '../../../lib/data_access/rank.coffee'
SyncModule = require '../../../lib/data_access/sync.coffee'
ShopModule = require '../../../lib/data_access/shop.coffee'
TwitchModule = require '../../../lib/data_access/twitch.coffee'
knex = require '../../../lib/data_access/knex'
DataAccessHelpers = require '../../../lib/data_access/helpers'
Logger = require '../../../../app/common/logger.coffee'
Errors = require '../../../lib/custom_errors'
# sdk
SDK = require '../../../../app/sdk.coffee'
FactionFactory = require '../../../../app/sdk/cards/factionFactory'
RankFactory = require '../../../../app/sdk/rank/rankFactory.coffee'
GiftCrateLookup = require '../../../../app/sdk/giftCrates/giftCrateLookup.coffee'
CosmeticsLookup = require '../../../../app/sdk/cosmetics/cosmeticsLookup.coffee'
GameSession = require '../../../../app/sdk/gameSession.coffee'
Redis = require '../../../redis/'
{SRankManager} = require '../../../redis/'
t = require 'tcomb-validation'
util = require 'util'
# Daily challenges
zlib = require 'zlib'
config = require '../../../../config/config.js'
CONFIG = require('app/common/config');
UtilsEnv = require('app/common/utils/utils_env');
generatePushId = require '../../../../app/common/generate_push_id'
{Jobs} = require '../../../redis/'
# create a S3 API client
AWS = require "aws-sdk"
AWS.config.update
accessKeyId: config.get("s3_archive.key")
secretAccessKey: config.get("s3_archive.secret")
s3 = new AWS.S3()
# Promise.promisifyAll(s3)
rankedQueue = new Redis.PlayerQueue(Redis.Redis, {name:'ranked'})
router = express.Router()
Logger.module("EXPRESS").log "QA routes ACTIVE".green
router.delete '/rank/history/:season_key/rewards', (req,res,next)->
user_id = req.user.d.id
season_key = req.params.season_key
if not validator.matches(season_key,/^[0-9]{4}\-[0-9]{2}/i)
return next(new Errors.BadRequestError())
season_starting_at = moment(season_key + " +0000", "YYYY-MM Z").utc()
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).first().then (row)-> console.log "found: ",row
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).update(
rewards_claimed_at:null,
reward_ids:null
is_unread:true
).then (updateCount)->
res.status(200).json({})
router.put '/rank/history/:season_key/top_rank', (req,res,next)->
user_id = req.user.d.id
season_key = req.params.season_key
rank = req.body.rank
if not validator.matches(season_key,/^[PI:KEY:<KEY>END_PI]{4PI:KEY:<KEY>END_PI}\-[0-PI:KEY:<KEY>END_PI]{PI:KEY:<KEY>END_PI)
return next(new Errors.BadRequestError())
season_starting_at = moment(season_key + " +0000", "YYYY-MM Z").utc()
knex("user_rank_history").where({'user_id':user_id,'starting_at':season_starting_at.toDate()}).update(
top_rank:rank,
).then ()->
res.status(200).json({})
# Updates the users current rank (and top rank if appropriate)
router.put '/rank', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
user_id = req.user.d.id
rank = req.body.rank
knex("users").where({'id':user_id}).first()
.bind {}
.then (row)->
@.userRow = row
@.updateData = {
rank: rank
rank_stars: 0
}
if rank < row.rank_top_rank
@.updateData.rank_top_rank = rank
if rank < row.top_rank
@.updateData.top_rank = rank
knex("users").where({'id':user_id}).update(@.updateData)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
FirebasePromises.set(@.fbRootRef.child('user-ranking').child(user_id).child('current'),{
rank: parseInt(@.updateData.rank)
stars: @.updateData.rank_stars
stars_required: RankFactory.starsNeededToAdvanceRank(@.updateData.rank) || 0
updated_at: MOMENT_UTC_NOW.valueOf() || null
created_at: moment.utc(@.userRow.rank_created_at).valueOf()
starting_at: moment.utc(@.userRow.rank_starting_at).valueOf()
})
if @.updateData.top_rank?
FirebasePromises.set(@.fbRootRef.child('user-ranking').child(user_id).child('top'),{
rank: parseInt(@.updateData.top_rank)
updated_at: MOMENT_UTC_NOW.valueOf() || null
created_at: moment.utc(@.userRow.rank_created_at).valueOf()
starting_at: moment.utc(@.userRow.rank_starting_at).valueOf()
})
.then () ->
# TODO: Remove rating data from fb and database if rank is not 0
return Promise.resolve()
.then () ->
res.status(200).json({
rank:@.updateData.rank
top_rank: if @.updateData.rank_top_rank? then @.updateData.rank_top_rank else @.userRow.rank_top_rank
})
# Updates the users current s rank rating
router.put '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
rank_rating = req.body.rank_rating
userRatingRowData =
rating: rank_rating
updated_at: MOMENT_UTC_NOW.toDate()
newLadderPosition = null
txPromise = knex.transaction (tx)->
tx("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).first()
.then (userRankRatingRow) ->
# Update or insert
if userRankRatingRow?
userRatingRowData.ladder_rating = RankModule._ladderRatingForRatingAndWinCount(userRatingRowData.rating,userRankRatingRow.srank_win_count)
return tx("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).update(userRatingRowData)
else
return tx("user_rank_ratings").insert({
user_id: user_id
season_starting_at: seasonStartingAt
rating: rank_rating
ladder_rating: RankModule._ladderRatingForRatingAndWinCount(rank_rating,0)
top_rating: rank_rating
rating_deviation: 200
volatility: 0.06
created_at: MOMENT_UTC_NOW.toDate()
updated_at: MOMENT_UTC_NOW.toDate()
})
.then () ->
return RankModule.updateAndGetUserLadderPosition(txPromise,tx,user_id,startOfSeasonMonth,MOMENT_UTC_NOW)
.then (ladderPosition) ->
newLadderPosition = ladderPosition
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({ladder_position:newLadderPosition})
# Resets the users current s rank rating
router.delete '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
return Promise.all([
knex("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).delete(),
knex("user_rank_ratings").where('user_id',user_id).andWhere('season_starting_at',seasonStartingAt).delete()
]).then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.remove(fbRootRef.child('users').child(user_id).child('presence').child('ladder_position'))
.then () ->
res.status(200).json({})
# Retrieves the users current s rank rating data
router.get '/rank_rating', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
user_rating_data = null
txPromise = knex.transaction (tx)->
RankModule.getUserRatingData(tx,user_id,MOMENT_UTC_NOW)
.then (userRatingRow) ->
user_rating_data = userRatingRow || {}
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({user_rating_data:user_rating_data})
# Retrieves the users current s rank ladder position (Does not update it anywhere)
router.get '/ladder_position', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
startOfSeasonMonth = moment(MOMENT_UTC_NOW).utc().startOf('month')
seasonStartingAt = startOfSeasonMonth.toDate()
user_id = req.user.d.id
user_ladder_position = null
txPromise = knex.transaction (tx)->
RankModule.getUserLadderPosition(tx,user_id,startOfSeasonMonth,MOMENT_UTC_NOW)
.then (userLadderPosition) ->
user_ladder_position = userLadderPosition || null
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({user_ladder_position:user_ladder_position})
# Marks the current season as last season (so that it is ready to be cycled) and deletes last season from history if needed
router.delete '/rank/history/last', (req,res,next)->
MOMENT_UTC_NOW = moment().utc()
previous_season_key = moment().utc().subtract(1,'month').format("YYYY-PI:KEY:<KEY>END_PI")
previous_season_starting_at = moment(previous_season_key + " +0000", "YYYY-MM Z").utc()
current_season_key = moment().utc().format("YYYY-PI:KEY:<KEY>END_PI")
current_season_starting_at = moment(current_season_key + " +0000", "YYYY-MM Z").utc()
user_id = req.user.d.id
Promise.all([
knex("user_rank_history").where({'user_id':user_id,'starting_at':previous_season_starting_at.toDate()}).delete(),
knex("user_rank_ratings").where({'user_id':user_id,'season_starting_at':previous_season_starting_at.toDate()}).delete(),
])
.bind {}
.then ()->
@.updateUserData = {
rank_starting_at: previous_season_starting_at.toDate()
}
@.updateRankRatingData = {
season_starting_at: previous_season_starting_at.toDate()
}
return Promise.all([
knex("users").where({'id':user_id}).update(@.updateUserData),
knex("user_rank_ratings").where({'user_id':user_id,'season_starting_at':current_season_starting_at}).update(@.updateRankRatingData),
SRankManager._removeUserFromLadder(user_id,moment.utc(current_season_starting_at))
])
.then () ->
res.status(200).json({})
router.post '/inventory/spirit', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
InventoryModule.giveUserSpirit(txPromise,tx,user_id,amount,'QA gift')
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/gold', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
InventoryModule.giveUserGold(txPromise,tx,user_id,amount,'QA gift')
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/premium', (req, res, next) ->
user_id = req.user.d.id
amount = req.body.amount
txPromise = knex.transaction (tx)->
if (amount > 0)
InventoryModule.giveUserPremium(txPromise,tx,user_id,amount,'QA gift')
else
InventoryModule.debitPremiumFromUser(txPromise,tx,user_id,-amount,'QA charge')
.then ()->
res.status(200).json({})
router.post '/inventory/rift_ticket', (req, res, next) ->
user_id = req.user.d.id
txPromise = knex.transaction (tx)->
# InventoryModule.giveUserGold(txPromise,tx,user_id,amount,'QA gift')
RiftModule.addRiftTicketToUser(txPromise,tx,user_id,"qa gift",generatePushId())
.then tx.commit
.catch tx.rollback
return;
.then ()->
res.status(200).json({})
router.post '/inventory/cards', (req, res, next) ->
user_id = req.user.d.id
cardIds = req.body.card_ids
if !cardIds or cardIds?.length <= 0
return res.status(400).json({})
txPromise = knex.transaction (tx)->
return InventoryModule.giveUserCards(txPromise,tx,user_id,cardIds,'QA','QA','QA gift')
.then ()->
res.status(200).json({})
router.post '/inventory/card_set_with_spirit', (req, res, next) ->
user_id = req.user.d.id
cardSetId = req.body.card_set_id
txPromise = knex.transaction (tx)->
return InventoryModule.buyRemainingSpiritOrbsWithSpirit(user_id,cardSetId)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.post '/inventory/fill_collection', (req, res, next) ->
user_id = req.user.d.id
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.then (cardCollectionRow) ->
missingCardIds = []
_.each(SDK.GameSession.getCardCaches().getIsCollectible(true).getIsUnlockable(false).getIsPrismatic(false).getCardIds(), (cardId) ->
if cardCollectionRow? and cardCollectionRow.cards?
cardData = cardCollectionRow.cards[cardId]
numMissing = 0
if (SDK.CardFactory.cardForIdentifier(cardId).getRarityId() == SDK.Rarity.Mythron)
if !cardData?
numMissing = 1
else if cardData?
numMissing = Math.max(0, 1 - cardData.count)
else
if !cardData?
numMissing = CONFIG.MAX_DECK_DUPLICATES
else if cardData?
numMissing = Math.max(0, CONFIG.MAX_DECK_DUPLICATES - cardData.count)
else
# If no card collection yet then they are missing all of this card
numMissing = CONFIG.MAX_DECK_DUPLICATES
if (SDK.CardFactory.cardForIdentifier(cardId).getRarityId() == SDK.Rarity.Mythron)
numMissing = 1
if numMissing > 0
for i in [0...numMissing]
missingCardIds.push(cardId)
)
if missingCardIds.length > 0
return InventoryModule.giveUserCards(txPromise,tx,user_id,missingCardIds,'QA','QA','QA gift')
else
return Promise.resolve()
return txPromise.then ()->
res.status(200).json({})
router.delete '/inventory/unused', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedUnusedCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (!sdkCard)
@.ownedUnusedCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedUnusedCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/inventory/bloodborn', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedBloodbornCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (sdkCard.getCardSetId() == SDK.CardSet.Bloodborn)
@.ownedBloodbornCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedBloodbornCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then () ->
return Promise.all([
tx("user_spirit_orbs_opened").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Bloodborn).delete(),
tx("user_spirit_orbs").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Bloodborn).delete(),
tx("users").where("id",user_id).update({
total_orb_count_set_3: 0
})
])
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/inventory/unity', (req, res, next) ->
user_id = req.user.d.id
this_obj = {}
txPromise = knex.transaction (tx)->
return tx("user_card_collection").where('user_id', user_id).first()
.bind this_obj
.then (cardCollectionRow) ->
@.newCardCollection = {}
@.ownedUnityCards = []
for cardId,cardCountData of cardCollectionRow.cards
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if (sdkCard.getCardSetId() == SDK.CardSet.Unity)
@.ownedUnityCards.push(cardId)
else
@.newCardCollection[cardId] = cardCountData
return tx("user_card_collection").where("user_id", user_id).update({
cards: @.newCardCollection
})
.then () ->
return Promise.map(@.ownedUnityCards,(cardId) ->
return tx("user_cards").where("user_id",user_id).andWhere("card_id",cardId).delete()
)
.then () ->
return Promise.all([
tx("user_spirit_orbs_opened").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Unity).delete(),
tx("user_spirit_orbs").where("user_id",user_id).andWhere("card_set",SDK.CardSet.Unity).delete(),
tx("users").where("id",user_id).update({
total_orb_count_set_4: null
})
])
.then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
res.status(200).json({})
router.delete '/quests/current', (req, res, next) ->
user_id = req.user.d.id
twoDaysAgoMoment = moment.utc().subtract(2,"day")
knex("user_quests").where({'user_id':user_id}).delete()
.then ()->
return knex("users").where('id',user_id).update(
free_card_of_the_day_claimed_at: twoDaysAgoMoment.toDate()
)
.then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests'))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("catch-up").child("current").child('quests'))
FirebasePromises.set(@.fbRootRef.child("users").child(user_id).child("free_card_of_the_day_claimed_at"),twoDaysAgoMoment.valueOf())
])
.then ()->
QuestsModule.generateDailyQuests(user_id)
.then ()->
res.status(200).json({})
router.put '/quests/current', (req, res, next) ->
user_id = req.user.d.id
quest_ids = req.body.quest_ids
# wipe old quests and regenerate just to treat this like a fresh generation
knex("user_quests").where({'user_id':user_id}).delete()
.then ()->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests'))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("catch-up").child("current").child('quests'))
])
.then ()->
QuestsModule.generateDailyQuests(user_id)
.then ()->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,null,quest_ids[0])
QuestsModule.mulliganDailyQuest(user_id,1,null,quest_ids[1])
])
.then ()->
return Promise.all([
knex("user_quests").where({'user_id':user_id}).update({mulliganed_at:null})
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests').child(0).child("mulliganed_at"))
FirebasePromises.remove(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('quests').child(1).child("mulliganed_at"))
])
.then ()->
res.status(200).json({})
router.put '/quests/current/progress', (req, res, next) ->
user_id = req.user.d.id
quest_slots = req.body.quest_slots
txPromise = knex.transaction (tx)->
return Promise.each(quest_slots, (quest_slot) ->
return tx("user_quests").first().where({'user_id':user_id,'quest_slot_index':quest_slot})
.then (questRow) ->
if questRow?
newProgress = questRow.progress || 0
newProgress += 1
return QuestsModule._setQuestProgress(txPromise,tx,questRow,newProgress)
else
return Promise.resolve()
)
return txPromise
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.put '/quests/generated_at', (req, res, next) ->
user_id = req.user.d.id
days_back = req.body.days_back
knex("users").where({'id':user_id}).first("daily_quests_generated_at")
.bind {}
.then (row)->
@.previousGeneratedAt = row.daily_quests_generated_at
@.newGeneratedAtMoment = moment.utc(row.daily_quests_generated_at).subtract(days_back,'days')
@.userRow = row
@.updateData = {
daily_quests_generated_at: @.newGeneratedAtMoment.toDate()
}
knex("users").where({'id':user_id}).update(@.updateData)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return Promise.all([
FirebasePromises.set(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('updated_at'),@.newGeneratedAtMoment.valueOf())
FirebasePromises.set(@.fbRootRef.child("user-quests").child(user_id).child("daily").child("current").child('generated_at'),@.newGeneratedAtMoment.valueOf())
])
.then () ->
res.status(200).json({
generated_at:@.newGeneratedAtMoment.valueOf()
})
router.post '/quests/setup_frostfire_2016', (req, res, next) ->
user_id = req.user.d.id
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",30001).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,moment.utc("2016-12-02"))
.then () ->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,moment.utc("2016-12-02"),101),
QuestsModule.mulliganDailyQuest(user_id,1,moment.utc("2016-12-02"),101)
])
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",0).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",1).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",QuestsModule.SEASONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: 13})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/quests/setup_seasonal_quest', (req, res, next) ->
user_id = req.user.d.id
generateQuestsAt = req.body.generate_quests_at
generateQuestsAtMoment = moment.utc(generateQuestsAt)
sdkQuestForGenerationTime = SDK.QuestFactory.seasonalQuestForMoment(generateQuestsAtMoment)
if not sdkQuestForGenerationTime?
res.status(403).json({message:"No seasonal quest for: " + generateQuestsAtMoment.toString()})
return
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",sdkQuestForGenerationTime.getId()).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,generateQuestsAtMoment)
.then () ->
return Promise.all([
QuestsModule.mulliganDailyQuest(user_id,0,generateQuestsAtMoment,101),
QuestsModule.mulliganDailyQuest(user_id,1,generateQuestsAtMoment,1500)
])
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",0).andWhere("user_id",user_id).update({progress: 3})
knex("user_quests").where("quest_slot_index",1).andWhere("user_id",user_id).update({progress: 7})
knex("user_quests").where("quest_slot_index",QuestsModule.SEASONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: 13})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/quests/setup_promotional_quest', (req, res, next) ->
user_id = req.user.d.id
generateQuestsAt = req.body.generate_quests_at
generateQuestsAtMoment = moment.utc(generateQuestsAt)
sdkQuestForGenerationTime = SDK.QuestFactory.promotionalQuestForMoment(generateQuestsAtMoment)
progressToStartWith = sdkQuestForGenerationTime.params["completionProgress"] - 1
if not sdkQuestForGenerationTime?
res.status(403).json({message:"No promo quest for: " + generateQuestsAtMoment.toString()})
return
Promise.all([
knex("users").where({'id':user_id}).update({
daily_quests_generated_at:null,
daily_quests_updated_at:null,
}),
knex("user_quests").where("user_id",user_id).delete(),
knex("user_quests_complete").where("user_id",user_id).andWhere("quest_type_id",sdkQuestForGenerationTime.getId()).delete()
]).then ()->
return QuestsModule.generateDailyQuests(user_id,generateQuestsAtMoment)
.then () ->
return Promise.all([
knex("user_quests").where("quest_slot_index",QuestsModule.PROMOTIONAL_QUEST_SLOT).andWhere("user_id",user_id).update({progress: progressToStartWith})
])
.then () ->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then () ->
res.status(200).json({})
router.post '/matchmaking/time_series/:division/values', (req, res, next) ->
division = req.params.division
ms = req.body.ms
rankedQueue.matchMade(division,ms)
res.status(200).json({})
router.post '/faction_progression/set_all_win_counts_to_99', (req,res,next)->
user_id = req.user.d.id
knex("user_faction_progression").where('user_id',user_id)
.then (rows)->
all = []
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
Logger.module("QA").log "factionIds ", factionIds
for factionId in factionIds
row = _.find(rows, (r)-> return r.faction_id == factionId)
Logger.module("QA").log "faction #{factionId}", row?.user_id
if row?
all.push knex("user_faction_progression").where({
'user_id':user_id,
'faction_id':row.faction_id
}).update(
'win_count':99
)
return Promise.all(all)
.then ()->
res.status(200).json({})
router.post '/faction_progression/add_level', (req,res,next)->
user_id = req.user.d.id
factionId = req.body.faction_id
if factionId?
knex("user_faction_progression").where({'user_id': user_id, "faction_id": factionId}).first()
.then (factionProgressionRow)->
if !factionProgressionRow?
return UsersModule.createFactionProgressionRecord(user_id,factionId, generatePushId(), SDK.GameType.Ranked)
.then () ->
return knex("user_faction_progression").where({'user_id': user_id, "faction_id": factionId}).first()
.then (factionProgressionRow) ->
if !factionProgressionRow?
return Promise.reject("No row found for faction #{factionId}")
else
currentXP = factionProgressionRow.xp || 0
currentLevel = SDK.FactionProgression.levelForXP(currentXP)
nextLevel = currentLevel + 1
nextLevelXP = SDK.FactionProgression.totalXPForLevel(nextLevel)
deltaXP = nextLevelXP - currentXP
if deltaXP <= 0
return Promise.reject("Cannot increase level for faction #{factionId}, currently at #{currentLevel}")
else
winsNeeded = Math.ceil(deltaXP / SDK.FactionProgression.winXP)
promises = []
for i in [0...winsNeeded]
promises.push(UsersModule.updateUserFactionProgressionWithGameOutcome(user_id, factionId, true, generatePushId(), SDK.GameType.Ranked))
return Promise.all(promises)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.post '/faction_progression/set_all_levels_to_10', (req,res,next)->
user_id = req.user.d.id
knex("user_faction_progression").where('user_id',user_id)
.then (rows)->
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
allPromises = []
for factionId in factionIds
row = _.find(rows, (r)-> return r.faction_id == factionId)
if !row?
allPromises.push(UsersModule.createFactionProgressionRecord(user_id,factionId,generatePushId(),SDK.GameType.SinglePlayer))
return Promise.all(allPromises)
.then () ->
return knex("user_faction_progression").where('user_id',user_id)
.then (factionRows) ->
factionIds = _.map(FactionFactory.getAllPlayableFactions(), (f)-> return f.id)
winsPerFaction = []
for factionId in factionIds
row = _.find(factionRows, (r)-> return r.faction_id == factionId)
if !row?
return Promise.reject("No row found for faction - #{factionId}")
else
factionXp = row.xp
xpForLevelTen = SDK.FactionProgression.levelXPTable[10]
neededXp = xpForLevelTen - factionXp
xpPerWin = SDK.FactionProgression.winXP
if neededXp > 0
neededWins = Math.ceil(neededXp / xpPerWin)
winsPerFaction = winsPerFaction.concat(Array(neededWins).fill(factionId))
return Promise.each(winsPerFaction, (factionId) ->
return UsersModule.updateUserFactionProgressionWithGameOutcome(user_id,factionId,true,generatePushId(),SDK.GameType.Ranked)
)
.then ()->
res.status(200).json({})
.catch (errorMessage) ->
res.status(500).json({message: errorMessage})
router.delete '/gauntlet/current', (req,res,next)->
userId = req.user.d.id
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return Promise.all([
knex("user_gauntlet_run").where('user_id',userId).delete()
FirebasePromises.remove(fbRootRef.child("user-gauntlet-run").child(userId).child("current"))
])
.then () ->
res.status(200).json({})
.catch (error) ->
res.status(403).json({message:error.toString()})
router.delete '/gauntlet/current/general', (req,res,next)->
userId = req.user.d.id
# Get current gauntlet data
knex("user_gauntlet_run").first().where('user_id',userId)
.bind({})
.then (gauntletData) ->
this.gauntletData = gauntletData
if (not gauntletData?)
return Promise.reject(new Error("You are not currently in a Gauntlet Run"))
if (not gauntletData.is_complete)
return Promise.reject(new Error("Current Gauntlet deck is not complete"))
cardIdInGeneralSlot = gauntletData.deck[0]
sdkCard = GameSession.getCardCaches().getCardById(cardIdInGeneralSlot)
if (not sdkCard.getIsGeneral())
return Promise.reject(new Error("Current Gauntlet deck does not have general in expected slot"))
this.newDeck = gauntletData.deck.slice(1)
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
updateData =
deck: this.newDeck
general_id: null
return Promise.all([
knex("user_gauntlet_run").where('user_id',userId).update(updateData)
FirebasePromises.update(fbRootRef.child("user-gauntlet-run").child(userId).child("current"),updateData)
])
.then () ->
res.status(200).json(this.gauntletData)
.catch (error) ->
res.status(403).json({message:error.toString()})
router.post '/gauntlet/progress', (req,res,next)->
userId = req.user.d.id
isWinner = req.body.is_winner
Redis.GameManager.generateGameId()
.then (gameId) ->
GauntletModule.updateArenaRunWithGameOutcome(userId,isWinner,gameId,false)
.then (runData) ->
res.status(200).json(runData)
.catch (error) ->
res.status(403).json({message:error.toString()})
router.post '/gauntlet/fill_deck', (req,res,next)->
userId = req.user.d.id
# Get current gauntlet data
knex("user_gauntlet_run").first().where('user_id',userId)
.then (gauntletData) ->
recursiveSelect = (gauntletData) ->
if !gauntletData? || !gauntletData.card_choices? || !gauntletData.card_choices[0]?
# No more card choices
res.status(200).json(gauntletData)
else
cardIdChoice = null;
if (gauntletData.card_choices?)
cardIdChoice = gauntletData.card_choices[0]
else if (gauntletData.general_choices?)
cardIdChoice = gauntletData.general_choices[0]
GauntletModule.chooseCard(userId,cardIdChoice)
.then (newGauntletData) ->
recursiveSelect(newGauntletData)
recursiveSelect(gauntletData)
.catch (error) ->
res.status(403).json({message:error.message})
router.post '/gift_crate/winter2015', (req,res,next)->
userId = req.user.d.id
txPromise = knex.transaction (tx)->
Promise.all([
tx("user_emotes").where("user_id",userId).andWhere("emote_id",CosmeticsLookup.Emote.OtherSnowChaserHoliday2015).delete()
tx("user_rewards").where("user_id",userId).andWhere("source_id",GiftCrateLookup.WinterHoliday2015).delete()
tx("user_gift_crates").where("user_id",userId).andWhere("crate_type",GiftCrateLookup.WinterHoliday2015).delete()
])
.then ()->
return GiftCrateModule.addGiftCrateToUser(txPromise,tx,userId,GiftCrateLookup.WinterHoliday2015)
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/gift_crate/lag2016', (req,res,next)->
userId = req.user.d.id
txPromise = knex.transaction (tx)->
Promise.all([
tx("user_rewards").where("user_id",userId).andWhere("source_id",GiftCrateLookup.FebruaryLag2016).delete()
tx("user_gift_crates").where("user_id",userId).andWhere("crate_type",GiftCrateLookup.FebruaryLag2016).delete()
])
.then ()->
return GiftCrateModule.addGiftCrateToUser(txPromise,tx,userId,GiftCrateLookup.FebruaryLag2016)
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic_chest/:chest_type', (req,res,next)->
userId = req.user.d.id
chestType = req.params.chest_type
hoursBack = parseInt(req.body.hours_back)
if not hoursBack?
hoursBack = 0
bossId = null
eventId = null
if chestType == SDK.CosmeticsChestTypeLookup.Boss
bossId = SDK.Cards.Boss.Boss3
eventId = "QA-" + generatePushId()
txPromise = knex.transaction (tx)->
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,chestType,bossId,eventId,1,"soft",generatePushId(),moment.utc().subtract(hoursBack,"hours"))
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic_chest_key/:chest_type', (req,res,next)->
userId = req.user.d.id
chestType = req.params.chest_type
txPromise = knex.transaction (tx)->
return CosmeticChestsModule.giveUserChestKey(txPromise,tx,userId,chestType,1,"soft",generatePushId())
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/cosmetic/:cosmetic_id', (req,res,next)->
userId = req.user.d.id
cosmetic_id = req.params.cosmetic_id
txPromise = knex.transaction (tx)->
return InventoryModule.giveUserCosmeticId(txPromise,tx,userId,cosmetic_id,"soft",generatePushId())
.then tx.commit
.catch tx.rollback
return
.then ()->
res.status(200).json({})
router.post '/referrals/events', (req,res,next)->
userId = req.user.d.id
eventType = req.body.event_type
knex("users").where('id',userId).first('referred_by_user_id')
.then (userRow)->
ReferralsModule.processReferralEventForUser(userId,userRow.referred_by_user_id,eventType)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.post '/referrals/mark', (req,res,next)->
userId = req.user.d.id
username = req.body.username
knex("users").where('username',username).first('id')
.then (userRow)->
ReferralsModule.markUserAsReferredByFriend(userId,userRow.id)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.put '/account/reset', (req,res,next)->
userId = req.user.d.id
return SyncModule.wipeUserData(userId)
.then ()->
res.status(200).json({})
.catch (err)->
next(err)
router.post '/daily_challenge', (req,res,next)->
Logger.module("QA").log "Pushing Daily challenge"
challengeName = req.body.challenge_name
challengeDescription = req.body.challenge_description
challengeDifficulty = req.body.challenge_difficulty
challengeGold = 5
challengeJSON = req.body.challenge_json
challengeDate = req.body.challenge_date
challengeInstructions = req.body.challenge_instructions
challengeHint = req.body.challenge_hint
Promise.promisifyAll(zlib)
zlib.gzipAsync(challengeJSON)
.bind({})
.then (gzipGameSessionData) ->
@.gzipGameSessionData = gzipGameSessionData
env = null
if (UtilsEnv.getIsInLocal())
env = "local"
else if (UtilsEnv.getIsInStaging())
env = "staging"
else
return Promise.reject(new Error("Unknown/Invalid ENV for storing Daily Challenge"))
bucket = "duelyst-challenges"
filename = env + "/" + challengeDate + ".json"
@.url = "https://s3-us-west-2.amazonaws.com/" + bucket + "/" + filename
Logger.module("QA").log "Pushing Daily challenge with url #{@.url}"
params =
Bucket: bucket
Key: filename
Body: @.gzipGameSessionData
ACL: 'public-read'
ContentEncoding: "gzip"
ContentType: "text/json"
return s3.putObjectAsync(params)
.then () ->
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.set(fbRootRef.child("daily-challenges").child(challengeDate),{
title: challengeName
description: challengeDescription
gold: challengeGold
difficulty: challengeDifficulty
instructions: challengeInstructions
url: @.url
challenge_id: generatePushId()
hint: challengeHint
})
.then () ->
Logger.module("QA").log "Success Pushing Daily challenge"
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed Pushing Daily challenge\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post "/daily_challenge/completed_at", (req, res, next) ->
user_id = req.user.d.id
completedAtTime = req.body.completed_at
lastCompletedData = {
daily_challenge_last_completed_at: completedAtTime
}
Promise.all([
knex("users").where('id',user_id).update(lastCompletedData),
knex("user_daily_challenges_completed").where('user_id',user_id).delete()
]).then () ->
lastCompletedData = DataAccessHelpers.restifyData(lastCompletedData)
res.status(200).json(lastCompletedData)
.catch (error) ->
Logger.module("QA").log "Failed updating daily challenge completed at\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post "/daily_challenge/passed_qa", (req, res, next) ->
dateKey = req.body.date_key
DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return FirebasePromises.update(@.fbRootRef.child('daily-challenges').child(dateKey),{
isQAReady: true
})
.then () ->
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed marking daily challenge as passing QA\n #{error.toString()}"
res.status(403).json({message:error.toString()})
# Updates the users current s rank rating
router.delete '/user_progression/last_crate_awarded_at', (req,res,next)->
user_id = req.user.d.id
knex("user_progression").where("user_id",user_id).update({
last_crate_awarded_at:null,
last_crate_awarded_game_count:null,
last_crate_awarded_win_count:null,
}).then ()->
res.status(200).json({})
# Resets data for an achievement then marks it as complete
router.post '/achievement/reset_and_complete', (req, res, next) ->
user_id = req.user.d.id
achievement_id = req.body.achievement_id
return knex("user_achievements").where("user_id",user_id).andWhere("achievement_id",achievement_id).delete()
.then ()->
sdkAchievement = SDK.AchievementsFactory.achievementForIdentifier(achievement_id)
if (sdkAchievement == null)
return Promise.reject("No such achievement with id: #{achievement_id}")
achProgressMap = {}
achProgressMap[achievement_id] = sdkAchievement.progressRequired
return AchievementsModule._applyAchievementProgressMapToUser(user_id,achProgressMap)
.then ()->
Logger.module("QA").log "Completed resetting and completing achievement #{achievement_id}"
res.status(200).json({})
.catch (error) ->
Logger.module("QA").log "Failed resetting and completing achievement\n #{error.toString()}"
res.status(403).json({message:error.toString()})
router.post '/migration/prismatic_backfill', (req, res, next) ->
user_id = req.user.d.id
numOrbs = req.body.num_orbs
numOrbs = parseInt(numOrbs)
return knex("users").where('id',user_id).update(
last_session_version: "1.72.0"
).bind {}
.then () ->
timeBeforePrismaticFeatureAddedMoment = moment.utc("2016-07-20 20:00")
return Promise.each([1..numOrbs], (index) ->
return knex("user_spirit_orbs_opened").insert({
id: generatePushId()
user_id: user_id
card_set: SDK.CardSet.Core
transaction_type: "soft"
created_at: timeBeforePrismaticFeatureAddedMoment.toDate()
opened_at: timeBeforePrismaticFeatureAddedMoment.toDate()
cards: [1,1,1,1,1]
})
)
.then ()->
Logger.module("QA").log "Completed setting up prismatic backfill"
res.status(200).json({})
router.delete '/boss_event', (req, res, next) ->
bossEventId = "QA-Boss-Event"
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
return FirebasePromises.remove(fbRootRef.child('boss-events').child(bossEventId))
.then ()->
Logger.module("QA").log "Completed setting up qa boss event"
res.status(200).json({})
router.delete '/boss_event/rewards', (req, res, next) ->
user_id = req.user.d.id
return Promise.all([
knex("user_bosses_defeated").where("user_id",user_id).delete(),
knex("user_cosmetic_chests").where("user_id",user_id).andWhere("chest_type",SDK.CosmeticsChestTypeLookup.Boss).delete(),
knex("user_cosmetic_chests_opened").where("user_id",user_id).andWhere("chest_type",SDK.CosmeticsChestTypeLookup.Boss).delete()
]).then ()->
return SyncModule._syncUserFromSQLToFirebase(user_id)
.then ()->
Logger.module("QA").log "Completed removing user's boss rewards"
res.status(200).json({})
router.put '/boss_event', (req, res, next) ->
adjustedMs = req.body.adjusted_ms
bossId = parseInt(req.body.boss_id)
eventStartMoment = moment.utc().add(adjustedMs,"milliseconds")
bossEventId = "QA-Boss-Event"
bossEventData = {
event_id: bossEventId
boss_id: bossId
event_start: eventStartMoment.valueOf()
event_end: eventStartMoment.clone().add(1,"week").valueOf()
valid_end: eventStartMoment.clone().add(1,"week").add(1,"hour").valueOf()
}
return DuelystFirebase.connect().getRootRef()
.bind {}
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
return FirebasePromises.remove(@.fbRootRef.child('boss-events').child(bossEventId))
.then () ->
return FirebasePromises.set(@.fbRootRef.child('boss-events').child(bossEventId),bossEventData)
.then ()->
Logger.module("QA").log "Completed setting up qa boss event"
res.status(200).json({})
router.put '/rift/duplicates', (req, res, next) ->
user_id = req.user.d.id
return knex("user_rift_runs").select().where('user_id', user_id)
.then (riftRuns) ->
return Promise.each(riftRuns, (riftRun) ->
if riftRun.card_choices?
return knex("user_rift_runs").where('ticket_id', riftRun.ticket_id).update({
card_choices: [11088, 20076, 11087, 11087, 20209, 11052]
})
else
return Promise.resolve()
)
.then ()->
res.status(200).json({})
# router.put '/premium_currency/amount', (req, res, next) ->
# user_id = req.user.d.id
# amount = parseInt(req.body.amount)
# amountPromise = null
# txPromise = knex.transaction (tx)->
# if (amount < 0)
# return ShopModule.debitUserPremiumCurrency(txPromise,tx,user_id,amount,generatePushId(),"qa tool gift")
# else
# return ShopModule.creditUserPremiumCurrency(txPromise,tx,user_id,amount,generatePushId(),"qa tool gift")
# .then ()->
# res.status(200).json({})
router.get '/shop/charge_log', (req, res, next) ->
user_id = req.user.d.id
return knex("user_charges").select().where('user_id',user_id)
.then (userChargeRows)->
res.status(200).json({userChargeRows:userChargeRows})
module.exports = router
|
[
{
"context": "ce, \"showModal\"\n\t\t\tthis.item =\n\t\t\t\tdisplay_name: \"Display Name\"\n\t\t\tthis.name = \"name\"\n\t\t\treturn\n\t\tit \"if name is",
"end": 1405,
"score": 0.9962601065635681,
"start": 1393,
"tag": "NAME",
"value": "Display Name"
},
{
"context": "\n\t\t\t\tdispl... | spec/services/modalServiceSpec.coffee | jimmynguyen/tracker | 0 | describe "ModalServiceTest", ->
beforeEach ->
angular.mock.module "app.services"
angular.mock.inject (ModalService, _keys_, CacheService, _$uibModal_) ->
this.modalService = ModalService
this.keys = _keys_
this.cacheService = CacheService
this.$uibModal = _$uibModal_
return
return
###
ModalService.show
###
describe "when ModalService.show()", ->
it "if valid, then show modal", ->
spyOn this.$uibModal, "open"
.and.returnValue
result: null
this.modalService.show {}, {}
expect this.$uibModal.open
.toHaveBeenCalled()
return
return
###
ModalService.showModal
###
describe "when ModalService.showModal()", ->
beforeEach ->
spyOn this.modalService, "show"
return
it "if invalid customModalDefaults, then show modal", ->
this.modalService.showModal null, {}
expect this.modalService.show
.toHaveBeenCalled()
return
it "if invalid customModalOptions, then show modal", ->
this.modalService.showModal {}, null
expect this.modalService.show
.toHaveBeenCalled()
return
it "if valid, then show modal", ->
this.modalService.showModal {}, {}
expect this.modalService.show
.toHaveBeenCalled()
return
return
###
ModalService.showDeleteModal
###
describe "when ModalService.showDeleteModal()", ->
beforeEach ->
spyOn this.modalService, "showModal"
this.item =
display_name: "Display Name"
this.name = "name"
return
it "if name is invalid, then throw error", ->
expect this.modalService.showDeleteModal
.toThrowError "\"name\" cannot be undefined"
return
it "if item is invalid, then show delete modal", ->
this.modalService.showDeleteModal null, this.name
expect this.modalService.showModal
.toHaveBeenCalled()
return
it "if valid, then show delete modal", ->
this.modalService.showDeleteModal this.item, this.name
expect this.modalService.showModal
.toHaveBeenCalled()
return
return
###
ModalService.showAddEditModal
###
describe "when ModalService.showAddEditModal()", ->
beforeEach ->
spyOn this.cacheService, "get"
spyOn this.modalService, "showModal"
return
it "if valid, then show add/edit modal", ->
this.modalService.showAddEditModal()
expect this.cacheService.get
.toHaveBeenCalledWith this.keys.app.dataTypeIdMap
expect this.modalService.showModal
.toHaveBeenCalled()
return
return
return
| 182893 | describe "ModalServiceTest", ->
beforeEach ->
angular.mock.module "app.services"
angular.mock.inject (ModalService, _keys_, CacheService, _$uibModal_) ->
this.modalService = ModalService
this.keys = _keys_
this.cacheService = CacheService
this.$uibModal = _$uibModal_
return
return
###
ModalService.show
###
describe "when ModalService.show()", ->
it "if valid, then show modal", ->
spyOn this.$uibModal, "open"
.and.returnValue
result: null
this.modalService.show {}, {}
expect this.$uibModal.open
.toHaveBeenCalled()
return
return
###
ModalService.showModal
###
describe "when ModalService.showModal()", ->
beforeEach ->
spyOn this.modalService, "show"
return
it "if invalid customModalDefaults, then show modal", ->
this.modalService.showModal null, {}
expect this.modalService.show
.toHaveBeenCalled()
return
it "if invalid customModalOptions, then show modal", ->
this.modalService.showModal {}, null
expect this.modalService.show
.toHaveBeenCalled()
return
it "if valid, then show modal", ->
this.modalService.showModal {}, {}
expect this.modalService.show
.toHaveBeenCalled()
return
return
###
ModalService.showDeleteModal
###
describe "when ModalService.showDeleteModal()", ->
beforeEach ->
spyOn this.modalService, "showModal"
this.item =
display_name: "<NAME>"
this.name = "<NAME>"
return
it "if name is invalid, then throw error", ->
expect this.modalService.showDeleteModal
.toThrowError "\"name\" cannot be undefined"
return
it "if item is invalid, then show delete modal", ->
this.modalService.showDeleteModal null, this.name
expect this.modalService.showModal
.toHaveBeenCalled()
return
it "if valid, then show delete modal", ->
this.modalService.showDeleteModal this.item, this.name
expect this.modalService.showModal
.toHaveBeenCalled()
return
return
###
ModalService.showAddEditModal
###
describe "when ModalService.showAddEditModal()", ->
beforeEach ->
spyOn this.cacheService, "get"
spyOn this.modalService, "showModal"
return
it "if valid, then show add/edit modal", ->
this.modalService.showAddEditModal()
expect this.cacheService.get
.toHaveBeenCalledWith this.keys.app.dataTypeIdMap
expect this.modalService.showModal
.toHaveBeenCalled()
return
return
return
| true | describe "ModalServiceTest", ->
beforeEach ->
angular.mock.module "app.services"
angular.mock.inject (ModalService, _keys_, CacheService, _$uibModal_) ->
this.modalService = ModalService
this.keys = _keys_
this.cacheService = CacheService
this.$uibModal = _$uibModal_
return
return
###
ModalService.show
###
describe "when ModalService.show()", ->
it "if valid, then show modal", ->
spyOn this.$uibModal, "open"
.and.returnValue
result: null
this.modalService.show {}, {}
expect this.$uibModal.open
.toHaveBeenCalled()
return
return
###
ModalService.showModal
###
describe "when ModalService.showModal()", ->
beforeEach ->
spyOn this.modalService, "show"
return
it "if invalid customModalDefaults, then show modal", ->
this.modalService.showModal null, {}
expect this.modalService.show
.toHaveBeenCalled()
return
it "if invalid customModalOptions, then show modal", ->
this.modalService.showModal {}, null
expect this.modalService.show
.toHaveBeenCalled()
return
it "if valid, then show modal", ->
this.modalService.showModal {}, {}
expect this.modalService.show
.toHaveBeenCalled()
return
return
###
ModalService.showDeleteModal
###
describe "when ModalService.showDeleteModal()", ->
beforeEach ->
spyOn this.modalService, "showModal"
this.item =
display_name: "PI:NAME:<NAME>END_PI"
this.name = "PI:NAME:<NAME>END_PI"
return
it "if name is invalid, then throw error", ->
expect this.modalService.showDeleteModal
.toThrowError "\"name\" cannot be undefined"
return
it "if item is invalid, then show delete modal", ->
this.modalService.showDeleteModal null, this.name
expect this.modalService.showModal
.toHaveBeenCalled()
return
it "if valid, then show delete modal", ->
this.modalService.showDeleteModal this.item, this.name
expect this.modalService.showModal
.toHaveBeenCalled()
return
return
###
ModalService.showAddEditModal
###
describe "when ModalService.showAddEditModal()", ->
beforeEach ->
spyOn this.cacheService, "get"
spyOn this.modalService, "showModal"
return
it "if valid, then show add/edit modal", ->
this.modalService.showAddEditModal()
expect this.cacheService.get
.toHaveBeenCalledWith this.keys.app.dataTypeIdMap
expect this.modalService.showModal
.toHaveBeenCalled()
return
return
return
|
[
{
"context": "_x: ->\n @x = @x + 1\n\n person: ->\n [{name: 'Joe'}, {name: 'Jack'}]\n\n people: ->\n ['Andy', 'Fr",
"end": 903,
"score": 0.9997153282165527,
"start": 900,
"tag": "NAME",
"value": "Joe"
},
{
"context": " @x + 1\n\n person: ->\n [{name: 'Joe'}, {name: 'Ja... | test/context.coffee | estum/skim | 40 | class Context
constructor: ->
@var = 'instance'
@x = 0
id_helper: ->
"notice"
hash: ->
a: 'The letter a', b: 'The letter b'
show_first: (show = false) ->
show
define_macro: (name, block) ->
@macro ||= {}
@macro[name] = block
''
call_macro: (name, args...) ->
@macro[name](args...)
hello_world: (text = "Hello World from @env", opts = {}) ->
text + ("#{key} #{value}" for key, value of opts).join(" ")
callback: (text, block) ->
if block
"#{text} #{block()} #{text}"
else
text
message: (args...) ->
args.join(' ')
action_path: (args...) ->
"/action-#{args.join('-')}"
in_keyword: ->
"starts with keyword"
evil_method: ->
"<script>do_something_evil();</script>"
method_which_returns_true: ->
true
output_number: ->
1337
succ_x: ->
@x = @x + 1
person: ->
[{name: 'Joe'}, {name: 'Jack'}]
people: ->
['Andy', 'Fred', 'Daniel'].map (n) -> new Person(n)
cities: ->
['Atlanta', 'Melbourne', 'Karlsruhe']
people_with_locations: ->
@people().map (p, i) =>
p.location = new Location(@cities()[i])
p
constant_object: ->
@_constant_object ||= {a: 1, b: 2}
constant_object_size: ->
i = 0
i++ for k, v of @constant_object()
i
class Person
constructor: (@_name) ->
name: => @_name
city: => @location.city()
class Location
constructor: (@_city) ->
city: => @_city
| 68587 | class Context
constructor: ->
@var = 'instance'
@x = 0
id_helper: ->
"notice"
hash: ->
a: 'The letter a', b: 'The letter b'
show_first: (show = false) ->
show
define_macro: (name, block) ->
@macro ||= {}
@macro[name] = block
''
call_macro: (name, args...) ->
@macro[name](args...)
hello_world: (text = "Hello World from @env", opts = {}) ->
text + ("#{key} #{value}" for key, value of opts).join(" ")
callback: (text, block) ->
if block
"#{text} #{block()} #{text}"
else
text
message: (args...) ->
args.join(' ')
action_path: (args...) ->
"/action-#{args.join('-')}"
in_keyword: ->
"starts with keyword"
evil_method: ->
"<script>do_something_evil();</script>"
method_which_returns_true: ->
true
output_number: ->
1337
succ_x: ->
@x = @x + 1
person: ->
[{name: '<NAME>'}, {name: '<NAME>'}]
people: ->
['<NAME>', '<NAME>', '<NAME>'].map (n) -> new Person(n)
cities: ->
['Atlanta', 'Melbourne', 'Karlsruhe']
people_with_locations: ->
@people().map (p, i) =>
p.location = new Location(@cities()[i])
p
constant_object: ->
@_constant_object ||= {a: 1, b: 2}
constant_object_size: ->
i = 0
i++ for k, v of @constant_object()
i
class Person
constructor: (@_name) ->
name: => @_name
city: => @location.city()
class Location
constructor: (@_city) ->
city: => @_city
| true | class Context
constructor: ->
@var = 'instance'
@x = 0
id_helper: ->
"notice"
hash: ->
a: 'The letter a', b: 'The letter b'
show_first: (show = false) ->
show
define_macro: (name, block) ->
@macro ||= {}
@macro[name] = block
''
call_macro: (name, args...) ->
@macro[name](args...)
hello_world: (text = "Hello World from @env", opts = {}) ->
text + ("#{key} #{value}" for key, value of opts).join(" ")
callback: (text, block) ->
if block
"#{text} #{block()} #{text}"
else
text
message: (args...) ->
args.join(' ')
action_path: (args...) ->
"/action-#{args.join('-')}"
in_keyword: ->
"starts with keyword"
evil_method: ->
"<script>do_something_evil();</script>"
method_which_returns_true: ->
true
output_number: ->
1337
succ_x: ->
@x = @x + 1
person: ->
[{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}]
people: ->
['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'].map (n) -> new Person(n)
cities: ->
['Atlanta', 'Melbourne', 'Karlsruhe']
people_with_locations: ->
@people().map (p, i) =>
p.location = new Location(@cities()[i])
p
constant_object: ->
@_constant_object ||= {a: 1, b: 2}
constant_object_size: ->
i = 0
i++ for k, v of @constant_object()
i
class Person
constructor: (@_name) ->
name: => @_name
city: => @location.city()
class Location
constructor: (@_city) ->
city: => @_city
|
[
{
"context": "###\n backbone-sql.js 0.5.7\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql\n Lice",
"end": 57,
"score": 0.9990986585617065,
"start": 49,
"tag": "NAME",
"value": "Vidigami"
},
{
"context": " Copyright (c) 2013 Vidigami - https://github.com/vi... | src/database_tools.coffee | michaelBenin/backbone-sql | 1 | ###
backbone-sql.js 0.5.7
Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-sql
License: MIT (http://www.opensource.org/licenses/mit-license.php)
###
_ = require 'underscore'
inflection = require 'inflection'
Knex = require 'knex'
Queue = require 'backbone-orm/lib/queue'
KNEX_COLUMN_OPERATORS = ['indexed', 'nullable', 'unique']
KNEX_COLUMN_OPTIONS = ['textType', 'length', 'precision', 'scale', 'value', 'values']
module.exports = class DatabaseTools
constructor: (@connection, @table_name, @schema, options={}) ->
@strict = options.strict ? true
@join_table_operations = []
@reset()
reset: =>
@promise = @table = null
return @
end: (callback) =>
unless @promise
return callback(new Error('end() called with no operations in progress, call createTable or editTable first')) if @strict
return callback()
@promise.exec (err) =>
# Always reset state
@reset()
return callback(err) if err
if @join_table_operations.length
queue = new Queue(1)
for join_table_fn in @join_table_operations
do (join_table_fn) => queue.defer (callback) =>
join_table_fn(callback)
queue.await (err) =>
@join_table_operations = []
callback(err)
else
callback()
# Create and edit table methods create a knex table instance and promise
# Operations are carried out (ie the promise is resolved) when end() is called
createTable: =>
if @promise and @table
throw Error("Table operation on #{@table_name} already in progress, call end() first") if @strict
return @
@promise = @connection.knex().schema.createTable(@table_name, (t) => @table = t)
return @
editTable: =>
if @promise and @table
throw Error("Table operation on #{@table_name} already in progress, call end() first") if @strict
return @
@promise = @connection.knex().schema.table(@table_name, (t) => @table = t)
return @
addField: (key, field) =>
@editTable() unless @table
type = "#{field.type[0].toLowerCase()}#{field.type.slice(1)}"
@addColumn(key, type, field)
return @
addIDColumn: =>
@addColumn('id', 'increments', ['primary'])
addColumn: (key, type, options={}) =>
@editTable() unless @table
column_args = [key]
# Assign column specific arguments
constructor_options = _.pick(options, KNEX_COLUMN_OPTIONS)
unless _.isEmpty(constructor_options)
# Special case as they take two args
if type in ['float', 'decimal']
column_args[1] = constructor_options['precision']
column_args[2] = constructor_options['scale']
# Assume we've been given one valid argument
else
column_args[1] = _.values(constructor_options)[0]
column = @table[type].apply(@table, column_args)
knex_methods = []
knex_methods.push['notNullable'] if options.nullable is false
knex_methods.push('index') if options.indexed
knex_methods.push('unique') if options.unique
column[method]() for method in knex_methods
return @
addRelation: (key, relation) =>
@editTable() unless @table
return if relation.isVirtual() # skip virtual
if relation.type is 'belongsTo'
@addColumn(relation.foreign_key, 'integer', ['nullable', 'index'])
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
@join_table_operations.push((callback) -> relation.findOrGenerateJoinTable().db().ensureSchema(callback))
return @
resetRelation: (key, relation) =>
@editTable() unless @table
return if relation.isVirtual() # skip virtual
if relation.type is 'belongsTo'
@addColumn(relation.foreign_key, 'integer', ['nullable', 'index'])
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
@join_table_operations.push((callback) -> relation.findOrGenerateJoinTable().resetSchema(callback))
return @
resetSchema: (options, callback) =>
(callback = options; options = {}) if arguments.length is 1
@connection.knex().schema.dropTableIfExists(@table_name).exec (err) =>
return callback(err) if err
@createTable()
console.log "Creating table: #{@table_name} with fields: '#{_.keys(@schema.fields).join(', ')}' and relations: '#{_.keys(@schema.relations).join(', ')}'" if options.verbose
@addIDColumn()
@addField(key, field) for key, field of @schema.fields
@resetRelation(key, relation) for key, relation of @schema.relations
@end(callback)
# Ensure that the schema is reflected correctly in the database
# Will create a table and add columns as required
# Will not remove columns
ensureSchema: (options, callback) =>
(callback = options; options = {}) if arguments.length is 1
return callback() if @ensuring
@ensuring = true
@hasTable (err, table_exists) =>
(@ensuring = false; return callback(err)) if err
console.log "Ensuring table: #{@table_name} with fields: '#{_.keys(@schema.fields).join(', ')}' and relations: '#{_.keys(@schema.relations).join(', ')}'" if options.verbose
unless table_exists
@createTable()
@addIDColumn()
@end (err) =>
(@ensuring = false; return callback(err)) if err
return @ensureSchemaForExistingTable(options, (err) => @ensuring = false; callback(err))
else
return @ensureSchemaForExistingTable(options, (err) => @ensuring = false; callback(err))
# Should only be called once the table exists - can't do column checks unless the table has been created
# Should only be called by @ensureSchema, sets @ensuring to false when complete
ensureSchemaForExistingTable: (options, callback) =>
@editTable()
queue = new Queue(1)
queue.defer (callback) => @ensureColumn('id', 'increments', ['primary'], callback)
if @schema.fields
for key, field of @schema.fields
do (key, field) => queue.defer (callback) =>
@ensureField(key, field, callback)
if @schema.relations
for key, relation of @schema.relations
do (key, relation) => queue.defer (callback) =>
@ensureRelation(key, relation, callback)
queue.await (err) =>
return callback(err) if err
@end(callback)
ensureRelation: (key, relation, callback) =>
if relation.type is 'belongsTo'
@hasColumn relation.foreign_key, (err, column_exists) =>
return callback(err) if err
@addRelation(key, relation) unless column_exists
callback()
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
relation.findOrGenerateJoinTable().db().ensureSchema(callback)
else
callback()
ensureField: (key, field, callback) =>
@hasColumn key, (err, column_exists) =>
return callback(err) if err
@addField(key, field) unless column_exists
callback()
ensureColumn: (key, type, options, callback) =>
@editTable() unless @table
@hasColumn key, (err, column_exists) =>
return callback(err) if err
@addColumn(key, type, options) unless column_exists
callback()
# knex method wrappers
hasColumn: (column, callback) => @connection.knex().schema.hasColumn(@table_name, column).exec callback
hasTable: (callback) => @connection.knex().schema.hasTable(@table_name).exec callback
dropTable: (callback) => @connection.knex().schema.dropTable(@table_name).exec callback
dropTableIfExists: (callback) => @connection.knex().schema.dropTableIfExists(@table_name).exec callback
renameTable: (to, callback) => @connection.knex().schema.renameTable(@table_name, to).exec callback
| 16549 | ###
backbone-sql.js 0.5.7
Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-sql
License: MIT (http://www.opensource.org/licenses/mit-license.php)
###
_ = require 'underscore'
inflection = require 'inflection'
Knex = require 'knex'
Queue = require 'backbone-orm/lib/queue'
KNEX_COLUMN_OPERATORS = ['indexed', 'nullable', 'unique']
KNEX_COLUMN_OPTIONS = ['textType', 'length', 'precision', 'scale', 'value', 'values']
module.exports = class DatabaseTools
constructor: (@connection, @table_name, @schema, options={}) ->
@strict = options.strict ? true
@join_table_operations = []
@reset()
reset: =>
@promise = @table = null
return @
end: (callback) =>
unless @promise
return callback(new Error('end() called with no operations in progress, call createTable or editTable first')) if @strict
return callback()
@promise.exec (err) =>
# Always reset state
@reset()
return callback(err) if err
if @join_table_operations.length
queue = new Queue(1)
for join_table_fn in @join_table_operations
do (join_table_fn) => queue.defer (callback) =>
join_table_fn(callback)
queue.await (err) =>
@join_table_operations = []
callback(err)
else
callback()
# Create and edit table methods create a knex table instance and promise
# Operations are carried out (ie the promise is resolved) when end() is called
createTable: =>
if @promise and @table
throw Error("Table operation on #{@table_name} already in progress, call end() first") if @strict
return @
@promise = @connection.knex().schema.createTable(@table_name, (t) => @table = t)
return @
editTable: =>
if @promise and @table
throw Error("Table operation on #{@table_name} already in progress, call end() first") if @strict
return @
@promise = @connection.knex().schema.table(@table_name, (t) => @table = t)
return @
addField: (key, field) =>
@editTable() unless @table
type = "#{field.type[0].toLowerCase()}#{field.type.slice(1)}"
@addColumn(key, type, field)
return @
addIDColumn: =>
@addColumn('id', 'increments', ['primary'])
addColumn: (key, type, options={}) =>
@editTable() unless @table
column_args = [key]
# Assign column specific arguments
constructor_options = _.pick(options, KNEX_COLUMN_OPTIONS)
unless _.isEmpty(constructor_options)
# Special case as they take two args
if type in ['float', 'decimal']
column_args[1] = constructor_options['precision']
column_args[2] = constructor_options['scale']
# Assume we've been given one valid argument
else
column_args[1] = _.values(constructor_options)[0]
column = @table[type].apply(@table, column_args)
knex_methods = []
knex_methods.push['notNullable'] if options.nullable is false
knex_methods.push('index') if options.indexed
knex_methods.push('unique') if options.unique
column[method]() for method in knex_methods
return @
addRelation: (key, relation) =>
@editTable() unless @table
return if relation.isVirtual() # skip virtual
if relation.type is 'belongsTo'
@addColumn(relation.foreign_key, 'integer', ['nullable', 'index'])
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
@join_table_operations.push((callback) -> relation.findOrGenerateJoinTable().db().ensureSchema(callback))
return @
resetRelation: (key, relation) =>
@editTable() unless @table
return if relation.isVirtual() # skip virtual
if relation.type is 'belongsTo'
@addColumn(relation.foreign_key, 'integer', ['nullable', 'index'])
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
@join_table_operations.push((callback) -> relation.findOrGenerateJoinTable().resetSchema(callback))
return @
resetSchema: (options, callback) =>
(callback = options; options = {}) if arguments.length is 1
@connection.knex().schema.dropTableIfExists(@table_name).exec (err) =>
return callback(err) if err
@createTable()
console.log "Creating table: #{@table_name} with fields: '#{_.keys(@schema.fields).join(', ')}' and relations: '#{_.keys(@schema.relations).join(', ')}'" if options.verbose
@addIDColumn()
@addField(key, field) for key, field of @schema.fields
@resetRelation(key, relation) for key, relation of @schema.relations
@end(callback)
# Ensure that the schema is reflected correctly in the database
# Will create a table and add columns as required
# Will not remove columns
ensureSchema: (options, callback) =>
(callback = options; options = {}) if arguments.length is 1
return callback() if @ensuring
@ensuring = true
@hasTable (err, table_exists) =>
(@ensuring = false; return callback(err)) if err
console.log "Ensuring table: #{@table_name} with fields: '#{_.keys(@schema.fields).join(', ')}' and relations: '#{_.keys(@schema.relations).join(', ')}'" if options.verbose
unless table_exists
@createTable()
@addIDColumn()
@end (err) =>
(@ensuring = false; return callback(err)) if err
return @ensureSchemaForExistingTable(options, (err) => @ensuring = false; callback(err))
else
return @ensureSchemaForExistingTable(options, (err) => @ensuring = false; callback(err))
# Should only be called once the table exists - can't do column checks unless the table has been created
# Should only be called by @ensureSchema, sets @ensuring to false when complete
ensureSchemaForExistingTable: (options, callback) =>
@editTable()
queue = new Queue(1)
queue.defer (callback) => @ensureColumn('id', 'increments', ['primary'], callback)
if @schema.fields
for key, field of @schema.fields
do (key, field) => queue.defer (callback) =>
@ensureField(key, field, callback)
if @schema.relations
for key, relation of @schema.relations
do (key, relation) => queue.defer (callback) =>
@ensureRelation(key, relation, callback)
queue.await (err) =>
return callback(err) if err
@end(callback)
ensureRelation: (key, relation, callback) =>
if relation.type is 'belongsTo'
@hasColumn relation.foreign_key, (err, column_exists) =>
return callback(err) if err
@addRelation(key, relation) unless column_exists
callback()
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
relation.findOrGenerateJoinTable().db().ensureSchema(callback)
else
callback()
ensureField: (key, field, callback) =>
@hasColumn key, (err, column_exists) =>
return callback(err) if err
@addField(key, field) unless column_exists
callback()
ensureColumn: (key, type, options, callback) =>
@editTable() unless @table
@hasColumn key, (err, column_exists) =>
return callback(err) if err
@addColumn(key, type, options) unless column_exists
callback()
# knex method wrappers
hasColumn: (column, callback) => @connection.knex().schema.hasColumn(@table_name, column).exec callback
hasTable: (callback) => @connection.knex().schema.hasTable(@table_name).exec callback
dropTable: (callback) => @connection.knex().schema.dropTable(@table_name).exec callback
dropTableIfExists: (callback) => @connection.knex().schema.dropTableIfExists(@table_name).exec callback
renameTable: (to, callback) => @connection.knex().schema.renameTable(@table_name, to).exec callback
| true | ###
backbone-sql.js 0.5.7
Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-sql
License: MIT (http://www.opensource.org/licenses/mit-license.php)
###
_ = require 'underscore'
inflection = require 'inflection'
Knex = require 'knex'
Queue = require 'backbone-orm/lib/queue'
KNEX_COLUMN_OPERATORS = ['indexed', 'nullable', 'unique']
KNEX_COLUMN_OPTIONS = ['textType', 'length', 'precision', 'scale', 'value', 'values']
module.exports = class DatabaseTools
constructor: (@connection, @table_name, @schema, options={}) ->
@strict = options.strict ? true
@join_table_operations = []
@reset()
reset: =>
@promise = @table = null
return @
end: (callback) =>
unless @promise
return callback(new Error('end() called with no operations in progress, call createTable or editTable first')) if @strict
return callback()
@promise.exec (err) =>
# Always reset state
@reset()
return callback(err) if err
if @join_table_operations.length
queue = new Queue(1)
for join_table_fn in @join_table_operations
do (join_table_fn) => queue.defer (callback) =>
join_table_fn(callback)
queue.await (err) =>
@join_table_operations = []
callback(err)
else
callback()
# Create and edit table methods create a knex table instance and promise
# Operations are carried out (ie the promise is resolved) when end() is called
createTable: =>
if @promise and @table
throw Error("Table operation on #{@table_name} already in progress, call end() first") if @strict
return @
@promise = @connection.knex().schema.createTable(@table_name, (t) => @table = t)
return @
editTable: =>
if @promise and @table
throw Error("Table operation on #{@table_name} already in progress, call end() first") if @strict
return @
@promise = @connection.knex().schema.table(@table_name, (t) => @table = t)
return @
addField: (key, field) =>
@editTable() unless @table
type = "#{field.type[0].toLowerCase()}#{field.type.slice(1)}"
@addColumn(key, type, field)
return @
addIDColumn: =>
@addColumn('id', 'increments', ['primary'])
addColumn: (key, type, options={}) =>
@editTable() unless @table
column_args = [key]
# Assign column specific arguments
constructor_options = _.pick(options, KNEX_COLUMN_OPTIONS)
unless _.isEmpty(constructor_options)
# Special case as they take two args
if type in ['float', 'decimal']
column_args[1] = constructor_options['precision']
column_args[2] = constructor_options['scale']
# Assume we've been given one valid argument
else
column_args[1] = _.values(constructor_options)[0]
column = @table[type].apply(@table, column_args)
knex_methods = []
knex_methods.push['notNullable'] if options.nullable is false
knex_methods.push('index') if options.indexed
knex_methods.push('unique') if options.unique
column[method]() for method in knex_methods
return @
addRelation: (key, relation) =>
@editTable() unless @table
return if relation.isVirtual() # skip virtual
if relation.type is 'belongsTo'
@addColumn(relation.foreign_key, 'integer', ['nullable', 'index'])
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
@join_table_operations.push((callback) -> relation.findOrGenerateJoinTable().db().ensureSchema(callback))
return @
resetRelation: (key, relation) =>
@editTable() unless @table
return if relation.isVirtual() # skip virtual
if relation.type is 'belongsTo'
@addColumn(relation.foreign_key, 'integer', ['nullable', 'index'])
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
@join_table_operations.push((callback) -> relation.findOrGenerateJoinTable().resetSchema(callback))
return @
resetSchema: (options, callback) =>
(callback = options; options = {}) if arguments.length is 1
@connection.knex().schema.dropTableIfExists(@table_name).exec (err) =>
return callback(err) if err
@createTable()
console.log "Creating table: #{@table_name} with fields: '#{_.keys(@schema.fields).join(', ')}' and relations: '#{_.keys(@schema.relations).join(', ')}'" if options.verbose
@addIDColumn()
@addField(key, field) for key, field of @schema.fields
@resetRelation(key, relation) for key, relation of @schema.relations
@end(callback)
# Ensure that the schema is reflected correctly in the database
# Will create a table and add columns as required
# Will not remove columns
ensureSchema: (options, callback) =>
(callback = options; options = {}) if arguments.length is 1
return callback() if @ensuring
@ensuring = true
@hasTable (err, table_exists) =>
(@ensuring = false; return callback(err)) if err
console.log "Ensuring table: #{@table_name} with fields: '#{_.keys(@schema.fields).join(', ')}' and relations: '#{_.keys(@schema.relations).join(', ')}'" if options.verbose
unless table_exists
@createTable()
@addIDColumn()
@end (err) =>
(@ensuring = false; return callback(err)) if err
return @ensureSchemaForExistingTable(options, (err) => @ensuring = false; callback(err))
else
return @ensureSchemaForExistingTable(options, (err) => @ensuring = false; callback(err))
# Should only be called once the table exists - can't do column checks unless the table has been created
# Should only be called by @ensureSchema, sets @ensuring to false when complete
ensureSchemaForExistingTable: (options, callback) =>
@editTable()
queue = new Queue(1)
queue.defer (callback) => @ensureColumn('id', 'increments', ['primary'], callback)
if @schema.fields
for key, field of @schema.fields
do (key, field) => queue.defer (callback) =>
@ensureField(key, field, callback)
if @schema.relations
for key, relation of @schema.relations
do (key, relation) => queue.defer (callback) =>
@ensureRelation(key, relation, callback)
queue.await (err) =>
return callback(err) if err
@end(callback)
ensureRelation: (key, relation, callback) =>
if relation.type is 'belongsTo'
@hasColumn relation.foreign_key, (err, column_exists) =>
return callback(err) if err
@addRelation(key, relation) unless column_exists
callback()
else if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany'
relation.findOrGenerateJoinTable().db().ensureSchema(callback)
else
callback()
ensureField: (key, field, callback) =>
@hasColumn key, (err, column_exists) =>
return callback(err) if err
@addField(key, field) unless column_exists
callback()
ensureColumn: (key, type, options, callback) =>
@editTable() unless @table
@hasColumn key, (err, column_exists) =>
return callback(err) if err
@addColumn(key, type, options) unless column_exists
callback()
# knex method wrappers
hasColumn: (column, callback) => @connection.knex().schema.hasColumn(@table_name, column).exec callback
hasTable: (callback) => @connection.knex().schema.hasTable(@table_name).exec callback
dropTable: (callback) => @connection.knex().schema.dropTable(@table_name).exec callback
dropTableIfExists: (callback) => @connection.knex().schema.dropTableIfExists(@table_name).exec callback
renameTable: (to, callback) => @connection.knex().schema.renameTable(@table_name, to).exec callback
|
[
{
"context": "-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i\n KEY: /^[A-Z0-9]+$/i\n CHANNEL: /^[#&][^\\x07\\x2C\\s]{0,200}$/ # rfc1459",
"end": 220,
"score": 0.9049139022827148,
"start": 209,
"tag": "KEY",
"value": "A-Z0-9]+$/i"
}
] | src/regex.coffee | fent/ann | 0 | # validating regexps
regex =
NICK: /^[A-Z_\-\[\]\\^{}|`][A-Z0-9_\-\[\]\\^{}|`]*$/i # rfc2812
PASSWORD: /^[^\s]{5,}$/ # checks for white space
EMAIL: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
KEY: /^[A-Z0-9]+$/i
CHANNEL: /^[#&][^\x07\x2C\s]{0,200}$/ # rfc1459
CHANNELPASSWORD: /^[^\s]{1,}$/
makeFun = (name) ->
r = regex[name.toUpperCase()]
module.exports[name] = (s) ->
not r.test s
for i of regex
makeFun i.toLowerCase()
| 136435 | # validating regexps
regex =
NICK: /^[A-Z_\-\[\]\\^{}|`][A-Z0-9_\-\[\]\\^{}|`]*$/i # rfc2812
PASSWORD: /^[^\s]{5,}$/ # checks for white space
EMAIL: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
KEY: /^[<KEY>
CHANNEL: /^[#&][^\x07\x2C\s]{0,200}$/ # rfc1459
CHANNELPASSWORD: /^[^\s]{1,}$/
makeFun = (name) ->
r = regex[name.toUpperCase()]
module.exports[name] = (s) ->
not r.test s
for i of regex
makeFun i.toLowerCase()
| true | # validating regexps
regex =
NICK: /^[A-Z_\-\[\]\\^{}|`][A-Z0-9_\-\[\]\\^{}|`]*$/i # rfc2812
PASSWORD: /^[^\s]{5,}$/ # checks for white space
EMAIL: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
KEY: /^[PI:KEY:<KEY>END_PI
CHANNEL: /^[#&][^\x07\x2C\s]{0,200}$/ # rfc1459
CHANNELPASSWORD: /^[^\s]{1,}$/
makeFun = (name) ->
r = regex[name.toUpperCase()]
module.exports[name] = (s) ->
not r.test s
for i of regex
makeFun i.toLowerCase()
|
[
{
"context": "eaders.location\n location.should.eql 'http://127.0.0.1:7632/tl/OAuthAuthorizeToken?oauth_token=trello_re",
"end": 487,
"score": 0.9995871782302856,
"start": 478,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "127.0.0.1:7632/tl/OAuthAuthorizeToken?oauth... | talk-account/test/apis/unions/trello.coffee | jianwo/jianwo | 0 | should = require 'should'
request = require 'supertest'
jwt = require 'jsonwebtoken'
app = require '../../../server/server'
util = require '../../util'
rq = require 'request'
describe 'Union#Trello', ->
before util.prepare
it 'should redirect to trello account page when visit redirect url', (done) ->
request(app).get '/union/trello'
.end (err, res) ->
res.statusCode.should.eql 302
location = res.headers.location
location.should.eql 'http://127.0.0.1:7632/tl/OAuthAuthorizeToken?oauth_token=trello_request_token_step_1&name=TalkIM'
done()
it 'should create new account with oauth_token and oauth_verifier from trello account api', (done) ->
options =
method: 'POST'
url: '/union/signin/trello'
body:
oauth_token: 'trello_authorize_token_step_2'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'name', 'refer', 'openId', 'accountToken', 'wasNew', 'showname'
user.wasNew.should.eql true
user.name.should.eql 'trello 用户'
user.showname.should.eql '席地'
user.openId.should.eql '1234567'
{_id, login} = jwt.decode user.accountToken
login.should.eql 'trello'
util.user = user
done err
it 'should not bind to an exist trello account', (done) ->
options =
method: 'POST'
url: '/union/bind/trello'
body:
accountToken: util.user.accountToken
oauth_token: 'trello_authorize_token_step_2'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, body) ->
err.message.should.eql '绑定账号已存在'
err.data.should.have.properties 'bindCode'
util.bindCode = err.data.bindCode
done()
it 'should bind to an exist trello account by bindCode', (done) ->
options =
method: 'POST'
url: '/union/forcebind/trello'
body:
accountToken: util.user.accountToken
bindCode: util.bindCode
util.request options, (err, res, user) ->
user.should.have.properties 'accountToken', 'refer', 'openId'
done err
it 'should unbind trello account', (done) ->
options =
method: 'POST'
url: '/union/unbind/trello'
body:
accountToken: util.user.accountToken
util.request options, (err, res, user) ->
user.should.not.have.properties 'refer', 'openId'
done err
it 'should bind trello account again', (done) ->
options =
method: 'POST'
url: '/union/bind/trello'
body:
accountToken: util.user.accountToken
oauth_token: 'trello_authorize_token_step_2'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'refer', 'openId'
done err
it 'should change the trello account', (done) ->
options =
method: 'POST'
url: '/union/change/trello'
body:
accountToken: util.user.accountToken
oauth_token: 'trello_authorize_token_step_2'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'refer', 'openId'
done err
after util.cleanup
| 105455 | should = require 'should'
request = require 'supertest'
jwt = require 'jsonwebtoken'
app = require '../../../server/server'
util = require '../../util'
rq = require 'request'
describe 'Union#Trello', ->
before util.prepare
it 'should redirect to trello account page when visit redirect url', (done) ->
request(app).get '/union/trello'
.end (err, res) ->
res.statusCode.should.eql 302
location = res.headers.location
location.should.eql 'http://127.0.0.1:7632/tl/OAuthAuthorizeToken?oauth_token=<PASSWORD>&name=TalkIM'
done()
it 'should create new account with oauth_token and oauth_verifier from trello account api', (done) ->
options =
method: 'POST'
url: '/union/signin/trello'
body:
oauth_token: '<PASSWORD>'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'name', 'refer', 'openId', 'accountToken', 'wasNew', 'showname'
user.wasNew.should.eql true
user.name.should.eql '<NAME> 用户'
user.showname.should.eql '席地'
user.openId.should.eql '1234567'
{_id, login} = jwt.decode user.accountToken
login.should.eql 'trello'
util.user = user
done err
it 'should not bind to an exist trello account', (done) ->
options =
method: 'POST'
url: '/union/bind/trello'
body:
accountToken: util.user.accountToken
oauth_token: '<PASSWORD>'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, body) ->
err.message.should.eql '绑定账号已存在'
err.data.should.have.properties 'bindCode'
util.bindCode = err.data.bindCode
done()
it 'should bind to an exist trello account by bindCode', (done) ->
options =
method: 'POST'
url: '/union/forcebind/trello'
body:
accountToken: util.user.accountToken
bindCode: util.bindCode
util.request options, (err, res, user) ->
user.should.have.properties 'accountToken', 'refer', 'openId'
done err
it 'should unbind trello account', (done) ->
options =
method: 'POST'
url: '/union/unbind/trello'
body:
accountToken: util.user.accountToken
util.request options, (err, res, user) ->
user.should.not.have.properties 'refer', 'openId'
done err
it 'should bind trello account again', (done) ->
options =
method: 'POST'
url: '/union/bind/trello'
body:
accountToken: util.user.accountToken
oauth_token: '<PASSWORD>'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'refer', 'openId'
done err
it 'should change the trello account', (done) ->
options =
method: 'POST'
url: '/union/change/trello'
body:
accountToken: util.user.accountToken
oauth_token: '<PASSWORD>'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'refer', 'openId'
done err
after util.cleanup
| true | should = require 'should'
request = require 'supertest'
jwt = require 'jsonwebtoken'
app = require '../../../server/server'
util = require '../../util'
rq = require 'request'
describe 'Union#Trello', ->
before util.prepare
it 'should redirect to trello account page when visit redirect url', (done) ->
request(app).get '/union/trello'
.end (err, res) ->
res.statusCode.should.eql 302
location = res.headers.location
location.should.eql 'http://127.0.0.1:7632/tl/OAuthAuthorizeToken?oauth_token=PI:PASSWORD:<PASSWORD>END_PI&name=TalkIM'
done()
it 'should create new account with oauth_token and oauth_verifier from trello account api', (done) ->
options =
method: 'POST'
url: '/union/signin/trello'
body:
oauth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'name', 'refer', 'openId', 'accountToken', 'wasNew', 'showname'
user.wasNew.should.eql true
user.name.should.eql 'PI:NAME:<NAME>END_PI 用户'
user.showname.should.eql '席地'
user.openId.should.eql '1234567'
{_id, login} = jwt.decode user.accountToken
login.should.eql 'trello'
util.user = user
done err
it 'should not bind to an exist trello account', (done) ->
options =
method: 'POST'
url: '/union/bind/trello'
body:
accountToken: util.user.accountToken
oauth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, body) ->
err.message.should.eql '绑定账号已存在'
err.data.should.have.properties 'bindCode'
util.bindCode = err.data.bindCode
done()
it 'should bind to an exist trello account by bindCode', (done) ->
options =
method: 'POST'
url: '/union/forcebind/trello'
body:
accountToken: util.user.accountToken
bindCode: util.bindCode
util.request options, (err, res, user) ->
user.should.have.properties 'accountToken', 'refer', 'openId'
done err
it 'should unbind trello account', (done) ->
options =
method: 'POST'
url: '/union/unbind/trello'
body:
accountToken: util.user.accountToken
util.request options, (err, res, user) ->
user.should.not.have.properties 'refer', 'openId'
done err
it 'should bind trello account again', (done) ->
options =
method: 'POST'
url: '/union/bind/trello'
body:
accountToken: util.user.accountToken
oauth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'refer', 'openId'
done err
it 'should change the trello account', (done) ->
options =
method: 'POST'
url: '/union/change/trello'
body:
accountToken: util.user.accountToken
oauth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
oauth_verifier: 'trello_authorize_verifier_step_2'
util.request options, (err, res, user) ->
user.should.have.properties 'refer', 'openId'
done err
after util.cleanup
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.999378502368927,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-net-binary.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
binaryString = ""
i = 255
while i >= 0
s = "'\\" + i.toString(8) + "'"
S = eval(s)
common.error s + " " + JSON.stringify(S) + " " + JSON.stringify(String.fromCharCode(i)) + " " + S.charCodeAt(0)
assert.ok S.charCodeAt(0) is i
assert.ok S is String.fromCharCode(i)
binaryString += S
i--
# safe constructor
echoServer = net.Server((connection) ->
console.error "SERVER got connection"
connection.setEncoding "binary"
connection.on "data", (chunk) ->
common.error "SERVER recved: " + JSON.stringify(chunk)
connection.write chunk, "binary"
return
connection.on "end", ->
console.error "SERVER ending"
connection.end()
return
return
)
echoServer.listen common.PORT
recv = ""
echoServer.on "listening", ->
console.error "SERVER listening"
j = 0
c = net.createConnection(port: common.PORT)
c.setEncoding "binary"
c.on "data", (chunk) ->
console.error "CLIENT data %j", chunk
n = j + chunk.length
while j < n and j < 256
common.error "CLIENT write " + j
c.write String.fromCharCode(j), "binary"
j++
if j is 256
console.error "CLIENT ending"
c.end()
recv += chunk
return
c.on "connect", ->
console.error "CLIENT connected, writing"
c.write binaryString, "binary"
return
c.on "close", ->
console.error "CLIENT closed"
console.dir recv
echoServer.close()
return
c.on "finish", ->
console.error "CLIENT finished"
return
return
process.on "exit", ->
console.log "recv: " + JSON.stringify(recv)
assert.equal 2 * 256, recv.length
a = recv.split("")
first = a.slice(0, 256).reverse().join("")
console.log "first: " + JSON.stringify(first)
second = a.slice(256, 2 * 256).join("")
console.log "second: " + JSON.stringify(second)
assert.equal first, second
return
| 219188 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
binaryString = ""
i = 255
while i >= 0
s = "'\\" + i.toString(8) + "'"
S = eval(s)
common.error s + " " + JSON.stringify(S) + " " + JSON.stringify(String.fromCharCode(i)) + " " + S.charCodeAt(0)
assert.ok S.charCodeAt(0) is i
assert.ok S is String.fromCharCode(i)
binaryString += S
i--
# safe constructor
echoServer = net.Server((connection) ->
console.error "SERVER got connection"
connection.setEncoding "binary"
connection.on "data", (chunk) ->
common.error "SERVER recved: " + JSON.stringify(chunk)
connection.write chunk, "binary"
return
connection.on "end", ->
console.error "SERVER ending"
connection.end()
return
return
)
echoServer.listen common.PORT
recv = ""
echoServer.on "listening", ->
console.error "SERVER listening"
j = 0
c = net.createConnection(port: common.PORT)
c.setEncoding "binary"
c.on "data", (chunk) ->
console.error "CLIENT data %j", chunk
n = j + chunk.length
while j < n and j < 256
common.error "CLIENT write " + j
c.write String.fromCharCode(j), "binary"
j++
if j is 256
console.error "CLIENT ending"
c.end()
recv += chunk
return
c.on "connect", ->
console.error "CLIENT connected, writing"
c.write binaryString, "binary"
return
c.on "close", ->
console.error "CLIENT closed"
console.dir recv
echoServer.close()
return
c.on "finish", ->
console.error "CLIENT finished"
return
return
process.on "exit", ->
console.log "recv: " + JSON.stringify(recv)
assert.equal 2 * 256, recv.length
a = recv.split("")
first = a.slice(0, 256).reverse().join("")
console.log "first: " + JSON.stringify(first)
second = a.slice(256, 2 * 256).join("")
console.log "second: " + JSON.stringify(second)
assert.equal first, second
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
binaryString = ""
i = 255
while i >= 0
s = "'\\" + i.toString(8) + "'"
S = eval(s)
common.error s + " " + JSON.stringify(S) + " " + JSON.stringify(String.fromCharCode(i)) + " " + S.charCodeAt(0)
assert.ok S.charCodeAt(0) is i
assert.ok S is String.fromCharCode(i)
binaryString += S
i--
# safe constructor
echoServer = net.Server((connection) ->
console.error "SERVER got connection"
connection.setEncoding "binary"
connection.on "data", (chunk) ->
common.error "SERVER recved: " + JSON.stringify(chunk)
connection.write chunk, "binary"
return
connection.on "end", ->
console.error "SERVER ending"
connection.end()
return
return
)
echoServer.listen common.PORT
recv = ""
echoServer.on "listening", ->
console.error "SERVER listening"
j = 0
c = net.createConnection(port: common.PORT)
c.setEncoding "binary"
c.on "data", (chunk) ->
console.error "CLIENT data %j", chunk
n = j + chunk.length
while j < n and j < 256
common.error "CLIENT write " + j
c.write String.fromCharCode(j), "binary"
j++
if j is 256
console.error "CLIENT ending"
c.end()
recv += chunk
return
c.on "connect", ->
console.error "CLIENT connected, writing"
c.write binaryString, "binary"
return
c.on "close", ->
console.error "CLIENT closed"
console.dir recv
echoServer.close()
return
c.on "finish", ->
console.error "CLIENT finished"
return
return
process.on "exit", ->
console.log "recv: " + JSON.stringify(recv)
assert.equal 2 * 256, recv.length
a = recv.split("")
first = a.slice(0, 256).reverse().join("")
console.log "first: " + JSON.stringify(first)
second = a.slice(256, 2 * 256).join("")
console.log "second: " + JSON.stringify(second)
assert.equal first, second
return
|
[
{
"context": " variables.push matched[1]\n dataStorageKey = ['arena-balancer-data', @levelSlug].join(':')\n data = storage.load d",
"end": 2328,
"score": 0.7911399602890015,
"start": 2309,
"tag": "KEY",
"value": "arena-balancer-data"
},
{
"context": "aStorageKey = ['arena-balan... | app/views/artisans/ArenaBalancerView.coffee | cihatislamdede/codecombat | 4,858 | require('app/styles/artisans/arena-balancer-view.sass')
RootView = require 'views/core/RootView'
template = require 'templates/artisans/arena-balancer-view'
Campaigns = require 'collections/Campaigns'
Campaign = require 'models/Campaign'
Levels = require 'collections/Levels'
Level = require 'models/Level'
LevelSessions = require 'collections/LevelSessions'
ace = require 'lib/aceContainer'
aceUtils = require 'core/aceUtils'
require 'lib/setupTreema'
treemaExt = require 'core/treema-ext'
storage = require 'core/storage'
ConfirmModal = require 'views/core/ConfirmModal'
module.exports = class ArenaBalancerView extends RootView
template: template
id: 'arena-balancer-view'
events:
'click #go-button': 'onClickGoButton'
levelSlug: 'infinite-inferno'
constructor: (options, @levelSlug) ->
super options
@getLevelInfo()
afterRender: ->
super()
editorElements = @$el.find('.ace')
for el in editorElements
lang = @$(el).data('language')
editor = ace.edit el
aceSession = editor.getSession()
aceDoc = aceSession.getDocument()
aceSession.setMode aceUtils.aceEditModes[lang]
editor.setTheme 'ace/theme/textmate'
#editor.setReadOnly true
getLevelInfo: () ->
@level = @supermodel.getModel(Level, @levelSlug) or new Level _id: @levelSlug
@supermodel.trackRequest @level.fetch()
@level.on 'error', (@level, error) =>
return @errorMessage = "Error loading level: #{error.statusText}"
if @level.loaded
@onLevelLoaded @level
else
@listenToOnce @level, 'sync', @onLevelLoaded
onLevelLoaded: (level) ->
solutions = []
hero = _.find level.get("thangs") ? [], id: 'Hero Placeholder'
plan = _.find(hero?.components ? [], (x) -> x?.config?.programmableMethods?.plan)?.config.programmableMethods.plan
unless @solution = _.find(plan?.solutions ? [], description: 'arena-balancer')
@errorMessage = 'Configure a solution with description arena-balancer to use as the default'
@render()
_.delay @setUpVariablesTreema, 100 # Dunno why we need to delay
setUpVariablesTreema: =>
return if @destroyed
variableRegex = /<%= ?(.*?) ?%>/g
variables = []
while matched = variableRegex.exec @solution.source
variables.push matched[1]
dataStorageKey = ['arena-balancer-data', @levelSlug].join(':')
data = storage.load dataStorageKey
data ?= {}
schema = type: 'object', additionalProperties: false, properties: {}, required: variables, title: 'Variants', description: 'Combinatoric choice options'
for variable in variables
schema.properties[variable] = type: 'array', items:
type: 'object'
additionalProperties: false
required: ['name', 'code']
default: {name: '', code: ''}
properties:
name:
type: 'string'
maxLength: 5
description: 'Very short name/code for variant that will appear in usernames'
code:
type: 'string'
format: 'code'
aceMode: 'ace/mode/javascript'
title: 'Variant'
description: 'Cartesian products will result'
data[variable] ?= [name: '', code: '']
treemaOptions =
schema: schema
data: data
nodeClasses:
code: treemaExt.JavaScriptTreema
callbacks:
change: @onVariablesChanged
@variablesTreema = @$el.find('#variables-treema').treema treemaOptions
@variablesTreema.build()
@variablesTreema.open(3)
@onVariablesChanged()
onVariablesChanged: (e) =>
dataStorageKey = ['arena-balancer-data', @levelSlug].join(':')
storage.save dataStorageKey, @variablesTreema.data
cartesian = (a) -> a.reduce((a, b) -> a.flatMap((d) -> b.map((e) -> [d, e].flat())))
variables = []
for variable of @variablesTreema.data
variants = []
for variant in @variablesTreema.data[variable]
variants.push {variable: variable, name: variant.name, code: variant.code}
variables.push variants
@choices = cartesian variables
@$('#go-button').text "Create/Update All #{@choices.length} Test Sessions"
onClickGoButton: (event) ->
renderData =
title: 'Are you really sure?'
body: "This will wipe all arena balancer sessions for #{@levelSlug} and submit #{@choices.length} new ones. Are you sure you want to do it? (Probably shouldn't be more than a couple thousand.)"
decline: 'Not really'
confirm: 'Definitely'
@confirmModal = new ConfirmModal renderData
@confirmModal.on 'confirm', @submitSessions
@openModalView @confirmModal
submitSessions: (e) =>
@confirmModal.$el.find('#confirm-button').attr('disabled', true).text('Working... (can take a while)')
postData = submissions: []
for choice in @choices
context = {}
context[variant.variable] = variant.code for variant in choice
code = _.template @solution.source, context
session = name: (variant.name for variant in choice).join('-'), code: code
postData.submissions.push session
$.ajax
data: JSON.stringify postData
success: (data, status, jqXHR) =>
noty
timeout: 5000
text: 'Arena balancing submission process started'
type: 'success'
layout: 'topCenter'
@confirmModal?.hide?()
error: (jqXHR, status, error) =>
console.error jqXHR
noty
timeout: 5000
text: "Arena balancing submission process failed with error code #{jqXHR.status}"
type: 'error'
layout: 'topCenter'
@confirmModal?.hide?()
url: "/db/level/#{@levelSlug}/arena-balancer-sessions" # TODO
type: 'POST'
contentType: 'application/json'
| 146272 | require('app/styles/artisans/arena-balancer-view.sass')
RootView = require 'views/core/RootView'
template = require 'templates/artisans/arena-balancer-view'
Campaigns = require 'collections/Campaigns'
Campaign = require 'models/Campaign'
Levels = require 'collections/Levels'
Level = require 'models/Level'
LevelSessions = require 'collections/LevelSessions'
ace = require 'lib/aceContainer'
aceUtils = require 'core/aceUtils'
require 'lib/setupTreema'
treemaExt = require 'core/treema-ext'
storage = require 'core/storage'
ConfirmModal = require 'views/core/ConfirmModal'
module.exports = class ArenaBalancerView extends RootView
template: template
id: 'arena-balancer-view'
events:
'click #go-button': 'onClickGoButton'
levelSlug: 'infinite-inferno'
constructor: (options, @levelSlug) ->
super options
@getLevelInfo()
afterRender: ->
super()
editorElements = @$el.find('.ace')
for el in editorElements
lang = @$(el).data('language')
editor = ace.edit el
aceSession = editor.getSession()
aceDoc = aceSession.getDocument()
aceSession.setMode aceUtils.aceEditModes[lang]
editor.setTheme 'ace/theme/textmate'
#editor.setReadOnly true
getLevelInfo: () ->
@level = @supermodel.getModel(Level, @levelSlug) or new Level _id: @levelSlug
@supermodel.trackRequest @level.fetch()
@level.on 'error', (@level, error) =>
return @errorMessage = "Error loading level: #{error.statusText}"
if @level.loaded
@onLevelLoaded @level
else
@listenToOnce @level, 'sync', @onLevelLoaded
onLevelLoaded: (level) ->
solutions = []
hero = _.find level.get("thangs") ? [], id: 'Hero Placeholder'
plan = _.find(hero?.components ? [], (x) -> x?.config?.programmableMethods?.plan)?.config.programmableMethods.plan
unless @solution = _.find(plan?.solutions ? [], description: 'arena-balancer')
@errorMessage = 'Configure a solution with description arena-balancer to use as the default'
@render()
_.delay @setUpVariablesTreema, 100 # Dunno why we need to delay
setUpVariablesTreema: =>
return if @destroyed
variableRegex = /<%= ?(.*?) ?%>/g
variables = []
while matched = variableRegex.exec @solution.source
variables.push matched[1]
dataStorageKey = ['<KEY>', @levelSlug].<KEY>(':')
data = storage.load dataStorageKey
data ?= {}
schema = type: 'object', additionalProperties: false, properties: {}, required: variables, title: 'Variants', description: 'Combinatoric choice options'
for variable in variables
schema.properties[variable] = type: 'array', items:
type: 'object'
additionalProperties: false
required: ['name', 'code']
default: {name: '', code: ''}
properties:
name:
type: 'string'
maxLength: 5
description: 'Very short name/code for variant that will appear in usernames'
code:
type: 'string'
format: 'code'
aceMode: 'ace/mode/javascript'
title: 'Variant'
description: 'Cartesian products will result'
data[variable] ?= [name: '', code: '']
treemaOptions =
schema: schema
data: data
nodeClasses:
code: treemaExt.JavaScriptTreema
callbacks:
change: @onVariablesChanged
@variablesTreema = @$el.find('#variables-treema').treema treemaOptions
@variablesTreema.build()
@variablesTreema.open(3)
@onVariablesChanged()
onVariablesChanged: (e) =>
dataStorageKey = ['<KEY>', @levelSlug].<KEY>')
storage.save dataStorageKey, @variablesTreema.data
cartesian = (a) -> a.reduce((a, b) -> a.flatMap((d) -> b.map((e) -> [d, e].flat())))
variables = []
for variable of @variablesTreema.data
variants = []
for variant in @variablesTreema.data[variable]
variants.push {variable: variable, name: variant.name, code: variant.code}
variables.push variants
@choices = cartesian variables
@$('#go-button').text "Create/Update All #{@choices.length} Test Sessions"
onClickGoButton: (event) ->
renderData =
title: 'Are you really sure?'
body: "This will wipe all arena balancer sessions for #{@levelSlug} and submit #{@choices.length} new ones. Are you sure you want to do it? (Probably shouldn't be more than a couple thousand.)"
decline: 'Not really'
confirm: 'Definitely'
@confirmModal = new ConfirmModal renderData
@confirmModal.on 'confirm', @submitSessions
@openModalView @confirmModal
submitSessions: (e) =>
@confirmModal.$el.find('#confirm-button').attr('disabled', true).text('Working... (can take a while)')
postData = submissions: []
for choice in @choices
context = {}
context[variant.variable] = variant.code for variant in choice
code = _.template @solution.source, context
session = name: (variant.name for variant in choice).join('-'), code: code
postData.submissions.push session
$.ajax
data: JSON.stringify postData
success: (data, status, jqXHR) =>
noty
timeout: 5000
text: 'Arena balancing submission process started'
type: 'success'
layout: 'topCenter'
@confirmModal?.hide?()
error: (jqXHR, status, error) =>
console.error jqXHR
noty
timeout: 5000
text: "Arena balancing submission process failed with error code #{jqXHR.status}"
type: 'error'
layout: 'topCenter'
@confirmModal?.hide?()
url: "/db/level/#{@levelSlug}/arena-balancer-sessions" # TODO
type: 'POST'
contentType: 'application/json'
| true | require('app/styles/artisans/arena-balancer-view.sass')
RootView = require 'views/core/RootView'
template = require 'templates/artisans/arena-balancer-view'
Campaigns = require 'collections/Campaigns'
Campaign = require 'models/Campaign'
Levels = require 'collections/Levels'
Level = require 'models/Level'
LevelSessions = require 'collections/LevelSessions'
ace = require 'lib/aceContainer'
aceUtils = require 'core/aceUtils'
require 'lib/setupTreema'
treemaExt = require 'core/treema-ext'
storage = require 'core/storage'
ConfirmModal = require 'views/core/ConfirmModal'
module.exports = class ArenaBalancerView extends RootView
template: template
id: 'arena-balancer-view'
events:
'click #go-button': 'onClickGoButton'
levelSlug: 'infinite-inferno'
constructor: (options, @levelSlug) ->
super options
@getLevelInfo()
afterRender: ->
super()
editorElements = @$el.find('.ace')
for el in editorElements
lang = @$(el).data('language')
editor = ace.edit el
aceSession = editor.getSession()
aceDoc = aceSession.getDocument()
aceSession.setMode aceUtils.aceEditModes[lang]
editor.setTheme 'ace/theme/textmate'
#editor.setReadOnly true
getLevelInfo: () ->
@level = @supermodel.getModel(Level, @levelSlug) or new Level _id: @levelSlug
@supermodel.trackRequest @level.fetch()
@level.on 'error', (@level, error) =>
return @errorMessage = "Error loading level: #{error.statusText}"
if @level.loaded
@onLevelLoaded @level
else
@listenToOnce @level, 'sync', @onLevelLoaded
onLevelLoaded: (level) ->
solutions = []
hero = _.find level.get("thangs") ? [], id: 'Hero Placeholder'
plan = _.find(hero?.components ? [], (x) -> x?.config?.programmableMethods?.plan)?.config.programmableMethods.plan
unless @solution = _.find(plan?.solutions ? [], description: 'arena-balancer')
@errorMessage = 'Configure a solution with description arena-balancer to use as the default'
@render()
_.delay @setUpVariablesTreema, 100 # Dunno why we need to delay
setUpVariablesTreema: =>
return if @destroyed
variableRegex = /<%= ?(.*?) ?%>/g
variables = []
while matched = variableRegex.exec @solution.source
variables.push matched[1]
dataStorageKey = ['PI:KEY:<KEY>END_PI', @levelSlug].PI:KEY:<KEY>END_PI(':')
data = storage.load dataStorageKey
data ?= {}
schema = type: 'object', additionalProperties: false, properties: {}, required: variables, title: 'Variants', description: 'Combinatoric choice options'
for variable in variables
schema.properties[variable] = type: 'array', items:
type: 'object'
additionalProperties: false
required: ['name', 'code']
default: {name: '', code: ''}
properties:
name:
type: 'string'
maxLength: 5
description: 'Very short name/code for variant that will appear in usernames'
code:
type: 'string'
format: 'code'
aceMode: 'ace/mode/javascript'
title: 'Variant'
description: 'Cartesian products will result'
data[variable] ?= [name: '', code: '']
treemaOptions =
schema: schema
data: data
nodeClasses:
code: treemaExt.JavaScriptTreema
callbacks:
change: @onVariablesChanged
@variablesTreema = @$el.find('#variables-treema').treema treemaOptions
@variablesTreema.build()
@variablesTreema.open(3)
@onVariablesChanged()
onVariablesChanged: (e) =>
dataStorageKey = ['PI:KEY:<KEY>END_PI', @levelSlug].PI:KEY:<KEY>END_PI')
storage.save dataStorageKey, @variablesTreema.data
cartesian = (a) -> a.reduce((a, b) -> a.flatMap((d) -> b.map((e) -> [d, e].flat())))
variables = []
for variable of @variablesTreema.data
variants = []
for variant in @variablesTreema.data[variable]
variants.push {variable: variable, name: variant.name, code: variant.code}
variables.push variants
@choices = cartesian variables
@$('#go-button').text "Create/Update All #{@choices.length} Test Sessions"
onClickGoButton: (event) ->
renderData =
title: 'Are you really sure?'
body: "This will wipe all arena balancer sessions for #{@levelSlug} and submit #{@choices.length} new ones. Are you sure you want to do it? (Probably shouldn't be more than a couple thousand.)"
decline: 'Not really'
confirm: 'Definitely'
@confirmModal = new ConfirmModal renderData
@confirmModal.on 'confirm', @submitSessions
@openModalView @confirmModal
submitSessions: (e) =>
@confirmModal.$el.find('#confirm-button').attr('disabled', true).text('Working... (can take a while)')
postData = submissions: []
for choice in @choices
context = {}
context[variant.variable] = variant.code for variant in choice
code = _.template @solution.source, context
session = name: (variant.name for variant in choice).join('-'), code: code
postData.submissions.push session
$.ajax
data: JSON.stringify postData
success: (data, status, jqXHR) =>
noty
timeout: 5000
text: 'Arena balancing submission process started'
type: 'success'
layout: 'topCenter'
@confirmModal?.hide?()
error: (jqXHR, status, error) =>
console.error jqXHR
noty
timeout: 5000
text: "Arena balancing submission process failed with error code #{jqXHR.status}"
type: 'error'
layout: 'topCenter'
@confirmModal?.hide?()
url: "/db/level/#{@levelSlug}/arena-balancer-sessions" # TODO
type: 'POST'
contentType: 'application/json'
|
[
{
"context": "# Stolen somewhat from Roy van de Water because I am lazy\n_ = require 'lodash'\n\nclass Rou",
"end": 39,
"score": 0.99956876039505,
"start": 23,
"tag": "NAME",
"value": "Roy van de Water"
}
] | lib/games/roulette.coffee | peterdemartini/betting-strategies | 0 | # Stolen somewhat from Roy van de Water because I am lazy
_ = require 'lodash'
class Roulette
constructor: ->
@pockets = @createPockets()
bet: (amount=0) =>
return amount * 2 if _.sample(@pockets) == 'black'
return -amount
createPockets: =>
reds = _.times 18, => 'red'
blacks = _.times 18, => 'black'
greens = _.times 2, => 'green'
[].concat reds, blacks, greens
module.exports = Roulette
| 60367 | # Stolen somewhat from <NAME> because I am lazy
_ = require 'lodash'
class Roulette
constructor: ->
@pockets = @createPockets()
bet: (amount=0) =>
return amount * 2 if _.sample(@pockets) == 'black'
return -amount
createPockets: =>
reds = _.times 18, => 'red'
blacks = _.times 18, => 'black'
greens = _.times 2, => 'green'
[].concat reds, blacks, greens
module.exports = Roulette
| true | # Stolen somewhat from PI:NAME:<NAME>END_PI because I am lazy
_ = require 'lodash'
class Roulette
constructor: ->
@pockets = @createPockets()
bet: (amount=0) =>
return amount * 2 if _.sample(@pockets) == 'black'
return -amount
createPockets: =>
reds = _.times 18, => 'red'
blacks = _.times 18, => 'black'
greens = _.times 2, => 'green'
[].concat reds, blacks, greens
module.exports = Roulette
|
[
{
"context": "###\n\t(c) 2016, 2017 Julian Gonggrijp\n###\n\nrequire.config\n\tbaseUrl: 'static'\n\tpaths:\n\t\t",
"end": 36,
"score": 0.9998791813850403,
"start": 20,
"tag": "NAME",
"value": "Julian Gonggrijp"
}
] | client/script/productionConfig.coffee | NBOCampbellToets/CampbellSoup | 0 | ###
(c) 2016, 2017 Julian Gonggrijp
###
require.config
baseUrl: 'static'
paths:
jquery: '//code.jquery.com/jquery-3.1.1.min'
backbone: '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min'
underscore: '//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min'
'handlebars.runtime': '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.runtime.amd.min'
| 84504 | ###
(c) 2016, 2017 <NAME>
###
require.config
baseUrl: 'static'
paths:
jquery: '//code.jquery.com/jquery-3.1.1.min'
backbone: '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min'
underscore: '//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min'
'handlebars.runtime': '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.runtime.amd.min'
| true | ###
(c) 2016, 2017 PI:NAME:<NAME>END_PI
###
require.config
baseUrl: 'static'
paths:
jquery: '//code.jquery.com/jquery-3.1.1.min'
backbone: '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min'
underscore: '//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.1/lodash.min'
'handlebars.runtime': '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.runtime.amd.min'
|
[
{
"context": " immediate assistance? Please [contact us](mailto:specialist@artsy.net)\n '\n pages:\n 'Bidding': 'how-auctions-",
"end": 280,
"score": 0.9999297857284546,
"start": 260,
"tag": "EMAIL",
"value": "specialist@artsy.net"
},
{
"context": " immediate assistance? P... | src/desktop/components/multi_page/config.coffee | kanaabe/force | 377 | module.exports =
'auction-faqs':
title: 'Auction FAQs'
description: '
How can we help you? Below are a few general categories to help you find the answers you’re looking for.\n\n
Need more immediate assistance? Please [contact us](mailto:specialist@artsy.net)
'
pages:
'Bidding': 'how-auctions-work-bidding'
'Buyers premium, taxes, & fees': 'how-auctions-work-buyers-premium-taxes-and-fees'
'Payments and Shipping': 'how-auctions-work-payments-and-shipping'
'Emails and alerts': 'how-auctions-work-emails-and-alerts'
'Conditions of sale': 'how-auctions-work-conditions-of-sale'
'collector-faqs':
title: 'Collector FAQs'
description: '
How can we help you? Below are answers to some of the most common questions from collectors.\n\n
Need more immediate assistance? Please [contact us](mailto:support@artsy.net)
'
pages:
'Buying on Artsy': 'collector-faqs-buying-on-artsy'
'Exploring Artsy': 'collector-faqs-exploring-artsy'
'Selling On Artsy': 'collector-faqs-selling-on-artsy'
'artist-faqs':
title: 'Artist FAQs'
description: '
How can we help you? Below are answers to some of the most common questions from artists.\n\n
'
pages:
'How Artsy Works': 'artist-faqs-how-artsy-works'
'Listing Artworks': 'artist-faqs-listing-artworks'
'Other Requests': 'artist-faqs-other-requests'
'consignment-faqs':
title: 'Consignment FAQs'
description: ''
pages:
'Overview': 'consignments-faq-overview'
'Fees & Estimates': 'consignments-faq-fees-and-estimates'
'Consignment Agreement': 'consignments-faq-consignment-agreement'
| 27360 | module.exports =
'auction-faqs':
title: 'Auction FAQs'
description: '
How can we help you? Below are a few general categories to help you find the answers you’re looking for.\n\n
Need more immediate assistance? Please [contact us](mailto:<EMAIL>)
'
pages:
'Bidding': 'how-auctions-work-bidding'
'Buyers premium, taxes, & fees': 'how-auctions-work-buyers-premium-taxes-and-fees'
'Payments and Shipping': 'how-auctions-work-payments-and-shipping'
'Emails and alerts': 'how-auctions-work-emails-and-alerts'
'Conditions of sale': 'how-auctions-work-conditions-of-sale'
'collector-faqs':
title: 'Collector FAQs'
description: '
How can we help you? Below are answers to some of the most common questions from collectors.\n\n
Need more immediate assistance? Please [contact us](mailto:<EMAIL>)
'
pages:
'Buying on Artsy': 'collector-faqs-buying-on-artsy'
'Exploring Artsy': 'collector-faqs-exploring-artsy'
'Selling On Artsy': 'collector-faqs-selling-on-artsy'
'artist-faqs':
title: 'Artist FAQs'
description: '
How can we help you? Below are answers to some of the most common questions from artists.\n\n
'
pages:
'How Artsy Works': 'artist-faqs-how-artsy-works'
'Listing Artworks': 'artist-faqs-listing-artworks'
'Other Requests': 'artist-faqs-other-requests'
'consignment-faqs':
title: 'Consignment FAQs'
description: ''
pages:
'Overview': 'consignments-faq-overview'
'Fees & Estimates': 'consignments-faq-fees-and-estimates'
'Consignment Agreement': 'consignments-faq-consignment-agreement'
| true | module.exports =
'auction-faqs':
title: 'Auction FAQs'
description: '
How can we help you? Below are a few general categories to help you find the answers you’re looking for.\n\n
Need more immediate assistance? Please [contact us](mailto:PI:EMAIL:<EMAIL>END_PI)
'
pages:
'Bidding': 'how-auctions-work-bidding'
'Buyers premium, taxes, & fees': 'how-auctions-work-buyers-premium-taxes-and-fees'
'Payments and Shipping': 'how-auctions-work-payments-and-shipping'
'Emails and alerts': 'how-auctions-work-emails-and-alerts'
'Conditions of sale': 'how-auctions-work-conditions-of-sale'
'collector-faqs':
title: 'Collector FAQs'
description: '
How can we help you? Below are answers to some of the most common questions from collectors.\n\n
Need more immediate assistance? Please [contact us](mailto:PI:EMAIL:<EMAIL>END_PI)
'
pages:
'Buying on Artsy': 'collector-faqs-buying-on-artsy'
'Exploring Artsy': 'collector-faqs-exploring-artsy'
'Selling On Artsy': 'collector-faqs-selling-on-artsy'
'artist-faqs':
title: 'Artist FAQs'
description: '
How can we help you? Below are answers to some of the most common questions from artists.\n\n
'
pages:
'How Artsy Works': 'artist-faqs-how-artsy-works'
'Listing Artworks': 'artist-faqs-listing-artworks'
'Other Requests': 'artist-faqs-other-requests'
'consignment-faqs':
title: 'Consignment FAQs'
description: ''
pages:
'Overview': 'consignments-faq-overview'
'Fees & Estimates': 'consignments-faq-fees-and-estimates'
'Consignment Agreement': 'consignments-faq-consignment-agreement'
|
[
{
"context": "bhook # (for verifying signatures)\n#\n# Author:\n# Matthew Weier O'Phinney\n\nbodyParser = require 'body-parser'\ndiscourse_pos",
"end": 934,
"score": 0.9997953772544861,
"start": 911,
"tag": "NAME",
"value": "Matthew Weier O'Phinney"
}
] | scripts/discourse.coffee | inovadeveloper/zfbot | 11 | # Description:
# Listen to Discourse webhooks. Listens for "topic" and "post" hooks, passing
# them on to dedicated webhook scripts. Middleware is registered that verifies
# the incoming payload's X-Discourse-Event-Signature against a known secret to
# validate the origin of the webhook payload.
#
# Register webhooks via the Discourse settings UI. When you do, use URIs of
# the format "/discourse/{ROOM_ID}/(topic|post)", where {ROOM_ID} is the
# identifier for the Slack room to which the webhook should post messages (you
# can retrieve that by right-clicking a room, copying the URL, and extracting
# the final path segment).
#
# Configuration:
#
# The following environment variables are required.
#
# HUBOT_DISCOURSE_URL: Base URL to the Discourse installation
# HUBOT_DISCOURSE_SECRET: Shared secret between Discourse instance and webhook # (for verifying signatures)
#
# Author:
# Matthew Weier O'Phinney
bodyParser = require 'body-parser'
discourse_post = require "../lib/discourse-post"
discourse_topic = require "../lib/discourse-topic"
verify_signature = require "../lib/discourse-verify-signature"
module.exports = (robot) ->
discourse_url = process.env.HUBOT_DISCOURSE_URL
discourse_secret = process.env.HUBOT_DISCOURSE_SECRET
# In order to calculate signatures, we need to shove the JSON body
# parser to the top of the stack and have it set the raw request body
# contents in the request when done parsing.
robot.router.stack.unshift {
route: "/discourse"
handle: bodyParser.json {
verify: (req, res, buf, encoding) ->
req.rawBody = buf
}
}
robot.router.post '/discourse/:room/:event', (req, res) ->
room = req.params.room
event = req.params.event
if event not in ["topic", "post"]
res.send 203, "Unrecognized event #{event}"
robot.logger.error "[Discourse] Unrecognized event '#{event}' was pinged"
return
if not verify_signature(req, discourse_secret)
res.send 203, "Invalid or missing signature"
robot.logger.error "Invalid payload submitted to /discourse/#{room}/#{event}; signature invalid"
return
# We can accept it now, so return a response immediately
res.send 202
data = req.body
# Now, we need to switch on the event, and determine what message to send
# to the room.
switch event
# Uncomment to enable broadcast of topic created/edited events
# when "topic"
# discourse_topic robot, room, discourse_url, data
when "post"
discourse_post robot, room, discourse_url, data
| 131519 | # Description:
# Listen to Discourse webhooks. Listens for "topic" and "post" hooks, passing
# them on to dedicated webhook scripts. Middleware is registered that verifies
# the incoming payload's X-Discourse-Event-Signature against a known secret to
# validate the origin of the webhook payload.
#
# Register webhooks via the Discourse settings UI. When you do, use URIs of
# the format "/discourse/{ROOM_ID}/(topic|post)", where {ROOM_ID} is the
# identifier for the Slack room to which the webhook should post messages (you
# can retrieve that by right-clicking a room, copying the URL, and extracting
# the final path segment).
#
# Configuration:
#
# The following environment variables are required.
#
# HUBOT_DISCOURSE_URL: Base URL to the Discourse installation
# HUBOT_DISCOURSE_SECRET: Shared secret between Discourse instance and webhook # (for verifying signatures)
#
# Author:
# <NAME>
bodyParser = require 'body-parser'
discourse_post = require "../lib/discourse-post"
discourse_topic = require "../lib/discourse-topic"
verify_signature = require "../lib/discourse-verify-signature"
module.exports = (robot) ->
discourse_url = process.env.HUBOT_DISCOURSE_URL
discourse_secret = process.env.HUBOT_DISCOURSE_SECRET
# In order to calculate signatures, we need to shove the JSON body
# parser to the top of the stack and have it set the raw request body
# contents in the request when done parsing.
robot.router.stack.unshift {
route: "/discourse"
handle: bodyParser.json {
verify: (req, res, buf, encoding) ->
req.rawBody = buf
}
}
robot.router.post '/discourse/:room/:event', (req, res) ->
room = req.params.room
event = req.params.event
if event not in ["topic", "post"]
res.send 203, "Unrecognized event #{event}"
robot.logger.error "[Discourse] Unrecognized event '#{event}' was pinged"
return
if not verify_signature(req, discourse_secret)
res.send 203, "Invalid or missing signature"
robot.logger.error "Invalid payload submitted to /discourse/#{room}/#{event}; signature invalid"
return
# We can accept it now, so return a response immediately
res.send 202
data = req.body
# Now, we need to switch on the event, and determine what message to send
# to the room.
switch event
# Uncomment to enable broadcast of topic created/edited events
# when "topic"
# discourse_topic robot, room, discourse_url, data
when "post"
discourse_post robot, room, discourse_url, data
| true | # Description:
# Listen to Discourse webhooks. Listens for "topic" and "post" hooks, passing
# them on to dedicated webhook scripts. Middleware is registered that verifies
# the incoming payload's X-Discourse-Event-Signature against a known secret to
# validate the origin of the webhook payload.
#
# Register webhooks via the Discourse settings UI. When you do, use URIs of
# the format "/discourse/{ROOM_ID}/(topic|post)", where {ROOM_ID} is the
# identifier for the Slack room to which the webhook should post messages (you
# can retrieve that by right-clicking a room, copying the URL, and extracting
# the final path segment).
#
# Configuration:
#
# The following environment variables are required.
#
# HUBOT_DISCOURSE_URL: Base URL to the Discourse installation
# HUBOT_DISCOURSE_SECRET: Shared secret between Discourse instance and webhook # (for verifying signatures)
#
# Author:
# PI:NAME:<NAME>END_PI
bodyParser = require 'body-parser'
discourse_post = require "../lib/discourse-post"
discourse_topic = require "../lib/discourse-topic"
verify_signature = require "../lib/discourse-verify-signature"
module.exports = (robot) ->
discourse_url = process.env.HUBOT_DISCOURSE_URL
discourse_secret = process.env.HUBOT_DISCOURSE_SECRET
# In order to calculate signatures, we need to shove the JSON body
# parser to the top of the stack and have it set the raw request body
# contents in the request when done parsing.
robot.router.stack.unshift {
route: "/discourse"
handle: bodyParser.json {
verify: (req, res, buf, encoding) ->
req.rawBody = buf
}
}
robot.router.post '/discourse/:room/:event', (req, res) ->
room = req.params.room
event = req.params.event
if event not in ["topic", "post"]
res.send 203, "Unrecognized event #{event}"
robot.logger.error "[Discourse] Unrecognized event '#{event}' was pinged"
return
if not verify_signature(req, discourse_secret)
res.send 203, "Invalid or missing signature"
robot.logger.error "Invalid payload submitted to /discourse/#{room}/#{event}; signature invalid"
return
# We can accept it now, so return a response immediately
res.send 202
data = req.body
# Now, we need to switch on the event, and determine what message to send
# to the room.
switch event
# Uncomment to enable broadcast of topic created/edited events
# when "topic"
# discourse_topic robot, room, discourse_url, data
when "post"
discourse_post robot, room, discourse_url, data
|
[
{
"context": "se: \"database\"\n password: \"passw0rd\"\n url: \"https://example.com",
"end": 415,
"score": 0.999157190322876,
"start": 407,
"tag": "PASSWORD",
"value": "passw0rd"
},
{
"context": "ttps://example.com/\"\n usernam... | node_modules/cfenv/tests/data-01.cson | fahamk/writersblock | 68 | PORT: "61165"
VCAP_APP_PORT: "61165"
VCAP_APP_HOST: "0.0.0.0"
DATABASE_URL: ""
MEMORY_LIMIT: "128m"
VCAP_SERVICES:
"user-provided": [
name: "cf-env-test"
label: "user-provided"
tags: []
credentials:
database: "database"
password: "passw0rd"
url: "https://example.com/"
username: "userid"
syslog_drain_url: "http://example.com/syslog"
]
VCAP_APPLICATION:
instance_id: "606eac20570f48e7b39390cf9d2b8fcc"
instance_index: 0
host: "0.0.0.0"
port: 61165
started_at: "2014-03-11 03:02:29 +0000"
started_at_timestamp: 1394506949,
start: "2014-03-11 03:02:29 +0000"
state_timestamp: 1394506949
limits:
mem: 128
disk: 1024
fds: 16384
application_version: "17378da2-08c7-4221-accb-46464c3ad755"
version: "17378da2-08c7-4221-accb-46464c3ad755"
application_name: "cf-env-test"
name: "cf-env-test"
application_uris: [
"cf-env-test.ng.bluemix.net"
]
uris: [
"cf-env-test.ng.bluemix.net"
]
users: null
| 109681 | PORT: "61165"
VCAP_APP_PORT: "61165"
VCAP_APP_HOST: "0.0.0.0"
DATABASE_URL: ""
MEMORY_LIMIT: "128m"
VCAP_SERVICES:
"user-provided": [
name: "cf-env-test"
label: "user-provided"
tags: []
credentials:
database: "database"
password: "<PASSWORD>"
url: "https://example.com/"
username: "userid"
syslog_drain_url: "http://example.com/syslog"
]
VCAP_APPLICATION:
instance_id: "606eac20570f48e7b39390cf9d2b8fcc"
instance_index: 0
host: "0.0.0.0"
port: 61165
started_at: "2014-03-11 03:02:29 +0000"
started_at_timestamp: 1394506949,
start: "2014-03-11 03:02:29 +0000"
state_timestamp: 1394506949
limits:
mem: 128
disk: 1024
fds: 16384
application_version: "17378da2-08c7-4221-accb-46464c3ad755"
version: "17378da2-08c7-4221-accb-46464c3ad755"
application_name: "cf-env-test"
name: "cf-env-test"
application_uris: [
"cf-env-test.ng.bluemix.net"
]
uris: [
"cf-env-test.ng.bluemix.net"
]
users: null
| true | PORT: "61165"
VCAP_APP_PORT: "61165"
VCAP_APP_HOST: "0.0.0.0"
DATABASE_URL: ""
MEMORY_LIMIT: "128m"
VCAP_SERVICES:
"user-provided": [
name: "cf-env-test"
label: "user-provided"
tags: []
credentials:
database: "database"
password: "PI:PASSWORD:<PASSWORD>END_PI"
url: "https://example.com/"
username: "userid"
syslog_drain_url: "http://example.com/syslog"
]
VCAP_APPLICATION:
instance_id: "606eac20570f48e7b39390cf9d2b8fcc"
instance_index: 0
host: "0.0.0.0"
port: 61165
started_at: "2014-03-11 03:02:29 +0000"
started_at_timestamp: 1394506949,
start: "2014-03-11 03:02:29 +0000"
state_timestamp: 1394506949
limits:
mem: 128
disk: 1024
fds: 16384
application_version: "17378da2-08c7-4221-accb-46464c3ad755"
version: "17378da2-08c7-4221-accb-46464c3ad755"
application_name: "cf-env-test"
name: "cf-env-test"
application_uris: [
"cf-env-test.ng.bluemix.net"
]
uris: [
"cf-env-test.ng.bluemix.net"
]
users: null
|
[
{
"context": "###\n Backbone BindTo 1.0.0\n\n Author: Radoslav Stankov\n Project site: https://github.com/RStankov/backbo",
"end": 53,
"score": 0.999878466129303,
"start": 37,
"tag": "NAME",
"value": "Radoslav Stankov"
},
{
"context": "adoslav Stankov\n Project site: https://github.c... | vendor/assets/javascripts/backbone/backbone-bind-to-1.0.0.coffee | chip-miller/social-devotional | 1 | ###
Backbone BindTo 1.0.0
Author: Radoslav Stankov
Project site: https://github.com/RStankov/backbone-bind-to
Licensed under the MIT License.
###
root = @
BackboneView = root.Backbone.View
class BindToView extends BackboneView
constructor: ->
super
@bindTo @model, eventName, methodName for eventName, methodName of @bindToModel if @model
@bindTo @collection, eventName, methodName for eventName, methodName of @bindToCollection if @collection
bindTo: (object, eventName, methodName) ->
unless object in [@model, @collection]
@_binded = []
@_binded.push object unless _.include @_binded, object
throw new Error "Method #{methodName} does not exists" unless @[methodName]
throw new Error "#{methodName} is not a function" unless typeof @[methodName] is 'function'
object.on eventName, @[methodName], @
remove: ->
@model.off null, null, @ if @model
@collection.off null, null, @ if @collection
_.invoke @_binded, 'off', null, null, @
delete @_binded
super
Backbone.BindTo =
VERSION: '1.0.0'
noConflict: ->
root.Backbone.View = BackboneView
BindToView
View: BindToView
root.Backbone.View = Backbone.BindTo.View
| 140566 | ###
Backbone BindTo 1.0.0
Author: <NAME>
Project site: https://github.com/RStankov/backbone-bind-to
Licensed under the MIT License.
###
root = @
BackboneView = root.Backbone.View
class BindToView extends BackboneView
constructor: ->
super
@bindTo @model, eventName, methodName for eventName, methodName of @bindToModel if @model
@bindTo @collection, eventName, methodName for eventName, methodName of @bindToCollection if @collection
bindTo: (object, eventName, methodName) ->
unless object in [@model, @collection]
@_binded = []
@_binded.push object unless _.include @_binded, object
throw new Error "Method #{methodName} does not exists" unless @[methodName]
throw new Error "#{methodName} is not a function" unless typeof @[methodName] is 'function'
object.on eventName, @[methodName], @
remove: ->
@model.off null, null, @ if @model
@collection.off null, null, @ if @collection
_.invoke @_binded, 'off', null, null, @
delete @_binded
super
Backbone.BindTo =
VERSION: '1.0.0'
noConflict: ->
root.Backbone.View = BackboneView
BindToView
View: BindToView
root.Backbone.View = Backbone.BindTo.View
| true | ###
Backbone BindTo 1.0.0
Author: PI:NAME:<NAME>END_PI
Project site: https://github.com/RStankov/backbone-bind-to
Licensed under the MIT License.
###
root = @
BackboneView = root.Backbone.View
class BindToView extends BackboneView
constructor: ->
super
@bindTo @model, eventName, methodName for eventName, methodName of @bindToModel if @model
@bindTo @collection, eventName, methodName for eventName, methodName of @bindToCollection if @collection
bindTo: (object, eventName, methodName) ->
unless object in [@model, @collection]
@_binded = []
@_binded.push object unless _.include @_binded, object
throw new Error "Method #{methodName} does not exists" unless @[methodName]
throw new Error "#{methodName} is not a function" unless typeof @[methodName] is 'function'
object.on eventName, @[methodName], @
remove: ->
@model.off null, null, @ if @model
@collection.off null, null, @ if @collection
_.invoke @_binded, 'off', null, null, @
delete @_binded
super
Backbone.BindTo =
VERSION: '1.0.0'
noConflict: ->
root.Backbone.View = BackboneView
BindToView
View: BindToView
root.Backbone.View = Backbone.BindTo.View
|
[
{
"context": "e Music\n * @category Web Components\n * @author Nazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright Copyright (c",
"end": 96,
"score": 0.9998943209648132,
"start": 80,
"tag": "NAME",
"value": "Nazar Mokrynskyi"
},
{
"context": "y Web Components\n * @author N... | html/cs-music-playlist/script.coffee | mariot/Klif-Mozika | 0 | ###*
* @package CleverStyle Music
* @category Web Components
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @copyright Copyright (c) 2014-2015, Nazar Mokrynskyi
* @license MIT License, see license.txt
###
document.webL10n.ready ->
music_library = cs.music_library
music_playlist = cs.music_playlist
music_settings = cs.music_settings
player = document.querySelector('cs-music-player')
scroll_interval = 0
Polymer(
'cs-music-playlist'
list : []
created : ->
cs.bus.on('player/play', (id) =>
if @list.length
@update_status(id)
)
ready : ->
switch music_settings.repeat
when 'none'
@.shadowRoot.querySelector('[icon=repeat]').setAttribute('disabled', '')
when 'one'
@.shadowRoot.querySelector('[icon=repeat]').innerHTML = 1
if !music_settings.shuffle
@.shadowRoot.querySelector('[icon=random]').setAttribute('disabled', '')
showChanged : ->
if @show
@update()
update : ->
music_playlist.current (current_id) =>
music_playlist.get_all (all) =>
index = 0
list = []
count = all.length
get_next_item = =>
if index < count
music_library.get_meta(all[index], (data) =>
data.playing = if data.id == current_id then 'yes' else 'no'
data.icon = if cs.bus.state.player == 'playing' then 'play' else 'pause'
data.artist_title = []
if data.artist
data.artist_title.push(data.artist)
if data.title
data.artist_title.push(data.title)
data.artist_title = data.artist_title.join(' — ') || _('unknown')
list.push(data)
data = null
++index
get_next_item()
)
else if @show
@list = list
scroll_interval = setInterval (=>
items_container = @shadowRoot.querySelector('cs-music-playlist-items')
if items_container
item = items_container.querySelector('cs-music-playlist-item[playing=yes]')
clearInterval(scroll_interval)
scroll_interval = 0
items_container.scrollTop = item.offsetTop
), 100
get_next_item()
play : (e) ->
music_playlist.current (old_id) =>
music_playlist.set_current(
e.target.dataset.index
)
music_playlist.current (id) =>
if id != old_id
player.play(id)
@update_status(id)
else
player.play()
@update_status(id)
update_status : (new_id) ->
@list.forEach (data, index) =>
if data.id == new_id
@list[index].playing = 'yes'
@list[index].icon = if cs.bus.state.player == 'playing' then 'play' else 'pause'
else
@list[index].playing = 'no'
delete @list[index].icon
back : ->
@go_back_screen()
items_container = @shadowRoot.querySelector('cs-music-playlist-items')
if items_container
items_container.style.opacity = 0
setTimeout (=>
@list = []
if scroll_interval
clearInterval(scroll_interval)
scroll_interval = 0
), 300
repeat : (e) ->
control = e.target
music_settings.repeat =
switch music_settings.repeat
when 'none' then 'all'
when 'all' then 'one'
when 'one' then 'none'
if music_settings.repeat == 'none'
control.setAttribute('disabled', '')
else
control.removeAttribute('disabled')
control.innerHTML = if music_settings.repeat == 'one' then 1 else ''
shuffle : (e) ->
control = e.target
music_settings.shuffle = !music_settings.shuffle
if !music_settings.shuffle
control.setAttribute('disabled', '')
else
control.removeAttribute('disabled')
@list = []
music_playlist.current (id) =>
music_playlist.refresh =>
music_playlist.set_current_id(id)
@update()
)
| 108984 | ###*
* @package CleverStyle Music
* @category Web Components
* @author <NAME> <<EMAIL>>
* @copyright Copyright (c) 2014-2015, <NAME>
* @license MIT License, see license.txt
###
document.webL10n.ready ->
music_library = cs.music_library
music_playlist = cs.music_playlist
music_settings = cs.music_settings
player = document.querySelector('cs-music-player')
scroll_interval = 0
Polymer(
'cs-music-playlist'
list : []
created : ->
cs.bus.on('player/play', (id) =>
if @list.length
@update_status(id)
)
ready : ->
switch music_settings.repeat
when 'none'
@.shadowRoot.querySelector('[icon=repeat]').setAttribute('disabled', '')
when 'one'
@.shadowRoot.querySelector('[icon=repeat]').innerHTML = 1
if !music_settings.shuffle
@.shadowRoot.querySelector('[icon=random]').setAttribute('disabled', '')
showChanged : ->
if @show
@update()
update : ->
music_playlist.current (current_id) =>
music_playlist.get_all (all) =>
index = 0
list = []
count = all.length
get_next_item = =>
if index < count
music_library.get_meta(all[index], (data) =>
data.playing = if data.id == current_id then 'yes' else 'no'
data.icon = if cs.bus.state.player == 'playing' then 'play' else 'pause'
data.artist_title = []
if data.artist
data.artist_title.push(data.artist)
if data.title
data.artist_title.push(data.title)
data.artist_title = data.artist_title.join(' — ') || _('unknown')
list.push(data)
data = null
++index
get_next_item()
)
else if @show
@list = list
scroll_interval = setInterval (=>
items_container = @shadowRoot.querySelector('cs-music-playlist-items')
if items_container
item = items_container.querySelector('cs-music-playlist-item[playing=yes]')
clearInterval(scroll_interval)
scroll_interval = 0
items_container.scrollTop = item.offsetTop
), 100
get_next_item()
play : (e) ->
music_playlist.current (old_id) =>
music_playlist.set_current(
e.target.dataset.index
)
music_playlist.current (id) =>
if id != old_id
player.play(id)
@update_status(id)
else
player.play()
@update_status(id)
update_status : (new_id) ->
@list.forEach (data, index) =>
if data.id == new_id
@list[index].playing = 'yes'
@list[index].icon = if cs.bus.state.player == 'playing' then 'play' else 'pause'
else
@list[index].playing = 'no'
delete @list[index].icon
back : ->
@go_back_screen()
items_container = @shadowRoot.querySelector('cs-music-playlist-items')
if items_container
items_container.style.opacity = 0
setTimeout (=>
@list = []
if scroll_interval
clearInterval(scroll_interval)
scroll_interval = 0
), 300
repeat : (e) ->
control = e.target
music_settings.repeat =
switch music_settings.repeat
when 'none' then 'all'
when 'all' then 'one'
when 'one' then 'none'
if music_settings.repeat == 'none'
control.setAttribute('disabled', '')
else
control.removeAttribute('disabled')
control.innerHTML = if music_settings.repeat == 'one' then 1 else ''
shuffle : (e) ->
control = e.target
music_settings.shuffle = !music_settings.shuffle
if !music_settings.shuffle
control.setAttribute('disabled', '')
else
control.removeAttribute('disabled')
@list = []
music_playlist.current (id) =>
music_playlist.refresh =>
music_playlist.set_current_id(id)
@update()
)
| true | ###*
* @package CleverStyle Music
* @category Web Components
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* @copyright Copyright (c) 2014-2015, PI:NAME:<NAME>END_PI
* @license MIT License, see license.txt
###
document.webL10n.ready ->
music_library = cs.music_library
music_playlist = cs.music_playlist
music_settings = cs.music_settings
player = document.querySelector('cs-music-player')
scroll_interval = 0
Polymer(
'cs-music-playlist'
list : []
created : ->
cs.bus.on('player/play', (id) =>
if @list.length
@update_status(id)
)
ready : ->
switch music_settings.repeat
when 'none'
@.shadowRoot.querySelector('[icon=repeat]').setAttribute('disabled', '')
when 'one'
@.shadowRoot.querySelector('[icon=repeat]').innerHTML = 1
if !music_settings.shuffle
@.shadowRoot.querySelector('[icon=random]').setAttribute('disabled', '')
showChanged : ->
if @show
@update()
update : ->
music_playlist.current (current_id) =>
music_playlist.get_all (all) =>
index = 0
list = []
count = all.length
get_next_item = =>
if index < count
music_library.get_meta(all[index], (data) =>
data.playing = if data.id == current_id then 'yes' else 'no'
data.icon = if cs.bus.state.player == 'playing' then 'play' else 'pause'
data.artist_title = []
if data.artist
data.artist_title.push(data.artist)
if data.title
data.artist_title.push(data.title)
data.artist_title = data.artist_title.join(' — ') || _('unknown')
list.push(data)
data = null
++index
get_next_item()
)
else if @show
@list = list
scroll_interval = setInterval (=>
items_container = @shadowRoot.querySelector('cs-music-playlist-items')
if items_container
item = items_container.querySelector('cs-music-playlist-item[playing=yes]')
clearInterval(scroll_interval)
scroll_interval = 0
items_container.scrollTop = item.offsetTop
), 100
get_next_item()
play : (e) ->
music_playlist.current (old_id) =>
music_playlist.set_current(
e.target.dataset.index
)
music_playlist.current (id) =>
if id != old_id
player.play(id)
@update_status(id)
else
player.play()
@update_status(id)
update_status : (new_id) ->
@list.forEach (data, index) =>
if data.id == new_id
@list[index].playing = 'yes'
@list[index].icon = if cs.bus.state.player == 'playing' then 'play' else 'pause'
else
@list[index].playing = 'no'
delete @list[index].icon
back : ->
@go_back_screen()
items_container = @shadowRoot.querySelector('cs-music-playlist-items')
if items_container
items_container.style.opacity = 0
setTimeout (=>
@list = []
if scroll_interval
clearInterval(scroll_interval)
scroll_interval = 0
), 300
repeat : (e) ->
control = e.target
music_settings.repeat =
switch music_settings.repeat
when 'none' then 'all'
when 'all' then 'one'
when 'one' then 'none'
if music_settings.repeat == 'none'
control.setAttribute('disabled', '')
else
control.removeAttribute('disabled')
control.innerHTML = if music_settings.repeat == 'one' then 1 else ''
shuffle : (e) ->
control = e.target
music_settings.shuffle = !music_settings.shuffle
if !music_settings.shuffle
control.setAttribute('disabled', '')
else
control.removeAttribute('disabled')
@list = []
music_playlist.current (id) =>
music_playlist.refresh =>
music_playlist.set_current_id(id)
@update()
)
|
[
{
"context": "'\n\n # Set auth if its given\n auth = if @get 'username'\n \"#{@get 'username'}:#{@get 'password'}\"\n ",
"end": 1097,
"score": 0.9948607683181763,
"start": 1089,
"tag": "USERNAME",
"value": "username"
},
{
"context": "iven\n auth = if @get 'username'\n ... | src/platform/node.coffee | Shipow/batman | 1 | #= require ./lib/dom_helpers
url = require 'url'
querystring = require 'querystring'
Batman.extend Batman.Request::,
getModule: (protocol) ->
requestModule = switch protocol
when 'http:', 'https:'
require protocol.slice(0,-1)
when undefined
require 'http'
else
throw "Unrecognized request protocol #{protocol}"
send: (data) ->
@fire 'loading'
requestURL = url.parse(@get 'url', true)
protocol = requestURL.protocol
# Figure out which module to use
requestModule = @getModule(protocol)
path = requestURL.pathname
if @get('method') is 'GET'
getParams = @get('data')
path += '?' if getParams
path += if typeof getParams is 'string'
getParams
else
querystring.stringify Batman.mixin({}, requestURL.query, getParams)
# Make the request and grab the ClientRequest object
options =
path: path
method: @get 'method'
port: requestURL.port
host: requestURL.hostname
headers: @get 'headers'
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
if @get('method') in ["PUT", "POST"]
options.headers["Content-type"] = @get 'contentType'
body = @get 'data'
options.headers["Content-length"] = Buffer.byteLength(body)
request = requestModule.request options, (response) =>
# Buffer all the chunks of data into an array
data = []
response.on 'data', (d) ->
data.push d
response.on 'end', () =>
@set 'request', request
@set 'responseHeaders', response.headers
# Join the array and set it as the response
data = data.join('')
@set 'response', data
# Dispatch the appropriate event based on the status code
status = @set 'status', response.statusCode
if (status >= 200 and status < 300) or status is 304
@fire 'success', data
else
request.request = @
@fire 'error', request
@fire 'loaded'
request.on 'error', (error) =>
@set 'response', error
@fire 'error', error
@fire 'loaded'
if @get('method') in ['POST', 'PUT']
request.write body
request.end()
request
| 202881 | #= require ./lib/dom_helpers
url = require 'url'
querystring = require 'querystring'
Batman.extend Batman.Request::,
getModule: (protocol) ->
requestModule = switch protocol
when 'http:', 'https:'
require protocol.slice(0,-1)
when undefined
require 'http'
else
throw "Unrecognized request protocol #{protocol}"
send: (data) ->
@fire 'loading'
requestURL = url.parse(@get 'url', true)
protocol = requestURL.protocol
# Figure out which module to use
requestModule = @getModule(protocol)
path = requestURL.pathname
if @get('method') is 'GET'
getParams = @get('data')
path += '?' if getParams
path += if typeof getParams is 'string'
getParams
else
querystring.stringify Batman.mixin({}, requestURL.query, getParams)
# Make the request and grab the ClientRequest object
options =
path: path
method: @get 'method'
port: requestURL.port
host: requestURL.hostname
headers: @get 'headers'
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get '<PASSWORD>'}"
else if requestURL.auth
requestURL.auth
if auth
options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
if @get('method') in ["PUT", "POST"]
options.headers["Content-type"] = @get 'contentType'
body = @get 'data'
options.headers["Content-length"] = Buffer.byteLength(body)
request = requestModule.request options, (response) =>
# Buffer all the chunks of data into an array
data = []
response.on 'data', (d) ->
data.push d
response.on 'end', () =>
@set 'request', request
@set 'responseHeaders', response.headers
# Join the array and set it as the response
data = data.join('')
@set 'response', data
# Dispatch the appropriate event based on the status code
status = @set 'status', response.statusCode
if (status >= 200 and status < 300) or status is 304
@fire 'success', data
else
request.request = @
@fire 'error', request
@fire 'loaded'
request.on 'error', (error) =>
@set 'response', error
@fire 'error', error
@fire 'loaded'
if @get('method') in ['POST', 'PUT']
request.write body
request.end()
request
| true | #= require ./lib/dom_helpers
url = require 'url'
querystring = require 'querystring'
Batman.extend Batman.Request::,
getModule: (protocol) ->
requestModule = switch protocol
when 'http:', 'https:'
require protocol.slice(0,-1)
when undefined
require 'http'
else
throw "Unrecognized request protocol #{protocol}"
send: (data) ->
@fire 'loading'
requestURL = url.parse(@get 'url', true)
protocol = requestURL.protocol
# Figure out which module to use
requestModule = @getModule(protocol)
path = requestURL.pathname
if @get('method') is 'GET'
getParams = @get('data')
path += '?' if getParams
path += if typeof getParams is 'string'
getParams
else
querystring.stringify Batman.mixin({}, requestURL.query, getParams)
# Make the request and grab the ClientRequest object
options =
path: path
method: @get 'method'
port: requestURL.port
host: requestURL.hostname
headers: @get 'headers'
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'PI:PASSWORD:<PASSWORD>END_PI'}"
else if requestURL.auth
requestURL.auth
if auth
options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
if @get('method') in ["PUT", "POST"]
options.headers["Content-type"] = @get 'contentType'
body = @get 'data'
options.headers["Content-length"] = Buffer.byteLength(body)
request = requestModule.request options, (response) =>
# Buffer all the chunks of data into an array
data = []
response.on 'data', (d) ->
data.push d
response.on 'end', () =>
@set 'request', request
@set 'responseHeaders', response.headers
# Join the array and set it as the response
data = data.join('')
@set 'response', data
# Dispatch the appropriate event based on the status code
status = @set 'status', response.statusCode
if (status >= 200 and status < 300) or status is 304
@fire 'success', data
else
request.request = @
@fire 'error', request
@fire 'loaded'
request.on 'error', (error) =>
@set 'response', error
@fire 'error', error
@fire 'loaded'
if @get('method') in ['POST', 'PUT']
request.write body
request.end()
request
|
[
{
"context": "###!\nCopyright (c) 2002-2017 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 44,
"score": 0.6208688020706177,
"start": 30,
"tag": "NAME",
"value": "Neo Technology"
}
] | src/components/D3Visualization/lib/visualization/utils/straightArrow.coffee | yezonggang/zcfx-admin-master | 24 | ###!
Copyright (c) 2002-2017 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
class neo.utils.straightArrow
constructor: (startRadius, endRadius, centreDistance, shaftWidth, headWidth, headHeight, captionLayout) ->
@length = centreDistance - (startRadius + endRadius)
@shaftLength = @length - headHeight
startArrow = startRadius
endShaft = startArrow + @shaftLength
endArrow = startArrow + @length
shaftRadius = shaftWidth / 2
headRadius = headWidth / 2
@midShaftPoint =
x: startArrow + @shaftLength / 2
y: 0
@outline = (shortCaptionLength) ->
if captionLayout is "external"
startBreak = startArrow + (@shaftLength - shortCaptionLength) / 2
endBreak = endShaft - (@shaftLength - shortCaptionLength) / 2
[
'M', startArrow, shaftRadius,
'L', startBreak, shaftRadius,
'L', startBreak, -shaftRadius,
'L', startArrow, -shaftRadius,
'Z'
'M', endBreak, shaftRadius,
'L', endShaft, shaftRadius,
'L', endShaft, headRadius,
'L', endArrow, 0,
'L', endShaft, -headRadius,
'L', endShaft, -shaftRadius,
'L', endBreak, -shaftRadius,
'Z'
].join(' ')
else
[
'M', startArrow, shaftRadius,
'L', endShaft, shaftRadius,
'L', endShaft, headRadius,
'L', endArrow, 0,
'L', endShaft, -headRadius,
'L', endShaft, -shaftRadius,
'L', startArrow, -shaftRadius,
'Z'
].join(' ')
@overlay = (minWidth) ->
radius = Math.max(minWidth / 2, shaftRadius)
[
'M', startArrow, radius,
'L', endArrow, radius,
'L', endArrow, -radius,
'L', startArrow, -radius,
'Z'
].join(' ')
deflection: 0
| 171935 | ###!
Copyright (c) 2002-2017 "<NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
class neo.utils.straightArrow
constructor: (startRadius, endRadius, centreDistance, shaftWidth, headWidth, headHeight, captionLayout) ->
@length = centreDistance - (startRadius + endRadius)
@shaftLength = @length - headHeight
startArrow = startRadius
endShaft = startArrow + @shaftLength
endArrow = startArrow + @length
shaftRadius = shaftWidth / 2
headRadius = headWidth / 2
@midShaftPoint =
x: startArrow + @shaftLength / 2
y: 0
@outline = (shortCaptionLength) ->
if captionLayout is "external"
startBreak = startArrow + (@shaftLength - shortCaptionLength) / 2
endBreak = endShaft - (@shaftLength - shortCaptionLength) / 2
[
'M', startArrow, shaftRadius,
'L', startBreak, shaftRadius,
'L', startBreak, -shaftRadius,
'L', startArrow, -shaftRadius,
'Z'
'M', endBreak, shaftRadius,
'L', endShaft, shaftRadius,
'L', endShaft, headRadius,
'L', endArrow, 0,
'L', endShaft, -headRadius,
'L', endShaft, -shaftRadius,
'L', endBreak, -shaftRadius,
'Z'
].join(' ')
else
[
'M', startArrow, shaftRadius,
'L', endShaft, shaftRadius,
'L', endShaft, headRadius,
'L', endArrow, 0,
'L', endShaft, -headRadius,
'L', endShaft, -shaftRadius,
'L', startArrow, -shaftRadius,
'Z'
].join(' ')
@overlay = (minWidth) ->
radius = Math.max(minWidth / 2, shaftRadius)
[
'M', startArrow, radius,
'L', endArrow, radius,
'L', endArrow, -radius,
'L', startArrow, -radius,
'Z'
].join(' ')
deflection: 0
| true | ###!
Copyright (c) 2002-2017 "PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
class neo.utils.straightArrow
constructor: (startRadius, endRadius, centreDistance, shaftWidth, headWidth, headHeight, captionLayout) ->
@length = centreDistance - (startRadius + endRadius)
@shaftLength = @length - headHeight
startArrow = startRadius
endShaft = startArrow + @shaftLength
endArrow = startArrow + @length
shaftRadius = shaftWidth / 2
headRadius = headWidth / 2
@midShaftPoint =
x: startArrow + @shaftLength / 2
y: 0
@outline = (shortCaptionLength) ->
if captionLayout is "external"
startBreak = startArrow + (@shaftLength - shortCaptionLength) / 2
endBreak = endShaft - (@shaftLength - shortCaptionLength) / 2
[
'M', startArrow, shaftRadius,
'L', startBreak, shaftRadius,
'L', startBreak, -shaftRadius,
'L', startArrow, -shaftRadius,
'Z'
'M', endBreak, shaftRadius,
'L', endShaft, shaftRadius,
'L', endShaft, headRadius,
'L', endArrow, 0,
'L', endShaft, -headRadius,
'L', endShaft, -shaftRadius,
'L', endBreak, -shaftRadius,
'Z'
].join(' ')
else
[
'M', startArrow, shaftRadius,
'L', endShaft, shaftRadius,
'L', endShaft, headRadius,
'L', endArrow, 0,
'L', endShaft, -headRadius,
'L', endShaft, -shaftRadius,
'L', startArrow, -shaftRadius,
'Z'
].join(' ')
@overlay = (minWidth) ->
radius = Math.max(minWidth / 2, shaftRadius)
[
'M', startArrow, radius,
'L', endArrow, radius,
'L', endArrow, -radius,
'L', startArrow, -radius,
'Z'
].join(' ')
deflection: 0
|
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\n_ = require 'underscore-pl",
"end": 35,
"score": 0.9995728731155396,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/core/attribute-run.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
_ = require 'underscore-plus'
module.exports =
class AttributeRun
constructor: (@location, @length, @attributes) ->
copy: ->
new AttributeRun(@location, @length, @copyAttributes())
copyAttributes: ->
JSON.parse(JSON.stringify(@attributes))
splitAtIndex: (index) ->
location = @location
length = @length
end = location + length
@length = index - location
newLength = (location + length) - index
newAttributes = if index is end then {} else @copyAttributes()
new AttributeRun(index, newLength, newAttributes)
toString: ->
attributes = @attributes
sortedNames = for name of attributes then name
sortedNames.sort()
nameValues = ("#{name}=#{attributes[name]}" for name in sortedNames)
"#{@location},#{@length}/#{nameValues.join("/")}"
_mergeWithNext: (attributeRun) ->
end = @location + @length
endsAtStart = end is attributeRun.location
if endsAtStart and _.isEqual(@attributes, attributeRun.attributes)
@length += attributeRun.length
true
else
false | 222815 | # Copyright (c) 2015 <NAME>. All rights reserved.
_ = require 'underscore-plus'
module.exports =
class AttributeRun
constructor: (@location, @length, @attributes) ->
copy: ->
new AttributeRun(@location, @length, @copyAttributes())
copyAttributes: ->
JSON.parse(JSON.stringify(@attributes))
splitAtIndex: (index) ->
location = @location
length = @length
end = location + length
@length = index - location
newLength = (location + length) - index
newAttributes = if index is end then {} else @copyAttributes()
new AttributeRun(index, newLength, newAttributes)
toString: ->
attributes = @attributes
sortedNames = for name of attributes then name
sortedNames.sort()
nameValues = ("#{name}=#{attributes[name]}" for name in sortedNames)
"#{@location},#{@length}/#{nameValues.join("/")}"
_mergeWithNext: (attributeRun) ->
end = @location + @length
endsAtStart = end is attributeRun.location
if endsAtStart and _.isEqual(@attributes, attributeRun.attributes)
@length += attributeRun.length
true
else
false | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
_ = require 'underscore-plus'
module.exports =
class AttributeRun
constructor: (@location, @length, @attributes) ->
copy: ->
new AttributeRun(@location, @length, @copyAttributes())
copyAttributes: ->
JSON.parse(JSON.stringify(@attributes))
splitAtIndex: (index) ->
location = @location
length = @length
end = location + length
@length = index - location
newLength = (location + length) - index
newAttributes = if index is end then {} else @copyAttributes()
new AttributeRun(index, newLength, newAttributes)
toString: ->
attributes = @attributes
sortedNames = for name of attributes then name
sortedNames.sort()
nameValues = ("#{name}=#{attributes[name]}" for name in sortedNames)
"#{@location},#{@length}/#{nameValues.join("/")}"
_mergeWithNext: (attributeRun) ->
end = @location + @length
endsAtStart = end is attributeRun.location
if endsAtStart and _.isEqual(@attributes, attributeRun.attributes)
@length += attributeRun.length
true
else
false |
[
{
"context": "KEY BLOCK-----\nVersion: GnuPG v1.4.14 (GNU/Linux)\n\nmI0EUqpp2QEEANFByr3uPGsG5DqmV3kPLsTEmew5d8NcD3SqASas342LB5sDE0D6\n0fTDvjLYAiCTgVlZrSIx+SeeskygKH/AwnTCBK04V0HgpR0tyw+dGIV5ujFIo236\nO8XvIqaVoR1/zizy8fOSaFqr8rPQf3JYWxQn8IMLUS+ricOUZS/YSgNVABEBAAG0\nM0dhdmlyaWxvIFByaW5jaXAgKHB3IGlzICdhJykgPGdtYW... | node_modules/gpg-wrapper/test/files/keyring.iced | AngelKey/Angelkey.nodeinstaller | 151 |
keyring = require '../../lib/keyring'
#-----------------------------------
class Log extends keyring.Log
debug : (x) ->
#-----------------------------------
ring2 = ring = null
key = null
key_data = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.14 (GNU/Linux)
mI0EUqpp2QEEANFByr3uPGsG5DqmV3kPLsTEmew5d8NcD3SqASas342LB5sDE0D6
0fTDvjLYAiCTgVlZrSIx+SeeskygKH/AwnTCBK04V0HgpR0tyw+dGIV5ujFIo236
O8XvIqaVoR1/zizy8fOSaFqr8rPQf3JYWxQn8IMLUS+ricOUZS/YSgNVABEBAAG0
M0dhdmlyaWxvIFByaW5jaXAgKHB3IGlzICdhJykgPGdtYW5AdGhlYmxhY2toYW5k
LmlvPoi+BBMBAgAoBQJSqmnZAhsDBQkSzAMABgsJCAcDAgYVCAIJCgsEFgIDAQIe
AQIXgAAKCRDuXBLqbhXbknHWBACGwlrWuJyAznzZ++EGpvhVZBdgcGlU3CK2YOHC
M9ijVndeXjAtAgUgW1RPjRCopjmi5QKm+YN1WcAdf6I+mnr/tdYhPYnRE+dNsEB7
AWGsiwZOxQbwtCOIR+5AU7pzIoIUW1GsqQK3TbiuSRYI5XG6UdcV5SzQI96aKGvk
S6O6uLiNBFKqadkBBADW31A7htB6sJ71zwel5yyX8NT5fD7t9xH/XA2dwyJFOKzj
R+h5q1KueTPUzrV781tQW+RbHOsFEG99gm3KxuyxFkenXb1sXLMFdAzLvBuHqAjQ
X9pJiMTCAK7ol6Ddtb/4cOg8c6UI/go4DU+/Aja2uYxuqOWzwrantCaIamVEywAR
AQABiKUEGAECAA8FAlKqadkCGwwFCRLMAwAACgkQ7lwS6m4V25IQqAQAg4X+exq1
+wJ3brILP8Izi74sBmA0QNnUWk1KdVA92k/k7qA/WNNobSZvW502CNHz/3SQRFKU
nUCByGMaH0uhI6Fr1J+pjDgP3ZelZg0Kw1kWvkvn+X6aushU3NHtyZbybjcBYV/t
6m5rzEEXCUsYrFvtAjG1/bMDLT0t1AA25jc=
=59sB
-----END PGP PUBLIC KEY BLOCK-----
"""
fingerprint = "1D1A20E57C763DD42258FBC5EE5C12EA6E15DB92"
payload = "I hereby approve of the Archduke's assassination. Please spare his wife.\n"
sig = """
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.14 (GNU/Linux)
owGbwMvMwMT4LkboVZ7o7UmMpwOSGIJu/27zVMhILUpNqlRILCgoyi9LVchPUyjJ
SFVwLErOSCnNTlUvVkgsLgaizLzEksz8PD0FhYCc1MTiVIXigsSiVIWMzGKF8sy0
VD2ujjksDIxMDGysTCBzGbg4BWCWrVNjYWg1Py9w8X/oMuuysk7JcilXkWqjy9uX
N8bOfbp+ZZK7rYGMD++edRt9Mk5ITp+2cPcunVXv2FmCO6d6SD3lnOybvcXytJFt
S+fz1cqTPdi3dT47XXj97IWY65u1pO9HBUZmy0/YzihX4Pz/ZIO7hnfb1N4l7Fw/
Hz30FTkcaHWq7oPoHAWeYwA=
=2ENa
-----END PGP MESSAGE-----
"""
#-----------------
kaiser2 =
key_data : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
mQENBFLf0DYBCADGz/jWmSDY8c4yVorLgDXK1GpHmqmGOaacBjdSC0Os0+oBcvI7
o7rVZkkOeHoLGfr4HaQ6iXF61PxMjRpvUmDMrznrYGnOsSiiY0S6IFmAoEnu7BqI
2ZPQEwqxV4o9iQ6ttffh0LC/5IX3+0sXt6uWebAyE0fW3Rw1drSaElUdzXRu7/nw
e75oLhNSVguLFMhhs6VvUglcYRsZJN+hNOW0oVOIBWHDCtI713U/wFepaOov0g48
Ysj2gFLnhUMGPgb+yTKeDLvlQQCZoIXBWWTy7sM/LU0xsegP0Wpsv+aj7fNcoxYp
tuqQwPOzu35B7J4++ECmQ0qoVND9j5iChA2xABEBAAG0IkthaXNlciBXaWxoZWxt
IDxrYWlzZXIyQHlhaG9vLmNvbT6JAT0EEwEKACcFAlLf0DYCGwMFCRLMAwAFCwkI
BwMFFQoJCAsFFgIDAQACHgECF4AACgkQY+EQEyiPLUiCcQf/REXdwDfJRHc7DpWJ
M/o+NDke4d60gh3wtNRUWlsbAF/Xc1aZjEJt0xRIx3QJ8P5+FYfMsk2/05UfXmrg
KE69AEP2x3FcbnkYeSG0jwbDi5h7such17SDxV9M/s4iHjJKBglyDxYltG2xZ8Xu
NNTi2VkvvulrRcwonQr/hPDibMKIgY7Xrxw3nZK/pOOXaidcIvuoGpOd9w3UniGc
zOzSi3CqTQrpf+5/p0rZE2tdJdNTm2MUww8FiUzpzdUfMAunVSpK1WazpWXkJ9sS
4H6dE+GUWh71f4j69NNfzOG4YWQ6syjJ12BtlLRNl403LvPubhVaKr0gHF5wEeI0
4h0YR7kBDQRS39A2AQgA6Vfl/9NBltJOxQ921rJJTqsjxW/chIX1HGYEYWRrJrfD
iEoC1jYDOKmP6q6PYREeyhB1G5uER2FQnjtxY8Wo+BpwsJ+s/stgRZoHUM2AsmPb
rnEt8J781trSjbTuySgRkqsQAQizhrsAq0jnpOCmAPVbsFvC4oV9kjiXDOet2j9j
tfZ5FnfESqQ0tmrdIXvKaa3+jE5hnRvyhBrwyoYny6SBw4eqogUjQnUa1yo4X0Si
dPmNDA6DdIFG6+OxR3emRNxeuYRq3oHJLAalGlhMQCn8QK1RyoyRqDcekMHB0hYV
uNgxgta11hIdipBohrJIeKVcGKXt29XSnS0iWdm/DQARAQABiQElBBgBCgAPBQJS
39A2AhsMBQkSzAMAAAoJEGPhEBMojy1I1t8H/3hXg/3WwN33iY1bodU8oXYVBbKG
pjs/A/fP/H3+3MqG6z/sspUfXluS7baNRmg5HB300vMGqPRJ5EU5/anOu/EJxj1A
NJpSiJnXyjwVx7EviMgLPlZC0HTYNPsiXZLe7p/WAWHy5HRH9iAgu0IOPon1MniV
9lgJHsOS+zF+ostVB6PFglEJt4y7ySeFuxpRTi0ulYyO/LHW7nJZkl6xzpvykJws
3it8W3ecYAodkySzgLN8zqS8nlqlsJgO/NYIQd3c67MKA+92A75VlCMJ25SrsaVm
Enqh2naqYfmkmhWk5KInf02pSAwD5I/roTYO9kO1QjLrVj1d058K2/T2Z0o=
=U857
-----END PGP PUBLIC KEY BLOCK-----
"""
username : "kaiser2@yahoo.com"
fingerprint : "A03CC843D8425771B59F731063E11013288F2D48"
payload_json : { ww : 1 }
payload : '{ "ww" : 1 }\n'
sig : """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
owEBQwG8/pANAwAKAWPhEBMojy1IAcsTYgBS39KUeyAid3ciIDogMSB9CokBHAQA
AQoABgUCUt/SlAAKCRBj4RATKI8tSN+tB/90cxDDxC0PjoPqbO2ZrbI1q2FGyZI3
Ayukt+u/cTadECcigJzE05ymKevKCVJFHASEp4SMn9nW4QSD5fTRcqo6QBfWImQi
UYbirBvhejAARusJmLKtpmosxxsiEYQ1bcFJjx2+UQLr40uw5RHXfgP8CuUqadrw
Wm+wqLwUwXxbrYb5FCZ8nziEUwOl2rpqV1NIj59D3BZps43Q5QCCTRZF5+eJJyg+
AhyYGythrOMbYKWmRRGhIdy3QU34IHGxNh3o2bz6YBiM/JD8CY0M0HT33xU93LvB
7UowhdY7p9M8R0Ql21T4+5AOxPxHQIypRKOl5oJPvZg8avtDT8sc5fRw
=Uy2n
-----END PGP MESSAGE-----
"""
#-----------------
exports.init = (T, cb) ->
keyring.init {
get_preserve_tmp_keyring : () -> false
get_tmp_keyring_dir : () -> "."
log : new Log()
}
cb()
#-----------------
exports.make_ring = (T,cb) ->
await keyring.TmpKeyRing.make defer err, tmp
T.no_error err
T.assert tmp, "keyring came back"
ring = tmp
cb()
#-----------------
exports.test_import = (T,cb) ->
key = ring.make_key {
key_data,
fingerprint,
username : "gavrilo"
}
await key.save defer err
T.no_error err
await key.load defer err
T.no_error err
cb()
#-----------------
exports.test_verify = (T,cb) ->
await key.verify_sig { sig, payload, which : "msg" }, defer err
T.no_error err
cb()
#-----------------
exports.test_read_uids = (T, cb) ->
await ring.read_uids_from_key { fingerprint }, defer err, uids
T.no_error err
T.equal uids.length, 1, "the right number of UIDs"
# Whoops, there was as typo when I made this key!
T.equal uids[0].username, "Gavirilo Princip" , "the right username"
cb()
#-----------------
exports.test_copy = (T,cb) ->
await keyring.TmpKeyRing.make defer err, ring2
T.no_error err
T.assert ring2, "keyring2 was made"
await ring2.read_uids_from_key { fingerprint }, defer err, uids
T.assert err, "ring2 should be empty"
key2 = key.copy_to_keyring ring2
await key2.save defer err
T.no_error err
await key2.load defer err
T.no_error
await key2.verify_sig { sig, payload, which : "key2" }, defer err
T.no_error err
await ring2.nuke defer err
T.no_error err
cb()
#-----------------
exports.test_find = (T, cb) ->
await ring.find_keys { query : "gman@" }, defer err, id64s
T.no_error err
T.equal id64s, [ fingerprint[-16...] ], "got back the 1 and only right key"
cb()
#-----------------
exports.test_list = (T,cb) ->
await ring.list_keys defer err, id64s
T.no_error err
T.equal id64s, [ fingerprint[-16...] ], "got back the 1 and only right key"
cb()
#-----------------
exports.test_one_shot = (T,cb) ->
await ring.make_oneshot_ring { query : fingerprint, single : true }, defer err, r1
T.no_error err
T.assert r1, "A ring came back"
await r1.nuke defer err
T.no_error err
cb()
#-----------------
exports.test_oneshot_verify = (T,cb) ->
key = ring.make_key kaiser2
await key.save defer err
T.no_error err
await ring.oneshot_verify { query : kaiser2.username, single : true, sig : kaiser2.sig }, defer err, json
T.no_error err
T.equal kaiser2.payload_json, json, "JSON payload checked out"
cb()
#-----------------
exports.test_verify_sig = (T,cb) ->
await key.verify_sig { which : "something", payload : kaiser2.payload, sig : kaiser2.sig }, defer err
T.no_error err
cb()
#-----------------
exports.test_import_by_username = (T,cb) ->
key = ring.make_key {username : "<gman@theblackhand.io>"}
await key.load defer err
T.no_error err
T.equal key.uid().username, 'Gavirilo Princip', "username came back correctly after load"
cb()
#-----------------
exports.test_import_by_username_with_space_and_control_chars = (T,cb) ->
if process.platform is 'win32'
T.waypoint "skipped on windows :("
else
key = ring.make_key keybase_v1_index
await key.save defer err
T.no_error err
key = ring.make_key {username : "(v1) <index@keybase.io>"}
await key.load defer err
T.no_error err
T.equal key.uid().username, 'Keybase.io Index Signing', "username came back correctly after load"
cb()
#-----------------
keybase_v1_index =
key_data : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
mQINBFLdcuoBEAC/cjoV7ZpfeQpa8TtCxhce+9psSFq7qrVrKHZDbGEHN3Ony2S+
P+7DBZc6H7dIKGBtP0PDzA/LLImrL/1aQhfdA9Z/ygbmLvNXKLIjvx5X0DAkJQXO
1jMKnYznd/aBzm/NTFRjHX/JvJrJPImTHsALfbxjL+po5Grv/tJwSlT5wAXNrLiM
9zRZ/iJLJZszWjQa9mNnOkJD8Ql8MhaZqzcUjW++Sj+ySztptblAaLXMorvdrNc1
u+2pH64wTbW0XOzzNHGjX7UX5wsfSQH6JvsxfmpNGKcCw56Eaj/62QxMEHLwakyU
CSYc8AK2Y9/EDYfbjQBGhYepgUmUxXNWPLIvtBBHosagwqo4FzM4lWCSQM9PT36w
Bj0H+dF8EK/rGsl5Zoh+Z92Cac7QEQDrowghXAizEY7VBmhhmR7GPGlvRwXhQEkZ
vuKTV4pVxr9ff8i7oiasCUj0FboQOyWurPUNhDK1V+rWiL6hd7Ex3hCPTR2jUovh
IS8addJlxKx4tE+vamwMLOV4F66jfAEtpWj7u8wKL71iapNAIGsUsJd0t4Kvkxv5
GECtUJy8eYnNJm2sOQ61zGP9RwFgFV9nRikPptb4gvVClFE9sdY3Xx5jOSd9B9Ed
ALd1c5VGs7MgkL28I7Vo92kJm/Y2rjSYB/y4e+QgEx83v2QdyguWkptgmwARAQAB
tDBLZXliYXNlLmlvIEluZGV4IFNpZ25pbmcgKHYxKSA8aW5kZXhAa2V5YmFzZS5p
bz6JAj0EEwEKACcFAlLdcuoCGwMFCRLMAwAFCwkIBwMFFQoJCAsFFgIDAQACHgEC
F4AACgkQGZolpX+ei/rS7w/+L378bJlqEAY4EuHKNdEqTeEoSFOlgFgo4CJiJvsA
QCtjYURO9YCEg7vh51O7M0ML0IdIGqxf9+4tAbSKqfYjtlCNS72vb61/gr+W8enb
8zD3Kun8d3GOUQYrj7pDvkvlvngKgotPYXbSEISSdD0Oligapd8+nYinwTMthnzq
JfCP9qjc0Yfby/di3/PdqTKKqgn3VrOsFwqYqMihO09cA3929BnmINJYg/eoSikX
xYToZvJHUSL0GAvH2d5vge/xTLVl0NZTOM/ObnikO/6y2y4bs/fpikf/v/99t2F+
v8kchSV5GHa0uVXBxmHl+7lwfLg3ebhtUU39B39oSeEDDjF/jJOvfdVExRRKWX67
7FF5Mt+S4zkLv0CaMeEloeQ7FSJcjSJw23uww1pwPdTfZ7X2DhCcr2cR6iKFDkbW
9Om5H6TO54yRqC5d2K7wMW/QRrBsdapVhoBwJiF1bBdE5e8moqdBo+fgurb9SVKd
9HUfG/4/7aZVGaur3yeeVNsS4OfrNzqdmHDh1svYR/pBJRdFq/ZBK5T9uKpwvGH2
Xibh3s5LaKiM31viTZ5Kg32RStIbEPR/lDgdH0FgEzreJ5gVzu558s6TGJdxkK8z
zSlfOvfJLQBkLDauk0OmNcN1SIv9UcUlqZx2dMnpAQo7dDMAUImkTtKV9brRtKQO
3vqJAhwEEAEKAAYFAlLdipUACgkQY4R7S4OTDwwyRQ//SxphV0JLQYgo+Sp/J54O
4lRhfz/jfAmLcJlkYikn1sxsH057vx8+wPJUeOQU0vhY2TMtqw4IVdm2yO54h+Mw
TtGrrpawOLdzBtt2ahGo15SJfGOhJMs5NtuaMZ3P/kpdOxuZTpmqhmPgK8BgOp4U
tfmjlZQriczGYVnO/oLwhdu14xy0uDkybp/dpWEBAR66P4PqVfccPoJLtqh9UKiI
oT2ZxalC4coCxxoFCkYkC8OHtmDBv0y9pPBP661Xo4lGjxvfMURpAuz3qu5bT7b9
Es4Z0wHB7kJQtM8uyrIIkQsnXRlpbP9cSDxyCSuajw2LWcDHqvYvItiwJpoOarim
3XBX+Y1forELjQf0s2InanR55yg1fI7tGxPu0uLnyqFEs0w+BwDV60L7nScL6po8
gbvUbFk7mniqVKF1xo7KIyMBY98XGCALEa5bANZnbSmPxghvbSL4Sp2dVkesqjH0
qNAvH7tIV90uNOGJ9AFyAGEZ0LMXjFL2lYSpmG8CqQEZiNwHgMi/8LfZaDsL2Kwi
qRPpt/WfY/V6aUw3m6+ltTBoljcSRKGT+XrW0ZHJc7vKDWPYzD+wJ83RW1fHVOuS
fF3bMlS/Xl1GSXfQzjs8ETyJtQj6zsZjVeklwlCxwmECg6HxrW2aojulEfQyiMCE
jlUWW31LLuqACOkpWvghb7y5Ag0EUt1y6gEQAKeNVFJsH7GICHFvD3C1macxMk49
B8KVH7+VMl7d8yqmj01VDxaSxK5aR8f98CNG7hTeK5RimKuyWlg+IRAbkwaly+4N
dewkXKQNzVQohi9Y8z88+lZ243KeOnrhZohui5zDg85kzDR8KkkkwEuCC5P3xXHN
TFW06O+EbAz8jL0Fyu982U8ZQaXV8kwklZhUpnCx2ZR+6IHld1bZ/dzedXipLJ8j
bLjsBIw4grp34VaOa/y0zRSZ4Yir/dXraZuhV931q2Q7V8ZlHtnuwSGnAypuzq5V
DMBlQ4E10M8qoAmzNVsfRxcyP6BzjY93KJJrDNnyDsKI46bAMccOZvKaPbtxEzk1
AZYsABn4qJCu6L+NMrpXntGb+E8AyAErJDVya+6F1iZCGYQIo7i9oaQ7dWgUXUXw
YfSVF2TDxw7YBw0l7qYk8kSPMhrN0N/dlS0bJNzqJeWsRI3NLph+7SrGMBzuBXWT
1KQ69ipQGvUFOE/zTw1Sqa9ZLuIlkuqxIGb4D3dwrm3fJmj/QNGN5FkUQP96nA5z
4oeVrbQQ1wU0KFq5E0kSjxFgBDLNqy6RehS+ENixtiUTEzB4/3HwDfz92a0nIgrF
cjK4BW2HB3YQ4q8WHUUYrhLLw555OKFbbyStP2Fs2jX+CMUjSgW4Z1REieaJidCo
BfOMAOcGSPEZD6m5ABEBAAGJAiUEGAEKAA8FAlLdcuoCGwwFCRLMAwAACgkQGZol
pX+ei/qBeg/+NiEj4IVOVgAxC+jTrIkhckcbw1IWsio2rGSxji6G71dxQieVtHBe
ib3TjcfrC8F1iIJx9tohnLMh9X0x9YpBTlJnbCrPXBNyfabFB9yRY00wKVs1dZy3
BW3jQCF5/ul2gFs/VKsn39ycTdAMliuE0Cy0xbFs3Nq/6BASl1Lh7Oa9qJl/PeKS
GwkVbsBzHjt0exV+5AlBBC/djGihVvOJ8uaUEwBgGm4NH5tcnjlqyrqcIrq0DpAM
zQImLN7a3fKSbR5Mdh37fYUEVaNSeyp+3hSLmBZ7twfC/lmYUGxvCjl+6+Wq2t36
U2BAgAuaTcN6dcY+wRVfu7DOBt8M3MgwO/QgEOsvyNRTwbKaEysUc6TiGt+jU2aT
Ih9BEWPXiQ1C/aUJ45ROfyZXBlm0+b9eECZt/n3TpBCeMfjDTFHUorqJT/bFSsgT
SZMGEc/UCiNZIFT804DzNB8l1jIJy49P3Cz8UxG6WzVzfeZTQO6xTP4ZGACIV7bH
7zbSIWdw7cxiiu2kb/oiiSimqQ4uJ0ywgfrsD8u/vpKBTCOcg2QtcB4feYi8BoJj
jsltz+iIRjeUjJekEqAagyaczXRsvEP93/6uFMaNSR9g2TqqALHql0RZMRdAciKa
L7FdE0JqQ2e8esB0oSswPy033CExDiDzdwB+ob2fICgLrWTvk47QX/g=
=kK8c
-----END PGP PUBLIC KEY BLOCK-----
"""
#-----------------
exports.nuke_ring = (T,cb) ->
await ring.nuke defer err
T.no_error err
cb()
#==================================================================
keyring_raw = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
mI0EUmGJaAEEAM/gj5yRV4q/3GDTJE+WammHO/UBUhUymEHD+esXygk/EK59YZDf
ropicBsnun0KJGw/I+0dYtUlEYI9JDjtcmXLJiRQ80pnf+9Jk29ZDZfsMOOBzMqb
TBaYRuEhimi29Aqg2xpjz9Eg6AjcY7AxbS4rNij83f3oKAOOlXq3aQilABEBAAG0
Em1heHRhY29Aa2V5YmFzZS5pb4izBBABCgAdBQJSYYloAhsvBQkSzAMAAwsJBwMV
CggCHgECF4AACgkQhPz25wF28buuIQQAzE4i3C6/L1e2/x65uZM6do5QATH/mzRa
0T4EhIg2TxXjnFALTNeswICH+M6/bzsEgTrT4r5NGxI9wDEsJbBq+eOYZbkdVtbQ
T3MgLmrfaGMPW/d/i3yVAhQMACOVfPtIhHqgoxOKkrBrMJpJuz5MHF1AOHyLHjks
YUzL9GU3qkm4jQRSYYloAQQAvlcAkUPPa+VSJxfCjV8VKgZkz9I1QoBHcr4GjLpZ
RCRgaM8+QDgsS4Dt41c+V0/TnsNKZsx39PgYnCozfOj0VkZFYkUlKaEF3AJqz5En
lelKdQkMBy5u1pwVWe5EucdpEARTnMmrSqi5u29i1GzLhdtFlfIdcRPObL1/SIFK
ch0AEQEAAYkBQwQYAQoADwUCUmGJaAUJAeEzgAIbLgCoCRCE/PbnAXbxu50gBBkB
CgAGBQJSYYloAAoJEOP3tdmxSNwFwC4D/3UNnN1socTcSgMeuB3t+FbV4UklhkVr
nCxbDdy8J277uG1dX1bW1BK9yLOTpwHZ4jp4ejlVLHgPIvjnqGQgU1YeXnu4lrN1
ggPk25CFHwxjB94DGBSF8vE7sjlo2PwTGx7m3+vD+DIsCXvZ4zUvUbERrch8z0EF
6MAW82Nvki9MrxcD/jPo4jkgUrBC9HeshjtGUAmjN82Ecx+BZh+lG2Q928fGZiCA
KiJ05RKxFoVkS7pWEdJoi2RUS7qsbcMjvpnZCz12H81AzQn/JvrwV2RHz/gy3hze
WHykIL9Y24Se1lmxx510AA+n1UiRPjVJWl48S2cXBtAshvNT21MmWC37cWG+mQIN
BFKLi6cBEACcP/W6NBY1Dy+1Tm6LWOpPGbP1DsxP+ggIA0LmxaXWwL6g/2KvoS/J
VmmY1uXIiiZoMqCTZq1RTlQP9wh/ky61XxZmElKxiWKvdgVql5XYYQxJUH+6vJHP
dcLOQeW6MTlP/cy6r6wFS4pOZ0I8gquufYcSp3IiCyDRfGndfZno3YABjC4QqtTw
PKMh4o7G4ScV6SAKWG28mHF02BkXTBlZCWmhI9foQWu04I45m6Eg00zaS2dYX8nw
U5H6k1N/3RUMYCJVmDOMl+p5Aml6ZuXhnUv0ma04yqeE0LsbVhsPOcWnVd4F/+x+
RJlhqM7v6j+mi5bSYrJSxzaXwBjQdSu/yTKsao799EO9Kt4D6D96Mg8AeBp7tsuj
OfQDCc4JKzq19V8CSbE1iwyuqVJOytp01guljwRedNbcAWcMkn/Mv4M4HMV8push
RX7guAxZrjpCgaWabThRXuhUhrhMXZie+kDQegczbuUG1w2RO/HvJecUX5E2/lmE
j4NA/lc+Ejgr9NGczC5Osf7TyJhcuaC9QMm/Mlfseb2d9DRb4V6ZOC6akZOlgRML
lFwWlfduGNGq8HWBETSJvMoh9Ef9nfEgdBi4Pu+WVAd3FDCbfhNj2SS79R9WPHAg
qHJD1/qv8NV1u8EmvuJP+/Nw50Dp5sBqoi5RTYJO+iLWaY4vDyMafQARAQABtC5L
ZXliYXNlLmlvIENvZGUgU2lnbmluZyAodjEpIDxjb2RlQGtleWJhc2UuaW8+iQI+
BBMBAgAoBQJSi4unAhsDBQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAK
CRBHSE5QZW0Wx+MnD/wI249WjV9x9hW2085KtRQK4U/79Y8BqDrw1JW9l0oppPZ1
n6ZRnpSel31IucC8NupFA5AyK4KuxMNej5KLF2kaqdgzlcuvSA6npQkyRnohE/PW
CDEJg/GE8DiqzMQx7yD/7rQp8I0aI9iX0SJCPqohuyYNVFBEamcLn+tDbH4U0jur
PuuAKtRSGxjzhnEiPM1hTgbQv8A1FY3IPClAfXlOK1RWI8pXSWfJFx+hT0ZYR+mS
BIwLhfobvip6yLM6I47IMdLTzi0ORatgDIEk5VHuHscDvgukVelmAql3dq4OhsnY
sT2G04r6L8Ksa6DKY0Y8QpQGjWXFcWp628f/XhFl3vaGho1nRxMcafvgpiJABrdL
mSl6WDEwXFYv7zozmU/6Ll/gLLEAcCSTX3+JLgqghUbR2CXTTAf2nD7oFOEp7p1+
sVyAPMhN76T+lrVVa9OZ7eYNwIUTp3VHGKlARI0kQvAs04H+PNOK/S2e81hnTqMj
1MpXvfJw6RtCl+An+lIrAOJiORxZv0tDgwm/u2DZGV4oLNBXGucnqjXMBj1fNcd7
FDcEiQ6CXWvmJEGNFsaD0tKtESTR/dzkAzN643qzd0clUV+N1TUD2q+LHA+QKk/e
nBlrPgW3VQEL/OMK0ugOMlmFBy4008fZG+kt84BLo/3Kpy3tMy7fLbFuvlWpWIkC
IgQTAQIADAUCUouLwwWDB4YfgAAKCRBjhHtLg5MPDMNZEACOSu3YQOkNIjmXhMPF
WtSUB++ktfhx7GSmeBzFx6BIJc1U+Kfpu4Cr7tpZTQk+k4lcmrCsZmkBElgDw4vW
Q4hOns+/L7ZKyj1/XyalAMZuLovzZL6E8MU7BycLfi2bvP/bNb0Jkm+e62T+gzuP
dSjHy2RUkr5Ofe2cvnzFc0cjzQPyOfoOkSB68OOM6DAAMbt7xZs7iex0iOxlNSYx
EOsw9+CBiHuLU08hnv4PlxfYiNouBbgeDEmB/ueMQpV8uKwN65rUYV0UHY0QhU1T
EwgBdde/D1io2fLLhWhxxLK+k2D5Kpb6fHTbVAvREWyjg93JcRqiD0vZqyE+4t6Y
9Bjc1nKkqHAz70viuxusCBS3zOwHInatOav0vOlXO67JNcdGO+HHv3+4KUeQvqsg
EfWMfvd48mjeZ7sU9Whlq0WJyeeUI2TRxReioBay5IcfysBh2s/G6rLKGuiJK7Rj
ixwkrJPADbCoIhJCivqdTMAG1HgQN5an6XDfYemwECJCRK8QTI/UwNVdt7p84qcY
DagrWiE7fB8MG98peXRVL94ROY3PCBbcWs5lFIINmaaHXOBGMb/RTh9EjxNBWwyi
fIsUkYuUTUEnzH8Ctdb/dcq98y/47JfaLxbMepC2E0bMxFZTtnDbhXUbXzongY5f
180kFDHOB+UJtKL7DUgFs5Vm3YkCIgQTAQoADAUCUouz9AWDB4YfgAAKCRD7wH1q
lwFss8A9D/9XYIuv7nXk+xaoWxmAJkHgNI2gcADLncxuiCZn43x8eD7xqjU8Dyr+
cFuHTldfVDDR8EaUWjGdmOrLNILgCIzmddaBdX0vf8zAvtSWCFtf5PSRpCINFyez
tA9kETjaSpsJLkdX6dMLnXOTTcP8ZT7mglIGltN/ys7SLYzcQufkbgLt1jLj1dHK
DuG204Z/DSXi0olnFsMp+JgnX4D5LtgfivF2m2DwMjZZSKoGP9ZVI2CaHex6ar1H
0NbbhOZQeaguqnBqm4xKOAY9vKwYVx5hsZLB8E48iCMyg3J5cfIGmmGNpT8V7i+K
1oV8TLl7KlTbVpF+Vq0HYGmdEpR0r1tE+HVJHWcmGtm0gVshnXHRxR540g4UGnN+
ykaRbHoy/6JGnct+4+E4YDcR97q7kwZtX+OfKIzO152WAp/Rdobea0zdGC12QK5c
JA+krYeB2waFFvuvV/ewUUCMwBDMTqhmrMoRQIcqsjQlGOUOyUIdO5BiTfjJ2rs9
pgvErTvenFZLKU6kp810iboHk2D+8eaonLhU1q37Iod5yfqvFuMRW4k9QS5+Tbpe
TCfRJ1VFZnSg9FpAIXzdMgRTNVrjvCaP79yjbEJX3n9X9isJkKjcYMKFG8CVLm/8
LLdfxMBNjOXIYtNCRpUB44AmtV0dzFH/XFQBLngyL2EnLWWy5cYEs7kCDQRSi4un
ARAAupbqu77i8emuB5zV20nHVrjT+bc1cp3iqwIakK/QBMNNjzefbHUpDQ6Lpnu1
/bykpO5UXmd9iBaL9nzMFyZR6bM/c7mjknaD0sV60aMOUAOwE3syXtQ+Go/J7dua
bWTXbN8VKiEAS+uYB1DJDvwJjCNj7viju/KveBLLHZiUdQlQXzRdnnuoPI2AZrKi
QjaUM5kLiYTyxKiBVtx3IX9khl9zg2sUthWke/DiH9W6l1nKYFkxvxheJTJoGLFq
nBUrPinK/3TsH/sKdR8+MfgUCkEN/SCRcsvczanMogGO6O09Gb3F3msLBX20Fs6Y
MSPXlZSI8odLAJVZnBxUjfwgplx5paqkg+1Yv2ok096MHzH7AzeCeZv6Nyf60Bij
rheMLOMtaXialot9ppgIoNMQcyretXepSPMgfBncq3o6A2FSHoiVJK94CEbCARMv
LrAiJfBt2SkrF8L+HaSOL8Ebt7yw85EKZjPhbhAA2Myv4FlBDJAPZAiUjSopkK+L
hSaFomQpjLHP5ZA2GvKIJn1ukgqSNrzdUcwR5SjxXijb8ecRRW8z2WCHT4P+W2en
WBKpleaDlbOf6vv+zkLDD9/OUMKMO+/yBdKYbW6N9IexIvbXy+mRv9WfSq9wG0N6
frYg00bp1H0F0D5kkAR/AMKTNyCSRFOqAsRhwlsgAy+W0qsAEQEAAYkCJQQYAQIA
DwUCUouLpwIbDAUJB4YfgAAKCRBHSE5QZW0WxxlYD/9cCGSNKR5twDvF8bI4TzGP
aHlA6IgY3yQGnbrxFXnY8XTMZXUgR7hVuxeoTsd5LXm5WilhydIIRVtSijRkrUC6
POuFbHqOodLohpMCyumFi/HVVbW0MEwwrFoyRm+aXymZid0nkHHbCO7j9pA5CoGq
fxNs3huhIYF6n2Gs+VGTTnUcrp/VkmwuJewiHFc6M11WKQBgmkNEYC0XDjO7aPsC
texiYryjoryf7CFHCnc7dYaULwB9Zp8OnZiBStSXJh3cWHAljiK3l0KQJcQb9Gfx
osY5xO1UkZSAgvwUbaU5qRxn95MOem9hnDkDGm6PbMZASi5scdE2UkpuFhNEFHIg
Om1LP5gKgdFHFeXYSd5ODnAjKnv0bcEW7E47+7ySX/snPhLOpbOW6K+X/JWMOVVi
n+5fk4ozJvWyyzQzr7oejmHcSoHsVMf5SUCzI3GPBPvuZKuAYwiRROFL6jNwqU+5
xAyRmiHr7PRzs+RDIeGWCSFqSlzvSk+WWCaGaD//uhFQROlX/209moyiFe2r3g9P
CZ+43F+uzn/T4DRpmOzOESxMySFgGBK0Mz8oo5ETgMtr22oHgCtdnjQ7u9x9Ajo8
SVNv+WMeFj1Xd/VnD1W9qByJkmnrUWd2WLYQQ8ROJDPJKPYUKXam03UJXZidoJO3
q10K/XeP2GohBf5q0imfU5kCDQRStxTMARAAuF4E7x4OOn5lWUEEBTbhID9C8H6H
3PLe1UG8/LFCrdgmVIAd9fJh3nJNvtJ00mrT/UVjxyM5vUpiyTBsr/o+lmCiHPh5
wN2yKA28bT/OBMSZcixcowNWP4+p7eiZ+EzjIswsANyYdAeHZB3GJ4cPeo2HKzxk
u4xY6kKNa7OAfq0mJkyzKt3bwO24eub/HHoJfYAocolBTuo2OYdbC2s52GuLpR4H
WC/oAAUJEWMcX4ndzq0PDoTiQeqEBSvjcApprYKkB2VW/MwEEXsffIpk/4f6sE78
dGar8VXsNsOzJGg3pwBODoMZjEhqE49NKlHg09NwQ1ARAtYkFiIp05hiaYPsibnK
NY4bwriLgkypOkuxRgsGE8p27zreQD9R/75wy6LzQ5Bfv7tMNG6TekdfYATVXng9
RExxrIVplH7uLcvLv7bz/5oPev9pAVswgbLVzSvNno605QCgf6mkFuzdW/K4haxU
pgu7HpNQie2mqffzbbjESWant4PouUhwIcs084GyRH7Si2oNZri4FInyIEkYQuUS
Bg1vdWzDtqX4YCYKE676cM++2lAToTIifTD5WR7Wr2v9/vUXz/tpMsUeas5xpwc1
lTqC5R5P5yRexuK/9uFpwgMSFJAizMtXQnC2W/+awiJbsbee5/s+40JlvzvgBOl2
09ScjHzPIJIbZNkAEQEAAbQsa2V5YmFzZS5pby90YWNvMyAodjAuMC4xKSA8dGFj
bzNAa2V5YmFzZS5pbz6JAjMEEAEKAB0FAlK3FMwCGy8FCRLMAwADCwkHAxUKCAIe
AQIXgAAKCRDJomE5cPucGii/D/9yhUElgTx3q0AUcsPWcM6XdWoaoqvzaDYGkGrp
+niJqvEkHDh0NrjJ4kyKTGwrkGVsyZYPHovPInBMyss/1RPMV9TiEWQCvgnxWxch
/DjEcfC8ZnQbbW2JGdEiIB2b3KKrc37rGyKvMtZI07pRYmrIT9FjgmJK1P+PtjaW
R8wz0ZgvP6PJy2P/iADdBpTWIdr83y/N92nnPGxNtfvX+OB13w8j/2XFeBbALVaL
DNOo7mwCIuJRCF61p3bWUjMO8gCPjZVyvH4aM5jb3Cniby8FXEXf6ywZbi4DUQWJ
BufhHFg6E/EaWKEMqOZUecySHM+HypfcqHQLcusidpPIwvk3Rka/wjXK8URU2CYs
9IWsn0N2aKlPZWAdwrDxg5hCRuAa3hcJN4QEJOLIyAGYhj6cVzy4MHYhbMeNhUtF
j1QNqPRZ3pFUw/82WK+kZA5cPB+l97D2LGqsfQWUXWJiqjXx+8dUPf5NVzG/APJ7
dICLLFU7Z3A/DxY0vVEU9rjc61c112QA1E7zmij17vN5PFkNyd11b9oCvd0CprN3
AGhD1OSm95mUhmOh9XOA1E7RRkDCKLXxG/hKmFmtqoUDHQGYhisGSodxoIMPtWz2
RqWpLsYmQh2rv6SwhKMNt9WO9Po0UQnNM+ZVa/oB77V0TZT/Ze2HzAebi1Cec9BU
gY2SlbkBDQRStxTMAQgAqh+qfZZCFtMpTlCEQhvjDdRelv+uLCniBI3lfqqX1GOl
MisLy/XeVgoN7ROtIPd878PdooISu9dKJDLbMzj/ov47N6YJ+fCytuSm3qQyQiK5
01lXKIyaid9WaBcMHibtnrF19eVKDMaXd54IeXwbPu7XyUuQomyb5XXq/ddg37l+
fPrWdNPqt2Tfjw7dG05AyHBXGOsSDYBIhmDWODsDiWpf/ExQ6m1gsffazgdV6Fn7
9nfRwdw/ubXkrAiYmAN2EHr+svv+ypknlOe9BviaAQ29i5mSOehUKtnvxjBxoymW
nkY2lzk/AZ5iPbe4QaNpJ7Ny2MGa2JWdCzMCd3pweQARAQABiQNEBBgBCgAPBQJS
txTMBQkB4TOAAhsuASkJEMmiYTlw+5wawF0gBBkBCgAGBQJStxTMAAoJECKgfTmK
9+g9fZIH/0e5w4g1HJMruqBaErrNVr9gL1hdI4ru4hJQW6kMLxCFg4S8Yp/3S+I+
0oFKgUxAE/7aVhJzWwd4PF42f51YpIXyFxjtEBUgCUnksodnjRngzHZWnZk/H59j
4ZSLF9BmpBbj3uMvCSsllouHY/zKQXAYoJQ1SLl4sATu1Og87DWLBfaOtITVbZBK
LlCvyWFvM9pCoRHzlHtvTlwz/ol9rIWm6CRBDToUX7//5iOBDEEjnhwDPZfhzdSQ
VW4lhrzaLew22EgPteFeSu7tuZJLq1S/Eg130EUVKVut3N1TljE9KT1Jqty5NIMC
jPDeS2AvA+PWjJH+Yr4tfA07LENZJTdoSA//cM7/udNcuipf2uK9AT+kBASL+2FK
3jlg8VRLNivsyKNgGsM3mNmYmFhZjJt2h2iyNUyvoanx8KmzcYIq9sOlizB/5Bkg
j3oLytUneRe1QZFZB65cruBb7C5398Uoy0+6wEYXNNJEF+PBupUGJYqomf96zaGC
dQzah3EAoH/TXw0Z65QYPxBrYds5qsAPeffcn43XII0imO0ybPo7CPPju8luL/9P
5xZWU7xBZ6NCu6FzhV0tvOZ5Uef7teDZ2dgERWHVYvw9irrGvAudUyv6HDkPS/n+
i7HbtUzXsnbZom3V2NizRa2AootKMaiU8wuqvKWMUic1A/hY/0VOWGix4tuRdnZg
tpCgrgv2KtUamyQhu21xkuEoELU7o5w1Y2hZDc/8CL6GyZqliQ+BlIx2gQX96MbQ
qGc9bUOfqzmU4YqtWWLO5gju+aq1ZaVtZ7OB5SrlNvRK4aRAQm+2BAdn1kKajUjQ
tmS4SGEN27IJ6DZotbi+T+p5oKQbIds1AX+Wk4FmnwRcNFH4LwCSIYvi4tUyH64J
S4jpXj1FRRC4vJk8QwJtzpHMwXQiKGWp8uN9JrFTdIOH9Eoct+hLaoNSrg0/6vvD
bysCqR9du4tf0d0bruWv3o+mgITvaKiteSVt0CG5vT0PQsjZaZjbHGhoBD90evWC
rZU60TsWHtBGGoqZAg0EUr2rAAEQALiXKWxbP3+5O58zBTMKoQh2kK/hcp8deE6S
5vwrSPkRTIfadPDvlIXgVnaSGZl5H6lQDVOPCMK1UBsIQWBRwHxxi/1xcUFy4+Lb
odaPAUVAztdk9sXNyZ3iWuBcZ05O4IShwePvVGq8a9wq/qyXX7DeEAdYeDVTBpb0
4v51o2AGMpfJvt8SyTvVYHFqfe6sUKz/0L66MuUNCV8yXViaMRY0hSDpeYt/8LhF
8y25aMsn0gVkcNaP59sC26yxYP+8E9RozYgNmXBqiGZO0JIbtJZ+tTvVtg1pFnnY
8hN1Ptbz7O1eOmGJdtX9tUtHKJco7HIHFzqHBmQnPhlGl989amb4XWrdlWiYiEG5
Ftm811QnNGyac9sHtF3QBfKAQWF4Ns6WB/eZbW1UiY55piBwxLtzKpAgzgSvs/KM
rirooWFejvLL5hk2nQjYUYVTRINisdGO30F7lzluLwNiDdBA0IfflfeR46dpqbbw
xe9AKLIqXCpJ1mpsr9JgzVS2mq5hzz9WMI/JyfATaT+hIhOPUjW9SuaYpmLTH3xk
oWu1iC3kyGuthl/WkqCPEyLj1IE8+L8SXCMp/qZw2qj42j5/q4DHC2UYIy6VqUGn
vZ0OwObCFwzHCJrd3H0usyeMLNaJnXpu9yHSpb0YkuM61KEGF9oSShrPtkkThZtP
Q07ogKy9ABEBAAG0KmtleWJhc2UuaW8vbm9vYiAodjAuMC4xKSA8bm9vYkBrZXli
YXNlLmlvPokCMwQQAQoAHQUCUr2rAAIbLwUJEswDAAMLCQcDFQoIAh4BAheAAAoJ
EG+wvnXAswGsq2MP/jpmFIJ/UQV0WGDRbg+9IvudYMvRSQ5D5Q2m+oZw8Ks+1rhM
8lrYV7CXkYtt+5IxeCTWBWYIK2KtC4ZwKuoBwMCJhSiI/tlQa0R+KkvVVZZgSkRp
90AslGSkDLoEW+KPtT4BFLGHQ7N+5Hf+LWymNNmkDpXnL1/FqX3tJCIafT3S6Htz
XJOSbBFnc06uZMrvK3BDcIQaPd+LHfp1mRUy0/UleHBQdpKNZvxwEX9oYnl31KCb
mmfUaSp598s0cEsSLZqHQjNeCrh321RrjOd++yabnZHvBz+LvF2GgZY9bbDWi06z
7HlvoLVsN1taEd5mcT5p1vQpDT5Pcp2EZEChdZyoxfdqsuQBXW+rTh0p8GvGyLsS
aELIyQKXpJAGcKt6iuIxIp8S6TZRPj4iXIJf5ldNJcu1ql0c6qgkDFJOChXbO1Qe
HgRPTY4VxcpIURugVSVi/mopUj4pKHmXwzroDDsEU2VuWk4+PdSH/tYal8bLGMHE
MiC7iBGiicPi5Gcl8B6cwiVEvCpvGDjOHGlxiuGDRejpLDvinYSiMyRpPgWhFDKu
s3BbPuAgyanPhAhwUL+6X4gj6KDtfCGY/dhb0ggBcHKuuxC/LizLXoGFzzwFa7+E
FQFB/3YGaUbmJeASpGMvge/UGR4tTMc88Q76sr62y1N8GNWCdcYYMJADQb2ziQEc
BBABAgAGBQJS3GGjAAoJEJOXlbBgVVuCaBQH/3KvJ1qzTDNRz5PXPnvZfh8BkI2z
iEL6V5w0Z2D7EBPKpH177u7bmTy3HZZAJWtf0bafEjfnT9sVrR7pWrqvmCRWVcC4
/kQymVZTyeD4gxZy+fENimPj4LP9KcoRt6qCTrBC5RQjto2yvblSBON9lmOhoRkh
SidDiNrbUb6MU/DtWhJPGfP+Bj+Wdz9VjVzgtOFBqwDuCklu5j+O2kYkee5o/f07
tvt+7Ah8PHZvbFpy+vnDE3t0pt+2LtiZo2AnObMihJ+1HQhGjGAOphxc6VfGeE6+
pgbh66COidmnqpDT7Iuh3lA8HapIS4WQfsVbKewBZDU4XL867lFXafUUoZ+5AQ0E
Ur2rAAEIALxOOhCgFc1ZnHQzUBntgD0byDpKnRQ+GgKjNRp356MhPtuPgJK+RDBZ
lolTn2wavk/a6MckpDA7KwageGsJ53y1UmUKvnKjtxBZiSO+tv4AtXPCG3zzVJcQ
+b8aEXjN/mt/efLtGGYHPTpF7C9a8mZgB60Na4vWj4kPuxmgnCdy7o80i4tmvLgc
RzzEKdTThCaKxi4UJ55ERxA2M1R2E7/gWHEQsbEByR9YT6NjmluvrQeRgSfp1kyk
akiKgBcJCLxc43Y80U2NhpQoLbIzITE9N9bxCJ7wV80vYLcZLFShBgfdEdqNYhdW
BvYDYiE7hnyrk81yAvToI+33KJ9foFkAEQEAAYkDRAQYAQoADwUCUr2rAAUJAeEz
gAIbLgEpCRBvsL51wLMBrMBdIAQZAQoABgUCUr2rAAAKCRDjWCbO2YbwrLrNB/9j
PO7oJF4HQl4iPjR/HWarA6M/6YSfR28xFgId5Kh1K1WF/mopJUuD9X981pT5T8gP
sCxLKaQG6BBgxkUsyChO88Y1tdMMcE9TV4K5rdShMDuN9AT3ECz79EnckFpXmhbE
0x0zcieqOKGoxa4XqJJhCuMLha//2WnWYcrNoX5U790SevfwVd/LyzhvPNjnWrXp
D8ERtcbXyyD9gewo3VGLHQ+VGdy2+V9xTI6scgEk2XY99er7XRq4H8kPvDebYkvT
xAPacx5RFcTok4X6T0ebFhCu2z3BugXxkrYsWoNrhzciecpNYMAxghatU0IW7TJ5
G5t0veI7wsg/yaDVFZSHmZAP/2yY3j06qU/Z5whOJ4Vn+xkdav947okiJqcidrFW
oEQkH0Gqxxg6QahAJ0d/lLMc5hcEYnDagivhI2ZyGmKehKvWMCuWUi50bABDSwxm
iS1Di/KrwibyVAzYtg3cXpFy6/ifD0LM0d/cH7167+nymhL7o+k0ZbbZFM/unbXZ
+/LIxXiF4ZsAn708CCG0EAltbOO5WsrYeoCDCwqAu2ds4BuWNkoMRWnSgneSYxJ5
nn9nvgJ/cDRISdW7YeOtrUMYTDXWsbVfxD+N35+sLjjAKw3P0yKVQeSW1c50iFGn
VxW0jFmYkWWfnn1+qNMrTkuxo64W/84iyCm5PTRQjRSmTPFkzxdcDJN3N/scA+6v
4CvDSCG+uwVS8p/6zQ+S9KKIdzQjZUdr8OLyt4FQsKbRT3ay24EdGUPN9WTLi7zb
L8l+j8sgpNe7zVMUDQXaHche5zjkjoPudHxXOw92dIK+JpWrXX9XYr/pnoWLQvpH
yZovEBckU8aXMfXLvPd4UqfocCvLFmwRxzbQCsL226kbgFWTKE6X1AfJZ30KhOPX
91R/9as1GcEMu8TeFVsQ625N3u2zS6zcOIGs+NYoSQ3SDHJSgTJ1U2r2q6CHdqlA
stPvZwHgsX8gRVgJkjPguUZzKD4qKs0K08WwHXFWHb+rCXZSYk23BjVqD8ieQx9M
ao11mI0EUtFEyQEEANaSng0CiUjyoBAoDdOIIKD6M1gOR91rg14xDG0uC1DzBvSP
VNPQzdtr94+bHH2g2X2WqeRvzJSLiyX1jDUw8R1nWNKgIp3tfVbHHYyGPUgdTJpj
/A+M9JVhww6Hu9LE7CS0hAKSQmQF+EwkthnQJx9pjD2+ncgLx6flunNEurBtABEB
AAG0LGtleWJhc2UuaW8vbm9vYjYgKHYwLjAuMSkgPG5vb2I2QGtleWJhc2UuaW8+
iLMEEAEKAB0FAlLRRMkCGy8FCRLMAwADCwkHAxUKCAIeAQIXgAAKCRDBSWVL2KLA
gNO3BACVfuhJeYHMEoRT9sb97n6T2JyvirsRCFNB5hpyN23vwVgOCBF9AOxf1dnK
oOdyn7+DZrRBka3uW6hEEZkhSvHkJDIO14gCbQpZLUF5HMCDYeGZnAabF60vCXkQ
tGvpGlyAiq0sR2z36kXgMQTHTMYpnOyRRpaJr04iRgaCoWV64biNBFLRRMkBBAC4
nFuaGeYC7S+Tp8yEuE/8pHdFK5zcPeATpKTsyNW1aKr4dPzZZGeF1d1viqYqkGde
hn5eIWe3T7oS4IWRfyy/WtT+b99pxyYU6GUcPh9hEe+2Dyi8z5rHpKRIeFzkH2uH
KQ3BJIt48FxSsB2qD/8Mpye/6GokDRV1Epytrxoj2wARAQABiQFDBBgBCgAPBQJS
0UTJBQkB4TOAAhsuAKgJEMFJZUvYosCAnSAEGQEKAAYFAlLRRMkACgkQ2hjfSkwj
GvHX5gP+L/YSTOf5tYLgPdmTW25axQzTbk3MTSYDX9WOb1+KS1fz1fwVn879t2cH
UIgzaey0zJRwDo4kNZNVoha3V6JNZDEaXvxUCGN+3gZoMzUNscq+vVtjDMFLqHSK
lGTSTrFt8Rg7sc0Hs2T+TIeiPO8N2HYlqXtMVLZzvsnFd9J9QBwTDwP9G6AWF+MN
GvpggymXGPpcyy1oGvFJhsPfTitV7AgbzoRKBUaTvAJ1Mc9shZxyYJp9+Y5KPwkD
JW7kaisxUFjCMuT9qybhT78VoYzfsxHMfHjUo6ssGdl52oZm443QaMn36N/FBBi/
Ecf1Bwl9qowiiXsEDpnpwgGrfrCzUhsLpcaZAg0EUt1y6gEQAL9yOhXtml95Clrx
O0LGFx772mxIWruqtWsodkNsYQc3c6fLZL4/7sMFlzoft0goYG0/Q8PMD8ssiasv
/VpCF90D1n/KBuYu81cosiO/HlfQMCQlBc7WMwqdjOd39oHOb81MVGMdf8m8msk8
iZMewAt9vGMv6mjkau/+0nBKVPnABc2suIz3NFn+IkslmzNaNBr2Y2c6QkPxCXwy
FpmrNxSNb75KP7JLO2m1uUBotcyiu92s1zW77akfrjBNtbRc7PM0caNftRfnCx9J
Afom+zF+ak0YpwLDnoRqP/rZDEwQcvBqTJQJJhzwArZj38QNh9uNAEaFh6mBSZTF
c1Y8si+0EEeixqDCqjgXMziVYJJAz09PfrAGPQf50XwQr+sayXlmiH5n3YJpztAR
AOujCCFcCLMRjtUGaGGZHsY8aW9HBeFASRm+4pNXilXGv19/yLuiJqwJSPQVuhA7
Ja6s9Q2EMrVX6taIvqF3sTHeEI9NHaNSi+EhLxp10mXErHi0T69qbAws5XgXrqN8
AS2laPu7zAovvWJqk0AgaxSwl3S3gq+TG/kYQK1QnLx5ic0mbaw5DrXMY/1HAWAV
X2dGKQ+m1viC9UKUUT2x1jdfHmM5J30H0R0At3VzlUazsyCQvbwjtWj3aQmb9jau
NJgH/Lh75CATHze/ZB3KC5aSm2CbABEBAAG0MEtleWJhc2UuaW8gSW5kZXggU2ln
bmluZyAodjEpIDxpbmRleEBrZXliYXNlLmlvPokCPQQTAQoAJwUCUt1y6gIbAwUJ
EswDAAULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRAZmiWlf56L+tLvD/4vfvxs
mWoQBjgS4co10SpN4ShIU6WAWCjgImIm+wBAK2NhRE71gISDu+HnU7szQwvQh0ga
rF/37i0BtIqp9iO2UI1Lva9vrX+Cv5bx6dvzMPcq6fx3cY5RBiuPukO+S+W+eAqC
i09hdtIQhJJ0PQ6WKBql3z6diKfBMy2GfOol8I/2qNzRh9vL92Lf892pMoqqCfdW
s6wXCpioyKE7T1wDf3b0GeYg0liD96hKKRfFhOhm8kdRIvQYC8fZ3m+B7/FMtWXQ
1lM4z85ueKQ7/rLbLhuz9+mKR/+//323YX6/yRyFJXkYdrS5VcHGYeX7uXB8uDd5
uG1RTf0Hf2hJ4QMOMX+Mk6991UTFFEpZfrvsUXky35LjOQu/QJox4SWh5DsVIlyN
InDbe7DDWnA91N9ntfYOEJyvZxHqIoUORtb06bkfpM7njJGoLl3YrvAxb9BGsGx1
qlWGgHAmIXVsF0Tl7yaip0Gj5+C6tv1JUp30dR8b/j/tplUZq6vfJ55U2xLg5+s3
Op2YcOHWy9hH+kElF0Wr9kErlP24qnC8YfZeJuHezktoqIzfW+JNnkqDfZFK0hsQ
9H+UOB0fQWATOt4nmBXO7nnyzpMYl3GQrzPNKV8698ktAGQsNq6TQ6Y1w3VIi/1R
xSWpnHZ0yekBCjt0MwBQiaRO0pX1utG0pA7e+okCHAQQAQoABgUCUt2KlQAKCRBj
hHtLg5MPDDJFD/9LGmFXQktBiCj5Kn8nng7iVGF/P+N8CYtwmWRiKSfWzGwfTnu/
Hz7A8lR45BTS+FjZMy2rDghV2bbI7niH4zBO0auulrA4t3MG23ZqEajXlIl8Y6Ek
yzk225oxnc/+Sl07G5lOmaqGY+ArwGA6nhS1+aOVlCuJzMZhWc7+gvCF27XjHLS4
OTJun92lYQEBHro/g+pV9xw+gku2qH1QqIihPZnFqULhygLHGgUKRiQLw4e2YMG/
TL2k8E/rrVejiUaPG98xRGkC7Peq7ltPtv0SzhnTAcHuQlC0zy7KsgiRCyddGWls
/1xIPHIJK5qPDYtZwMeq9i8i2LAmmg5quKbdcFf5jV+isQuNB/SzYidqdHnnKDV8
ju0bE+7S4ufKoUSzTD4HANXrQvudJwvqmjyBu9RsWTuaeKpUoXXGjsojIwFj3xcY
IAsRrlsA1mdtKY/GCG9tIvhKnZ1WR6yqMfSo0C8fu0hX3S404Yn0AXIAYRnQsxeM
UvaVhKmYbwKpARmI3AeAyL/wt9loOwvYrCKpE+m39Z9j9XppTDebr6W1MGiWNxJE
oZP5etbRkclzu8oNY9jMP7AnzdFbV8dU65J8XdsyVL9eXUZJd9DOOzwRPIm1CPrO
xmNV6SXCULHCYQKDofGtbZqiO6UR9DKIwISOVRZbfUsu6oAI6Sla+CFvvLkCDQRS
3XLqARAAp41UUmwfsYgIcW8PcLWZpzEyTj0HwpUfv5UyXt3zKqaPTVUPFpLErlpH
x/3wI0buFN4rlGKYq7JaWD4hEBuTBqXL7g117CRcpA3NVCiGL1jzPzz6Vnbjcp46
euFmiG6LnMODzmTMNHwqSSTAS4ILk/fFcc1MVbTo74RsDPyMvQXK73zZTxlBpdXy
TCSVmFSmcLHZlH7ogeV3Vtn93N51eKksnyNsuOwEjDiCunfhVo5r/LTNFJnhiKv9
1etpm6FX3fWrZDtXxmUe2e7BIacDKm7OrlUMwGVDgTXQzyqgCbM1Wx9HFzI/oHON
j3cokmsM2fIOwojjpsAxxw5m8po9u3ETOTUBliwAGfiokK7ov40yulee0Zv4TwDI
ASskNXJr7oXWJkIZhAijuL2hpDt1aBRdRfBh9JUXZMPHDtgHDSXupiTyRI8yGs3Q
392VLRsk3Ool5axEjc0umH7tKsYwHO4FdZPUpDr2KlAa9QU4T/NPDVKpr1ku4iWS
6rEgZvgPd3Cubd8maP9A0Y3kWRRA/3qcDnPih5WttBDXBTQoWrkTSRKPEWAEMs2r
LpF6FL4Q2LG2JRMTMHj/cfAN/P3ZrSciCsVyMrgFbYcHdhDirxYdRRiuEsvDnnk4
oVtvJK0/YWzaNf4IxSNKBbhnVESJ5omJ0KgF84wA5wZI8RkPqbkAEQEAAYkCJQQY
AQoADwUCUt1y6gIbDAUJEswDAAAKCRAZmiWlf56L+oF6D/42ISPghU5WADEL6NOs
iSFyRxvDUhayKjasZLGOLobvV3FCJ5W0cF6JvdONx+sLwXWIgnH22iGcsyH1fTH1
ikFOUmdsKs9cE3J9psUH3JFjTTApWzV1nLcFbeNAIXn+6XaAWz9Uqyff3JxN0AyW
K4TQLLTFsWzc2r/oEBKXUuHs5r2omX894pIbCRVuwHMeO3R7FX7kCUEEL92MaKFW
84ny5pQTAGAabg0fm1yeOWrKupwiurQOkAzNAiYs3trd8pJtHkx2Hft9hQRVo1J7
Kn7eFIuYFnu3B8L+WZhQbG8KOX7r5ara3fpTYECAC5pNw3p1xj7BFV+7sM4G3wzc
yDA79CAQ6y/I1FPBspoTKxRzpOIa36NTZpMiH0ERY9eJDUL9pQnjlE5/JlcGWbT5
v14QJm3+fdOkEJ4x+MNMUdSiuolP9sVKyBNJkwYRz9QKI1kgVPzTgPM0HyXWMgnL
j0/cLPxTEbpbNXN95lNA7rFM/hkYAIhXtsfvNtIhZ3DtzGKK7aRv+iKJKKapDi4n
TLCB+uwPy7++koFMI5yDZC1wHh95iLwGgmOOyW3P6IhGN5SMl6QSoBqDJpzNdGy8
Q/3f/q4Uxo1JH2DZOqoAseqXRFkxF0ByIpovsV0TQmpDZ7x6wHShKzA/LTfcITEO
IPN3AH6hvZ8gKAutZO+TjtBf+JkCDQRS8rt8ARAAtc6u/t5Jh8tYRfWgq+OzwjwZ
JGwA8zQBKeSgdP/aeAzpk3A51uQEFv64fcB/IpQ4WSjzx/8TqpSmtF0p+ybHE/yq
YoMHmLvVr6Zwdp5z6V9o+7QQ/8fP47aK6Cca54vrOYK2aNDHd6uTLHjzsBXSQq6/
Hs0B2gQFVYPCzVTHGN+x9/lGzfzcwvIlGJeflTQN3mqf2x0YuoFitkRQAy/xAksX
MXL6EwQsKP39lF7PFRsttvZRxmHOCu1VnCFDnUnVFSdjAP+R4s4BFLXvRiwXw6US
puffTjMIkE26OCEZXlD2E+v9GpJbIfZrT853jVl2tahCeXovlpO2Yl7dLowC/WJ5
OQxqOqggVlO4TL+yjnhI4R69NSVaH/ot4NvOilEGJNDenaOBPYROY0cCUKfudLI/
ROci49PqRFkNMf/tgt7rn/aLa70VmJOlwu/fWbyNwvtLTxA7E2pIE0CZunHlLVFx
rSv0zwHp+4cADOMfVV40HO3QmQWYo6PBkdYjGpLUKcrL2tDfXsDfOvhYnXV7cmne
iuFnpWUEEa4+bYs3oYy05tfBtRr/0eAQjCBYGxPJ2gQQftX3Cw3O0oiucFFr9NGA
0YpV/M44f9/9HQWcGOwJc/Y7cF0QNU245a+RUnOcecKAq0l+XMgsFnzKzgzfrqE0
p+AMLfE9NaYqEoB1adcAEQEAAbQoa2V5YmFzZS5pby9tYXggKHYwLjAuMSkgPG1h
eEBrZXliYXNlLmlvPokCMwQQAQoAHQUCUvK7fAIbLwUJEswDAAMLCQcDFQoIAh4B
AheAAAoJEGBSsq0xpmMcZr4QAI/yEdCksc3SFMFMIrBwJJXdPpYmt3g7JoYyovJ1
I/6QUH4LcR3EBd0mmYnumGyOfy1kfkpiXYlOykRMyuUORqBw9siqCbm6FYY4qAq9
flYbj7CWf+1OHT7xYdGM79DDvX/SrpI6byChOXZ89nI3gKMakDEoemiRlWivOLeO
kucfcGRpG5Tut12Ctgyg2XB9Oj5gz9jBgsFHUYwk2YacX/L/BPPFGqxnRivYq4Ji
0Aujv37Ve83hkzbLdtTT3VRbKp+ERRAQYCwwD4vvSPFhnVRNw/b7Xd0UjDimJVDS
hdJGjFTd8s/5jHpntbECLcSukddL8XS4HzHD/j9JjcA3xo0dbD5UARFTwS+ALnRt
HUFdre/KeVRFt31bLmUscpPR1mHYE9gdq88A9w8lOUrZo9fOTHBksIjvZj096lWR
beX9VG2O1JYDnofQjO75hM+EXDuuTrKnBHyA73xWlHAAn+pevDXIS53dLnzr3ST8
CiyJuBMNzjVC/PlwCFoGGeoRQffM+bZ3XyWL+b9Wywk0UnP6XvuRHui9g5zL8abU
KBaa1ILoXGtlv68fvEqFvPgmyQluHxOK5lHcemyIYjOGB86WUGxR6KhztwvuUnYF
QeMKcQ8Yu5Qh4XAruaK8mX3QhVchCaWpAoqCcUIS0j9cTO0oRtIjZlF/kyn/kPtY
ADpXuQENBFLyu3wBCADMNxfQlPyGgnjp3jAIhwFJbK5DIJgZOdCh/IdtyPsyyvo8
S1iraIbJhp9I53M59KeLohHYakROOuE/3pkhRxGwEHfK/W4HCRNN94SidxV65tR5
wHgnhcFTcYktnFkYJ1D+sNe2F5NmXatl/bgz8ilIadqUSpYnPxZIRKc9ZmpMyr5u
pVFKbavf8VM2KV1A6Nsaqk+HwH9A8L9IeLpuY3fO4q12dU8XNEDAXhcllrir5py+
W3QhlnnS8k6d1Cwl3sbruxnewHQ1FOYnAy0nvx6crLf0rPVLOL02buoYirCwZ60f
zv+FURJ55hAJiTJsdaWb2BUlaFw81gYqxuC4THALABEBAAGJA0QEGAEKAA8FAlLy
u3wFCQHhM4ACGy4BKQkQYFKyrTGmYxzAXSAEGQEKAAYFAlLyu3wACgkQmAo/DQH+
BN+M+wf/V4/hBFm59NZdnLzzDJp7B+bxWKh5G75PU/AlxP0HibsjIJXT49Cyhhwn
AD+6VJVMS5QDDQCRPDXfnr812jbE6oxd2pInWZ6oyl/1EaI9XZUVR3re7tNbAI8z
WIjGt8rFkQehQ60LKd+os9ZEfpRlaYnmTZ/IAvspUM9PUlRxU62bselxxyXttxqx
WTpo8iZ4kw30P6jbZ6ADiv09ZR14HnOpcQfa3GodYIASoYnq//rNfXS1J8MExtes
/X+XbRg+5OLy/iGEpGZES0zVt3ioiESXe37YR0bFTjw4TggMz9m/NqeyokexLazA
xYh6V8SnAUFY3jrHLLO6FLq1+5YShaf4D/9Afpnb0j1xeWsZKyE68Jo5Fu+tMiYL
NuKiprnZ1KorDQULZFmHjVFvv8LN8y9rh/9ccCkKUY0XbcQ4SmkRGUsyFBsSlVtc
7bsJ2clBwwQ4rc0kql40X9GOOs7E2iulcabx9g0K15DO7A5qnhyxntJhB6864Zu9
9WU2gBRKffoVFjnZ1BxozF+C41lcEeOKlvYGmZCRKViaQrRIQoLs/y71aEHF9M28
fZHvEpkRMjcncL1Ra1/L/C02DhVI6WQzJmmlfyhfRP+RC+ZtGCmEd6V60cpCZyVX
kaqJoac9b3T/LbGKivPpD0iQhQ5+W4apQZxS7SVmhQCgLHrBQuvwtQ1Crh4Rh/Xi
kQxDoS4zV9hXOw+bfjp4vQFcidekJLt7IoKNxPCMp16GxIGMYMXcwwCiroMZ18fo
xxNOM7dFlqMWSffRlckbmcAaCdLVcVhGiONE89M6nKoBcNX9feckGPTMrEIdj6/2
ZXnOGN3b1uPsDCSp4o8CqAhR0a/RW0KILz58igBV9cWDMa0vb9Xlk0PQze27EvOn
dgb6qDiF/k4e/+6AVrw1ziStDRo0PJuLi9geWtwk3QAZWHSm+of3xEjT5Nwze8vI
aKzKOi2wsrSs7bQSnD2c41aKq5TPkySxJaXv4huEXsjM3x8AcTNzkVhZ3LvO/hx/
/6eFUsNDH74yM5kCDQRS+9qAARAA2tKIVfuMz0XXZx1grJWEJRsPWFPVirPr8+yj
IyAajQIXj0uZuQ20ZIuGHwZENl9Z0c/ooKMDdaA9E9/tsNyfJLzUeNxKmDdYHtg6
Ikej7XMLfecJbejbw3zv5vl6kfauJO6+9/PMPbrAfMKXFqv6X8IHVa1uEUoDT8Zh
2azfuT7hALTFTSk1Pn9tbPPsv8j04a7EhyglfKsugxQRcWTkeDVqLqB70A1xna0j
sWtWE/EwOaEchdL95xGxEO8K/P4sHBgqDopNc0PGMVKoCRqsMpUqsPPEeH2SALul
MzZkITaJVwOOs9PCe8d9QTYMg46Wl8NAwyHLV8+jAim+wWTcfAKOSt2ymlt6wMYO
YDe11TgelblMQAQ7h665tPCyz39UDIQaogkTgKRZTd/yhz3HydX4Cz7DjgCVfEFT
m+4HSxqCJsAN71TIzqLvoCRyA1TWYnhmjQYvQcynzOtTJP6CxkSPhBPKjkReDVjT
aR+6eaRA3m/byvS+Wk35oOiyD3ju1Gi8sIdRfnL/eFhMp+kkHEs3foQCRXgsXvX1
IweBwJbAvTcnoNkvzqjdPwF1McWd/zl+HeQUiiQDEToQGHDcgQhTcgl3HOUjZeAl
akQBvLKddW8oy47DM8ZyRh3AH9NfZdCeuWIFRAi2g4+s78l1y7nVLLOlAJtVHZFT
9O0t7JkAEQEAAbQ2a2V5YmFzZS5pby9jYXBuZGVzaWduICh2MC4wLjEpIDxjYXBu
ZGVzaWduQGtleWJhc2UuaW8+iQIzBBABCgAdBQJS+9qAAhsvBQkSzAMAAwsJBwMV
CggCHgECF4AACgkQWwlJSLERUfIFjQ//Wg1uky7tgjitBQH8V0Yf2fyRE+rKmh1N
8NlSMrBuBUERf3IvLjkwk8CTtoOgF6WJk6NXHOUboGtVL2JvtJ48CTYntdEeFdN3
678hfiur/xnbMRXoV5IHq9Ph5n5h1xOysRLVPkdxJfNBgDRVoyx1Tqo0Vqj5a5il
N9rT+1z9Me6VX0QbTRvsX3dUWOX6PXnSgoKqEzsYPNsBRwxGz4anR34DBXcRVrpM
dHeCI6Zhja2or0nPCKMBtorkoSqgw5AgIjY+ZmPEYI9NaCdkl29CpjvMg9Ii40x4
g5/jQARFaLZtJ8Ngd299v5RVbQ2CpysHdo7kzaXoFEEEF9yF5Y1BKsMSbmv/q0XD
YeeqqkqcZCEWh3eZc5ns12ju7E3z8EoVejaTB7aB6jjuYWLLhgkzUZfcGknrxPCG
W8TI1aP/eVaWYJFL18ay2vZzqCRrGqv1d0aAF1rbm/CSZLz7+grhhuW/20Q2x12D
s9h/nKyeIFcy2TnCbZdwcayP8nj9Z2bRFsRjouSMO3erOzICRmQ7QsZcXOftIt5g
3DSBgoIYRpRIshyHjgJbM8dzHaB0lawM3TSA9pYmSwdc6w7xlpQT8HGz4YK0Z7wU
ZOJNmlHZyg3TruVdR7As3NKhjCdBR7wU54n8SWlDlAX4a5ItTzt/ggiiMGyleO1X
893VaE3Iko+5AQ0EUvvagAEIANvCWawMogfHD8xZECFefVfVo54bGvG7ZT0fGCN7
FR6jN7U58x+HppL2dK2BqYYOOzzsZGSnXBLq5REt0qL0Pap8oSe3wenn1MFGRTdY
qlJTu0vsxgmbvVQoTq7RGl24gKsTIDyHlfQSs9fgKn4muR1RyZeNGXO8RCTlN50Q
VRuI+y7kuwgG3waIsRUO8D7N3W3aP7HLzzaWVh8CQZS9nBI7D/wzwalBAElv5I0d
4tNUurS+gOBgO8/rvFhZxHPEpOKPGKfDlQqw9iR5jOgn6NzfTsHDwr8UOhadNzEo
AjdrCyn1Yj8gZSOjnx3LfDdNHN5nLZ0m1klMsfkVkAInSZ0AEQEAAYkDRAQYAQoA
DwUCUvvagAUJAeEzgAIbLgEpCRBbCUlIsRFR8sBdIAQZAQoABgUCUvvagAAKCRBL
q/m8CroyO2AXB/4yFGAhmoFq3qYeWC4MX3FJPmXp8BTBzYeK2atATyZevikVUE7d
HAm+Se4NlUnjEpfbuNE0OTIevNs6SFbIf1xXXZyOU5NvQvSKktVEQIVgay92YW+r
w1D8DZWwaGY2t6RvP/6hjvehwiSo9PGCzP5gVB9elAtNx1pWL6IFmNnbOKHBgiWC
jVtI4mpJrEl/fJjAZtdiprs2xujOTyk2UBbVQNHiqSIAUIEN8PNF0H5L0AjxucgD
dqe6MuhNSiqejEdfdZSDIBu4OF3J+zEz+bTZ3DPTnXJ77PGERMINCcTagmFc6ovc
/uoxmzCoT+zbEfdT53wLiDBamVkLdKl717GmaTkQAK6UD+7KgxyJcNiTV/1pjX5W
6ZRqcsiF8uIuxU/DWp+QQbHLoLvbggJZqJt0RrLw1AUe3Li6kDoMChXXYMPBS2xL
f+omhD36AXhpeqJQKoRJ2ANV5VyWuoRCkIokxbeAcqR53lPv4vx05tVEJLHet/9X
ETrsdVlcDvxDTc03+viC8ELOQRZ9RYTMWVNiJd30WV8XoDPxb/ZSEMizCW4o8Xo8
6xkxWk8XWxQtR1fPcH2Z3GQPSiNZgOXIMT9X9xa0oE7ZhxtINp7LhN5Y+BAjbxsO
qdHbQ3fYMjAiDC/X8Vm/fXJCc7yKB576MJOrkxbQ8MKnOI3P45XIVtg2HPgb3Zpy
Pg0jFv2mSjeK1LOmRi8pGy1rWdD3nXI7hvfCyiihZVXVdHcB+dyPIiI42j8HBn6X
C1QJUgv60GOIM+DbBwfcmQI2MRtUHytpPWVQc199qpVH7P1QzrKItTXN0q5QsEiV
1Xsu6cqfLaI4jr30WNxqhfdy11N2OwB8+1C/TOdTBUVSjxieHo1H1AADBZDiwFnG
/xekL0nxnQW5l5BCiXB6Pk4pCVpkHikq0at6byMpObP9NU9/YmRAUsprVNcrtojj
+mQbuq3M7n3jaCv18hKcK+23dolzlhQjqD/QvHiRgJoJUrnAfqtHsDdkyQDTwLJo
A+k/SlaiV1ZqK5YbGFS+
=7jBz
-----END PGP PUBLIC KEY BLOCK-----
"""
exports.index_keyring = (T,cb) ->
await keyring.TmpKeyRing.make defer err, ring
T.no_error err, "make tmp key ring"
await ring.gpg { args : [ "--import"], stdin : keyring_raw, quiet : true }, defer err
T.no_error err, "import worked ok"
await ring.index defer err, index
fp = "E0600318C622F735D82EDF3D5B094948B11151F2".toLowerCase()
keys = index.lookup().fingerprint.get(fp)
T.assert keys?, "key came back for our fingerprint #{fp}"
T.equal keys.length, 1, "only one key came back"
T.equal keys[0].userids().length, 1, "only 1 userid"
T.equal keys[0].userids()[0].username, "keybase.io/capndesign", "and it was the capn"
T.no_error err, "indexing worked ok"
await ring.nuke defer err
T.no_error err, "nuked the ring ok"
cb()
#======================================================================
| 91795 |
keyring = require '../../lib/keyring'
#-----------------------------------
class Log extends keyring.Log
debug : (x) ->
#-----------------------------------
ring2 = ring = null
key = null
key_data = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.14 (GNU/Linux)
<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
fingerprint = "<KEY>"
payload = "I hereby approve of the Archduke's assassination. Please spare his wife.\n"
sig = """
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.14 (GNU/Linux)
<KEY>7XXj97IWY65u1pO9HBUZmy0/YzihX4Pz/ZIO7hnfb1N4l7Fw/
Hz30FTkcaHWq7oPoHAWeYwA=
=2ENa
-----END PGP MESSAGE-----
"""
#-----------------
kaiser2 =
key_data : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
username : "<EMAIL>"
fingerprint : "A03CC843D8425771B59F731063E11013288F2D48"
payload_json : { ww : 1 }
payload : '{ "ww" : 1 }\n'
sig : """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
<KEY>
-----END PGP MESSAGE-----
"""
#-----------------
exports.init = (T, cb) ->
keyring.init {
get_preserve_tmp_keyring : () -> false
get_tmp_keyring_dir : () -> "."
log : new Log()
}
cb()
#-----------------
exports.make_ring = (T,cb) ->
await keyring.TmpKeyRing.make defer err, tmp
T.no_error err
T.assert tmp, "keyring came back"
ring = tmp
cb()
#-----------------
exports.test_import = (T,cb) ->
key = ring.make_key {
key_data,
fingerprint,
username : "gavrilo"
}
await key.save defer err
T.no_error err
await key.load defer err
T.no_error err
cb()
#-----------------
exports.test_verify = (T,cb) ->
await key.verify_sig { sig, payload, which : "msg" }, defer err
T.no_error err
cb()
#-----------------
exports.test_read_uids = (T, cb) ->
await ring.read_uids_from_key { fingerprint }, defer err, uids
T.no_error err
T.equal uids.length, 1, "the right number of UIDs"
# Whoops, there was as typo when I made this key!
T.equal uids[0].username, "<NAME>" , "the right username"
cb()
#-----------------
exports.test_copy = (T,cb) ->
await keyring.TmpKeyRing.make defer err, ring2
T.no_error err
T.assert ring2, "keyring2 was made"
await ring2.read_uids_from_key { fingerprint }, defer err, uids
T.assert err, "ring2 should be empty"
key2 = key.copy_to_keyring ring2
await key2.save defer err
T.no_error err
await key2.load defer err
T.no_error
await key2.verify_sig { sig, payload, which : "key2" }, defer err
T.no_error err
await ring2.nuke defer err
T.no_error err
cb()
#-----------------
exports.test_find = (T, cb) ->
await ring.find_keys { query : "gman@" }, defer err, id64s
T.no_error err
T.equal id64s, [ fingerprint[-16...] ], "got back the 1 and only right key"
cb()
#-----------------
exports.test_list = (T,cb) ->
await ring.list_keys defer err, id64s
T.no_error err
T.equal id64s, [ fingerprint[-16...] ], "got back the 1 and only right key"
cb()
#-----------------
exports.test_one_shot = (T,cb) ->
await ring.make_oneshot_ring { query : fingerprint, single : true }, defer err, r1
T.no_error err
T.assert r1, "A ring came back"
await r1.nuke defer err
T.no_error err
cb()
#-----------------
exports.test_oneshot_verify = (T,cb) ->
key = ring.make_key kaiser2
await key.save defer err
T.no_error err
await ring.oneshot_verify { query : kaiser2.username, single : true, sig : kaiser2.sig }, defer err, json
T.no_error err
T.equal kaiser2.payload_json, json, "JSON payload checked out"
cb()
#-----------------
exports.test_verify_sig = (T,cb) ->
await key.verify_sig { which : "something", payload : kaiser2.payload, sig : kaiser2.sig }, defer err
T.no_error err
cb()
#-----------------
exports.test_import_by_username = (T,cb) ->
key = ring.make_key {username : "<<EMAIL>>"}
await key.load defer err
T.no_error err
T.equal key.uid().username, 'Gavirilo Princip', "username came back correctly after load"
cb()
#-----------------
exports.test_import_by_username_with_space_and_control_chars = (T,cb) ->
if process.platform is 'win32'
T.waypoint "skipped on windows :("
else
key = ring.make_key keybase_v1_index
await key.save defer err
T.no_error err
key = ring.make_key {username : "(v1) <<EMAIL>>"}
await key.load defer err
T.no_error err
T.equal key.uid().username, 'Keybase.io Index Signing', "username came back correctly after load"
cb()
#-----------------
keybase_v1_index =
key_data : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
#-----------------
exports.nuke_ring = (T,cb) ->
await ring.nuke defer err
T.no_error err
cb()
#==================================================================
keyring_raw = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
ch<KEY>
01<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
exports.index_keyring = (T,cb) ->
await keyring.TmpKeyRing.make defer err, ring
T.no_error err, "make tmp key ring"
await ring.gpg { args : [ "--import"], stdin : keyring_raw, quiet : true }, defer err
T.no_error err, "import worked ok"
await ring.index defer err, index
fp = "E0600318C622F735D82EDF3D5B094948B11151F2".toLowerCase()
keys = index.lookup().fingerprint.get(fp)
T.assert keys?, "key came back for our fingerprint #{fp}"
T.equal keys.length, 1, "only one key came back"
T.equal keys[0].userids().length, 1, "only 1 userid"
T.equal keys[0].userids()[0].username, "keybase.io/capndesign", "and it was the capn"
T.no_error err, "indexing worked ok"
await ring.nuke defer err
T.no_error err, "nuked the ring ok"
cb()
#======================================================================
| true |
keyring = require '../../lib/keyring'
#-----------------------------------
class Log extends keyring.Log
debug : (x) ->
#-----------------------------------
ring2 = ring = null
key = null
key_data = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.14 (GNU/Linux)
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
fingerprint = "PI:KEY:<KEY>END_PI"
payload = "I hereby approve of the Archduke's assassination. Please spare his wife.\n"
sig = """
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.14 (GNU/Linux)
PI:KEY:<KEY>END_PI7XXj97IWY65u1pO9HBUZmy0/YzihX4Pz/ZIO7hnfb1N4l7Fw/
Hz30FTkcaHWq7oPoHAWeYwA=
=2ENa
-----END PGP MESSAGE-----
"""
#-----------------
kaiser2 =
key_data : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
username : "PI:EMAIL:<EMAIL>END_PI"
fingerprint : "A03CC843D8425771B59F731063E11013288F2D48"
payload_json : { ww : 1 }
payload : '{ "ww" : 1 }\n'
sig : """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----
"""
#-----------------
exports.init = (T, cb) ->
keyring.init {
get_preserve_tmp_keyring : () -> false
get_tmp_keyring_dir : () -> "."
log : new Log()
}
cb()
#-----------------
exports.make_ring = (T,cb) ->
await keyring.TmpKeyRing.make defer err, tmp
T.no_error err
T.assert tmp, "keyring came back"
ring = tmp
cb()
#-----------------
exports.test_import = (T,cb) ->
key = ring.make_key {
key_data,
fingerprint,
username : "gavrilo"
}
await key.save defer err
T.no_error err
await key.load defer err
T.no_error err
cb()
#-----------------
exports.test_verify = (T,cb) ->
await key.verify_sig { sig, payload, which : "msg" }, defer err
T.no_error err
cb()
#-----------------
exports.test_read_uids = (T, cb) ->
await ring.read_uids_from_key { fingerprint }, defer err, uids
T.no_error err
T.equal uids.length, 1, "the right number of UIDs"
# Whoops, there was as typo when I made this key!
T.equal uids[0].username, "PI:NAME:<NAME>END_PI" , "the right username"
cb()
#-----------------
exports.test_copy = (T,cb) ->
await keyring.TmpKeyRing.make defer err, ring2
T.no_error err
T.assert ring2, "keyring2 was made"
await ring2.read_uids_from_key { fingerprint }, defer err, uids
T.assert err, "ring2 should be empty"
key2 = key.copy_to_keyring ring2
await key2.save defer err
T.no_error err
await key2.load defer err
T.no_error
await key2.verify_sig { sig, payload, which : "key2" }, defer err
T.no_error err
await ring2.nuke defer err
T.no_error err
cb()
#-----------------
exports.test_find = (T, cb) ->
await ring.find_keys { query : "gman@" }, defer err, id64s
T.no_error err
T.equal id64s, [ fingerprint[-16...] ], "got back the 1 and only right key"
cb()
#-----------------
exports.test_list = (T,cb) ->
await ring.list_keys defer err, id64s
T.no_error err
T.equal id64s, [ fingerprint[-16...] ], "got back the 1 and only right key"
cb()
#-----------------
exports.test_one_shot = (T,cb) ->
await ring.make_oneshot_ring { query : fingerprint, single : true }, defer err, r1
T.no_error err
T.assert r1, "A ring came back"
await r1.nuke defer err
T.no_error err
cb()
#-----------------
exports.test_oneshot_verify = (T,cb) ->
key = ring.make_key kaiser2
await key.save defer err
T.no_error err
await ring.oneshot_verify { query : kaiser2.username, single : true, sig : kaiser2.sig }, defer err, json
T.no_error err
T.equal kaiser2.payload_json, json, "JSON payload checked out"
cb()
#-----------------
exports.test_verify_sig = (T,cb) ->
await key.verify_sig { which : "something", payload : kaiser2.payload, sig : kaiser2.sig }, defer err
T.no_error err
cb()
#-----------------
exports.test_import_by_username = (T,cb) ->
key = ring.make_key {username : "<PI:EMAIL:<EMAIL>END_PI>"}
await key.load defer err
T.no_error err
T.equal key.uid().username, 'Gavirilo Princip', "username came back correctly after load"
cb()
#-----------------
exports.test_import_by_username_with_space_and_control_chars = (T,cb) ->
if process.platform is 'win32'
T.waypoint "skipped on windows :("
else
key = ring.make_key keybase_v1_index
await key.save defer err
T.no_error err
key = ring.make_key {username : "(v1) <PI:EMAIL:<EMAIL>END_PI>"}
await key.load defer err
T.no_error err
T.equal key.uid().username, 'Keybase.io Index Signing', "username came back correctly after load"
cb()
#-----------------
keybase_v1_index =
key_data : """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
#-----------------
exports.nuke_ring = (T,cb) ->
await ring.nuke defer err
T.no_error err
cb()
#==================================================================
keyring_raw = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
chPI:KEY:<KEY>END_PI
01PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
exports.index_keyring = (T,cb) ->
await keyring.TmpKeyRing.make defer err, ring
T.no_error err, "make tmp key ring"
await ring.gpg { args : [ "--import"], stdin : keyring_raw, quiet : true }, defer err
T.no_error err, "import worked ok"
await ring.index defer err, index
fp = "E0600318C622F735D82EDF3D5B094948B11151F2".toLowerCase()
keys = index.lookup().fingerprint.get(fp)
T.assert keys?, "key came back for our fingerprint #{fp}"
T.equal keys.length, 1, "only one key came back"
T.equal keys[0].userids().length, 1, "only 1 userid"
T.equal keys[0].userids()[0].username, "keybase.io/capndesign", "and it was the capn"
T.no_error err, "indexing worked ok"
await ring.nuke defer err
T.no_error err, "nuked the ring ok"
cb()
#======================================================================
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.