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": "ack at the highest level\n# see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices\n#", "end": 623, "score": 0.9994912147521973, "start": 612, "tag": "USERNAME", "value": "TooTallNate" }, { "context": " + authInfo.mountPoint, 403)\n\n ...
src/server/application_manager/index.coffee
bladepan/cloudbrowser
0
Fs = require('fs') Path = require('path') {EventEmitter} = require('events') Weak = require('weak') Async = require('async') lodash = require('lodash') debug = require('debug') request = require('request') Application = require('./application') AppConfig = require('./app_config') User = require('../user') {getConfigFromFile} = require('../../shared/utils') routes = require('./routes') # Defining callback at the highest level # see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices # Dummy callback, does nothing cleanupApp = (mountPoint) -> return () -> console.log("Garbage collected application #{mountPoint}") logger = debug("cloudbrowser:worker:appmanager") class ApplicationManager extends EventEmitter __r_mode : 'methods' constructor : (dependencies, callback) -> {@config, @database, @permissionManager, @httpServer, @sessionManager, @masterStub} = dependencies @_appConfigs = dependencies.appConfigs # the services exported to api /applications/app instances/vbs @server = { config : @config.serverConfig #keep this naming for compatibility mongoInterface : @database permissionManager : @permissionManager httpServer : @httpServer eventTracker : dependencies.eventTracker sessionManager : dependencies.sessionManager uuidService : dependencies.uuidService applicationManager : this, masterStub : @masterStub } @applications = {} @weakRefsToApps = {} @_setupGoogleAuthRoutes() @loadApplications((err)=> logger("all apps loaded") callback err,this ) #load applications after the routes on http_server is ready loadApplications : (callback)-> for mountPoint, masterApp of @_appConfigs logger("load #{mountPoint}") app = new Application(masterApp, @server) @addApplication(app) app.mount() # FIXME : temp solution, should listen on the master's appManager @emit('addApp', app) # no point to keep reference at this point @_appConfigs = null callback null ### start existing apps ### start : (callback)-> logger("start existing apps") for k, app of @applications if app.isStandalone() and app.mounted app.mount() @_setupGoogleAuthRoutes() callback() addApplication : (app) -> mountPoint = app.mountPoint @applications[mountPoint] = app @weakRefsToApps[mountPoint] = Weak(@applications[mountPoint], cleanupApp(mountPoint)) if app.subApps for subApp in app.subApps @addApplication(subApp) remove : (mountPoint, callback) -> logger("remove #{mountPoint}") app = @applications[mountPoint] if app? delete @applications[mountPoint] delete @weakRefsToApps[mountPoint] # FIXME : temp solution, should listen on the master's appManager @emit('removeApp', app) if app.subApps? and app.subApps.length>0 Async.each(app.subApps, (subApp, next)=> @remove(subApp.mountPoint, next) (err)-> if err? logger("remove app #{mountPoint} failed:#{err}") return callback(err) app.close(callback) ) else app.close(callback) else callback() _setDisableFlag : (mountPoint)-> app = @applications[mountPoint] if app? app.mounted = false if app.subApps? and app.subApps.length>0 lodash.each(app.subApps, @_setDisableFlag, this) disable : (mountPoint, callback)-> @_setDisableFlag(mountPoint) Async.series([ (next)=> @stop(next) (next)=> # FIXME put this into httpServer @socketIOServer.stop(next) (next)=> @httpServer.restart(next) (next)=> # this thing would return itself @socketIOServer.start(next) (next)=> @start(next) ],(err)-> logger("disable app #{mountPoint} failed : #{err}") if err? callback(err) ) enable : (masterApp, callback)-> logger("enable #{masterApp.mountPoint}") @remove(masterApp.mountPoint, (err)=> if err? logger("remove old app failed #{err}") return callback(err) app = new Application(masterApp, @server) @addApplication(app) app.mount() # FIXME : temp solution, should listen on the master's appManager @emit('addApp', app) callback() ) find : (mountPoint) -> # Hand out weak references to other modules @weakRefsToApps[mountPoint] get : () -> # Hand out weak references to other modules # Permission Check Required # for all apps and for only a particular user's apps return @weakRefsToApps _setupGoogleAuthRoutes : () -> # This is the URL google redirects the client to after authentication @httpServer.mount('/checkauth', lodash.bind(@_googleCheckAuthHandler,this)) _googleCheckAuthHandler : (req, res, next) -> authInfo = @sessionManager.findPropOnSession(req.session, 'googleAuthInfo') if not authInfo then return res.send('cannot find corresponding authentication record', 403) code = req.query.code state = req.query.state if authInfo.state != state logger("receivedState is #{state}, the state we stored is #{authInfo.state}") return routes.internalError(res, "Invalid authentication information") app = @find(authInfo.mountPoint) if not app then return res.send('cannot find application ' + authInfo.mountPoint, 403) clientId = "247142348909-2s8tudf2n69iedmt4tvt2bun5bu2ro5t.apps.googleusercontent.com" clientSecret = "rPk5XM_ggD2bHku2xewOmf-U" redirectUri = "#{@server.config.getHttpAddr()}/checkauth" Async.waterfall([ (next)-> request.post({ url:'https://www.googleapis.com/oauth2/v3/token', form: { code: code client_id : clientId client_secret : clientSecret redirect_uri : redirectUri grant_type : "authorization_code" }}, next) (httpResponse, body, next)-> logger("request token get response from token request : #{httpResponse}") logger("response body is #{typeof body} : #{body}") tokenResponse = JSON.parse(body) accessToken = tokenResponse['access_token'] tokenType = tokenResponse['token_type'] request.get({ url : 'https://www.googleapis.com/oauth2/v2/userinfo' headers: { 'Authorization': "#{tokenType} #{accessToken}" } }, next) (httpResponse, body, next)-> logger("userinfo response #{body}") userInfoResp = JSON.parse(body) logger("user email #{userInfoResp.email}") app.addNewUser new User(userInfoResp.email), next (user, next)=> mountPoint = authInfo.mountPoint @sessionManager.addAppUserID(req.session, mountPoint, user) redirectto = @sessionManager.findAndSetPropOnSession(req.session, 'redirectto', null) if not redirectto then redirectto = mountPoint routes.redirect(res, redirectto) ], (err)-> if err? logger(err) routes.internalError(res, "Authentication error #{err}") return ) # called by master createAppInstance : (mountPoint, callback) -> app = @applications[mountPoint] app.createAppInstance(callback) # called by master createAppInstanceForUser : (mountPoint, user, callback) -> app = @applications[mountPoint] app.createAppInstanceForUser(user, callback) stop :(callback)-> logger("stop all apps") apps = lodash.values(@applications) Async.each(apps, (app, next)-> app.stop(next) ,(err)-> logger("applicationManager stop failed: #{err}") if err? callback(err) if callback? ) uploadAppConfig : (buffer, callback)-> @masterStub.appManager.uploadAppConfig(buffer, callback) module.exports = ApplicationManager
102197
Fs = require('fs') Path = require('path') {EventEmitter} = require('events') Weak = require('weak') Async = require('async') lodash = require('lodash') debug = require('debug') request = require('request') Application = require('./application') AppConfig = require('./app_config') User = require('../user') {getConfigFromFile} = require('../../shared/utils') routes = require('./routes') # Defining callback at the highest level # see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices # Dummy callback, does nothing cleanupApp = (mountPoint) -> return () -> console.log("Garbage collected application #{mountPoint}") logger = debug("cloudbrowser:worker:appmanager") class ApplicationManager extends EventEmitter __r_mode : 'methods' constructor : (dependencies, callback) -> {@config, @database, @permissionManager, @httpServer, @sessionManager, @masterStub} = dependencies @_appConfigs = dependencies.appConfigs # the services exported to api /applications/app instances/vbs @server = { config : @config.serverConfig #keep this naming for compatibility mongoInterface : @database permissionManager : @permissionManager httpServer : @httpServer eventTracker : dependencies.eventTracker sessionManager : dependencies.sessionManager uuidService : dependencies.uuidService applicationManager : this, masterStub : @masterStub } @applications = {} @weakRefsToApps = {} @_setupGoogleAuthRoutes() @loadApplications((err)=> logger("all apps loaded") callback err,this ) #load applications after the routes on http_server is ready loadApplications : (callback)-> for mountPoint, masterApp of @_appConfigs logger("load #{mountPoint}") app = new Application(masterApp, @server) @addApplication(app) app.mount() # FIXME : temp solution, should listen on the master's appManager @emit('addApp', app) # no point to keep reference at this point @_appConfigs = null callback null ### start existing apps ### start : (callback)-> logger("start existing apps") for k, app of @applications if app.isStandalone() and app.mounted app.mount() @_setupGoogleAuthRoutes() callback() addApplication : (app) -> mountPoint = app.mountPoint @applications[mountPoint] = app @weakRefsToApps[mountPoint] = Weak(@applications[mountPoint], cleanupApp(mountPoint)) if app.subApps for subApp in app.subApps @addApplication(subApp) remove : (mountPoint, callback) -> logger("remove #{mountPoint}") app = @applications[mountPoint] if app? delete @applications[mountPoint] delete @weakRefsToApps[mountPoint] # FIXME : temp solution, should listen on the master's appManager @emit('removeApp', app) if app.subApps? and app.subApps.length>0 Async.each(app.subApps, (subApp, next)=> @remove(subApp.mountPoint, next) (err)-> if err? logger("remove app #{mountPoint} failed:#{err}") return callback(err) app.close(callback) ) else app.close(callback) else callback() _setDisableFlag : (mountPoint)-> app = @applications[mountPoint] if app? app.mounted = false if app.subApps? and app.subApps.length>0 lodash.each(app.subApps, @_setDisableFlag, this) disable : (mountPoint, callback)-> @_setDisableFlag(mountPoint) Async.series([ (next)=> @stop(next) (next)=> # FIXME put this into httpServer @socketIOServer.stop(next) (next)=> @httpServer.restart(next) (next)=> # this thing would return itself @socketIOServer.start(next) (next)=> @start(next) ],(err)-> logger("disable app #{mountPoint} failed : #{err}") if err? callback(err) ) enable : (masterApp, callback)-> logger("enable #{masterApp.mountPoint}") @remove(masterApp.mountPoint, (err)=> if err? logger("remove old app failed #{err}") return callback(err) app = new Application(masterApp, @server) @addApplication(app) app.mount() # FIXME : temp solution, should listen on the master's appManager @emit('addApp', app) callback() ) find : (mountPoint) -> # Hand out weak references to other modules @weakRefsToApps[mountPoint] get : () -> # Hand out weak references to other modules # Permission Check Required # for all apps and for only a particular user's apps return @weakRefsToApps _setupGoogleAuthRoutes : () -> # This is the URL google redirects the client to after authentication @httpServer.mount('/checkauth', lodash.bind(@_googleCheckAuthHandler,this)) _googleCheckAuthHandler : (req, res, next) -> authInfo = @sessionManager.findPropOnSession(req.session, 'googleAuthInfo') if not authInfo then return res.send('cannot find corresponding authentication record', 403) code = req.query.code state = req.query.state if authInfo.state != state logger("receivedState is #{state}, the state we stored is #{authInfo.state}") return routes.internalError(res, "Invalid authentication information") app = @find(authInfo.mountPoint) if not app then return res.send('cannot find application ' + authInfo.mountPoint, 403) clientId = "<KEY>" clientSecret = "<KEY>" redirectUri = "#{@server.config.getHttpAddr()}/checkauth" Async.waterfall([ (next)-> request.post({ url:'https://www.googleapis.com/oauth2/v3/token', form: { code: code client_id : clientId client_secret : clientSecret redirect_uri : redirectUri grant_type : "authorization_code" }}, next) (httpResponse, body, next)-> logger("request token get response from token request : #{httpResponse}") logger("response body is #{typeof body} : #{body}") tokenResponse = JSON.parse(body) accessToken = tokenResponse['access_token'] tokenType = tokenResponse['token_type'] request.get({ url : 'https://www.googleapis.com/oauth2/v2/userinfo' headers: { 'Authorization': "#{tokenType} #{accessToken}" } }, next) (httpResponse, body, next)-> logger("userinfo response #{body}") userInfoResp = JSON.parse(body) logger("user email #{userInfoResp.email}") app.addNewUser new User(userInfoResp.email), next (user, next)=> mountPoint = authInfo.mountPoint @sessionManager.addAppUserID(req.session, mountPoint, user) redirectto = @sessionManager.findAndSetPropOnSession(req.session, 'redirectto', null) if not redirectto then redirectto = mountPoint routes.redirect(res, redirectto) ], (err)-> if err? logger(err) routes.internalError(res, "Authentication error #{err}") return ) # called by master createAppInstance : (mountPoint, callback) -> app = @applications[mountPoint] app.createAppInstance(callback) # called by master createAppInstanceForUser : (mountPoint, user, callback) -> app = @applications[mountPoint] app.createAppInstanceForUser(user, callback) stop :(callback)-> logger("stop all apps") apps = lodash.values(@applications) Async.each(apps, (app, next)-> app.stop(next) ,(err)-> logger("applicationManager stop failed: #{err}") if err? callback(err) if callback? ) uploadAppConfig : (buffer, callback)-> @masterStub.appManager.uploadAppConfig(buffer, callback) module.exports = ApplicationManager
true
Fs = require('fs') Path = require('path') {EventEmitter} = require('events') Weak = require('weak') Async = require('async') lodash = require('lodash') debug = require('debug') request = require('request') Application = require('./application') AppConfig = require('./app_config') User = require('../user') {getConfigFromFile} = require('../../shared/utils') routes = require('./routes') # Defining callback at the highest level # see https://github.com/TooTallNate/node-weak#weak-callback-function-best-practices # Dummy callback, does nothing cleanupApp = (mountPoint) -> return () -> console.log("Garbage collected application #{mountPoint}") logger = debug("cloudbrowser:worker:appmanager") class ApplicationManager extends EventEmitter __r_mode : 'methods' constructor : (dependencies, callback) -> {@config, @database, @permissionManager, @httpServer, @sessionManager, @masterStub} = dependencies @_appConfigs = dependencies.appConfigs # the services exported to api /applications/app instances/vbs @server = { config : @config.serverConfig #keep this naming for compatibility mongoInterface : @database permissionManager : @permissionManager httpServer : @httpServer eventTracker : dependencies.eventTracker sessionManager : dependencies.sessionManager uuidService : dependencies.uuidService applicationManager : this, masterStub : @masterStub } @applications = {} @weakRefsToApps = {} @_setupGoogleAuthRoutes() @loadApplications((err)=> logger("all apps loaded") callback err,this ) #load applications after the routes on http_server is ready loadApplications : (callback)-> for mountPoint, masterApp of @_appConfigs logger("load #{mountPoint}") app = new Application(masterApp, @server) @addApplication(app) app.mount() # FIXME : temp solution, should listen on the master's appManager @emit('addApp', app) # no point to keep reference at this point @_appConfigs = null callback null ### start existing apps ### start : (callback)-> logger("start existing apps") for k, app of @applications if app.isStandalone() and app.mounted app.mount() @_setupGoogleAuthRoutes() callback() addApplication : (app) -> mountPoint = app.mountPoint @applications[mountPoint] = app @weakRefsToApps[mountPoint] = Weak(@applications[mountPoint], cleanupApp(mountPoint)) if app.subApps for subApp in app.subApps @addApplication(subApp) remove : (mountPoint, callback) -> logger("remove #{mountPoint}") app = @applications[mountPoint] if app? delete @applications[mountPoint] delete @weakRefsToApps[mountPoint] # FIXME : temp solution, should listen on the master's appManager @emit('removeApp', app) if app.subApps? and app.subApps.length>0 Async.each(app.subApps, (subApp, next)=> @remove(subApp.mountPoint, next) (err)-> if err? logger("remove app #{mountPoint} failed:#{err}") return callback(err) app.close(callback) ) else app.close(callback) else callback() _setDisableFlag : (mountPoint)-> app = @applications[mountPoint] if app? app.mounted = false if app.subApps? and app.subApps.length>0 lodash.each(app.subApps, @_setDisableFlag, this) disable : (mountPoint, callback)-> @_setDisableFlag(mountPoint) Async.series([ (next)=> @stop(next) (next)=> # FIXME put this into httpServer @socketIOServer.stop(next) (next)=> @httpServer.restart(next) (next)=> # this thing would return itself @socketIOServer.start(next) (next)=> @start(next) ],(err)-> logger("disable app #{mountPoint} failed : #{err}") if err? callback(err) ) enable : (masterApp, callback)-> logger("enable #{masterApp.mountPoint}") @remove(masterApp.mountPoint, (err)=> if err? logger("remove old app failed #{err}") return callback(err) app = new Application(masterApp, @server) @addApplication(app) app.mount() # FIXME : temp solution, should listen on the master's appManager @emit('addApp', app) callback() ) find : (mountPoint) -> # Hand out weak references to other modules @weakRefsToApps[mountPoint] get : () -> # Hand out weak references to other modules # Permission Check Required # for all apps and for only a particular user's apps return @weakRefsToApps _setupGoogleAuthRoutes : () -> # This is the URL google redirects the client to after authentication @httpServer.mount('/checkauth', lodash.bind(@_googleCheckAuthHandler,this)) _googleCheckAuthHandler : (req, res, next) -> authInfo = @sessionManager.findPropOnSession(req.session, 'googleAuthInfo') if not authInfo then return res.send('cannot find corresponding authentication record', 403) code = req.query.code state = req.query.state if authInfo.state != state logger("receivedState is #{state}, the state we stored is #{authInfo.state}") return routes.internalError(res, "Invalid authentication information") app = @find(authInfo.mountPoint) if not app then return res.send('cannot find application ' + authInfo.mountPoint, 403) clientId = "PI:KEY:<KEY>END_PI" clientSecret = "PI:KEY:<KEY>END_PI" redirectUri = "#{@server.config.getHttpAddr()}/checkauth" Async.waterfall([ (next)-> request.post({ url:'https://www.googleapis.com/oauth2/v3/token', form: { code: code client_id : clientId client_secret : clientSecret redirect_uri : redirectUri grant_type : "authorization_code" }}, next) (httpResponse, body, next)-> logger("request token get response from token request : #{httpResponse}") logger("response body is #{typeof body} : #{body}") tokenResponse = JSON.parse(body) accessToken = tokenResponse['access_token'] tokenType = tokenResponse['token_type'] request.get({ url : 'https://www.googleapis.com/oauth2/v2/userinfo' headers: { 'Authorization': "#{tokenType} #{accessToken}" } }, next) (httpResponse, body, next)-> logger("userinfo response #{body}") userInfoResp = JSON.parse(body) logger("user email #{userInfoResp.email}") app.addNewUser new User(userInfoResp.email), next (user, next)=> mountPoint = authInfo.mountPoint @sessionManager.addAppUserID(req.session, mountPoint, user) redirectto = @sessionManager.findAndSetPropOnSession(req.session, 'redirectto', null) if not redirectto then redirectto = mountPoint routes.redirect(res, redirectto) ], (err)-> if err? logger(err) routes.internalError(res, "Authentication error #{err}") return ) # called by master createAppInstance : (mountPoint, callback) -> app = @applications[mountPoint] app.createAppInstance(callback) # called by master createAppInstanceForUser : (mountPoint, user, callback) -> app = @applications[mountPoint] app.createAppInstanceForUser(user, callback) stop :(callback)-> logger("stop all apps") apps = lodash.values(@applications) Async.each(apps, (app, next)-> app.stop(next) ,(err)-> logger("applicationManager stop failed: #{err}") if err? callback(err) if callback? ) uploadAppConfig : (buffer, callback)-> @masterStub.appManager.uploadAppConfig(buffer, callback) module.exports = ApplicationManager
[ { "context": "\n# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 19, "score": 0.9995740056037903, "start": 13, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-event-emitter-listeners.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. listener = -> listener2 = -> common = require("../common") assert = require("assert") events = require("events") e1 = new events.EventEmitter() e1.on "foo", listener fooListeners = e1.listeners("foo") assert.deepEqual e1.listeners("foo"), [listener] e1.removeAllListeners "foo" assert.deepEqual e1.listeners("foo"), [] assert.deepEqual fooListeners, [listener] e2 = new events.EventEmitter() e2.on "foo", listener e2ListenersCopy = e2.listeners("foo") assert.deepEqual e2ListenersCopy, [listener] assert.deepEqual e2.listeners("foo"), [listener] e2ListenersCopy.push listener2 assert.deepEqual e2.listeners("foo"), [listener] assert.deepEqual e2ListenersCopy, [ listener listener2 ] e3 = new events.EventEmitter() e3.on "foo", listener e3ListenersCopy = e3.listeners("foo") e3.on "foo", listener2 assert.deepEqual e3.listeners("foo"), [ listener listener2 ] assert.deepEqual e3ListenersCopy, [listener]
209854
# 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. listener = -> listener2 = -> common = require("../common") assert = require("assert") events = require("events") e1 = new events.EventEmitter() e1.on "foo", listener fooListeners = e1.listeners("foo") assert.deepEqual e1.listeners("foo"), [listener] e1.removeAllListeners "foo" assert.deepEqual e1.listeners("foo"), [] assert.deepEqual fooListeners, [listener] e2 = new events.EventEmitter() e2.on "foo", listener e2ListenersCopy = e2.listeners("foo") assert.deepEqual e2ListenersCopy, [listener] assert.deepEqual e2.listeners("foo"), [listener] e2ListenersCopy.push listener2 assert.deepEqual e2.listeners("foo"), [listener] assert.deepEqual e2ListenersCopy, [ listener listener2 ] e3 = new events.EventEmitter() e3.on "foo", listener e3ListenersCopy = e3.listeners("foo") e3.on "foo", listener2 assert.deepEqual e3.listeners("foo"), [ listener listener2 ] assert.deepEqual e3ListenersCopy, [listener]
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. listener = -> listener2 = -> common = require("../common") assert = require("assert") events = require("events") e1 = new events.EventEmitter() e1.on "foo", listener fooListeners = e1.listeners("foo") assert.deepEqual e1.listeners("foo"), [listener] e1.removeAllListeners "foo" assert.deepEqual e1.listeners("foo"), [] assert.deepEqual fooListeners, [listener] e2 = new events.EventEmitter() e2.on "foo", listener e2ListenersCopy = e2.listeners("foo") assert.deepEqual e2ListenersCopy, [listener] assert.deepEqual e2.listeners("foo"), [listener] e2ListenersCopy.push listener2 assert.deepEqual e2.listeners("foo"), [listener] assert.deepEqual e2ListenersCopy, [ listener listener2 ] e3 = new events.EventEmitter() e3.on "foo", listener e3ListenersCopy = e3.listeners("foo") e3.on "foo", listener2 assert.deepEqual e3.listeners("foo"), [ listener listener2 ] assert.deepEqual e3ListenersCopy, [listener]
[ { "context": "ort default {\n sizes:\n shootOut:\n name: 'Shoot-out'\n soulstones:\n min: 0\n max: 25", "end": 62, "score": 0.9538982510566711, "start": 53, "tag": "NAME", "value": "Shoot-out" }, { "context": " max: 25\n typical: 20\n lead...
src/data/Encounters.coffee
AppSynergy/malifaux-crew-explorer
0
export default { sizes: shootOut: name: 'Shoot-out' soulstones: min: 0 max: 25 typical: 20 leader: ['Henchman'] dustup: name: 'Dustup' soulstones: min: 26 max: 40 typical: 30 leader: ['Master', 'Henchman'] scrap: name: 'Scrap' soulstones: min: 41 max: 9000 typical: 50 leader: ['Master'] }
180806
export default { sizes: shootOut: name: '<NAME>' soulstones: min: 0 max: 25 typical: 20 leader: ['<NAME>'] dustup: name: '<NAME>' soulstones: min: 26 max: 40 typical: 30 leader: ['<NAME>', '<NAME>'] scrap: name: '<NAME>' soulstones: min: 41 max: 9000 typical: 50 leader: ['<NAME>'] }
true
export default { sizes: shootOut: name: 'PI:NAME:<NAME>END_PI' soulstones: min: 0 max: 25 typical: 20 leader: ['PI:NAME:<NAME>END_PI'] dustup: name: 'PI:NAME:<NAME>END_PI' soulstones: min: 26 max: 40 typical: 30 leader: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] scrap: name: 'PI:NAME:<NAME>END_PI' soulstones: min: 41 max: 9000 typical: 50 leader: ['PI:NAME:<NAME>END_PI'] }
[ { "context": "data = [\n {\n id: 1,\n active: 1,\n name: 'Katra',\n slug: 'katra',\n url: 'https://github.com", "end": 651, "score": 0.9139847755432129, "start": 646, "tag": "NAME", "value": "Katra" }, { "context": ",\n slug: 'katra',\n url: 'https://github.com/...
bin/automigrate.coffee
darkoverlordofdata/games
0
path = require('path') app = require(path.resolve(__dirname, '../server')) DataSource = require('loopback-datasource-juggler').DataSource Sqlite3 = require('loopback-connector-sqlite') db = new DataSource(Sqlite3, file_name: 'db.sqlite3', debug: false) model = id: type: Number, required: true active: type: Boolean name: type: String slug: type: String url: type: String author: type: String description: type: String version: type: String icon: type: String main: type: String height: type: Number width: type: Number Games = db.define('Game', model) data = [ { id: 1, active: 1, name: 'Katra', slug: 'katra', url: 'https://github.com/darkoverlordofdata/katra', author: 'darkoverlordofdata', description: '', version: '0.0.1', icon: 'katra.png', main: 'katra.html', height: 600, width: 800 }, { id: 2, active: 1, name: 'Asteroid Simulator', slug: 'asteroids', url: 'https://github.com/darkoverlordofdata/asteroids', author: 'darkoverlordofdata', description: 'Classic Asteroids using modern physics', version: '0.0.1', icon: 'asteroids36.png', main: 'asteroids.html', height: 600, width: 800 } ] db.automigrate -> Games.create data, (err, h) -> if err console.log err else console.log h model = id: type: Number, required: true active: type: Boolean slug: type: String title: type: String description: type: String image: type: String Katra = db.define('Katra', model) data = [ { id: 1, active: 1, slug: 'katra/sttr1', title: 'Katra . . .', description: 'Like, beam me up, dude.', image: 'assets/katra.png', }, { id: 2, active: 1, slug: 'katra/wumpus', title: 'Hunt the Wumpus', description: 'What\'s a Wumpus?', image: 'assets/wumpus.png', }, { id: 3, active: 1, slug: 'katra/eliza', title: 'Eliza', description: 'A shrink with a \'tude.', image: 'assets/wumpus.png', }, { id: 4, active: 1, slug: 'katra/oregon', title: 'Oregon', description: 'Why do you put your wagons in a circle?<br>To get better Wi-Fi!', image: 'assets/oregon.png', } ] db.automigrate -> Katra.create data, (err, h) -> if err console.log err else console.log h
44751
path = require('path') app = require(path.resolve(__dirname, '../server')) DataSource = require('loopback-datasource-juggler').DataSource Sqlite3 = require('loopback-connector-sqlite') db = new DataSource(Sqlite3, file_name: 'db.sqlite3', debug: false) model = id: type: Number, required: true active: type: Boolean name: type: String slug: type: String url: type: String author: type: String description: type: String version: type: String icon: type: String main: type: String height: type: Number width: type: Number Games = db.define('Game', model) data = [ { id: 1, active: 1, name: '<NAME>', slug: 'katra', url: 'https://github.com/darkoverlordofdata/katra', author: 'darkoverlordofdata', description: '', version: '0.0.1', icon: 'katra.png', main: 'katra.html', height: 600, width: 800 }, { id: 2, active: 1, name: 'Asteroid Simulator', slug: 'asteroids', url: 'https://github.com/darkoverlordofdata/asteroids', author: 'darkoverlordofdata', description: 'Classic Asteroids using modern physics', version: '0.0.1', icon: 'asteroids36.png', main: 'asteroids.html', height: 600, width: 800 } ] db.automigrate -> Games.create data, (err, h) -> if err console.log err else console.log h model = id: type: Number, required: true active: type: Boolean slug: type: String title: type: String description: type: String image: type: String Katra = db.define('Katra', model) data = [ { id: 1, active: 1, slug: 'katra/sttr1', title: 'Katra . . .', description: 'Like, beam me up, dude.', image: 'assets/katra.png', }, { id: 2, active: 1, slug: 'katra/wumpus', title: 'Hunt the Wumpus', description: 'What\'s a Wumpus?', image: 'assets/wumpus.png', }, { id: 3, active: 1, slug: 'katra/eliza', title: 'Eliza', description: 'A shrink with a \'tude.', image: 'assets/wumpus.png', }, { id: 4, active: 1, slug: 'katra/oregon', title: 'Oregon', description: 'Why do you put your wagons in a circle?<br>To get better Wi-Fi!', image: 'assets/oregon.png', } ] db.automigrate -> Katra.create data, (err, h) -> if err console.log err else console.log h
true
path = require('path') app = require(path.resolve(__dirname, '../server')) DataSource = require('loopback-datasource-juggler').DataSource Sqlite3 = require('loopback-connector-sqlite') db = new DataSource(Sqlite3, file_name: 'db.sqlite3', debug: false) model = id: type: Number, required: true active: type: Boolean name: type: String slug: type: String url: type: String author: type: String description: type: String version: type: String icon: type: String main: type: String height: type: Number width: type: Number Games = db.define('Game', model) data = [ { id: 1, active: 1, name: 'PI:NAME:<NAME>END_PI', slug: 'katra', url: 'https://github.com/darkoverlordofdata/katra', author: 'darkoverlordofdata', description: '', version: '0.0.1', icon: 'katra.png', main: 'katra.html', height: 600, width: 800 }, { id: 2, active: 1, name: 'Asteroid Simulator', slug: 'asteroids', url: 'https://github.com/darkoverlordofdata/asteroids', author: 'darkoverlordofdata', description: 'Classic Asteroids using modern physics', version: '0.0.1', icon: 'asteroids36.png', main: 'asteroids.html', height: 600, width: 800 } ] db.automigrate -> Games.create data, (err, h) -> if err console.log err else console.log h model = id: type: Number, required: true active: type: Boolean slug: type: String title: type: String description: type: String image: type: String Katra = db.define('Katra', model) data = [ { id: 1, active: 1, slug: 'katra/sttr1', title: 'Katra . . .', description: 'Like, beam me up, dude.', image: 'assets/katra.png', }, { id: 2, active: 1, slug: 'katra/wumpus', title: 'Hunt the Wumpus', description: 'What\'s a Wumpus?', image: 'assets/wumpus.png', }, { id: 3, active: 1, slug: 'katra/eliza', title: 'Eliza', description: 'A shrink with a \'tude.', image: 'assets/wumpus.png', }, { id: 4, active: 1, slug: 'katra/oregon', title: 'Oregon', description: 'Why do you put your wagons in a circle?<br>To get better Wi-Fi!', image: 'assets/oregon.png', } ] db.automigrate -> Katra.create data, (err, h) -> if err console.log err else console.log h
[ { "context": "s the JSUri library from here: https://github.com/derek-watson/jsUri\n # Thanks to Jake Moffat for the suggestio", "end": 771, "score": 0.9996837377548218, "start": 759, "tag": "USERNAME", "value": "derek-watson" }, { "context": "ttps://github.com/derek-watson/jsUri\n ...
core/app/assets/javascripts/spree.js.coffee
javierJordan10/outlet
1
#= require jsuri class window.Spree @ready: (callback) -> jQuery(document).ready(callback) # fire ready callbacks also on turbolinks page change event jQuery(document).on 'page:load', -> callback(jQuery) @mountedAt: -> window.SpreePaths.mounted_at @adminPath: -> window.SpreePaths.admin @pathFor: (path) -> locationOrigin = "#{window.location.protocol}//#{window.location.hostname}" + (if window.location.port then ":#{window.location.port}" else "") @url("#{locationOrigin}#{@mountedAt()}#{path}", @url_params).toString() @adminPathFor: (path) -> @pathFor("#{@adminPath()}#{path}") # Helper function to take a URL and add query parameters to it # Uses the JSUri library from here: https://github.com/derek-watson/jsUri # Thanks to Jake Moffat for the suggestion: https://twitter.com/jakeonrails/statuses/321776992221544449 @url: (uri, query) -> if uri.path == undefined uri = new Uri(uri) if query $.each query, (key, value) -> uri.addQueryParam(key, value) return uri # This function automatically appends the API token # for the user to the end of any URL. # Immediately after, this string is then passed to jQuery.ajax. # # ajax works in two ways in jQuery: # # $.ajax("url", {settings: 'go here'}) # or: # $.ajax({url: "url", settings: 'go here'}) # # This function will support both of these calls. @ajax: (url_or_settings, settings) -> if (typeof(url_or_settings) == "string") $.ajax(Spree.url(url_or_settings).toString(), settings) else url = url_or_settings['url'] delete url_or_settings['url'] $.ajax(Spree.url(url).toString(), url_or_settings) @routes: states_search: @pathFor('api/v1/states') apply_coupon_code: (order_id) -> Spree.pathFor("api/v1/orders/#{order_id}/apply_coupon_code") @url_params: {}
23517
#= require jsuri class window.Spree @ready: (callback) -> jQuery(document).ready(callback) # fire ready callbacks also on turbolinks page change event jQuery(document).on 'page:load', -> callback(jQuery) @mountedAt: -> window.SpreePaths.mounted_at @adminPath: -> window.SpreePaths.admin @pathFor: (path) -> locationOrigin = "#{window.location.protocol}//#{window.location.hostname}" + (if window.location.port then ":#{window.location.port}" else "") @url("#{locationOrigin}#{@mountedAt()}#{path}", @url_params).toString() @adminPathFor: (path) -> @pathFor("#{@adminPath()}#{path}") # Helper function to take a URL and add query parameters to it # Uses the JSUri library from here: https://github.com/derek-watson/jsUri # Thanks to <NAME> for the suggestion: https://twitter.com/jakeonrails/statuses/321776992221544449 @url: (uri, query) -> if uri.path == undefined uri = new Uri(uri) if query $.each query, (key, value) -> uri.addQueryParam(key, value) return uri # This function automatically appends the API token # for the user to the end of any URL. # Immediately after, this string is then passed to jQuery.ajax. # # ajax works in two ways in jQuery: # # $.ajax("url", {settings: 'go here'}) # or: # $.ajax({url: "url", settings: 'go here'}) # # This function will support both of these calls. @ajax: (url_or_settings, settings) -> if (typeof(url_or_settings) == "string") $.ajax(Spree.url(url_or_settings).toString(), settings) else url = url_or_settings['url'] delete url_or_settings['url'] $.ajax(Spree.url(url).toString(), url_or_settings) @routes: states_search: @pathFor('api/v1/states') apply_coupon_code: (order_id) -> Spree.pathFor("api/v1/orders/#{order_id}/apply_coupon_code") @url_params: {}
true
#= require jsuri class window.Spree @ready: (callback) -> jQuery(document).ready(callback) # fire ready callbacks also on turbolinks page change event jQuery(document).on 'page:load', -> callback(jQuery) @mountedAt: -> window.SpreePaths.mounted_at @adminPath: -> window.SpreePaths.admin @pathFor: (path) -> locationOrigin = "#{window.location.protocol}//#{window.location.hostname}" + (if window.location.port then ":#{window.location.port}" else "") @url("#{locationOrigin}#{@mountedAt()}#{path}", @url_params).toString() @adminPathFor: (path) -> @pathFor("#{@adminPath()}#{path}") # Helper function to take a URL and add query parameters to it # Uses the JSUri library from here: https://github.com/derek-watson/jsUri # Thanks to PI:NAME:<NAME>END_PI for the suggestion: https://twitter.com/jakeonrails/statuses/321776992221544449 @url: (uri, query) -> if uri.path == undefined uri = new Uri(uri) if query $.each query, (key, value) -> uri.addQueryParam(key, value) return uri # This function automatically appends the API token # for the user to the end of any URL. # Immediately after, this string is then passed to jQuery.ajax. # # ajax works in two ways in jQuery: # # $.ajax("url", {settings: 'go here'}) # or: # $.ajax({url: "url", settings: 'go here'}) # # This function will support both of these calls. @ajax: (url_or_settings, settings) -> if (typeof(url_or_settings) == "string") $.ajax(Spree.url(url_or_settings).toString(), settings) else url = url_or_settings['url'] delete url_or_settings['url'] $.ajax(Spree.url(url).toString(), url_or_settings) @routes: states_search: @pathFor('api/v1/states') apply_coupon_code: (order_id) -> Spree.pathFor("api/v1/orders/#{order_id}/apply_coupon_code") @url_params: {}
[ { "context": "@data, parent, @hidden) ->\n\t\t\t\tself = @\n\t\t\t\tname = @name\n\t\t\t\tdataArrayFlag = false\n\t\t\t\tif _.isType @da", "end": 723, "score": 0.7453282475471497, "start": 723, "tag": "NAME", "value": "" }, { "context": "ata, parent, @hidden) ->\n\t\t\t\tself = @\n\t...
js/workflow/Data.coffee
imsun/visboard
4
(() -> Workflow = (@owner) -> owner = @owner wf = @ @outPool = outPool = {} @checkInput = () -> if Primitives.list[owner].prop.parent? parent = Primitives.list[owner].prop.parent.value inPool = Data.workflow(parent).outPool for key, value of inPool if not DataModel.list[key] new wf.DataModel key, value.data @DataModel = DataModel = class @list: {} @tree: [] @members: {} @getNode: (name, trees) -> for tree in trees if tree.name is name return tree for tree in trees result = @getNode name, tree.children return result if result output: () -> outPool[@name] = @ constructor: (@name, @data, parent, @hidden) -> self = @ name = @name dataArrayFlag = false if _.isType @data[0], 'Array' dataArrayFlag = true keys = Object.keys data[0][0] else keys = Object.keys data[0] DataModel.list[name] = @data DataModel.members[name] = @ dataNode = name: name type: 'data' parent: parent children: [] hidden: hidden prop: title: name: (() -> return 'Data Set' if dataArrayFlag return 'Data' )() type: 'title' name: name: 'Name' type: 'label' value: name rows: name: 'Rows' type: 'label' value: (() -> return self.data.length )() preview: name: 'Preview' type: 'html' value: (() -> data = DataModel.list[name] tr = '' th = '<thead><tr><th>' + (keys.join '</th><th>') + '</th></tr></thead>' if not dataArrayFlag data.forEach (row, i) -> td = '' keys.forEach (key, j) -> td += "<td>#{row[key]}</td>" tr += "<tr>#{td}</tr>" table = "<table>#{th}<tbody>#{tr}</tbody></table>" return table )() if dataArrayFlag @data.forEach (data, index) -> new wf.DataModel name + '.' + index, data, parent, true if not hidden if parent? node = DataModel.getNode parent, DataModel.tree node.children.push dataNode else DataModel.tree.push dataNode # d3.tree() will remove `children` from tree's nodes DataPool.display _.copy DataModel.tree if DataPool? DataPanel.display dataNode if DataPanel? return @ @Tool = Tool = class constructor: () -> self = @ name = 'Tool ' + Tool.counter++ @name = name dataNode = id: _.cid() name: name type: 'tool' parent: null children: [] prop: title: name: 'Tool' type: 'title' name: name: 'Name' type: 'text' value: name listener: (value) -> self.dataNode.name = value self.dataNode.prop.name.value = value self.update() input: name: 'Input' type: 'select' value: null set: () -> result = [ name: 'none' value: null ] for key, value of DataModel.list result.push name: key value: key return result listener: (value) -> self.setInput value @dataNode = dataNode @init() DataModel.tree.push dataNode DataPool.display DataModel.tree if DataPool? DataPanel.display dataNode if DataPanel? @counter: 0 update: () -> for child in @dataNode.children delete Data.list[child.name] @dataNode.children = [] setInput: (value) -> value = null if value is 'null' if @dataNode.parent? oldParent = DataModel.getNode @dataNode.parent, Data.tree .children else oldParent = DataModel.tree index = oldParent.indexOf @dataNode oldParent.splice index, 1 @dataNode.parent = value @dataNode.prop.input.value = value if value? parent = DataModel.getNode value, DataModel.tree .children else parent = DataModel.tree parent.push @dataNode @update() init: () -> # Filter and Cluster need to be reduced @Filter = Filter = class extends @Tool @counter: 0 init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'filter ' + Filter.counter++ @dataNode.prop.title.name = 'Filter' @dataNode.type = 'filter' _.extend @dataNode.prop, select: name: 'Select' type: 'text' value: null listener: (value) -> value = null if value is 'null' self.dataNode.prop.select.value = value self.update() rules: name: 'Rules' type: 'text' value: null listener: (value) -> self.dataNode.prop.rules.value = value self.update() update: () -> super() inputName = @dataNode.prop.input.value select = @dataNode.prop.select.value rules = @dataNode.prop.rules.value if not select or not inputName DataPool.display DataModel.tree return input = DataModel.list[inputName] if select isnt '*' select = select.split ',' .map (row) -> return row.trim() output = [] input.forEach (row, index) -> if rules fn = eval "(function ($data, $index) { return #{rules}})" if not fn row, index return if select is '*' output.push (_.copy row) else result = {} select.forEach (key) -> result[key] = _.copy row[key] output.push result i = 0 i++ while DataModel.list[inputName + '.' + i] new DataModel inputName + '.' + i, output, @dataNode.name @Cluster = Cluster = class extends @Tool @counter: 0 init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'cluster ' + Cluster.counter++ @dataNode.prop.title.name = 'Cluster' @dataNode.type = 'cluster' _.extend @dataNode.prop, key: name: 'Key' type: 'text' value: null listener: (value) -> value = null if value is 'null' self.dataNode.prop.key.value = value self.update() update: () -> super() self = @ inputName = @dataNode.prop.input.value key = @dataNode.prop.key.value if not key or not inputName DataPool.display DataModel.tree return genChildren = (input) -> group = {} list = [] input.forEach (row, index) -> if not group[row[key]] group[row[key]] = [] group[row[key]].push (_.copy row) keys = Object.keys group .map (row) -> list.push group[row] temp = {} temp[key] = row return temp # TO DO # may exist name conflict new DataModel inputName + '.' + key, keys, self.dataNode.name # for index, item of group new DataModel inputName + '.' + key + '.set', list, self.dataNode.name input = DataModel.list[inputName] if _.isType input[0], 'Array' input.forEach (data, index) -> genChildren data else genChildren input @Scale = Scale = class extends Tool @counter: 0 @list: [] init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'scale' + Scale.counter++ @dataNode.prop.title.name = 'Scale' @dataNode.type = 'scale' @dataNode.prop.input.listener Scale.list.push @dataNode _.extend @dataNode.prop, domain: name: 'Domain' type: 'select' value: null set: () -> result = [ name: 'none' value: null ] listener: (value) -> self.dataNode.prop.domain.value = value from: name: 'From' type: 'range' value: ['$Min($domain)', '$Max($domain)'] listener: (value) -> self.dataNode.prop.from.value = value to: name: 'To' type: 'range' value: [0, 100] listener: (value) -> self.dataNode.prop.to.value = value update: () -> super() DataPool.display _.copy DataModel.tree if DataPool? setInput: (value) -> value = null if value is 'null' super value @dataNode.prop.domain.set = () -> result = [ name: 'none' value: null ] if value? Object.keys DataModel.list[value][0] .forEach (key) -> result.push name: key value: key return result DataPanel.display @dataNode if DataPanel? return @ Data = list: {} add: (id) -> Data.list[id] = new Workflow(id) workflow: (id) -> return Data.list[id] if id? return Data.list[TreePanel.selected.target.id] if TreePanel? return null get: (id) -> return Data.list[id].DataModel if id? return Data.list[TreePanel.selected.target.id].DataModel if TreePanel? return null tools: (id) -> return Data.list[id] if id? return Data.list[TreePanel.selected.target.id] if TreePanel? return null outPool: (id) -> return Data.list[id].outPool if id? return Data.list[TreePanel.selected.target.id].outPool if TreePanel? return null remove: (id) -> delete Data.list[id] if exports? module.exports = Data else @Data = Data )()
85718
(() -> Workflow = (@owner) -> owner = @owner wf = @ @outPool = outPool = {} @checkInput = () -> if Primitives.list[owner].prop.parent? parent = Primitives.list[owner].prop.parent.value inPool = Data.workflow(parent).outPool for key, value of inPool if not DataModel.list[key] new wf.DataModel key, value.data @DataModel = DataModel = class @list: {} @tree: [] @members: {} @getNode: (name, trees) -> for tree in trees if tree.name is name return tree for tree in trees result = @getNode name, tree.children return result if result output: () -> outPool[@name] = @ constructor: (@name, @data, parent, @hidden) -> self = @ name =<NAME> @name dataArrayFlag = false if _.isType @data[0], 'Array' dataArrayFlag = true keys = Object.keys data[0][0] else keys = Object.keys data[0] DataModel.list[name] = @data DataModel.members[name] = @ dataNode = name: <NAME> type: 'data' parent: parent children: [] hidden: hidden prop: title: name: (() -> return 'Data Set' if dataArrayFlag return 'Data' )() type: 'title' name: name: 'Name' type: 'label' value: name rows: name: 'Rows' type: 'label' value: (() -> return self.data.length )() preview: name: 'Preview' type: 'html' value: (() -> data = DataModel.list[name] tr = '' th = '<thead><tr><th>' + (keys.join '</th><th>') + '</th></tr></thead>' if not dataArrayFlag data.forEach (row, i) -> td = '' keys.forEach (key, j) -> td += "<td>#{row[key]}</td>" tr += "<tr>#{td}</tr>" table = "<table>#{th}<tbody>#{tr}</tbody></table>" return table )() if dataArrayFlag @data.forEach (data, index) -> new wf.DataModel name + '.' + index, data, parent, true if not hidden if parent? node = DataModel.getNode parent, DataModel.tree node.children.push dataNode else DataModel.tree.push dataNode # d3.tree() will remove `children` from tree's nodes DataPool.display _.copy DataModel.tree if DataPool? DataPanel.display dataNode if DataPanel? return @ @Tool = Tool = class constructor: () -> self = @ name = 'Tool ' + Tool.counter++ @name = name dataNode = id: _.cid() name: name type: 'tool' parent: null children: [] prop: title: name: 'Tool' type: 'title' name: name: 'Name' type: 'text' value: name listener: (value) -> self.dataNode.name = value self.dataNode.prop.name.value = value self.update() input: name: 'Input' type: 'select' value: null set: () -> result = [ name: 'none' value: null ] for key, value of DataModel.list result.push name: key value: key return result listener: (value) -> self.setInput value @dataNode = dataNode @init() DataModel.tree.push dataNode DataPool.display DataModel.tree if DataPool? DataPanel.display dataNode if DataPanel? @counter: 0 update: () -> for child in @dataNode.children delete Data.list[child.name] @dataNode.children = [] setInput: (value) -> value = null if value is 'null' if @dataNode.parent? oldParent = DataModel.getNode @dataNode.parent, Data.tree .children else oldParent = DataModel.tree index = oldParent.indexOf @dataNode oldParent.splice index, 1 @dataNode.parent = value @dataNode.prop.input.value = value if value? parent = DataModel.getNode value, DataModel.tree .children else parent = DataModel.tree parent.push @dataNode @update() init: () -> # Filter and Cluster need to be reduced @Filter = Filter = class extends @Tool @counter: 0 init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'filter ' + Filter.counter++ @dataNode.prop.title.name = 'Filter' @dataNode.type = 'filter' _.extend @dataNode.prop, select: name: 'Select' type: 'text' value: null listener: (value) -> value = null if value is 'null' self.dataNode.prop.select.value = value self.update() rules: name: 'Rules' type: 'text' value: null listener: (value) -> self.dataNode.prop.rules.value = value self.update() update: () -> super() inputName = @dataNode.prop.input.value select = @dataNode.prop.select.value rules = @dataNode.prop.rules.value if not select or not inputName DataPool.display DataModel.tree return input = DataModel.list[inputName] if select isnt '*' select = select.split ',' .map (row) -> return row.trim() output = [] input.forEach (row, index) -> if rules fn = eval "(function ($data, $index) { return #{rules}})" if not fn row, index return if select is '*' output.push (_.copy row) else result = {} select.forEach (key) -> result[key] = _.copy row[key] output.push result i = 0 i++ while DataModel.list[inputName + '.' + i] new DataModel inputName + '.' + i, output, @dataNode.name @Cluster = Cluster = class extends @Tool @counter: 0 init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'cluster ' + Cluster.counter++ @dataNode.prop.title.name = 'Cluster' @dataNode.type = 'cluster' _.extend @dataNode.prop, key: name: 'Key' type: 'text' value: null listener: (value) -> value = null if value is 'null' self.dataNode.prop.key.value = value self.update() update: () -> super() self = @ inputName = @dataNode.prop.input.value key = @dataNode.prop.key.value if not key or not inputName DataPool.display DataModel.tree return genChildren = (input) -> group = {} list = [] input.forEach (row, index) -> if not group[row[key]] group[row[key]] = [] group[row[key]].push (_.copy row) keys = Object.keys group .map (row) -> list.push group[row] temp = {} temp[key] = row return temp # TO DO # may exist name conflict new DataModel inputName + '.' + key, keys, self.dataNode.name # for index, item of group new DataModel inputName + '.' + key + '.set', list, self.dataNode.name input = DataModel.list[inputName] if _.isType input[0], 'Array' input.forEach (data, index) -> genChildren data else genChildren input @Scale = Scale = class extends Tool @counter: 0 @list: [] init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'scale' + Scale.counter++ @dataNode.prop.title.name = 'Scale' @dataNode.type = 'scale' @dataNode.prop.input.listener Scale.list.push @dataNode _.extend @dataNode.prop, domain: name: 'Domain' type: 'select' value: null set: () -> result = [ name: 'none' value: null ] listener: (value) -> self.dataNode.prop.domain.value = value from: name: 'From' type: 'range' value: ['$Min($domain)', '$Max($domain)'] listener: (value) -> self.dataNode.prop.from.value = value to: name: 'To' type: 'range' value: [0, 100] listener: (value) -> self.dataNode.prop.to.value = value update: () -> super() DataPool.display _.copy DataModel.tree if DataPool? setInput: (value) -> value = null if value is 'null' super value @dataNode.prop.domain.set = () -> result = [ name: 'none' value: null ] if value? Object.keys DataModel.list[value][0] .forEach (key) -> result.push name: key value: key return result DataPanel.display @dataNode if DataPanel? return @ Data = list: {} add: (id) -> Data.list[id] = new Workflow(id) workflow: (id) -> return Data.list[id] if id? return Data.list[TreePanel.selected.target.id] if TreePanel? return null get: (id) -> return Data.list[id].DataModel if id? return Data.list[TreePanel.selected.target.id].DataModel if TreePanel? return null tools: (id) -> return Data.list[id] if id? return Data.list[TreePanel.selected.target.id] if TreePanel? return null outPool: (id) -> return Data.list[id].outPool if id? return Data.list[TreePanel.selected.target.id].outPool if TreePanel? return null remove: (id) -> delete Data.list[id] if exports? module.exports = Data else @Data = Data )()
true
(() -> Workflow = (@owner) -> owner = @owner wf = @ @outPool = outPool = {} @checkInput = () -> if Primitives.list[owner].prop.parent? parent = Primitives.list[owner].prop.parent.value inPool = Data.workflow(parent).outPool for key, value of inPool if not DataModel.list[key] new wf.DataModel key, value.data @DataModel = DataModel = class @list: {} @tree: [] @members: {} @getNode: (name, trees) -> for tree in trees if tree.name is name return tree for tree in trees result = @getNode name, tree.children return result if result output: () -> outPool[@name] = @ constructor: (@name, @data, parent, @hidden) -> self = @ name =PI:NAME:<NAME>END_PI @name dataArrayFlag = false if _.isType @data[0], 'Array' dataArrayFlag = true keys = Object.keys data[0][0] else keys = Object.keys data[0] DataModel.list[name] = @data DataModel.members[name] = @ dataNode = name: PI:NAME:<NAME>END_PI type: 'data' parent: parent children: [] hidden: hidden prop: title: name: (() -> return 'Data Set' if dataArrayFlag return 'Data' )() type: 'title' name: name: 'Name' type: 'label' value: name rows: name: 'Rows' type: 'label' value: (() -> return self.data.length )() preview: name: 'Preview' type: 'html' value: (() -> data = DataModel.list[name] tr = '' th = '<thead><tr><th>' + (keys.join '</th><th>') + '</th></tr></thead>' if not dataArrayFlag data.forEach (row, i) -> td = '' keys.forEach (key, j) -> td += "<td>#{row[key]}</td>" tr += "<tr>#{td}</tr>" table = "<table>#{th}<tbody>#{tr}</tbody></table>" return table )() if dataArrayFlag @data.forEach (data, index) -> new wf.DataModel name + '.' + index, data, parent, true if not hidden if parent? node = DataModel.getNode parent, DataModel.tree node.children.push dataNode else DataModel.tree.push dataNode # d3.tree() will remove `children` from tree's nodes DataPool.display _.copy DataModel.tree if DataPool? DataPanel.display dataNode if DataPanel? return @ @Tool = Tool = class constructor: () -> self = @ name = 'Tool ' + Tool.counter++ @name = name dataNode = id: _.cid() name: name type: 'tool' parent: null children: [] prop: title: name: 'Tool' type: 'title' name: name: 'Name' type: 'text' value: name listener: (value) -> self.dataNode.name = value self.dataNode.prop.name.value = value self.update() input: name: 'Input' type: 'select' value: null set: () -> result = [ name: 'none' value: null ] for key, value of DataModel.list result.push name: key value: key return result listener: (value) -> self.setInput value @dataNode = dataNode @init() DataModel.tree.push dataNode DataPool.display DataModel.tree if DataPool? DataPanel.display dataNode if DataPanel? @counter: 0 update: () -> for child in @dataNode.children delete Data.list[child.name] @dataNode.children = [] setInput: (value) -> value = null if value is 'null' if @dataNode.parent? oldParent = DataModel.getNode @dataNode.parent, Data.tree .children else oldParent = DataModel.tree index = oldParent.indexOf @dataNode oldParent.splice index, 1 @dataNode.parent = value @dataNode.prop.input.value = value if value? parent = DataModel.getNode value, DataModel.tree .children else parent = DataModel.tree parent.push @dataNode @update() init: () -> # Filter and Cluster need to be reduced @Filter = Filter = class extends @Tool @counter: 0 init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'filter ' + Filter.counter++ @dataNode.prop.title.name = 'Filter' @dataNode.type = 'filter' _.extend @dataNode.prop, select: name: 'Select' type: 'text' value: null listener: (value) -> value = null if value is 'null' self.dataNode.prop.select.value = value self.update() rules: name: 'Rules' type: 'text' value: null listener: (value) -> self.dataNode.prop.rules.value = value self.update() update: () -> super() inputName = @dataNode.prop.input.value select = @dataNode.prop.select.value rules = @dataNode.prop.rules.value if not select or not inputName DataPool.display DataModel.tree return input = DataModel.list[inputName] if select isnt '*' select = select.split ',' .map (row) -> return row.trim() output = [] input.forEach (row, index) -> if rules fn = eval "(function ($data, $index) { return #{rules}})" if not fn row, index return if select is '*' output.push (_.copy row) else result = {} select.forEach (key) -> result[key] = _.copy row[key] output.push result i = 0 i++ while DataModel.list[inputName + '.' + i] new DataModel inputName + '.' + i, output, @dataNode.name @Cluster = Cluster = class extends @Tool @counter: 0 init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'cluster ' + Cluster.counter++ @dataNode.prop.title.name = 'Cluster' @dataNode.type = 'cluster' _.extend @dataNode.prop, key: name: 'Key' type: 'text' value: null listener: (value) -> value = null if value is 'null' self.dataNode.prop.key.value = value self.update() update: () -> super() self = @ inputName = @dataNode.prop.input.value key = @dataNode.prop.key.value if not key or not inputName DataPool.display DataModel.tree return genChildren = (input) -> group = {} list = [] input.forEach (row, index) -> if not group[row[key]] group[row[key]] = [] group[row[key]].push (_.copy row) keys = Object.keys group .map (row) -> list.push group[row] temp = {} temp[key] = row return temp # TO DO # may exist name conflict new DataModel inputName + '.' + key, keys, self.dataNode.name # for index, item of group new DataModel inputName + '.' + key + '.set', list, self.dataNode.name input = DataModel.list[inputName] if _.isType input[0], 'Array' input.forEach (data, index) -> genChildren data else genChildren input @Scale = Scale = class extends Tool @counter: 0 @list: [] init: () -> self = @ @dataNode.name = @dataNode.prop.name.value = @name = 'scale' + Scale.counter++ @dataNode.prop.title.name = 'Scale' @dataNode.type = 'scale' @dataNode.prop.input.listener Scale.list.push @dataNode _.extend @dataNode.prop, domain: name: 'Domain' type: 'select' value: null set: () -> result = [ name: 'none' value: null ] listener: (value) -> self.dataNode.prop.domain.value = value from: name: 'From' type: 'range' value: ['$Min($domain)', '$Max($domain)'] listener: (value) -> self.dataNode.prop.from.value = value to: name: 'To' type: 'range' value: [0, 100] listener: (value) -> self.dataNode.prop.to.value = value update: () -> super() DataPool.display _.copy DataModel.tree if DataPool? setInput: (value) -> value = null if value is 'null' super value @dataNode.prop.domain.set = () -> result = [ name: 'none' value: null ] if value? Object.keys DataModel.list[value][0] .forEach (key) -> result.push name: key value: key return result DataPanel.display @dataNode if DataPanel? return @ Data = list: {} add: (id) -> Data.list[id] = new Workflow(id) workflow: (id) -> return Data.list[id] if id? return Data.list[TreePanel.selected.target.id] if TreePanel? return null get: (id) -> return Data.list[id].DataModel if id? return Data.list[TreePanel.selected.target.id].DataModel if TreePanel? return null tools: (id) -> return Data.list[id] if id? return Data.list[TreePanel.selected.target.id] if TreePanel? return null outPool: (id) -> return Data.list[id].outPool if id? return Data.list[TreePanel.selected.target.id].outPool if TreePanel? return null remove: (id) -> delete Data.list[id] if exports? module.exports = Data else @Data = Data )()
[ { "context": " 'abc', '10001', 'USD 5950', \"\", \"\", \"\", '', '', 'John' ],\n [ 'abc',\n '10001',\n ", "end": 672, "score": 0.9992302060127258, "start": 668, "tag": "NAME", "value": "John" }, { "context": " 'abc', '10001', 'USD 5950', '', '', '', '', '', 'J...
src/spec/csv-mapping.spec.coffee
commercetools/sphere-order-export
3
_ = require 'underscore' _.mixin require('underscore-mixins') Mapping = require '../lib/mapping-utils/csv' testOrders = require '../data/orders' template = 'id,orderNumber,totalPrice,customLineItems.id,customLineItems.slug,customLineItems.quantity,lineItems.id,lineItems.productId,billingAddress.firstName' describe 'CsvMapping', -> it '#_mapOrder should remove redundant info', (done) -> mapping = new Mapping mapping._analyseTemplate template .then ([header, mappings]) -> rows = mapping._mapOrder(testOrders[0], mappings) expect(rows.length).toBe 4 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', "", "", "", '', '', 'John' ], [ 'abc', '10001', undefined, undefined, undefined, undefined, 'LineItemId-1-1', 'ProductId-1-1', undefined ], [ 'abc', '10001', undefined, undefined, undefined, undefined, 'LineItemId-1-2', 'ProductId-1-2', undefined ], [ 'abc', '10001', undefined, "64d8843b-3b53-497c-8d31-fcca82bee6f3", "slug", 1, undefined, undefined, undefined ] ] done() it '#_mapOrder should fill all rows', (done) -> mapping = new Mapping fillAllRows: true mapping._analyseTemplate template .then ([header, mappings]) -> rows = mapping._mapOrder(testOrders[0], mappings) expect(rows.length).toBe 4 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', '', '', '', '', '', 'John' ], [ 'abc', '10001', 'USD 5950', '', '', '', 'LineItemId-1-1', 'ProductId-1-1', 'John' ], [ 'abc', '10001', 'USD 5950', "", "", "", 'LineItemId-1-2', 'ProductId-1-2', 'John' ], [ 'abc', '10001', 'USD 5950', "64d8843b-3b53-497c-8d31-fcca82bee6f3", "slug", 1, '', '', 'John' ] ] done() it '#_mapOrder should return order even when lineItems are missing', (done) -> mapping = new Mapping fillAllRows: true mapping._analyseTemplate template .then ([header, mappings]) -> order = _.deepClone(testOrders[0]) order.lineItems = [] rows = mapping._mapOrder(order, mappings) expect(rows.length).toBe 2 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', '', '', '', '', '', 'John' ], [ 'abc', '10001', 'USD 5950', '64d8843b-3b53-497c-8d31-fcca82bee6f3', 'slug', 1, '', '', 'John' ], ] done()
132093
_ = require 'underscore' _.mixin require('underscore-mixins') Mapping = require '../lib/mapping-utils/csv' testOrders = require '../data/orders' template = 'id,orderNumber,totalPrice,customLineItems.id,customLineItems.slug,customLineItems.quantity,lineItems.id,lineItems.productId,billingAddress.firstName' describe 'CsvMapping', -> it '#_mapOrder should remove redundant info', (done) -> mapping = new Mapping mapping._analyseTemplate template .then ([header, mappings]) -> rows = mapping._mapOrder(testOrders[0], mappings) expect(rows.length).toBe 4 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', "", "", "", '', '', '<NAME>' ], [ 'abc', '10001', undefined, undefined, undefined, undefined, 'LineItemId-1-1', 'ProductId-1-1', undefined ], [ 'abc', '10001', undefined, undefined, undefined, undefined, 'LineItemId-1-2', 'ProductId-1-2', undefined ], [ 'abc', '10001', undefined, "64d8843b-3b53-497c-8d31-fcca82bee6f3", "slug", 1, undefined, undefined, undefined ] ] done() it '#_mapOrder should fill all rows', (done) -> mapping = new Mapping fillAllRows: true mapping._analyseTemplate template .then ([header, mappings]) -> rows = mapping._mapOrder(testOrders[0], mappings) expect(rows.length).toBe 4 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', '', '', '', '', '', '<NAME>' ], [ 'abc', '10001', 'USD 5950', '', '', '', 'LineItemId-1-1', 'ProductId-1-1', '<NAME>' ], [ 'abc', '10001', 'USD 5950', "", "", "", 'LineItemId-1-2', 'ProductId-1-2', '<NAME>' ], [ 'abc', '10001', 'USD 5950', "64d8843b-3b53-497c-8d31-fcca82bee6f3", "slug", 1, '', '', '<NAME>' ] ] done() it '#_mapOrder should return order even when lineItems are missing', (done) -> mapping = new Mapping fillAllRows: true mapping._analyseTemplate template .then ([header, mappings]) -> order = _.deepClone(testOrders[0]) order.lineItems = [] rows = mapping._mapOrder(order, mappings) expect(rows.length).toBe 2 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', '', '', '', '', '', '<NAME>' ], [ 'abc', '10001', 'USD 5950', '64d8843b-3b53-497c-8d31-fcca82bee6f3', 'slug', 1, '', '', '<NAME>' ], ] done()
true
_ = require 'underscore' _.mixin require('underscore-mixins') Mapping = require '../lib/mapping-utils/csv' testOrders = require '../data/orders' template = 'id,orderNumber,totalPrice,customLineItems.id,customLineItems.slug,customLineItems.quantity,lineItems.id,lineItems.productId,billingAddress.firstName' describe 'CsvMapping', -> it '#_mapOrder should remove redundant info', (done) -> mapping = new Mapping mapping._analyseTemplate template .then ([header, mappings]) -> rows = mapping._mapOrder(testOrders[0], mappings) expect(rows.length).toBe 4 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', "", "", "", '', '', 'PI:NAME:<NAME>END_PI' ], [ 'abc', '10001', undefined, undefined, undefined, undefined, 'LineItemId-1-1', 'ProductId-1-1', undefined ], [ 'abc', '10001', undefined, undefined, undefined, undefined, 'LineItemId-1-2', 'ProductId-1-2', undefined ], [ 'abc', '10001', undefined, "64d8843b-3b53-497c-8d31-fcca82bee6f3", "slug", 1, undefined, undefined, undefined ] ] done() it '#_mapOrder should fill all rows', (done) -> mapping = new Mapping fillAllRows: true mapping._analyseTemplate template .then ([header, mappings]) -> rows = mapping._mapOrder(testOrders[0], mappings) expect(rows.length).toBe 4 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', '', '', '', '', '', 'PI:NAME:<NAME>END_PI' ], [ 'abc', '10001', 'USD 5950', '', '', '', 'LineItemId-1-1', 'ProductId-1-1', 'PI:NAME:<NAME>END_PI' ], [ 'abc', '10001', 'USD 5950', "", "", "", 'LineItemId-1-2', 'ProductId-1-2', 'PI:NAME:<NAME>END_PI' ], [ 'abc', '10001', 'USD 5950', "64d8843b-3b53-497c-8d31-fcca82bee6f3", "slug", 1, '', '', 'PI:NAME:<NAME>END_PI' ] ] done() it '#_mapOrder should return order even when lineItems are missing', (done) -> mapping = new Mapping fillAllRows: true mapping._analyseTemplate template .then ([header, mappings]) -> order = _.deepClone(testOrders[0]) order.lineItems = [] rows = mapping._mapOrder(order, mappings) expect(rows.length).toBe 2 expect(rows).toEqual [ [ 'abc', '10001', 'USD 5950', '', '', '', '', '', 'PI:NAME:<NAME>END_PI' ], [ 'abc', '10001', 'USD 5950', '64d8843b-3b53-497c-8d31-fcca82bee6f3', 'slug', 1, '', '', 'PI:NAME:<NAME>END_PI' ], ] done()
[ { "context": "changePassword({email: profile.email, oldPassword: oldPass, newPassword: newPass})\n # * .then(func", "end": 779, "score": 0.9287199974060059, "start": 772, "tag": "PASSWORD", "value": "oldPass" }, { "context": " profile.email, oldPassword: oldPass, newPasswor...
app/scripts/controllers/account.coffee
nerdfiles/utxo_us
0
"use strict" ###* @ngdoc function @name muck2App.controller:AccountCtrl @description # AccountCtrl Provides rudimentary account management functions. ### angular.module("utxoPmc").controller "AccountCtrl", ($scope, Auth, Ref, $firebaseObject, $timeout, person) -> #var profile = $firebaseObject(Ref.child('users/' + user.uid)); #profile.$bindTo($scope, 'profile'); # # *$scope.changePassword = function(oldPass, newPass, confirm) { # * $scope.err = null; # * if( !oldPass || !newPass ) { # * error('Please enter all fields'); # * } # * else if( newPass !== confirm ) { # * error('Passwords do not match'); # * } # * else { # * Auth.$changePassword({email: profile.email, oldPassword: oldPass, newPassword: newPass}) # * .then(function() { # * success('Password changed'); # * }, error); # * } # *}; # # # *$scope.changeEmail = function(pass, newEmail) { # * $scope.err = null; # * Auth.$changeEmail({password: pass, newEmail: newEmail, oldEmail: profile.email}) # * .then(function() { # * profile.email = newEmail; # * profile.$save(); # * success('Email changed'); # * }) # * .catch(error); # *}; # error = (err) -> alert err, "danger" return success = (msg) -> alert msg, "success" return alert = (msg, type) -> obj = text: msg + "" type: type $scope.messages.unshift obj $timeout (-> $scope.messages.splice $scope.messages.indexOf(obj), 1 return ), 10000 return $scope.logout = -> Auth.$unauth() return $scope.messages = [] return
134686
"use strict" ###* @ngdoc function @name muck2App.controller:AccountCtrl @description # AccountCtrl Provides rudimentary account management functions. ### angular.module("utxoPmc").controller "AccountCtrl", ($scope, Auth, Ref, $firebaseObject, $timeout, person) -> #var profile = $firebaseObject(Ref.child('users/' + user.uid)); #profile.$bindTo($scope, 'profile'); # # *$scope.changePassword = function(oldPass, newPass, confirm) { # * $scope.err = null; # * if( !oldPass || !newPass ) { # * error('Please enter all fields'); # * } # * else if( newPass !== confirm ) { # * error('Passwords do not match'); # * } # * else { # * Auth.$changePassword({email: profile.email, oldPassword: <PASSWORD>, newPassword: <PASSWORD>}) # * .then(function() { # * success('Password changed'); # * }, error); # * } # *}; # # # *$scope.changeEmail = function(pass, newEmail) { # * $scope.err = null; # * Auth.$changeEmail({password: <PASSWORD>, newEmail: newEmail, oldEmail: profile.email}) # * .then(function() { # * profile.email = newEmail; # * profile.$save(); # * success('Email changed'); # * }) # * .catch(error); # *}; # error = (err) -> alert err, "danger" return success = (msg) -> alert msg, "success" return alert = (msg, type) -> obj = text: msg + "" type: type $scope.messages.unshift obj $timeout (-> $scope.messages.splice $scope.messages.indexOf(obj), 1 return ), 10000 return $scope.logout = -> Auth.$unauth() return $scope.messages = [] return
true
"use strict" ###* @ngdoc function @name muck2App.controller:AccountCtrl @description # AccountCtrl Provides rudimentary account management functions. ### angular.module("utxoPmc").controller "AccountCtrl", ($scope, Auth, Ref, $firebaseObject, $timeout, person) -> #var profile = $firebaseObject(Ref.child('users/' + user.uid)); #profile.$bindTo($scope, 'profile'); # # *$scope.changePassword = function(oldPass, newPass, confirm) { # * $scope.err = null; # * if( !oldPass || !newPass ) { # * error('Please enter all fields'); # * } # * else if( newPass !== confirm ) { # * error('Passwords do not match'); # * } # * else { # * Auth.$changePassword({email: profile.email, oldPassword: PI:PASSWORD:<PASSWORD>END_PI, newPassword: PI:PASSWORD:<PASSWORD>END_PI}) # * .then(function() { # * success('Password changed'); # * }, error); # * } # *}; # # # *$scope.changeEmail = function(pass, newEmail) { # * $scope.err = null; # * Auth.$changeEmail({password: PI:PASSWORD:<PASSWORD>END_PI, newEmail: newEmail, oldEmail: profile.email}) # * .then(function() { # * profile.email = newEmail; # * profile.$save(); # * success('Email changed'); # * }) # * .catch(error); # *}; # error = (err) -> alert err, "danger" return success = (msg) -> alert msg, "success" return alert = (msg, type) -> obj = text: msg + "" type: type $scope.messages.unshift obj $timeout (-> $scope.messages.splice $scope.messages.indexOf(obj), 1 return ), 10000 return $scope.logout = -> Auth.$unauth() return $scope.messages = [] return
[ { "context": ")\n return 'over' if node.data.key == 'query-root'\n # prevent dropping a parent below it", "end": 2109, "score": 0.6121812462806702, "start": 2109, "tag": "KEY", "value": "" } ]
app/assets/javascripts/query_builder/query_tree_options.coffee
BI/enterprise-search-os
0
window.QueryTreeOptions = class QueryTreeOptions @defaults: debugLevel: 0 onQueryActivate: (node) -> false onQuerySelect: (node) -> false keyboard: false clickFolderMode: 1 fx: height: 'toggle' duration: 300 onCustomRender: (node) -> node.data.query = new (node.data.isFolder && QueryGroup || QueryClause) node node.data.query.render() onRender: (node, nodeSpan) -> $(nodeSpan).find('.query-item').hover( -> $(this).addClass('hovered-query-item') unless queryTree.isDragging == true || QueryTree.activeInput() -> $(this).removeClass('hovered-query-item') unless $(document.activeElement).is( $(this) ) ) return if node.data.isFolder new ClauseInput node, nodeSpan node.data.query.containerFeedback(node) onExpand: (flag, node) -> node.render() if flag # resize input queryTree.setStatus() dnd: onDragStart: (node) -> # This function MUST be defined to enable dragging for the tree. # Return false to cancel dragging of node. #logMsg("tree.onDragStart(%o)", node) queryTree.isDragging = true # prevent dragging the first node (which we use as root) # return false if node.data.key == 'query-root' true onDragStop: (node) -> queryTree.isDragging = false autoExpandMS: 500 # Prevent dropping nodes 'before self', etc. preventVoidMoves: true onDragEnter: (node, sourceNode) -> # sourceNode may be null for non-dynatree droppables. # Return false to disallow dropping on node. In this case # onDragOver and onDragLeave are not called. # Return 'over', 'before, or 'after' to force a hitMode. # Return ['before', 'after'] to restrict available hitModes. # Any other return value will calc the hitMode from the cursor position. #logMsg("tree.onDragEnter(%o, %o)", node, sourceNode) # prevent creating siblings of first node (which we use as root node) return 'over' if node.data.key == 'query-root' # prevent dropping a parent below it's own child return false if node.isDescendantOf(sourceNode) # prevent creating childs in non-folders (allows only before and after for non-folders) return ['before', 'after'] unless node.data.isFolder true onDrop: (node, sourceNode, hitMode, ui, draggable) => # This function MUST be defined to enable dropping of items on the tree. #logMsg("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode) sourceNode.move(node, hitMode) node.render() node.expand(true) sourceNode.expand(true) queryTree.update()
51337
window.QueryTreeOptions = class QueryTreeOptions @defaults: debugLevel: 0 onQueryActivate: (node) -> false onQuerySelect: (node) -> false keyboard: false clickFolderMode: 1 fx: height: 'toggle' duration: 300 onCustomRender: (node) -> node.data.query = new (node.data.isFolder && QueryGroup || QueryClause) node node.data.query.render() onRender: (node, nodeSpan) -> $(nodeSpan).find('.query-item').hover( -> $(this).addClass('hovered-query-item') unless queryTree.isDragging == true || QueryTree.activeInput() -> $(this).removeClass('hovered-query-item') unless $(document.activeElement).is( $(this) ) ) return if node.data.isFolder new ClauseInput node, nodeSpan node.data.query.containerFeedback(node) onExpand: (flag, node) -> node.render() if flag # resize input queryTree.setStatus() dnd: onDragStart: (node) -> # This function MUST be defined to enable dragging for the tree. # Return false to cancel dragging of node. #logMsg("tree.onDragStart(%o)", node) queryTree.isDragging = true # prevent dragging the first node (which we use as root) # return false if node.data.key == 'query-root' true onDragStop: (node) -> queryTree.isDragging = false autoExpandMS: 500 # Prevent dropping nodes 'before self', etc. preventVoidMoves: true onDragEnter: (node, sourceNode) -> # sourceNode may be null for non-dynatree droppables. # Return false to disallow dropping on node. In this case # onDragOver and onDragLeave are not called. # Return 'over', 'before, or 'after' to force a hitMode. # Return ['before', 'after'] to restrict available hitModes. # Any other return value will calc the hitMode from the cursor position. #logMsg("tree.onDragEnter(%o, %o)", node, sourceNode) # prevent creating siblings of first node (which we use as root node) return 'over' if node.data.key == 'query<KEY>-root' # prevent dropping a parent below it's own child return false if node.isDescendantOf(sourceNode) # prevent creating childs in non-folders (allows only before and after for non-folders) return ['before', 'after'] unless node.data.isFolder true onDrop: (node, sourceNode, hitMode, ui, draggable) => # This function MUST be defined to enable dropping of items on the tree. #logMsg("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode) sourceNode.move(node, hitMode) node.render() node.expand(true) sourceNode.expand(true) queryTree.update()
true
window.QueryTreeOptions = class QueryTreeOptions @defaults: debugLevel: 0 onQueryActivate: (node) -> false onQuerySelect: (node) -> false keyboard: false clickFolderMode: 1 fx: height: 'toggle' duration: 300 onCustomRender: (node) -> node.data.query = new (node.data.isFolder && QueryGroup || QueryClause) node node.data.query.render() onRender: (node, nodeSpan) -> $(nodeSpan).find('.query-item').hover( -> $(this).addClass('hovered-query-item') unless queryTree.isDragging == true || QueryTree.activeInput() -> $(this).removeClass('hovered-query-item') unless $(document.activeElement).is( $(this) ) ) return if node.data.isFolder new ClauseInput node, nodeSpan node.data.query.containerFeedback(node) onExpand: (flag, node) -> node.render() if flag # resize input queryTree.setStatus() dnd: onDragStart: (node) -> # This function MUST be defined to enable dragging for the tree. # Return false to cancel dragging of node. #logMsg("tree.onDragStart(%o)", node) queryTree.isDragging = true # prevent dragging the first node (which we use as root) # return false if node.data.key == 'query-root' true onDragStop: (node) -> queryTree.isDragging = false autoExpandMS: 500 # Prevent dropping nodes 'before self', etc. preventVoidMoves: true onDragEnter: (node, sourceNode) -> # sourceNode may be null for non-dynatree droppables. # Return false to disallow dropping on node. In this case # onDragOver and onDragLeave are not called. # Return 'over', 'before, or 'after' to force a hitMode. # Return ['before', 'after'] to restrict available hitModes. # Any other return value will calc the hitMode from the cursor position. #logMsg("tree.onDragEnter(%o, %o)", node, sourceNode) # prevent creating siblings of first node (which we use as root node) return 'over' if node.data.key == 'queryPI:KEY:<KEY>END_PI-root' # prevent dropping a parent below it's own child return false if node.isDescendantOf(sourceNode) # prevent creating childs in non-folders (allows only before and after for non-folders) return ['before', 'after'] unless node.data.isFolder true onDrop: (node, sourceNode, hitMode, ui, draggable) => # This function MUST be defined to enable dropping of items on the tree. #logMsg("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode) sourceNode.move(node, hitMode) node.render() node.expand(true) sourceNode.expand(true) queryTree.update()
[ { "context": "t'\n $scope.user =\n username : \"admin@admin.com\"\n password : 12345\n\n $scope.ableToCo", "end": 734, "score": 0.9999017715454102, "start": 719, "tag": "EMAIL", "value": "admin@admin.com" }, { "context": "username : \"admin@admin.com\...
client/web/src/features/login/scripts/login-controller.coffee
TimeoutZero/ProjectTrail
0
'use strict' # ============================================= # Module # ============================================= angular.module 'ProjectTrailApp.controllers' # ============================================= # LoginController # ============================================= .controller 'LoginController', ['$scope', '$window', 'LoginService', '$state', '$filter', '$modal', '$q', ($scope, $window, LoginService, $state, $filter, $modal, $q) -> # ============================================= # Attributes # ============================================= @facebookOptions = scope : 'email, publish_actions', auth_type: 'rerequest' $scope.user = username : "admin@admin.com" password : 12345 $scope.ableToConnectWithFacebook = yes # ============================================= # Initialize # ============================================= # ============================================= # Handlers # ============================================= # ============================================= # Methods # ============================================= # Login Methods # =============================== $scope.loginWithFacebook = (response) => dataParams = accessToken : response.authResponse.accessToken promise = LoginService.loginWithFacebook(dataParams) promise.success -> $scope.openNotificationModal('Connected By Facebook') promise.error -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') $scope.doLogin = -> promise = LoginService.login($scope.user) promise.success (data, status, headers, config) -> $state.go 'team.list' promise.error (data, status, headers, config, statusText) -> $scope.openNotificationModal('Could not connect') # Aux Methods # =============================== @loginByFacebookSDKCallback = (response) -> if response.status is 'connected' $scope.loginWithFacebookResponse response else $scope.$apply -> $scope.ableToConnectWithFacebook = yes @loginByFacebookSDK = => defer = $q.defer() defer.resolve( $window.FB.login(@loginByFacebookSDKCallback, @facebookOptions , yes) ) defer.promise.catch (e) -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') @statusChangeCallback = (response) => if response.status is 'connected' then $scope.loginWithFacebook response else do @loginByFacebookSDK @checkFacebookLoginState = () -> $scope.ableToConnectWithFacebook = no defer = $q.defer() defer.resolve( $window.FB.getLoginStatus( (response) => @statusChangeCallback(response) ) ) defer.promise.catch (e) -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') $scope.startLoginWithFacebookProcess = () => if $window.FB then do @checkFacebookLoginState else $scope.openNotificationModal('Could not connect by Facebook') $scope.openNotificationModal = (text) -> $modal.open windowClass : 'modal modal-theme-plain myo-modal' backdrop : yes template : """ <h3>#{text}</h3> """ return @ ]
163128
'use strict' # ============================================= # Module # ============================================= angular.module 'ProjectTrailApp.controllers' # ============================================= # LoginController # ============================================= .controller 'LoginController', ['$scope', '$window', 'LoginService', '$state', '$filter', '$modal', '$q', ($scope, $window, LoginService, $state, $filter, $modal, $q) -> # ============================================= # Attributes # ============================================= @facebookOptions = scope : 'email, publish_actions', auth_type: 'rerequest' $scope.user = username : "<EMAIL>" password : <PASSWORD> $scope.ableToConnectWithFacebook = yes # ============================================= # Initialize # ============================================= # ============================================= # Handlers # ============================================= # ============================================= # Methods # ============================================= # Login Methods # =============================== $scope.loginWithFacebook = (response) => dataParams = accessToken : response.authResponse.accessToken promise = LoginService.loginWithFacebook(dataParams) promise.success -> $scope.openNotificationModal('Connected By Facebook') promise.error -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') $scope.doLogin = -> promise = LoginService.login($scope.user) promise.success (data, status, headers, config) -> $state.go 'team.list' promise.error (data, status, headers, config, statusText) -> $scope.openNotificationModal('Could not connect') # Aux Methods # =============================== @loginByFacebookSDKCallback = (response) -> if response.status is 'connected' $scope.loginWithFacebookResponse response else $scope.$apply -> $scope.ableToConnectWithFacebook = yes @loginByFacebookSDK = => defer = $q.defer() defer.resolve( $window.FB.login(@loginByFacebookSDKCallback, @facebookOptions , yes) ) defer.promise.catch (e) -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') @statusChangeCallback = (response) => if response.status is 'connected' then $scope.loginWithFacebook response else do @loginByFacebookSDK @checkFacebookLoginState = () -> $scope.ableToConnectWithFacebook = no defer = $q.defer() defer.resolve( $window.FB.getLoginStatus( (response) => @statusChangeCallback(response) ) ) defer.promise.catch (e) -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') $scope.startLoginWithFacebookProcess = () => if $window.FB then do @checkFacebookLoginState else $scope.openNotificationModal('Could not connect by Facebook') $scope.openNotificationModal = (text) -> $modal.open windowClass : 'modal modal-theme-plain myo-modal' backdrop : yes template : """ <h3>#{text}</h3> """ return @ ]
true
'use strict' # ============================================= # Module # ============================================= angular.module 'ProjectTrailApp.controllers' # ============================================= # LoginController # ============================================= .controller 'LoginController', ['$scope', '$window', 'LoginService', '$state', '$filter', '$modal', '$q', ($scope, $window, LoginService, $state, $filter, $modal, $q) -> # ============================================= # Attributes # ============================================= @facebookOptions = scope : 'email, publish_actions', auth_type: 'rerequest' $scope.user = username : "PI:EMAIL:<EMAIL>END_PI" password : PI:PASSWORD:<PASSWORD>END_PI $scope.ableToConnectWithFacebook = yes # ============================================= # Initialize # ============================================= # ============================================= # Handlers # ============================================= # ============================================= # Methods # ============================================= # Login Methods # =============================== $scope.loginWithFacebook = (response) => dataParams = accessToken : response.authResponse.accessToken promise = LoginService.loginWithFacebook(dataParams) promise.success -> $scope.openNotificationModal('Connected By Facebook') promise.error -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') $scope.doLogin = -> promise = LoginService.login($scope.user) promise.success (data, status, headers, config) -> $state.go 'team.list' promise.error (data, status, headers, config, statusText) -> $scope.openNotificationModal('Could not connect') # Aux Methods # =============================== @loginByFacebookSDKCallback = (response) -> if response.status is 'connected' $scope.loginWithFacebookResponse response else $scope.$apply -> $scope.ableToConnectWithFacebook = yes @loginByFacebookSDK = => defer = $q.defer() defer.resolve( $window.FB.login(@loginByFacebookSDKCallback, @facebookOptions , yes) ) defer.promise.catch (e) -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') @statusChangeCallback = (response) => if response.status is 'connected' then $scope.loginWithFacebook response else do @loginByFacebookSDK @checkFacebookLoginState = () -> $scope.ableToConnectWithFacebook = no defer = $q.defer() defer.resolve( $window.FB.getLoginStatus( (response) => @statusChangeCallback(response) ) ) defer.promise.catch (e) -> $scope.ableToConnectWithFacebook = yes $scope.openNotificationModal('Could not connect by Facebook') $scope.startLoginWithFacebookProcess = () => if $window.FB then do @checkFacebookLoginState else $scope.openNotificationModal('Could not connect by Facebook') $scope.openNotificationModal = (text) -> $modal.open windowClass : 'modal modal-theme-plain myo-modal' backdrop : yes template : """ <h3>#{text}</h3> """ return @ ]
[ { "context": "having all events happen more often.\n *\n * @name Jester\n * @physical\n * @hp 30+[level*10]+[con*9]\n * @", "end": 199, "score": 0.7034942507743835, "start": 193, "tag": "NAME", "value": "Jester" } ]
src/character/classes/Jester.coffee
sadbear-/IdleLands
3
Class = require "./../base/Class" `/** * This class is a very lucky class. It uses its luck to affect everything. It also gets a bonus to having all events happen more often. * * @name Jester * @physical * @hp 30+[level*10]+[con*9] * @mp 0 * @itemScore luck*5 + luckPercent*5 (Note, all other stats are ignored except for special stats like offense, defense, etc) * @statPerLevel {str} 0 * @statPerLevel {dex} 0 * @statPerLevel {con} 0 * @statPerLevel {int} 0 * @statPerLevel {wis} 0 * @statPerLevel {agi} 0 * @statPerLevel {luck} 13 * @category Classes * @package Player */` class Jester extends Class baseHp: 30 baseHpPerLevel: 10 baseHpPerCon: 9 baseMp: 0 baseMpPerLevel: 0 baseMpPerInt: 0 baseConPerLevel: 0 baseDexPerLevel: 0 baseAgiPerLevel: 0 baseStrPerLevel: 0 baseIntPerLevel: 0 baseWisPerLevel: 0 baseLuckPerLevel: 13 itemScore: (player, item) -> item.luck*5 + item.luckPercent*5 - item.agi - item.agiPercent - item.dex - item.dexPercent - item.str - item.strPercent - item.con - item.conPercent - item.wis - item.wisPercent - item.int - item.intPercent - item.xp - item.xpPercent - item.gold - item.goldPercent - item.hp - item.hpPercent - item.mp - item.mpPercent - item.ice - item.icePercent - item.fire - item.firePercent - item.water - item.waterPercent - item.earth - item.earthPercent - item.thunder - item.thunderPercent str: (player) -> player.calc.stat 'luck' dex: (player) -> player.calc.stat 'luck' int: (player) -> player.calc.stat 'luck' con: (player) -> player.calc.stat 'luck' agi: (player) -> player.calc.stat 'luck' wis: (player) -> player.calc.stat 'luck' strPercent: (player) -> player.calc.stat 'luckPercent' dexPercent: (player) -> player.calc.stat 'luckPercent' intPercent: (player) -> player.calc.stat 'luckPercent' conPercent: (player) -> player.calc.stat 'luckPercent' agiPercent: (player) -> player.calc.stat 'luckPercent' wisPercent: (player) -> player.calc.stat 'luckPercent' eventMod: (player) -> player.level.getValue() fleePercent: (player) -> if (player.hasPersonality 'Drunk' and player.hasPersonality 'Brave') then 205 else if (player.hasPersonality 'Drunk' or player.hasPersonality 'Brave') then 105 else 5 load: (player) -> super player module.exports = exports = Jester
101276
Class = require "./../base/Class" `/** * This class is a very lucky class. It uses its luck to affect everything. It also gets a bonus to having all events happen more often. * * @name <NAME> * @physical * @hp 30+[level*10]+[con*9] * @mp 0 * @itemScore luck*5 + luckPercent*5 (Note, all other stats are ignored except for special stats like offense, defense, etc) * @statPerLevel {str} 0 * @statPerLevel {dex} 0 * @statPerLevel {con} 0 * @statPerLevel {int} 0 * @statPerLevel {wis} 0 * @statPerLevel {agi} 0 * @statPerLevel {luck} 13 * @category Classes * @package Player */` class Jester extends Class baseHp: 30 baseHpPerLevel: 10 baseHpPerCon: 9 baseMp: 0 baseMpPerLevel: 0 baseMpPerInt: 0 baseConPerLevel: 0 baseDexPerLevel: 0 baseAgiPerLevel: 0 baseStrPerLevel: 0 baseIntPerLevel: 0 baseWisPerLevel: 0 baseLuckPerLevel: 13 itemScore: (player, item) -> item.luck*5 + item.luckPercent*5 - item.agi - item.agiPercent - item.dex - item.dexPercent - item.str - item.strPercent - item.con - item.conPercent - item.wis - item.wisPercent - item.int - item.intPercent - item.xp - item.xpPercent - item.gold - item.goldPercent - item.hp - item.hpPercent - item.mp - item.mpPercent - item.ice - item.icePercent - item.fire - item.firePercent - item.water - item.waterPercent - item.earth - item.earthPercent - item.thunder - item.thunderPercent str: (player) -> player.calc.stat 'luck' dex: (player) -> player.calc.stat 'luck' int: (player) -> player.calc.stat 'luck' con: (player) -> player.calc.stat 'luck' agi: (player) -> player.calc.stat 'luck' wis: (player) -> player.calc.stat 'luck' strPercent: (player) -> player.calc.stat 'luckPercent' dexPercent: (player) -> player.calc.stat 'luckPercent' intPercent: (player) -> player.calc.stat 'luckPercent' conPercent: (player) -> player.calc.stat 'luckPercent' agiPercent: (player) -> player.calc.stat 'luckPercent' wisPercent: (player) -> player.calc.stat 'luckPercent' eventMod: (player) -> player.level.getValue() fleePercent: (player) -> if (player.hasPersonality 'Drunk' and player.hasPersonality 'Brave') then 205 else if (player.hasPersonality 'Drunk' or player.hasPersonality 'Brave') then 105 else 5 load: (player) -> super player module.exports = exports = Jester
true
Class = require "./../base/Class" `/** * This class is a very lucky class. It uses its luck to affect everything. It also gets a bonus to having all events happen more often. * * @name PI:NAME:<NAME>END_PI * @physical * @hp 30+[level*10]+[con*9] * @mp 0 * @itemScore luck*5 + luckPercent*5 (Note, all other stats are ignored except for special stats like offense, defense, etc) * @statPerLevel {str} 0 * @statPerLevel {dex} 0 * @statPerLevel {con} 0 * @statPerLevel {int} 0 * @statPerLevel {wis} 0 * @statPerLevel {agi} 0 * @statPerLevel {luck} 13 * @category Classes * @package Player */` class Jester extends Class baseHp: 30 baseHpPerLevel: 10 baseHpPerCon: 9 baseMp: 0 baseMpPerLevel: 0 baseMpPerInt: 0 baseConPerLevel: 0 baseDexPerLevel: 0 baseAgiPerLevel: 0 baseStrPerLevel: 0 baseIntPerLevel: 0 baseWisPerLevel: 0 baseLuckPerLevel: 13 itemScore: (player, item) -> item.luck*5 + item.luckPercent*5 - item.agi - item.agiPercent - item.dex - item.dexPercent - item.str - item.strPercent - item.con - item.conPercent - item.wis - item.wisPercent - item.int - item.intPercent - item.xp - item.xpPercent - item.gold - item.goldPercent - item.hp - item.hpPercent - item.mp - item.mpPercent - item.ice - item.icePercent - item.fire - item.firePercent - item.water - item.waterPercent - item.earth - item.earthPercent - item.thunder - item.thunderPercent str: (player) -> player.calc.stat 'luck' dex: (player) -> player.calc.stat 'luck' int: (player) -> player.calc.stat 'luck' con: (player) -> player.calc.stat 'luck' agi: (player) -> player.calc.stat 'luck' wis: (player) -> player.calc.stat 'luck' strPercent: (player) -> player.calc.stat 'luckPercent' dexPercent: (player) -> player.calc.stat 'luckPercent' intPercent: (player) -> player.calc.stat 'luckPercent' conPercent: (player) -> player.calc.stat 'luckPercent' agiPercent: (player) -> player.calc.stat 'luckPercent' wisPercent: (player) -> player.calc.stat 'luckPercent' eventMod: (player) -> player.level.getValue() fleePercent: (player) -> if (player.hasPersonality 'Drunk' and player.hasPersonality 'Brave') then 205 else if (player.hasPersonality 'Drunk' or player.hasPersonality 'Brave') then 105 else 5 load: (player) -> super player module.exports = exports = Jester
[ { "context": "itude\n g.name = g.name\n .replace(\"Bezirk\", \"\")\n .replace(\",\", \" \")\n .rep", "end": 1188, "score": 0.9926771521568298, "start": 1182, "tag": "NAME", "value": "Bezirk" }, { "context": " else cb p\n else cb p\n\n ...
geonames.coffee
orangeman/geodata
0
exec = require('child_process').exec csv = require('csv-streamify') request = require('request') through = require('through2') es = require('event-stream') level = require('level') fs = require('fs') alt = level "./data/alt" tmp = level "./data/tmp", valueEncoding: 'json' #tmp.createReadStream gte: "ADM", lt: "ADM~" #.pipe es.mapSync (p) -> console.log "#{p.key} -> #{p.value.name}" module.exports = storeAlts: () -> fs.createReadStream "./alternateNames.txt" .pipe csv delimiter: "\t", objectMode: true .on "data", (data) -> #console.log "DATA " + data[1] + ":" + data[2] + ":" + data[4] + ":" + data[5] + ":" + data[6] + " -> " + data[3] alts.put data[1] + ":" + data[2] + ":" + data[4] + ":" + data[5] + ":" + data[6], data[3] storeCountry: (country) -> console.log " load " + url country request.get url country .pipe require('geonames-stream').pipeline .pipe through.obj (g, enc, next) -> if g.feature_code.match(/PPL.*|ADM5/) && g.population != "0" g.latlon = [parseFloat(g.latitude), parseFloat(g.longitude)] delete g.latitude delete g.longitude g.name = g.name .replace("Bezirk", "") .replace(",", " ") .replace("'", "") .replace("ˈ", "") .trim() delete g.alternatenames tmp.put "pop:" + normalize(g.population) + ":" + g._id, g, next console.log " + store #{g.name} #{JSON.stringify g.latlon} pop=#{g.population}" else if l = g.feature_code.match /ADM(\d)/ #console.log g.feature_code + ":" + g["admin#{l[1]}_code"] tmp.put g.feature_code + ":" + g["admin#{l[1]}_code"], g, next else next() , () -> console.log "done" processPlaces: () -> exec "rm -r data/place", (err, out) -> console.log " deleted place db" place = level "./data/place", valueEncoding: "json" count = 0 ambig = 0 append = 0 replace = 0 taken = 0 alts = 0 byPopulation 1 * 1000 .pipe through.obj (g, enc, next) -> store = (k, v, i, cb) -> place.get k, (err, p) -> if !p count += 1 if i < 2 append += 1 if i == 1 alts += 1 if i == 2 place.put k, v, () -> cb v if i < 2 tmp.put "id:" + v._id, k #console.log " + place #{count}: #{k} #{JSON.stringify v.latlon} pop=#{v.population} #{i}" else if p.feature_code.match(/ADM/) && v.feature_code.match(/PPL/) if !v.population ambig += 1 console.log " + keep #{p.feature_code} #{p.name} #{p.population} because batter than #{v.feature_code} #{v.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else replace += 1 console.log " + replace #{p.feature_code} #{p.name} #{p.population} with #{v.feature_code} #{v.population}" (v.ambig ||= []).push p place.put k, v, () -> cb v tmp.put "id:" + v._id, k else if i == 0 if v.feature_code.match(/PPLX/) if v.name.match /Bayerbach/ console.log "SKIP #{v.name} #{v.feature_code} #{v.population} keep #{p.name} #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + p._id, k ambig += 1 return adm = (ex, ca, l) -> if ca["adm" + l] && ca["adm" + l] != ca.name if v["adm" + l].indexOf(ca.name) >= 0 #console.log " #{k} try ADM#{l} #{ca['adm' + l]} for #{ca.name} #{ca.feature_code} #{ca.population} because already #{ex.feature_code} #{ex.name} #{ex.population}" ca.name = ca["adm" + l] else if ca.name.match /Bayerbach/ console.log " #{k} append ADM#{l} #{ex.name} + #{ca['adm' + l]} #{ca.feature_code} #{ca.population} because already #{ex.feature_code} #{ex.name} #{ex.population}" ca.name += (" - " + ca["adm" + l]) store ca.name.toUpperCase(), ca, i + 1, cb true else false if !adm(p, v, 4) if !adm(p, v, 3) if !adm(p, v, 2) if !adm(p, v, 1) ambig += 1 console.log " NO PLACE FOR #{k} #{v.feature_code} #{v.population} already #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else if i < 2 ambig += 1 console.log " NO PLACE FOR #{k} #{v.feature_code} #{v.population} already #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else taken += 1 cb() synonym = (p, c, cb) -> alt.createReadStream gte: g.value._id, lte: g.value._id + "~" .pipe through.obj (a, enc, nextAlt) -> k = a.key.split(":")[1] if k == c a.value = a.value .replace("Bezirk", "") .replace(",", " ") .replace("'", "") .replace("ˈ", "") .trim() store a.value.toUpperCase(), p, 2, (at) -> if at if !(p.alts ||= {})[a.value] p.alts[a.value] = c place.put kk.toUpperCase(), p for kk,u of p.alts place.put p.name.toUpperCase(), p, nextAlt else console.log " - no #{a.value} #{a.key} gibt schon #{p.alts[c]}" nextAlt() else nextAlt() else nextAlt() , () -> cb() admin = (p, l, cb) -> ac = "admin#{l}_code" if p[ac] tmp.get "ADM#{l}:#{p[ac]}", (err, adm) -> if adm p["adm" + l] = adm.name #console.log "#{g.value.name} -> adm#{l} #{p[ac]} " + adm.name if l == 5 #if p.name == "Bayerbach" delete p[ac] cb p else cb p else cb p key = g.value.name.toUpperCase() g.value.adm1 = state[g.value.country_code][g.value.admin1_code] delete g.value.admin1_code admin g.value, 2, (p2) -> admin p2, 3, (p3) -> admin p3, 4, (p4) -> store key, p4, 0, (p) -> synonym p, "cs", () -> synonym p, "de", () -> synonym p, "en", next , () -> console.log " done #{count} keys for #{count + ambig} places with #{alts} synonyms of #{taken + alts}," + " Therof #{replace} times replaced and #{append} times appended. No place for #{ambig} places." computeDists: () -> exec "rm -rf data/dist data/path", (err, out) -> console.log "deleted dist and path db" dist = level "./data/dist" path = level "./data/path" time = new Date().getTime() count = 0 byPopulation 20 .pipe through.obj (from, enc, nextFrom) -> byPopulation 20 .pipe through.obj (to, enc, nextTo) => @push [from, to] nextTo() .on "end", nextFrom .pipe through.obj (route, enc, next) -> console.log "+ compute " + route[0].name + " -> " + route[1].name url = (country) -> "http://download.geonames.org/" + "export/dump/#{country.toUpperCase() || "DE"}.zip" normalize = (n) -> if !n n = "0" else n = "0" + n n = "0" + n for i in [0..(8 - n.length)] n byPopulation = (pop) -> tmp.createReadStream gte: "pop:" + normalize(pop), lt: "pop:10000000", reverse: true state = "AT": "09": "Wien" "08": "Vorarlberg" "07": "Tirol" "06": "Steiermark" "05": "Salzburg" "04": "Oberösterreich" "03": "Niederösterreich" "02": "Kärnten" "01": "Burgenland" "CZ": "52": "Praha" "78": "South Moravian" "79": "Jihočeský" "80": "Vysočina" "81": "Karlovarský" "82": "Královéhradecký" "83": "Liberecký" "84": "Olomoucký" "85": "Moravskoslezský" "86": "Pardubický" "87": "Plzeňský" "88": "Central Bohemia" "89": "Ústecký" "90": "Zlín" "DE": "15": "Thüringen" "10": "Schleswig-Holstein" "14": "Sachsen-Anhalt" "13": "Sachsen" "09": "Saarland" "08": "Rheinland-Pfalz" "07": "Nordrhein-Westfalen" "06": "Niedersachsen" "12": "Mecklenburg-Vorpommern" "05": "Hessen" "04": "Hamburg" "03": "Bremen" "11": "Brandenburg" "16": "Berlin" "02": "Bayern" "01": "Baden-Württemberg"
90258
exec = require('child_process').exec csv = require('csv-streamify') request = require('request') through = require('through2') es = require('event-stream') level = require('level') fs = require('fs') alt = level "./data/alt" tmp = level "./data/tmp", valueEncoding: 'json' #tmp.createReadStream gte: "ADM", lt: "ADM~" #.pipe es.mapSync (p) -> console.log "#{p.key} -> #{p.value.name}" module.exports = storeAlts: () -> fs.createReadStream "./alternateNames.txt" .pipe csv delimiter: "\t", objectMode: true .on "data", (data) -> #console.log "DATA " + data[1] + ":" + data[2] + ":" + data[4] + ":" + data[5] + ":" + data[6] + " -> " + data[3] alts.put data[1] + ":" + data[2] + ":" + data[4] + ":" + data[5] + ":" + data[6], data[3] storeCountry: (country) -> console.log " load " + url country request.get url country .pipe require('geonames-stream').pipeline .pipe through.obj (g, enc, next) -> if g.feature_code.match(/PPL.*|ADM5/) && g.population != "0" g.latlon = [parseFloat(g.latitude), parseFloat(g.longitude)] delete g.latitude delete g.longitude g.name = g.name .replace("<NAME>", "") .replace(",", " ") .replace("'", "") .replace("ˈ", "") .trim() delete g.alternatenames tmp.put "pop:" + normalize(g.population) + ":" + g._id, g, next console.log " + store #{g.name} #{JSON.stringify g.latlon} pop=#{g.population}" else if l = g.feature_code.match /ADM(\d)/ #console.log g.feature_code + ":" + g["admin#{l[1]}_code"] tmp.put g.feature_code + ":" + g["admin#{l[1]}_code"], g, next else next() , () -> console.log "done" processPlaces: () -> exec "rm -r data/place", (err, out) -> console.log " deleted place db" place = level "./data/place", valueEncoding: "json" count = 0 ambig = 0 append = 0 replace = 0 taken = 0 alts = 0 byPopulation 1 * 1000 .pipe through.obj (g, enc, next) -> store = (k, v, i, cb) -> place.get k, (err, p) -> if !p count += 1 if i < 2 append += 1 if i == 1 alts += 1 if i == 2 place.put k, v, () -> cb v if i < 2 tmp.put "id:" + v._id, k #console.log " + place #{count}: #{k} #{JSON.stringify v.latlon} pop=#{v.population} #{i}" else if p.feature_code.match(/ADM/) && v.feature_code.match(/PPL/) if !v.population ambig += 1 console.log " + keep #{p.feature_code} #{p.name} #{p.population} because batter than #{v.feature_code} #{v.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else replace += 1 console.log " + replace #{p.feature_code} #{p.name} #{p.population} with #{v.feature_code} #{v.population}" (v.ambig ||= []).push p place.put k, v, () -> cb v tmp.put "id:" + v._id, k else if i == 0 if v.feature_code.match(/PPLX/) if v.name.match /Bayerbach/ console.log "SKIP #{v.name} #{v.feature_code} #{v.population} keep #{p.name} #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + p._id, k ambig += 1 return adm = (ex, ca, l) -> if ca["adm" + l] && ca["adm" + l] != ca.name if v["adm" + l].indexOf(ca.name) >= 0 #console.log " #{k} try ADM#{l} #{ca['adm' + l]} for #{ca.name} #{ca.feature_code} #{ca.population} because already #{ex.feature_code} #{ex.name} #{ex.population}" ca.name = ca["adm" + l] else if ca.name.match /Bayerbach/ console.log " #{k} append ADM#{l} #{ex.name} + #{ca['adm' + l]} #{ca.feature_code} #{ca.population} because already #{ex.feature_code} #{ex.name} #{ex.population}" ca.name += (" - " + ca["adm" + l]) store ca.name.toUpperCase(), ca, i + 1, cb true else false if !adm(p, v, 4) if !adm(p, v, 3) if !adm(p, v, 2) if !adm(p, v, 1) ambig += 1 console.log " NO PLACE FOR #{k} #{v.feature_code} #{v.population} already #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else if i < 2 ambig += 1 console.log " NO PLACE FOR #{k} #{v.feature_code} #{v.population} already #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else taken += 1 cb() synonym = (p, c, cb) -> alt.createReadStream gte: g.value._id, lte: g.value._id + "~" .pipe through.obj (a, enc, nextAlt) -> k = a.key.split(":")[1] if k == c a.value = a.value .replace("Bezirk", "") .replace(",", " ") .replace("'", "") .replace("ˈ", "") .trim() store a.value.toUpperCase(), p, 2, (at) -> if at if !(p.alts ||= {})[a.value] p.alts[a.value] = c place.put kk.toUpperCase(), p for kk,u of p.alts place.put p.name.toUpperCase(), p, nextAlt else console.log " - no #{a.value} #{a.key} gibt schon #{p.alts[c]}" nextAlt() else nextAlt() else nextAlt() , () -> cb() admin = (p, l, cb) -> ac = "admin#{l}_code" if p[ac] tmp.get "ADM#{l}:#{p[ac]}", (err, adm) -> if adm p["adm" + l] = adm.name #console.log "#{g.value.name} -> adm#{l} #{p[ac]} " + adm.name if l == 5 #if p.name == "Bayerbach" delete p[ac] cb p else cb p else cb p key = g.<KEY> g.value.adm1 = state[g.value.country_code][g.value.admin1_code] delete g.value.admin1_code admin g.value, 2, (p2) -> admin p2, 3, (p3) -> admin p3, 4, (p4) -> store key, p4, 0, (p) -> synonym p, "cs", () -> synonym p, "de", () -> synonym p, "en", next , () -> console.log " done #{count} keys for #{count + ambig} places with #{alts} synonyms of #{taken + alts}," + " Therof #{replace} times replaced and #{append} times appended. No place for #{ambig} places." computeDists: () -> exec "rm -rf data/dist data/path", (err, out) -> console.log "deleted dist and path db" dist = level "./data/dist" path = level "./data/path" time = new Date().getTime() count = 0 byPopulation 20 .pipe through.obj (from, enc, nextFrom) -> byPopulation 20 .pipe through.obj (to, enc, nextTo) => @push [from, to] nextTo() .on "end", nextFrom .pipe through.obj (route, enc, next) -> console.log "+ compute " + route[0].name + " -> " + route[1].name url = (country) -> "http://download.geonames.org/" + "export/dump/#{country.toUpperCase() || "DE"}.zip" normalize = (n) -> if !n n = "0" else n = "0" + n n = "0" + n for i in [0..(8 - n.length)] n byPopulation = (pop) -> tmp.createReadStream gte: "pop:" + normalize(pop), lt: "pop:10000000", reverse: true state = "AT": "09": "<NAME>" "08": "<NAME>" "07": "<NAME>" "06": "<NAME>" "05": "<NAME>" "04": "Oberösterreich" "03": "Niederösterreich" "02": "Kärnten" "01": "Burgenland" "CZ": "52": "P<NAME>ha" "78": "South Moravian" "79": "<NAME>" "80": "<NAME>" "81": "<NAME>" "82": "<NAME>" "83": "<NAME>" "84": "<NAME>" "85": "<NAME>" "86": "<NAME>" "87": "<NAME>ý" "88": "Central Bohemia" "89": "<NAME>ý" "90": "<NAME>" "DE": "15": "<NAME>" "10": "<NAME>" "14": "<NAME>" "13": "<NAME>" "09": "Saarland" "08": "R<NAME>inland-Pfalz" "07": "Nordrhein-Westfalen" "06": "<NAME>" "12": "Mecklenburg-Vorpommern" "05": "H<NAME>en" "04": "Hamburg" "03": "Bremen" "11": "<NAME>enburg" "16": "Berlin" "02": "Bayern" "01": "<NAME>-<NAME>ember<NAME>"
true
exec = require('child_process').exec csv = require('csv-streamify') request = require('request') through = require('through2') es = require('event-stream') level = require('level') fs = require('fs') alt = level "./data/alt" tmp = level "./data/tmp", valueEncoding: 'json' #tmp.createReadStream gte: "ADM", lt: "ADM~" #.pipe es.mapSync (p) -> console.log "#{p.key} -> #{p.value.name}" module.exports = storeAlts: () -> fs.createReadStream "./alternateNames.txt" .pipe csv delimiter: "\t", objectMode: true .on "data", (data) -> #console.log "DATA " + data[1] + ":" + data[2] + ":" + data[4] + ":" + data[5] + ":" + data[6] + " -> " + data[3] alts.put data[1] + ":" + data[2] + ":" + data[4] + ":" + data[5] + ":" + data[6], data[3] storeCountry: (country) -> console.log " load " + url country request.get url country .pipe require('geonames-stream').pipeline .pipe through.obj (g, enc, next) -> if g.feature_code.match(/PPL.*|ADM5/) && g.population != "0" g.latlon = [parseFloat(g.latitude), parseFloat(g.longitude)] delete g.latitude delete g.longitude g.name = g.name .replace("PI:NAME:<NAME>END_PI", "") .replace(",", " ") .replace("'", "") .replace("ˈ", "") .trim() delete g.alternatenames tmp.put "pop:" + normalize(g.population) + ":" + g._id, g, next console.log " + store #{g.name} #{JSON.stringify g.latlon} pop=#{g.population}" else if l = g.feature_code.match /ADM(\d)/ #console.log g.feature_code + ":" + g["admin#{l[1]}_code"] tmp.put g.feature_code + ":" + g["admin#{l[1]}_code"], g, next else next() , () -> console.log "done" processPlaces: () -> exec "rm -r data/place", (err, out) -> console.log " deleted place db" place = level "./data/place", valueEncoding: "json" count = 0 ambig = 0 append = 0 replace = 0 taken = 0 alts = 0 byPopulation 1 * 1000 .pipe through.obj (g, enc, next) -> store = (k, v, i, cb) -> place.get k, (err, p) -> if !p count += 1 if i < 2 append += 1 if i == 1 alts += 1 if i == 2 place.put k, v, () -> cb v if i < 2 tmp.put "id:" + v._id, k #console.log " + place #{count}: #{k} #{JSON.stringify v.latlon} pop=#{v.population} #{i}" else if p.feature_code.match(/ADM/) && v.feature_code.match(/PPL/) if !v.population ambig += 1 console.log " + keep #{p.feature_code} #{p.name} #{p.population} because batter than #{v.feature_code} #{v.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else replace += 1 console.log " + replace #{p.feature_code} #{p.name} #{p.population} with #{v.feature_code} #{v.population}" (v.ambig ||= []).push p place.put k, v, () -> cb v tmp.put "id:" + v._id, k else if i == 0 if v.feature_code.match(/PPLX/) if v.name.match /Bayerbach/ console.log "SKIP #{v.name} #{v.feature_code} #{v.population} keep #{p.name} #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + p._id, k ambig += 1 return adm = (ex, ca, l) -> if ca["adm" + l] && ca["adm" + l] != ca.name if v["adm" + l].indexOf(ca.name) >= 0 #console.log " #{k} try ADM#{l} #{ca['adm' + l]} for #{ca.name} #{ca.feature_code} #{ca.population} because already #{ex.feature_code} #{ex.name} #{ex.population}" ca.name = ca["adm" + l] else if ca.name.match /Bayerbach/ console.log " #{k} append ADM#{l} #{ex.name} + #{ca['adm' + l]} #{ca.feature_code} #{ca.population} because already #{ex.feature_code} #{ex.name} #{ex.population}" ca.name += (" - " + ca["adm" + l]) store ca.name.toUpperCase(), ca, i + 1, cb true else false if !adm(p, v, 4) if !adm(p, v, 3) if !adm(p, v, 2) if !adm(p, v, 1) ambig += 1 console.log " NO PLACE FOR #{k} #{v.feature_code} #{v.population} already #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else if i < 2 ambig += 1 console.log " NO PLACE FOR #{k} #{v.feature_code} #{v.population} already #{p.feature_code} #{p.population}" (p.ambig ||= []).push v place.put k, p, () -> cb p tmp.put "id:" + v._id, k else taken += 1 cb() synonym = (p, c, cb) -> alt.createReadStream gte: g.value._id, lte: g.value._id + "~" .pipe through.obj (a, enc, nextAlt) -> k = a.key.split(":")[1] if k == c a.value = a.value .replace("Bezirk", "") .replace(",", " ") .replace("'", "") .replace("ˈ", "") .trim() store a.value.toUpperCase(), p, 2, (at) -> if at if !(p.alts ||= {})[a.value] p.alts[a.value] = c place.put kk.toUpperCase(), p for kk,u of p.alts place.put p.name.toUpperCase(), p, nextAlt else console.log " - no #{a.value} #{a.key} gibt schon #{p.alts[c]}" nextAlt() else nextAlt() else nextAlt() , () -> cb() admin = (p, l, cb) -> ac = "admin#{l}_code" if p[ac] tmp.get "ADM#{l}:#{p[ac]}", (err, adm) -> if adm p["adm" + l] = adm.name #console.log "#{g.value.name} -> adm#{l} #{p[ac]} " + adm.name if l == 5 #if p.name == "Bayerbach" delete p[ac] cb p else cb p else cb p key = g.PI:KEY:<KEY>END_PI g.value.adm1 = state[g.value.country_code][g.value.admin1_code] delete g.value.admin1_code admin g.value, 2, (p2) -> admin p2, 3, (p3) -> admin p3, 4, (p4) -> store key, p4, 0, (p) -> synonym p, "cs", () -> synonym p, "de", () -> synonym p, "en", next , () -> console.log " done #{count} keys for #{count + ambig} places with #{alts} synonyms of #{taken + alts}," + " Therof #{replace} times replaced and #{append} times appended. No place for #{ambig} places." computeDists: () -> exec "rm -rf data/dist data/path", (err, out) -> console.log "deleted dist and path db" dist = level "./data/dist" path = level "./data/path" time = new Date().getTime() count = 0 byPopulation 20 .pipe through.obj (from, enc, nextFrom) -> byPopulation 20 .pipe through.obj (to, enc, nextTo) => @push [from, to] nextTo() .on "end", nextFrom .pipe through.obj (route, enc, next) -> console.log "+ compute " + route[0].name + " -> " + route[1].name url = (country) -> "http://download.geonames.org/" + "export/dump/#{country.toUpperCase() || "DE"}.zip" normalize = (n) -> if !n n = "0" else n = "0" + n n = "0" + n for i in [0..(8 - n.length)] n byPopulation = (pop) -> tmp.createReadStream gte: "pop:" + normalize(pop), lt: "pop:10000000", reverse: true state = "AT": "09": "PI:NAME:<NAME>END_PI" "08": "PI:NAME:<NAME>END_PI" "07": "PI:NAME:<NAME>END_PI" "06": "PI:NAME:<NAME>END_PI" "05": "PI:NAME:<NAME>END_PI" "04": "Oberösterreich" "03": "Niederösterreich" "02": "Kärnten" "01": "Burgenland" "CZ": "52": "PPI:NAME:<NAME>END_PIha" "78": "South Moravian" "79": "PI:NAME:<NAME>END_PI" "80": "PI:NAME:<NAME>END_PI" "81": "PI:NAME:<NAME>END_PI" "82": "PI:NAME:<NAME>END_PI" "83": "PI:NAME:<NAME>END_PI" "84": "PI:NAME:<NAME>END_PI" "85": "PI:NAME:<NAME>END_PI" "86": "PI:NAME:<NAME>END_PI" "87": "PI:NAME:<NAME>END_PIý" "88": "Central Bohemia" "89": "PI:NAME:<NAME>END_PIý" "90": "PI:NAME:<NAME>END_PI" "DE": "15": "PI:NAME:<NAME>END_PI" "10": "PI:NAME:<NAME>END_PI" "14": "PI:NAME:<NAME>END_PI" "13": "PI:NAME:<NAME>END_PI" "09": "Saarland" "08": "RPI:NAME:<NAME>END_PIinland-Pfalz" "07": "Nordrhein-Westfalen" "06": "PI:NAME:<NAME>END_PI" "12": "Mecklenburg-Vorpommern" "05": "HPI:NAME:<NAME>END_PIen" "04": "Hamburg" "03": "Bremen" "11": "PI:NAME:<NAME>END_PIenburg" "16": "Berlin" "02": "Bayern" "01": "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PIemberPI:NAME:<NAME>END_PI"
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992459416389465, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "closeSync fd\n return\n), 10\n\n# https://github.com/joyent/node/issues/2293 - non-persistent...
test/simple/test-fs-watch.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") path = require("path") fs = require("fs") expectFilePath = process.platform is "win32" or process.platform is "linux" or process.platform is "darwin" watchSeenOne = 0 watchSeenTwo = 0 watchSeenThree = 0 testDir = common.tmpDir filenameOne = "watch.txt" filepathOne = path.join(testDir, filenameOne) filenameTwo = "hasOwnProperty" filepathTwo = filenameTwo filepathTwoAbs = path.join(testDir, filenameTwo) filenameThree = "newfile.txt" testsubdir = path.join(testDir, "testsubdir") filepathThree = path.join(testsubdir, filenameThree) process.on "exit", -> assert.ok watchSeenOne > 0 assert.ok watchSeenTwo > 0 assert.ok watchSeenThree > 0 return # Clean up stale files (if any) from previous run. try fs.unlinkSync filepathOne try fs.unlinkSync filepathTwoAbs try fs.unlinkSync filepathThree try fs.rmdirSync testsubdir fs.writeFileSync filepathOne, "hello" assert.doesNotThrow -> watcher = fs.watch(filepathOne) watcher.on "change", (event, filename) -> assert.equal "change", event assert.equal "watch.txt", filename if expectFilePath watcher.close() ++watchSeenOne return return setTimeout (-> fs.writeFileSync filepathOne, "world" return ), 10 process.chdir testDir fs.writeFileSync filepathTwoAbs, "howdy" assert.doesNotThrow -> watcher = fs.watch(filepathTwo, (event, filename) -> assert.equal "change", event assert.equal "hasOwnProperty", filename if expectFilePath watcher.close() ++watchSeenTwo return ) return setTimeout (-> fs.writeFileSync filepathTwoAbs, "pardner" return ), 10 try fs.unlinkSync filepathThree try fs.mkdirSync testsubdir, 0700 assert.doesNotThrow -> watcher = fs.watch(testsubdir, (event, filename) -> renameEv = (if process.platform is "sunos" then "change" else "rename") assert.equal renameEv, event if expectFilePath assert.equal "newfile.txt", filename else assert.equal null, filename watcher.close() ++watchSeenThree return ) return setTimeout (-> fd = fs.openSync(filepathThree, "w") fs.closeSync fd return ), 10 # https://github.com/joyent/node/issues/2293 - non-persistent watcher should # not block the event loop fs.watch __filename, persistent: false , -> assert 0 return # whitebox test to ensure that wrapped FSEvent is safe # https://github.com/joyent/node/issues/6690 oldhandle = undefined assert.throws (-> w = fs.watch(__filename, (event, filename) -> ) oldhandle = w._handle w._handle = close: w._handle.close w.close() return ), TypeError oldhandle.close() # clean up assert.throws (-> w = fs.watchFile(__filename, persistent: false , -> ) oldhandle = w._handle w._handle = stop: w._handle.stop w.stop() return ), TypeError oldhandle.stop() # clean up
61504
# 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") path = require("path") fs = require("fs") expectFilePath = process.platform is "win32" or process.platform is "linux" or process.platform is "darwin" watchSeenOne = 0 watchSeenTwo = 0 watchSeenThree = 0 testDir = common.tmpDir filenameOne = "watch.txt" filepathOne = path.join(testDir, filenameOne) filenameTwo = "hasOwnProperty" filepathTwo = filenameTwo filepathTwoAbs = path.join(testDir, filenameTwo) filenameThree = "newfile.txt" testsubdir = path.join(testDir, "testsubdir") filepathThree = path.join(testsubdir, filenameThree) process.on "exit", -> assert.ok watchSeenOne > 0 assert.ok watchSeenTwo > 0 assert.ok watchSeenThree > 0 return # Clean up stale files (if any) from previous run. try fs.unlinkSync filepathOne try fs.unlinkSync filepathTwoAbs try fs.unlinkSync filepathThree try fs.rmdirSync testsubdir fs.writeFileSync filepathOne, "hello" assert.doesNotThrow -> watcher = fs.watch(filepathOne) watcher.on "change", (event, filename) -> assert.equal "change", event assert.equal "watch.txt", filename if expectFilePath watcher.close() ++watchSeenOne return return setTimeout (-> fs.writeFileSync filepathOne, "world" return ), 10 process.chdir testDir fs.writeFileSync filepathTwoAbs, "howdy" assert.doesNotThrow -> watcher = fs.watch(filepathTwo, (event, filename) -> assert.equal "change", event assert.equal "hasOwnProperty", filename if expectFilePath watcher.close() ++watchSeenTwo return ) return setTimeout (-> fs.writeFileSync filepathTwoAbs, "pardner" return ), 10 try fs.unlinkSync filepathThree try fs.mkdirSync testsubdir, 0700 assert.doesNotThrow -> watcher = fs.watch(testsubdir, (event, filename) -> renameEv = (if process.platform is "sunos" then "change" else "rename") assert.equal renameEv, event if expectFilePath assert.equal "newfile.txt", filename else assert.equal null, filename watcher.close() ++watchSeenThree return ) return setTimeout (-> fd = fs.openSync(filepathThree, "w") fs.closeSync fd return ), 10 # https://github.com/joyent/node/issues/2293 - non-persistent watcher should # not block the event loop fs.watch __filename, persistent: false , -> assert 0 return # whitebox test to ensure that wrapped FSEvent is safe # https://github.com/joyent/node/issues/6690 oldhandle = undefined assert.throws (-> w = fs.watch(__filename, (event, filename) -> ) oldhandle = w._handle w._handle = close: w._handle.close w.close() return ), TypeError oldhandle.close() # clean up assert.throws (-> w = fs.watchFile(__filename, persistent: false , -> ) oldhandle = w._handle w._handle = stop: w._handle.stop w.stop() return ), TypeError oldhandle.stop() # clean up
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") path = require("path") fs = require("fs") expectFilePath = process.platform is "win32" or process.platform is "linux" or process.platform is "darwin" watchSeenOne = 0 watchSeenTwo = 0 watchSeenThree = 0 testDir = common.tmpDir filenameOne = "watch.txt" filepathOne = path.join(testDir, filenameOne) filenameTwo = "hasOwnProperty" filepathTwo = filenameTwo filepathTwoAbs = path.join(testDir, filenameTwo) filenameThree = "newfile.txt" testsubdir = path.join(testDir, "testsubdir") filepathThree = path.join(testsubdir, filenameThree) process.on "exit", -> assert.ok watchSeenOne > 0 assert.ok watchSeenTwo > 0 assert.ok watchSeenThree > 0 return # Clean up stale files (if any) from previous run. try fs.unlinkSync filepathOne try fs.unlinkSync filepathTwoAbs try fs.unlinkSync filepathThree try fs.rmdirSync testsubdir fs.writeFileSync filepathOne, "hello" assert.doesNotThrow -> watcher = fs.watch(filepathOne) watcher.on "change", (event, filename) -> assert.equal "change", event assert.equal "watch.txt", filename if expectFilePath watcher.close() ++watchSeenOne return return setTimeout (-> fs.writeFileSync filepathOne, "world" return ), 10 process.chdir testDir fs.writeFileSync filepathTwoAbs, "howdy" assert.doesNotThrow -> watcher = fs.watch(filepathTwo, (event, filename) -> assert.equal "change", event assert.equal "hasOwnProperty", filename if expectFilePath watcher.close() ++watchSeenTwo return ) return setTimeout (-> fs.writeFileSync filepathTwoAbs, "pardner" return ), 10 try fs.unlinkSync filepathThree try fs.mkdirSync testsubdir, 0700 assert.doesNotThrow -> watcher = fs.watch(testsubdir, (event, filename) -> renameEv = (if process.platform is "sunos" then "change" else "rename") assert.equal renameEv, event if expectFilePath assert.equal "newfile.txt", filename else assert.equal null, filename watcher.close() ++watchSeenThree return ) return setTimeout (-> fd = fs.openSync(filepathThree, "w") fs.closeSync fd return ), 10 # https://github.com/joyent/node/issues/2293 - non-persistent watcher should # not block the event loop fs.watch __filename, persistent: false , -> assert 0 return # whitebox test to ensure that wrapped FSEvent is safe # https://github.com/joyent/node/issues/6690 oldhandle = undefined assert.throws (-> w = fs.watch(__filename, (event, filename) -> ) oldhandle = w._handle w._handle = close: w._handle.close w.close() return ), TypeError oldhandle.close() # clean up assert.throws (-> w = fs.watchFile(__filename, persistent: false , -> ) oldhandle = w._handle w._handle = stop: w._handle.stop w.stop() return ), TypeError oldhandle.stop() # clean up
[ { "context": "a template for new repos. E.g. https://github.com/cfpb/open-source-project-template.git\n# HUBOT_GITHUB", "end": 507, "score": 0.9595479965209961, "start": 503, "tag": "USERNAME", "value": "cfpb" }, { "context": "ganization\n#\n# Notes:\n# Based on hubot-github by O...
src/github-management.coffee
catops/hubot-github-management
8
# Description: # Allow Hubot to manage your github organization members and teams. # # Configuration: # HUBOT_GITHUB_ORG_TOKEN - (required) Github access token. See https://help.github.com/articles/creating-an-access-token-for-command-line-use/. # HUBOT_GITHUB_ORG_NAME - (required) Github organization name. The <org_name> in https://github.com/<org_name>/awesome-repo. # HUBOT_GITHUB_REPO_TEMPLATE - (optional) A git repo that will be used as a template for new repos. E.g. https://github.com/cfpb/open-source-project-template.git # HUBOT_GITHUB_REQUIRE_ADMIN - (optional) Set this to true to restrict create, delete and add commands to Hubot admins. # # Commands: # hubot github info - returns a summary of your organization # hubot github info (team|repo) <team or repo name> - returns a summary of your organization # hubot github list (teams|repos|members) - returns a list of members, teams or repos in your organization # hubot github list public repos - returns a list of all public repos in your organization # hubot github create team <team name> - creates a team with the following name # hubot github create repo <repo name>/<private|public> - creates a repo with the following name, description and type (private or public) # hubot github add (members|repos) <members|repos> to team <team name> - adds a comma separated list of members or repos to a given team # hubot github remove (repos|members) <members|repos> from team <team name> - removes the repos or members from the given team # hubot github delete team <team name> - deletes the given team from your organization # # Notes: # Based on hubot-github by Ollie Jennings <ollie@olliejennings.co.uk> # # Author: # contolini org = require './lib/github' icons = require './lib/icons' TextMessage = require('hubot').TextMessage module.exports = (robot) -> return robot.logger.error "Please set a GitHub API token at HUBOT_GITHUB_ORG_TOKEN" if not process.env.HUBOT_GITHUB_ORG_TOKEN return robot.logger.error "Please specify a GitHub organization name at HUBOT_GITHUB_ORG_NAME" if not process.env.HUBOT_GITHUB_ORG_NAME org.init() robot.respond /(github|gh)$/i, (msg) -> message = """ ``` #{robot.name} github info - returns a summary of your organization #{robot.name} github info (team|repo) <team or repo name> - returns a summary of your organization #{robot.name} github list (teams|repos|members) - returns a list of members, teams or repos in your organization #{robot.name} github list public repos - returns a list of all public repos in your organization #{robot.name} github create team <team name> - creates a team with the following name #{robot.name} github create repo <repo name>/<private|public> - creates a repo with the following name, description and type (private or public) #{robot.name} github add (members|repos) <members|repos> to team <team name> - adds a comma separated list of members or repos to a given team #{robot.name} github remove (repos|members) <members|repos> from team <team name> - removes the repos or members from the given team #{robot.name} github delete team <team name> - deletes the given team from your organization ``` """ msg.send message robot.respond /(github|gh) info$/i, (msg) -> org.summary.all msg robot.respond /(github|gh) info (team|repo) (\w.+)/i, (msg) -> org.summary[msg.match[2]] msg, msg.match[3] robot.respond /(github|gh) list (team|member|repo)s?/i, (msg) -> cmd = "#{msg.match[2]}s" if not /s$/.test(msg.match[2]) org.list[cmd] msg robot.respond /(github|gh) list public (repos)/i, (msg) -> org.list.public msg, msg.match[2] robot.respond /(github|gh) create (team|repo) (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can use `create` commands" else org.create[msg.match[2]] msg, msg.match[3].split('/')[0], msg.match[3].split('/')[1] robot.respond /(github|gh) add (member|user|repo)s? (\w.+) to team (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can use `add` commands" else cmd = if /(member|user)/.test msg.match[2] then 'members' else 'repos' org.add[cmd] msg, msg.match[3], msg.match[4] robot.respond /(github|gh) remove (member|user|repo)s? (\w.+) from team (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can `remove` users from teams." else cmd = if /(member|user)/.test msg.match[2] then 'members' else 'repos' org.remove[cmd] msg, msg.match[3], msg.match[4] robot.respond /(github|gh) (delete|remove) team (\w.+)/, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can `delete` teams." else org.delete.team msg, msg.match[3]
202355
# Description: # Allow Hubot to manage your github organization members and teams. # # Configuration: # HUBOT_GITHUB_ORG_TOKEN - (required) Github access token. See https://help.github.com/articles/creating-an-access-token-for-command-line-use/. # HUBOT_GITHUB_ORG_NAME - (required) Github organization name. The <org_name> in https://github.com/<org_name>/awesome-repo. # HUBOT_GITHUB_REPO_TEMPLATE - (optional) A git repo that will be used as a template for new repos. E.g. https://github.com/cfpb/open-source-project-template.git # HUBOT_GITHUB_REQUIRE_ADMIN - (optional) Set this to true to restrict create, delete and add commands to Hubot admins. # # Commands: # hubot github info - returns a summary of your organization # hubot github info (team|repo) <team or repo name> - returns a summary of your organization # hubot github list (teams|repos|members) - returns a list of members, teams or repos in your organization # hubot github list public repos - returns a list of all public repos in your organization # hubot github create team <team name> - creates a team with the following name # hubot github create repo <repo name>/<private|public> - creates a repo with the following name, description and type (private or public) # hubot github add (members|repos) <members|repos> to team <team name> - adds a comma separated list of members or repos to a given team # hubot github remove (repos|members) <members|repos> from team <team name> - removes the repos or members from the given team # hubot github delete team <team name> - deletes the given team from your organization # # Notes: # Based on hubot-github by <NAME> <<EMAIL>> # # Author: # contolini org = require './lib/github' icons = require './lib/icons' TextMessage = require('hubot').TextMessage module.exports = (robot) -> return robot.logger.error "Please set a GitHub API token at HUBOT_GITHUB_ORG_TOKEN" if not process.env.HUBOT_GITHUB_ORG_TOKEN return robot.logger.error "Please specify a GitHub organization name at HUBOT_GITHUB_ORG_NAME" if not process.env.HUBOT_GITHUB_ORG_NAME org.init() robot.respond /(github|gh)$/i, (msg) -> message = """ ``` #{robot.name} github info - returns a summary of your organization #{robot.name} github info (team|repo) <team or repo name> - returns a summary of your organization #{robot.name} github list (teams|repos|members) - returns a list of members, teams or repos in your organization #{robot.name} github list public repos - returns a list of all public repos in your organization #{robot.name} github create team <team name> - creates a team with the following name #{robot.name} github create repo <repo name>/<private|public> - creates a repo with the following name, description and type (private or public) #{robot.name} github add (members|repos) <members|repos> to team <team name> - adds a comma separated list of members or repos to a given team #{robot.name} github remove (repos|members) <members|repos> from team <team name> - removes the repos or members from the given team #{robot.name} github delete team <team name> - deletes the given team from your organization ``` """ msg.send message robot.respond /(github|gh) info$/i, (msg) -> org.summary.all msg robot.respond /(github|gh) info (team|repo) (\w.+)/i, (msg) -> org.summary[msg.match[2]] msg, msg.match[3] robot.respond /(github|gh) list (team|member|repo)s?/i, (msg) -> cmd = "#{msg.match[2]}s" if not /s$/.test(msg.match[2]) org.list[cmd] msg robot.respond /(github|gh) list public (repos)/i, (msg) -> org.list.public msg, msg.match[2] robot.respond /(github|gh) create (team|repo) (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can use `create` commands" else org.create[msg.match[2]] msg, msg.match[3].split('/')[0], msg.match[3].split('/')[1] robot.respond /(github|gh) add (member|user|repo)s? (\w.+) to team (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can use `add` commands" else cmd = if /(member|user)/.test msg.match[2] then 'members' else 'repos' org.add[cmd] msg, msg.match[3], msg.match[4] robot.respond /(github|gh) remove (member|user|repo)s? (\w.+) from team (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can `remove` users from teams." else cmd = if /(member|user)/.test msg.match[2] then 'members' else 'repos' org.remove[cmd] msg, msg.match[3], msg.match[4] robot.respond /(github|gh) (delete|remove) team (\w.+)/, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can `delete` teams." else org.delete.team msg, msg.match[3]
true
# Description: # Allow Hubot to manage your github organization members and teams. # # Configuration: # HUBOT_GITHUB_ORG_TOKEN - (required) Github access token. See https://help.github.com/articles/creating-an-access-token-for-command-line-use/. # HUBOT_GITHUB_ORG_NAME - (required) Github organization name. The <org_name> in https://github.com/<org_name>/awesome-repo. # HUBOT_GITHUB_REPO_TEMPLATE - (optional) A git repo that will be used as a template for new repos. E.g. https://github.com/cfpb/open-source-project-template.git # HUBOT_GITHUB_REQUIRE_ADMIN - (optional) Set this to true to restrict create, delete and add commands to Hubot admins. # # Commands: # hubot github info - returns a summary of your organization # hubot github info (team|repo) <team or repo name> - returns a summary of your organization # hubot github list (teams|repos|members) - returns a list of members, teams or repos in your organization # hubot github list public repos - returns a list of all public repos in your organization # hubot github create team <team name> - creates a team with the following name # hubot github create repo <repo name>/<private|public> - creates a repo with the following name, description and type (private or public) # hubot github add (members|repos) <members|repos> to team <team name> - adds a comma separated list of members or repos to a given team # hubot github remove (repos|members) <members|repos> from team <team name> - removes the repos or members from the given team # hubot github delete team <team name> - deletes the given team from your organization # # Notes: # Based on hubot-github by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Author: # contolini org = require './lib/github' icons = require './lib/icons' TextMessage = require('hubot').TextMessage module.exports = (robot) -> return robot.logger.error "Please set a GitHub API token at HUBOT_GITHUB_ORG_TOKEN" if not process.env.HUBOT_GITHUB_ORG_TOKEN return robot.logger.error "Please specify a GitHub organization name at HUBOT_GITHUB_ORG_NAME" if not process.env.HUBOT_GITHUB_ORG_NAME org.init() robot.respond /(github|gh)$/i, (msg) -> message = """ ``` #{robot.name} github info - returns a summary of your organization #{robot.name} github info (team|repo) <team or repo name> - returns a summary of your organization #{robot.name} github list (teams|repos|members) - returns a list of members, teams or repos in your organization #{robot.name} github list public repos - returns a list of all public repos in your organization #{robot.name} github create team <team name> - creates a team with the following name #{robot.name} github create repo <repo name>/<private|public> - creates a repo with the following name, description and type (private or public) #{robot.name} github add (members|repos) <members|repos> to team <team name> - adds a comma separated list of members or repos to a given team #{robot.name} github remove (repos|members) <members|repos> from team <team name> - removes the repos or members from the given team #{robot.name} github delete team <team name> - deletes the given team from your organization ``` """ msg.send message robot.respond /(github|gh) info$/i, (msg) -> org.summary.all msg robot.respond /(github|gh) info (team|repo) (\w.+)/i, (msg) -> org.summary[msg.match[2]] msg, msg.match[3] robot.respond /(github|gh) list (team|member|repo)s?/i, (msg) -> cmd = "#{msg.match[2]}s" if not /s$/.test(msg.match[2]) org.list[cmd] msg robot.respond /(github|gh) list public (repos)/i, (msg) -> org.list.public msg, msg.match[2] robot.respond /(github|gh) create (team|repo) (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can use `create` commands" else org.create[msg.match[2]] msg, msg.match[3].split('/')[0], msg.match[3].split('/')[1] robot.respond /(github|gh) add (member|user|repo)s? (\w.+) to team (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can use `add` commands" else cmd = if /(member|user)/.test msg.match[2] then 'members' else 'repos' org.add[cmd] msg, msg.match[3], msg.match[4] robot.respond /(github|gh) remove (member|user|repo)s? (\w.+) from team (\w.+)/i, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can `remove` users from teams." else cmd = if /(member|user)/.test msg.match[2] then 'members' else 'repos' org.remove[cmd] msg, msg.match[3], msg.match[4] robot.respond /(github|gh) (delete|remove) team (\w.+)/, (msg) -> if process.env.HUBOT_GITHUB_REQUIRE_ADMIN and not robot.auth.isAdmin msg.envelope.user msg.send "#{icons.failure} Sorry, only admins can `delete` teams." else org.delete.team msg, msg.match[3]
[ { "context": "# Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com>\n# Copyright (C)", "end": 46, "score": 0.6498240232467651, "start": 31, "tag": "NAME", "value": "ctic Ice Studio" }, { "context": "# Copyright (C) 2016-present Arctic Ice Studio <developmen...
spec/full-width-tab-sizing-spec.coffee
germanescobar/nord-atom-ui
125
# Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com> # Copyright (C) 2016-present Sven Greb <development@svengreb.de> # Project: Nord Atom UI # Repository: https://github.com/arcticicestudio/nord-atom-ui # License: MIT describe "Nord Atom UI theme", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('nord-atom-ui') it "allows to disable full-width tab sizing to be set via theme settings", -> expect(document.documentElement.getAttribute('theme-nord-atom-ui-tabsizing')).toBe null atom.config.set('nord-atom-ui.tabSizing', false) expect(document.documentElement.getAttribute('theme-nord-atom-ui-tabsizing')).toBe 'nofullwidth'
154852
# Copyright (C) 2016-present Ar<NAME> <<EMAIL>> # Copyright (C) 2016-present <NAME> <<EMAIL>> # Project: Nord Atom UI # Repository: https://github.com/arcticicestudio/nord-atom-ui # License: MIT describe "Nord Atom UI theme", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('nord-atom-ui') it "allows to disable full-width tab sizing to be set via theme settings", -> expect(document.documentElement.getAttribute('theme-nord-atom-ui-tabsizing')).toBe null atom.config.set('nord-atom-ui.tabSizing', false) expect(document.documentElement.getAttribute('theme-nord-atom-ui-tabsizing')).toBe 'nofullwidth'
true
# Copyright (C) 2016-present ArPI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2016-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Project: Nord Atom UI # Repository: https://github.com/arcticicestudio/nord-atom-ui # License: MIT describe "Nord Atom UI theme", -> beforeEach -> waitsForPromise -> atom.packages.activatePackage('nord-atom-ui') it "allows to disable full-width tab sizing to be set via theme settings", -> expect(document.documentElement.getAttribute('theme-nord-atom-ui-tabsizing')).toBe null atom.config.set('nord-atom-ui.tabSizing', false) expect(document.documentElement.getAttribute('theme-nord-atom-ui-tabsizing')).toBe 'nofullwidth'
[ { "context": " 还要存入内容\n bookInfo =\n name : name,\n path : path,\n map ", "end": 788, "score": 0.72158282995224, "start": 784, "tag": "NAME", "value": "name" } ]
tools/updata.coffee
ruicky/node-wiki
99
treeModel = require '../models/tree' bookModel = require '../models/book' fs = require 'fs' _ = require 'underscore' path = require 'path' updata = menu : (port) -> #console.log(port); saveBook = (name,path) -> bookModel.findByUrl path, (err,book) -> if err console.log err if book.length <= 0 # 新建储存 newBook = new bookModel name : name path : path map : path.split('doc/')[1].split('/') url : '/book?md='+path.split('doc/')[1].split('.')[0] newBook.save (err,book) -> if err console.log err return else #更新储存(一个 URL 只会有一条) #do more 还要存入内容 bookInfo = name : name, path : path, map : path.split('doc/')[1].split('/'), url : '/book?md='+path.split('doc/')[1].split('.')[0] newBook = _.extend book[0],bookInfo newBook.save (err,book) -> if err console.log err return return return treeNode = {} # 目录遍历 walk = (path, treeNode, callback) -> callback = callback or ()-> treeNode.path = path treeNode.subNodes = [] treeNode.files = [] treeNode.pathName = path.split('/')[path.split('/').length - 1] dirList = fs.readdirSync path dirList.forEach (item) -> if fs.statSync(path + '/' + item).isDirectory() subNode = {} treeNode.subNodes.push(subNode) walk(path + '/' + item, subNode) else if item isnt '.DS_Store' and item isnt 'readme.md' and item.indexOf('.md') isnt -1 saveBook item.split('.')[0],path + '/'+item treeNode.files.push item.split('.')[0] return callback treeNode return walk path.join(__dirname, '../doc'), treeNode, (treeNode) -> #存入数据库 treeModel.fetch (err,tree) -> if err console.log err if tree.length<=0 _tree = new treeModel tree : treeNode _tree.save (err, tree) -> if err console.log err console.log '成功更新目录数据库' return else _tree = _.extend(tree[0],{tree:treeNode}); _tree.save (err, tree) -> if err console.log err console.log '成功更新目录数据库' return return return return module.exports = updata
106506
treeModel = require '../models/tree' bookModel = require '../models/book' fs = require 'fs' _ = require 'underscore' path = require 'path' updata = menu : (port) -> #console.log(port); saveBook = (name,path) -> bookModel.findByUrl path, (err,book) -> if err console.log err if book.length <= 0 # 新建储存 newBook = new bookModel name : name path : path map : path.split('doc/')[1].split('/') url : '/book?md='+path.split('doc/')[1].split('.')[0] newBook.save (err,book) -> if err console.log err return else #更新储存(一个 URL 只会有一条) #do more 还要存入内容 bookInfo = name : <NAME>, path : path, map : path.split('doc/')[1].split('/'), url : '/book?md='+path.split('doc/')[1].split('.')[0] newBook = _.extend book[0],bookInfo newBook.save (err,book) -> if err console.log err return return return treeNode = {} # 目录遍历 walk = (path, treeNode, callback) -> callback = callback or ()-> treeNode.path = path treeNode.subNodes = [] treeNode.files = [] treeNode.pathName = path.split('/')[path.split('/').length - 1] dirList = fs.readdirSync path dirList.forEach (item) -> if fs.statSync(path + '/' + item).isDirectory() subNode = {} treeNode.subNodes.push(subNode) walk(path + '/' + item, subNode) else if item isnt '.DS_Store' and item isnt 'readme.md' and item.indexOf('.md') isnt -1 saveBook item.split('.')[0],path + '/'+item treeNode.files.push item.split('.')[0] return callback treeNode return walk path.join(__dirname, '../doc'), treeNode, (treeNode) -> #存入数据库 treeModel.fetch (err,tree) -> if err console.log err if tree.length<=0 _tree = new treeModel tree : treeNode _tree.save (err, tree) -> if err console.log err console.log '成功更新目录数据库' return else _tree = _.extend(tree[0],{tree:treeNode}); _tree.save (err, tree) -> if err console.log err console.log '成功更新目录数据库' return return return return module.exports = updata
true
treeModel = require '../models/tree' bookModel = require '../models/book' fs = require 'fs' _ = require 'underscore' path = require 'path' updata = menu : (port) -> #console.log(port); saveBook = (name,path) -> bookModel.findByUrl path, (err,book) -> if err console.log err if book.length <= 0 # 新建储存 newBook = new bookModel name : name path : path map : path.split('doc/')[1].split('/') url : '/book?md='+path.split('doc/')[1].split('.')[0] newBook.save (err,book) -> if err console.log err return else #更新储存(一个 URL 只会有一条) #do more 还要存入内容 bookInfo = name : PI:NAME:<NAME>END_PI, path : path, map : path.split('doc/')[1].split('/'), url : '/book?md='+path.split('doc/')[1].split('.')[0] newBook = _.extend book[0],bookInfo newBook.save (err,book) -> if err console.log err return return return treeNode = {} # 目录遍历 walk = (path, treeNode, callback) -> callback = callback or ()-> treeNode.path = path treeNode.subNodes = [] treeNode.files = [] treeNode.pathName = path.split('/')[path.split('/').length - 1] dirList = fs.readdirSync path dirList.forEach (item) -> if fs.statSync(path + '/' + item).isDirectory() subNode = {} treeNode.subNodes.push(subNode) walk(path + '/' + item, subNode) else if item isnt '.DS_Store' and item isnt 'readme.md' and item.indexOf('.md') isnt -1 saveBook item.split('.')[0],path + '/'+item treeNode.files.push item.split('.')[0] return callback treeNode return walk path.join(__dirname, '../doc'), treeNode, (treeNode) -> #存入数据库 treeModel.fetch (err,tree) -> if err console.log err if tree.length<=0 _tree = new treeModel tree : treeNode _tree.save (err, tree) -> if err console.log err console.log '成功更新目录数据库' return else _tree = _.extend(tree[0],{tree:treeNode}); _tree.save (err, tree) -> if err console.log err console.log '成功更新目录数据库' return return return return module.exports = updata
[ { "context": "s User\n\naccounts = [\n {\n email: 'admin@admin.com'\n firstName: 'Sir Super'\n username", "end": 114, "score": 0.9999223947525024, "start": 99, "tag": "EMAIL", "value": "admin@admin.com" }, { "context": " 'admin@admin.com'\n fi...
server/db/seeds/development/000005-account.coffee
Contactis/translation-manager
0
moment = require 'moment' # Info: Account extends User accounts = [ { email: 'admin@admin.com' firstName: 'Sir Super' username: 'Sir Admin' lastName: 'Admin' password: 'admin' role: 'admin' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: 'manager@manager.com' firstName: 'Sir Super' username: 'Sir Manager' lastName: 'Manager' password: 'manager' role: 'manager' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: 'translator@translator.com' firstName: 'Sir Super' username: 'Sir Translator' lastName: 'Translator' password: 'translator' role: 'translator' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: 'programmer@programmer.com' firstName: 'Sir Super' username: 'Sir Programmer' lastName: 'Programmer' password: 'programmer' role: 'programmer' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } ] accounts.forEach (value, i) -> Account.seed value
101199
moment = require 'moment' # Info: Account extends User accounts = [ { email: '<EMAIL>' firstName: '<NAME>' username: 'Sir Admin' lastName: 'Admin' password: '<PASSWORD>' role: 'admin' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: '<EMAIL>' firstName: '<NAME>' username: 'Sir Manager' lastName: 'Manager' password: '<PASSWORD>' role: 'manager' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: '<EMAIL>' firstName: '<NAME>' username: 'Sir Translator' lastName: 'Translator' password: '<PASSWORD>' role: 'translator' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: '<EMAIL>' firstName: '<NAME>' username: '<NAME>ir Program<NAME>' lastName: 'Programmer' password: '<PASSWORD>' role: 'programmer' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } ] accounts.forEach (value, i) -> Account.seed value
true
moment = require 'moment' # Info: Account extends User accounts = [ { email: 'PI:EMAIL:<EMAIL>END_PI' firstName: 'PI:NAME:<NAME>END_PI' username: 'Sir Admin' lastName: 'Admin' password: 'PI:PASSWORD:<PASSWORD>END_PI' role: 'admin' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: 'PI:EMAIL:<EMAIL>END_PI' firstName: 'PI:NAME:<NAME>END_PI' username: 'Sir Manager' lastName: 'Manager' password: 'PI:PASSWORD:<PASSWORD>END_PI' role: 'manager' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: 'PI:EMAIL:<EMAIL>END_PI' firstName: 'PI:NAME:<NAME>END_PI' username: 'Sir Translator' lastName: 'Translator' password: 'PI:PASSWORD:<PASSWORD>END_PI' role: 'translator' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } { email: 'PI:EMAIL:<EMAIL>END_PI' firstName: 'PI:NAME:<NAME>END_PI' username: 'PI:NAME:<NAME>END_PIir ProgramPI:NAME:<NAME>END_PI' lastName: 'Programmer' password: 'PI:PASSWORD:<PASSWORD>END_PI' role: 'programmer' interfaceLanguage: 'en-us' emailVerified: true lastUpdated: moment().format() } ] accounts.forEach (value, i) -> Account.seed value
[ { "context": "ient\n settings handler in client\n\n copyright mark hahn 2013\n MIT license\n https://github.com/mark-", "end": 93, "score": 0.9998284578323364, "start": 84, "tag": "NAME", "value": "mark hahn" }, { "context": " hahn 2013\n MIT license\n https://githu...
src/client/settings-client.coffee
mark-hahn/bace
1
### file: src/client/settings-client settings handler in client copyright mark hahn 2013 MIT license https://github.com/mark-hahn/bace/ ### bace = (window.bace ?= {}) settings = (bace.settings ?= {}) helpers = (bace.helpers ?= {}) popup = (bace.popup ?= {}) edit = (bace.edit ?= {}) {render,div,img,label,input,button,text,textarea} = teacup settings.init = -> # console.log 'settings.init' bace.server.emit 'getThemeList', {loginData: bace.loginData} bace.server.on 'themeList', (themeList) -> bace.themeList = themeList bace.server.emit 'getLanguageList', {loginData: bace.loginData} bace.server.on 'languageList', (languageList) -> bace.languageList = languageList # console.log 'languageList', bace.languageList bace.server.on 'userSetting', (data) -> {data, setting, opt} = data switch data.setting when 'language' fields = [ render -> textarea style:"margin:5px; width:240px; height:100", data ] $popup = popup.show popupId: 'suffixesPopup' right: 20 top: 35 width: 300 height: 150 title: "Suffixes for " + opt fields: fields showCancel: yes showClose: yes onSubmit: (values) -> settingChoices = Suffixes: -> rows = [] for language in bace.languageList rows.push render -> div class:'settingChoice', language $popup = popup.show popupId: 'languagePopUp' right: 20 top: 35 width: 175 title: "Select Language" rows: rows showClose: yes onClick: ($tgt) -> language = $tgt.text() bace.server.emit 'getUserSettings', {loginData: bace.loginData, setting: 'suffixes', opt: language} User: -> fields = [ popup.inputHtml 'timeoutMins', 'Login Timeout (mins)', bace.userData.timeoutMins, null, null, 'focus' ] $popup = popup.show popupId: 'userSettingPopup' right: 20 top: 35 width: 250 height: 300 title: "Misc Settings For User" fields: fields showCancel: yes showClose: yes onSubmit: (values) -> # console.log 'onSubmit values', values for key, val of values switch key when 'timeoutMins' if (val = parseInt(val)) is NaN alert 'Login timeout must be numeric' return bace.server.emit 'setUserSettings', {loginData: bace.loginData, values} Theme: -> edit.insert \ '\nThis is a sample document to view while trying out different themes.\n\n' + 'A selected word.', 1 edit.setSelection 3, 11, 3, 15 curTheme = bace.editor.getTheme().split('/')[-1..-1][0] rows = [] for theme in bace.themeList style = (if curTheme is theme then "background-color:yellow" else '') rows.push render -> div {class:'settingChoice', style}, theme $popup = popup.show popupId: 'themePopUp' right: 20 top: 35 width: 250 title: "Change Theme (Live)" rows: rows showClose: yes onClick: ($tgt) -> lbl = $tgt.text() $('.settingChoice', $popup).css backgroundColor:'white' $tgt.css backgroundColor:'yellow' bace.editor.setTheme 'ace/theme/' + lbl bace.userData.theme = lbl bace.server.emit 'setTheme', {loginData: bace.loginData, lbl} settings.handleBtn = ($settBtn) -> $settBtn.click -> rows = [] for settingChoice of settingChoices rows.push render -> div class:'settingChoice', style:"", settingChoice popup.show popupId: 'settings' right: 20 top: 35 width: 100 title: "Settings" rows: rows showClose: yes onClick: ($tgt) -> settingChoices[$tgt.text()]() false
16764
### file: src/client/settings-client settings handler in client copyright <NAME> 2013 MIT license https://github.com/mark-hahn/bace/ ### bace = (window.bace ?= {}) settings = (bace.settings ?= {}) helpers = (bace.helpers ?= {}) popup = (bace.popup ?= {}) edit = (bace.edit ?= {}) {render,div,img,label,input,button,text,textarea} = teacup settings.init = -> # console.log 'settings.init' bace.server.emit 'getThemeList', {loginData: bace.loginData} bace.server.on 'themeList', (themeList) -> bace.themeList = themeList bace.server.emit 'getLanguageList', {loginData: bace.loginData} bace.server.on 'languageList', (languageList) -> bace.languageList = languageList # console.log 'languageList', bace.languageList bace.server.on 'userSetting', (data) -> {data, setting, opt} = data switch data.setting when 'language' fields = [ render -> textarea style:"margin:5px; width:240px; height:100", data ] $popup = popup.show popupId: 'suffixesPopup' right: 20 top: 35 width: 300 height: 150 title: "Suffixes for " + opt fields: fields showCancel: yes showClose: yes onSubmit: (values) -> settingChoices = Suffixes: -> rows = [] for language in bace.languageList rows.push render -> div class:'settingChoice', language $popup = popup.show popupId: 'languagePopUp' right: 20 top: 35 width: 175 title: "Select Language" rows: rows showClose: yes onClick: ($tgt) -> language = $tgt.text() bace.server.emit 'getUserSettings', {loginData: bace.loginData, setting: 'suffixes', opt: language} User: -> fields = [ popup.inputHtml 'timeoutMins', 'Login Timeout (mins)', bace.userData.timeoutMins, null, null, 'focus' ] $popup = popup.show popupId: 'userSettingPopup' right: 20 top: 35 width: 250 height: 300 title: "Misc Settings For User" fields: fields showCancel: yes showClose: yes onSubmit: (values) -> # console.log 'onSubmit values', values for key, val of values switch key when 'timeoutMins' if (val = parseInt(val)) is NaN alert 'Login timeout must be numeric' return bace.server.emit 'setUserSettings', {loginData: bace.loginData, values} Theme: -> edit.insert \ '\nThis is a sample document to view while trying out different themes.\n\n' + 'A selected word.', 1 edit.setSelection 3, 11, 3, 15 curTheme = bace.editor.getTheme().split('/')[-1..-1][0] rows = [] for theme in bace.themeList style = (if curTheme is theme then "background-color:yellow" else '') rows.push render -> div {class:'settingChoice', style}, theme $popup = popup.show popupId: 'themePopUp' right: 20 top: 35 width: 250 title: "Change Theme (Live)" rows: rows showClose: yes onClick: ($tgt) -> lbl = $tgt.text() $('.settingChoice', $popup).css backgroundColor:'white' $tgt.css backgroundColor:'yellow' bace.editor.setTheme 'ace/theme/' + lbl bace.userData.theme = lbl bace.server.emit 'setTheme', {loginData: bace.loginData, lbl} settings.handleBtn = ($settBtn) -> $settBtn.click -> rows = [] for settingChoice of settingChoices rows.push render -> div class:'settingChoice', style:"", settingChoice popup.show popupId: 'settings' right: 20 top: 35 width: 100 title: "Settings" rows: rows showClose: yes onClick: ($tgt) -> settingChoices[$tgt.text()]() false
true
### file: src/client/settings-client settings handler in client copyright PI:NAME:<NAME>END_PI 2013 MIT license https://github.com/mark-hahn/bace/ ### bace = (window.bace ?= {}) settings = (bace.settings ?= {}) helpers = (bace.helpers ?= {}) popup = (bace.popup ?= {}) edit = (bace.edit ?= {}) {render,div,img,label,input,button,text,textarea} = teacup settings.init = -> # console.log 'settings.init' bace.server.emit 'getThemeList', {loginData: bace.loginData} bace.server.on 'themeList', (themeList) -> bace.themeList = themeList bace.server.emit 'getLanguageList', {loginData: bace.loginData} bace.server.on 'languageList', (languageList) -> bace.languageList = languageList # console.log 'languageList', bace.languageList bace.server.on 'userSetting', (data) -> {data, setting, opt} = data switch data.setting when 'language' fields = [ render -> textarea style:"margin:5px; width:240px; height:100", data ] $popup = popup.show popupId: 'suffixesPopup' right: 20 top: 35 width: 300 height: 150 title: "Suffixes for " + opt fields: fields showCancel: yes showClose: yes onSubmit: (values) -> settingChoices = Suffixes: -> rows = [] for language in bace.languageList rows.push render -> div class:'settingChoice', language $popup = popup.show popupId: 'languagePopUp' right: 20 top: 35 width: 175 title: "Select Language" rows: rows showClose: yes onClick: ($tgt) -> language = $tgt.text() bace.server.emit 'getUserSettings', {loginData: bace.loginData, setting: 'suffixes', opt: language} User: -> fields = [ popup.inputHtml 'timeoutMins', 'Login Timeout (mins)', bace.userData.timeoutMins, null, null, 'focus' ] $popup = popup.show popupId: 'userSettingPopup' right: 20 top: 35 width: 250 height: 300 title: "Misc Settings For User" fields: fields showCancel: yes showClose: yes onSubmit: (values) -> # console.log 'onSubmit values', values for key, val of values switch key when 'timeoutMins' if (val = parseInt(val)) is NaN alert 'Login timeout must be numeric' return bace.server.emit 'setUserSettings', {loginData: bace.loginData, values} Theme: -> edit.insert \ '\nThis is a sample document to view while trying out different themes.\n\n' + 'A selected word.', 1 edit.setSelection 3, 11, 3, 15 curTheme = bace.editor.getTheme().split('/')[-1..-1][0] rows = [] for theme in bace.themeList style = (if curTheme is theme then "background-color:yellow" else '') rows.push render -> div {class:'settingChoice', style}, theme $popup = popup.show popupId: 'themePopUp' right: 20 top: 35 width: 250 title: "Change Theme (Live)" rows: rows showClose: yes onClick: ($tgt) -> lbl = $tgt.text() $('.settingChoice', $popup).css backgroundColor:'white' $tgt.css backgroundColor:'yellow' bace.editor.setTheme 'ace/theme/' + lbl bace.userData.theme = lbl bace.server.emit 'setTheme', {loginData: bace.loginData, lbl} settings.handleBtn = ($settBtn) -> $settBtn.click -> rows = [] for settingChoice of settingChoices rows.push render -> div class:'settingChoice', style:"", settingChoice popup.show popupId: 'settings' right: 20 top: 35 width: 100 title: "Settings" rows: rows showClose: yes onClick: ($tgt) -> settingChoices[$tgt.text()]() false
[ { "context": "sition in transitions\n key = transition.from.join(' ')\n hops = (@transitions[key] ?= {})\n ", "end": 614, "score": 0.7901707887649536, "start": 610, "tag": "KEY", "value": "join" }, { "context": " the object.\n get: (prior, callback) ->\n key = prior...
src/storage/memory.coffee
migstopheles/hubot-markov
57
# Markov storage implementation that uses entirely in-memory storage. class MemoryStorage # Create a storage module. constructor: (connStr, modelName) -> @transitions = {} # No initialization necessary. initialize: (callback) -> process.nextTick callback # Record a series of transitions within the model. "transition.from" is an array of Strings and # nulls marking the prior state and "transition.to" is the observed next state, which # may be an end-of-chain sentinel. incrementTransitions: (transitions, callback) -> for transition in transitions key = transition.from.join(' ') hops = (@transitions[key] ?= {}) prior = hops[transition.to] or 0 hops[transition.to] = prior + 1 process.nextTick callback # Retrieve an object containing the possible next hops from a prior state and their # relative frequencies. Invokes "callback" with any errors and the object. get: (prior, callback) -> key = prior.join(' ') hash = @transitions[key] or {} process.nextTick -> callback(null, hash) # Memory storage has no persistent backing. destroy: (callback) -> process.nextTick -> callback(null) disconnect: (callback) -> process.nextTick -> callback(null) module.exports = MemoryStorage
98270
# Markov storage implementation that uses entirely in-memory storage. class MemoryStorage # Create a storage module. constructor: (connStr, modelName) -> @transitions = {} # No initialization necessary. initialize: (callback) -> process.nextTick callback # Record a series of transitions within the model. "transition.from" is an array of Strings and # nulls marking the prior state and "transition.to" is the observed next state, which # may be an end-of-chain sentinel. incrementTransitions: (transitions, callback) -> for transition in transitions key = transition.from.<KEY>(' ') hops = (@transitions[key] ?= {}) prior = hops[transition.to] or 0 hops[transition.to] = prior + 1 process.nextTick callback # Retrieve an object containing the possible next hops from a prior state and their # relative frequencies. Invokes "callback" with any errors and the object. get: (prior, callback) -> key = <KEY> hash = @transitions[key] or {} process.nextTick -> callback(null, hash) # Memory storage has no persistent backing. destroy: (callback) -> process.nextTick -> callback(null) disconnect: (callback) -> process.nextTick -> callback(null) module.exports = MemoryStorage
true
# Markov storage implementation that uses entirely in-memory storage. class MemoryStorage # Create a storage module. constructor: (connStr, modelName) -> @transitions = {} # No initialization necessary. initialize: (callback) -> process.nextTick callback # Record a series of transitions within the model. "transition.from" is an array of Strings and # nulls marking the prior state and "transition.to" is the observed next state, which # may be an end-of-chain sentinel. incrementTransitions: (transitions, callback) -> for transition in transitions key = transition.from.PI:KEY:<KEY>END_PI(' ') hops = (@transitions[key] ?= {}) prior = hops[transition.to] or 0 hops[transition.to] = prior + 1 process.nextTick callback # Retrieve an object containing the possible next hops from a prior state and their # relative frequencies. Invokes "callback" with any errors and the object. get: (prior, callback) -> key = PI:KEY:<KEY>END_PI hash = @transitions[key] or {} process.nextTick -> callback(null, hash) # Memory storage has no persistent backing. destroy: (callback) -> process.nextTick -> callback(null) disconnect: (callback) -> process.nextTick -> callback(null) module.exports = MemoryStorage
[ { "context": "hange jwtSecret key \n\ntoken_config =\n\t\n\tjwtSecret: \"$WBOeEhzbaYhdbFKMg0hd@R_\"\n\texpires: \"120m\"\n\nmodule.exports = token_config", "end": 90, "score": 0.9956672191619873, "start": 64, "tag": "KEY", "value": "\"$WBOeEhzbaYhdbFKMg0hd@R_\"" } ]
config/auth_config.coffee
GermanMtzmx/Mokarest
0
#you should change jwtSecret key token_config = jwtSecret: "$WBOeEhzbaYhdbFKMg0hd@R_" expires: "120m" module.exports = token_config
151023
#you should change jwtSecret key token_config = jwtSecret: <KEY> expires: "120m" module.exports = token_config
true
#you should change jwtSecret key token_config = jwtSecret: PI:KEY:<KEY>END_PI expires: "120m" module.exports = token_config
[ { "context": "ext Completions converted from https://github.com/Southclaw/pawn-sublime-language\n# Converter created by Rena", "end": 103, "score": 0.9995208382606506, "start": 94, "tag": "USERNAME", "value": "Southclaw" }, { "context": "hclaw/pawn-sublime-language\n# Converter creat...
snippets/socket.cson
Wuzi/language-pawn
4
# Socket Plugin Atom Snippets from Sublime Text Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by Renato "Hii" Garcia. # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'socket_create': 'prefix': 'socket_create' 'body': 'socket_create(${1:pType:TCP})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_bind': 'prefix': 'socket_bind' 'body': 'socket_bind(${1:Socket:id}, ${2:ip[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_connect': 'prefix': 'socket_connect' 'body': 'socket_connect(${1:Socket:id}, ${2:host[]}, ${3:port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_listen': 'prefix': 'socket_listen' 'body': 'socket_listen(${1:Socket:id}, ${2:port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_stop_listen': 'prefix': 'socket_stop_listen' 'body': 'socket_stop_listen(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_destroy': 'prefix': 'socket_destroy' 'body': 'socket_destroy(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_send': 'prefix': 'socket_send' 'body': 'socket_send(${1:Socket:id}, ${2:data[]}, ${3:len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_sendto': 'prefix': 'socket_sendto' 'body': 'socket_sendto(${1:Socket:id}, ${2:const ip[]}, ${3:port}, ${4:data[]}, ${5:len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_send_array': 'prefix': 'socket_send_array' 'body': 'socket_send_array(${1:Socket:id}, ${2:data[]}, ${3:size=sizeof(data})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'is_socket_valid': 'prefix': 'is_socket_valid' 'body': 'is_socket_valid(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_set_max_connections': 'prefix': 'socket_set_max_connections' 'body': 'socket_set_max_connections(${1:Socket:id}, ${2:max_remote_clients})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_close_remote_client': 'prefix': 'socket_close_remote_client' 'body': 'socket_close_remote_client(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_sendto_remote_client': 'prefix': 'socket_sendto_remote_client' 'body': 'socket_sendto_remote_client(${1:Socket:id}, ${2:remote_clientid}, ${3:data[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_remote_client_connected': 'prefix': 'socket_remote_client_connected' 'body': 'socket_remote_client_connected(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'get_remote_client_ip': 'prefix': 'get_remote_client_ip' 'body': 'get_remote_client_ip(${1:Socket:id}, ${2:remote_clientid}, ${3:ip[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_init': 'prefix': 'ssl_init' 'body': 'ssl_init()' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_create_context': 'prefix': 'ssl_create_context' 'body': 'ssl_create_context(${1:Socket:id}, ${2:method})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_connect': 'prefix': 'ssl_connect' 'body': 'ssl_connect(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_load_cert_into_context': 'prefix': 'ssl_load_cert_into_context' 'body': 'ssl_load_cert_into_context(${1:Socket:id}, ${2:const certificate[]}, ${3:const private_key[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_shutdown': 'prefix': 'ssl_shutdown' 'body': 'ssl_shutdown(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_get_peer_certificate': 'prefix': 'ssl_get_peer_certificate' 'body': 'ssl_get_peer_certificate(${1:Socket:id}, ${2:method}, ${3:subject[]}, ${4:issuer[]}, ${5:remote_clientid = 0xFFFF})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_set_accept_timeout': 'prefix': 'ssl_set_accept_timeout' 'body': 'ssl_set_accept_timeout(${1:Socket:id}, ${2:interval})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_set_mode': 'prefix': 'ssl_set_mode' 'body': 'ssl_set_mode(${1:Socket:id}, ${2:mode})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onUDPReceiveData': 'prefix': 'onUDPReceiveData' 'body': 'onUDPReceiveData(${1:Socket:id}, ${2:data[]}, ${3:data_len}, ${4:remote_client_ip[]}, ${5:remote_client_port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketAnswer': 'prefix': 'onSocketAnswer' 'body': 'onSocketAnswer(${1:Socket:id}, ${2:data[]}, ${3:data_len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketClose': 'prefix': 'onSocketClose' 'body': 'onSocketClose(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketReceiveData': 'prefix': 'onSocketReceiveData' 'body': 'onSocketReceiveData(${1:Socket:id}, ${2:remote_clientid}, ${3:data[]}, ${4:data_len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketRemoteConnect': 'prefix': 'onSocketRemoteConnect' 'body': 'onSocketRemoteConnect(${1:Socket:id}, ${2:remote_client[]}, ${3:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketRemoteDisconnect': 'prefix': 'onSocketRemoteDisconnect' 'body': 'onSocketRemoteDisconnect(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934'
52199
# Socket Plugin Atom Snippets from Sublime Text Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by <NAME> "<NAME>" <NAME>. # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'socket_create': 'prefix': 'socket_create' 'body': 'socket_create(${1:pType:TCP})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_bind': 'prefix': 'socket_bind' 'body': 'socket_bind(${1:Socket:id}, ${2:ip[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_connect': 'prefix': 'socket_connect' 'body': 'socket_connect(${1:Socket:id}, ${2:host[]}, ${3:port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_listen': 'prefix': 'socket_listen' 'body': 'socket_listen(${1:Socket:id}, ${2:port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_stop_listen': 'prefix': 'socket_stop_listen' 'body': 'socket_stop_listen(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_destroy': 'prefix': 'socket_destroy' 'body': 'socket_destroy(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_send': 'prefix': 'socket_send' 'body': 'socket_send(${1:Socket:id}, ${2:data[]}, ${3:len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_sendto': 'prefix': 'socket_sendto' 'body': 'socket_sendto(${1:Socket:id}, ${2:const ip[]}, ${3:port}, ${4:data[]}, ${5:len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_send_array': 'prefix': 'socket_send_array' 'body': 'socket_send_array(${1:Socket:id}, ${2:data[]}, ${3:size=sizeof(data})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'is_socket_valid': 'prefix': 'is_socket_valid' 'body': 'is_socket_valid(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_set_max_connections': 'prefix': 'socket_set_max_connections' 'body': 'socket_set_max_connections(${1:Socket:id}, ${2:max_remote_clients})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_close_remote_client': 'prefix': 'socket_close_remote_client' 'body': 'socket_close_remote_client(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_sendto_remote_client': 'prefix': 'socket_sendto_remote_client' 'body': 'socket_sendto_remote_client(${1:Socket:id}, ${2:remote_clientid}, ${3:data[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_remote_client_connected': 'prefix': 'socket_remote_client_connected' 'body': 'socket_remote_client_connected(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'get_remote_client_ip': 'prefix': 'get_remote_client_ip' 'body': 'get_remote_client_ip(${1:Socket:id}, ${2:remote_clientid}, ${3:ip[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_init': 'prefix': 'ssl_init' 'body': 'ssl_init()' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_create_context': 'prefix': 'ssl_create_context' 'body': 'ssl_create_context(${1:Socket:id}, ${2:method})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_connect': 'prefix': 'ssl_connect' 'body': 'ssl_connect(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_load_cert_into_context': 'prefix': 'ssl_load_cert_into_context' 'body': 'ssl_load_cert_into_context(${1:Socket:id}, ${2:const certificate[]}, ${3:const private_key[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_shutdown': 'prefix': 'ssl_shutdown' 'body': 'ssl_shutdown(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_get_peer_certificate': 'prefix': 'ssl_get_peer_certificate' 'body': 'ssl_get_peer_certificate(${1:Socket:id}, ${2:method}, ${3:subject[]}, ${4:issuer[]}, ${5:remote_clientid = 0xFFFF})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_set_accept_timeout': 'prefix': 'ssl_set_accept_timeout' 'body': 'ssl_set_accept_timeout(${1:Socket:id}, ${2:interval})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_set_mode': 'prefix': 'ssl_set_mode' 'body': 'ssl_set_mode(${1:Socket:id}, ${2:mode})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onUDPReceiveData': 'prefix': 'onUDPReceiveData' 'body': 'onUDPReceiveData(${1:Socket:id}, ${2:data[]}, ${3:data_len}, ${4:remote_client_ip[]}, ${5:remote_client_port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketAnswer': 'prefix': 'onSocketAnswer' 'body': 'onSocketAnswer(${1:Socket:id}, ${2:data[]}, ${3:data_len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketClose': 'prefix': 'onSocketClose' 'body': 'onSocketClose(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketReceiveData': 'prefix': 'onSocketReceiveData' 'body': 'onSocketReceiveData(${1:Socket:id}, ${2:remote_clientid}, ${3:data[]}, ${4:data_len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketRemoteConnect': 'prefix': 'onSocketRemoteConnect' 'body': 'onSocketRemoteConnect(${1:Socket:id}, ${2:remote_client[]}, ${3:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketRemoteDisconnect': 'prefix': 'onSocketRemoteDisconnect' 'body': 'onSocketRemoteDisconnect(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934'
true
# Socket Plugin Atom Snippets from Sublime Text Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI. # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'socket_create': 'prefix': 'socket_create' 'body': 'socket_create(${1:pType:TCP})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_bind': 'prefix': 'socket_bind' 'body': 'socket_bind(${1:Socket:id}, ${2:ip[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_connect': 'prefix': 'socket_connect' 'body': 'socket_connect(${1:Socket:id}, ${2:host[]}, ${3:port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_listen': 'prefix': 'socket_listen' 'body': 'socket_listen(${1:Socket:id}, ${2:port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_stop_listen': 'prefix': 'socket_stop_listen' 'body': 'socket_stop_listen(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_destroy': 'prefix': 'socket_destroy' 'body': 'socket_destroy(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_send': 'prefix': 'socket_send' 'body': 'socket_send(${1:Socket:id}, ${2:data[]}, ${3:len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_sendto': 'prefix': 'socket_sendto' 'body': 'socket_sendto(${1:Socket:id}, ${2:const ip[]}, ${3:port}, ${4:data[]}, ${5:len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_send_array': 'prefix': 'socket_send_array' 'body': 'socket_send_array(${1:Socket:id}, ${2:data[]}, ${3:size=sizeof(data})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'is_socket_valid': 'prefix': 'is_socket_valid' 'body': 'is_socket_valid(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_set_max_connections': 'prefix': 'socket_set_max_connections' 'body': 'socket_set_max_connections(${1:Socket:id}, ${2:max_remote_clients})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_close_remote_client': 'prefix': 'socket_close_remote_client' 'body': 'socket_close_remote_client(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_sendto_remote_client': 'prefix': 'socket_sendto_remote_client' 'body': 'socket_sendto_remote_client(${1:Socket:id}, ${2:remote_clientid}, ${3:data[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'socket_remote_client_connected': 'prefix': 'socket_remote_client_connected' 'body': 'socket_remote_client_connected(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'get_remote_client_ip': 'prefix': 'get_remote_client_ip' 'body': 'get_remote_client_ip(${1:Socket:id}, ${2:remote_clientid}, ${3:ip[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_init': 'prefix': 'ssl_init' 'body': 'ssl_init()' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_create_context': 'prefix': 'ssl_create_context' 'body': 'ssl_create_context(${1:Socket:id}, ${2:method})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_connect': 'prefix': 'ssl_connect' 'body': 'ssl_connect(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_load_cert_into_context': 'prefix': 'ssl_load_cert_into_context' 'body': 'ssl_load_cert_into_context(${1:Socket:id}, ${2:const certificate[]}, ${3:const private_key[]})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_shutdown': 'prefix': 'ssl_shutdown' 'body': 'ssl_shutdown(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_get_peer_certificate': 'prefix': 'ssl_get_peer_certificate' 'body': 'ssl_get_peer_certificate(${1:Socket:id}, ${2:method}, ${3:subject[]}, ${4:issuer[]}, ${5:remote_clientid = 0xFFFF})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_set_accept_timeout': 'prefix': 'ssl_set_accept_timeout' 'body': 'ssl_set_accept_timeout(${1:Socket:id}, ${2:interval})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'ssl_set_mode': 'prefix': 'ssl_set_mode' 'body': 'ssl_set_mode(${1:Socket:id}, ${2:mode})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onUDPReceiveData': 'prefix': 'onUDPReceiveData' 'body': 'onUDPReceiveData(${1:Socket:id}, ${2:data[]}, ${3:data_len}, ${4:remote_client_ip[]}, ${5:remote_client_port})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketAnswer': 'prefix': 'onSocketAnswer' 'body': 'onSocketAnswer(${1:Socket:id}, ${2:data[]}, ${3:data_len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketClose': 'prefix': 'onSocketClose' 'body': 'onSocketClose(${1:Socket:id})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketReceiveData': 'prefix': 'onSocketReceiveData' 'body': 'onSocketReceiveData(${1:Socket:id}, ${2:remote_clientid}, ${3:data[]}, ${4:data_len})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketRemoteConnect': 'prefix': 'onSocketRemoteConnect' 'body': 'onSocketRemoteConnect(${1:Socket:id}, ${2:remote_client[]}, ${3:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934' 'onSocketRemoteDisconnect': 'prefix': 'onSocketRemoteDisconnect' 'body': 'onSocketRemoteDisconnect(${1:Socket:id}, ${2:remote_clientid})' 'description': 'Function from: Socket plugin' 'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=333934'
[ { "context": "ertFile = \"localhost-cine-io.crt\"\n sslKeyFile = \"localhost-cine-io.key\"\n sslIntermediateCertFiles = [ \"COMODORSADom", "end": 200, "score": 0.9237928986549377, "start": 183, "tag": "KEY", "value": "localhost-cine-io" } ]
create_cine_https_server.coffee
ccns1/ccns71
52
https = require("https") fs = require("fs") module.exports = (app)-> sslCertsPath = process.env.SSL_CERTS_PATH or __dirname sslCertFile = "localhost-cine-io.crt" sslKeyFile = "localhost-cine-io.key" sslIntermediateCertFiles = [ "COMODORSADomainValidationSecureServerCA.crt", "COMODORSAAddTrustCA.crt", "AddTrustExternalCARoot.crt" ] sslKey = fs.readFileSync("#{sslCertsPath}/#{sslKeyFile}") sslCert = fs.readFileSync("#{sslCertsPath}/#{sslCertFile}") sslCA = (fs.readFileSync "#{sslCertsPath}/#{file}" for file in sslIntermediateCertFiles) options = ca: sslCA cert: sslCert key: sslKey requestCert: true rejectUnauthorized: false agent: false httpsServer = https.createServer(options, app)
120970
https = require("https") fs = require("fs") module.exports = (app)-> sslCertsPath = process.env.SSL_CERTS_PATH or __dirname sslCertFile = "localhost-cine-io.crt" sslKeyFile = "<KEY>.key" sslIntermediateCertFiles = [ "COMODORSADomainValidationSecureServerCA.crt", "COMODORSAAddTrustCA.crt", "AddTrustExternalCARoot.crt" ] sslKey = fs.readFileSync("#{sslCertsPath}/#{sslKeyFile}") sslCert = fs.readFileSync("#{sslCertsPath}/#{sslCertFile}") sslCA = (fs.readFileSync "#{sslCertsPath}/#{file}" for file in sslIntermediateCertFiles) options = ca: sslCA cert: sslCert key: sslKey requestCert: true rejectUnauthorized: false agent: false httpsServer = https.createServer(options, app)
true
https = require("https") fs = require("fs") module.exports = (app)-> sslCertsPath = process.env.SSL_CERTS_PATH or __dirname sslCertFile = "localhost-cine-io.crt" sslKeyFile = "PI:KEY:<KEY>END_PI.key" sslIntermediateCertFiles = [ "COMODORSADomainValidationSecureServerCA.crt", "COMODORSAAddTrustCA.crt", "AddTrustExternalCARoot.crt" ] sslKey = fs.readFileSync("#{sslCertsPath}/#{sslKeyFile}") sslCert = fs.readFileSync("#{sslCertsPath}/#{sslCertFile}") sslCA = (fs.readFileSync "#{sslCertsPath}/#{file}" for file in sslIntermediateCertFiles) options = ca: sslCA cert: sslCert key: sslKey requestCert: true rejectUnauthorized: false agent: false httpsServer = https.createServer(options, app)
[ { "context": "# author Alex Bardas\n# Converts a valid XML ontology generated in *Pro", "end": 20, "score": 0.9998527765274048, "start": 9, "tag": "NAME", "value": "Alex Bardas" } ]
tools/naflex/NUCMD/htmlib/help/onto/js/ontology.coffee
Multiscale-Genomics/VRE
5
# author Alex Bardas # Converts a valid XML ontology generated in *Protege* into a JSON # First it creates the ontology's tree defined by root and children nodes # Then, it creates a proper json from this tree define ['cs!log', 'cs!tree'], (log, Tree) -> # set debug to true or false log.debug(false) print = log.info warn = log.warn error = log.error Node = Tree.Node Root = Tree.Root class Ontology type = Object.prototype.toString constructor: (owl) -> print "Initialize Ontology" # receives a string and checks if it is # a valid XML so it can return a proper JSON # after parsing it if not (xml = @_isValidXML?(owl)) return { status: "Error" message: "The parameter is not a valid XML" } else root = @_toTreeObject(xml) if not type.call(root) == "[object Object]" return false return [@toSimpleJSON(root), @toJSON(root)] _isValidXML: (owl) -> print "Test if XML is valid" # tries to see if ontology is a valid XML document # return false if the document is not a XML # else returns the document try owl = $.parseXML(owl) catch err error "The ontology is not a valid XML", err return false return owl _toTreeObject: (xml) -> ### Receives a valid xml, parses it and receives a valid tree ### print "Create Tree" tree = {} root = 0 $.each $(xml).find("Declaration"), (k, v) -> v = $(v).children().eq(0) name = v.attr("IRI") if name? # remove first character if it is "#" name = name.replace(/^#/, '') tree[name] = new Node({name: name}) else root_name = v.attr("abbreviatedIRI") # remove first characters until ":" # e.g.: owl:Thing -> Thing # e.g.: owl:owl:Thing -> owl:Thing root_name = root_name.replace(/.*?:/, '') if root_name tree[root_name] = new Root({name: root_name}) root = tree[root_name] true $.each $(xml).find("SubClassOf"), (k, v) -> v = $(v).children() name = v.eq(0).attr("IRI").replace(/^#/, '') parent_name = v.eq(1).attr("IRI") parent_name = if parent_name then parent_name.replace(/^#/, '') else v.eq(1).attr("abbreviatedIRI").replace(/.*?:/, '') tree[name].parent = tree[parent_name] tree[parent_name].children.push(tree[name]) true # the root has information about the whole tree root toSimpleJSON: (root) -> print "Create Simple JSON" ### Transforms the tree obtained from parsing the xml into an expressive object The tree will be an object similar: root: { child1: { child1_1: {} } child2: {} } Can have any depth, the name of the Node is actually the key name If the key is a leaf, it's value would be an empty object Else it's value would be an object containing its children Probably the easiest way to represent a Tree as a javascript object ### json = {} json[root.name] = {} traversal = (node, json) -> # check if it is a leaf # console.log node if (node.children?) if node.children.length is 0 {} else for child in node.children json[node.name][child.name] = {} traversal(child, json[node.name]) traversal(root, json) return json toJSON: (root) -> ### Transforms the tree obtained from parsing the xml into an expressive object The tree will be an object similar: { name: "root" children: [ { name: "child1" children: [ { name: "child1_1" children: [] } ] }, { name: "child2" children: [] } ] } Can have any depth It's harder to manually create a JSON like this (than the JSON returned by Simple JSON function) but can be more useful because it can store more data ### print "Create JSON" json = name: root.name id: root.name children: [] traversal = (node, json) -> # check if it is a leaf if (node.children?) if node.children.length is 0 return { name: node.name id: node.name children: [] } else node.children.forEach( (child, index) -> json.push( name: child.name id: child.name children: [] ) traversal(child, json[index].children) ) traversal(root, json.children) return json
109594
# author <NAME> # Converts a valid XML ontology generated in *Protege* into a JSON # First it creates the ontology's tree defined by root and children nodes # Then, it creates a proper json from this tree define ['cs!log', 'cs!tree'], (log, Tree) -> # set debug to true or false log.debug(false) print = log.info warn = log.warn error = log.error Node = Tree.Node Root = Tree.Root class Ontology type = Object.prototype.toString constructor: (owl) -> print "Initialize Ontology" # receives a string and checks if it is # a valid XML so it can return a proper JSON # after parsing it if not (xml = @_isValidXML?(owl)) return { status: "Error" message: "The parameter is not a valid XML" } else root = @_toTreeObject(xml) if not type.call(root) == "[object Object]" return false return [@toSimpleJSON(root), @toJSON(root)] _isValidXML: (owl) -> print "Test if XML is valid" # tries to see if ontology is a valid XML document # return false if the document is not a XML # else returns the document try owl = $.parseXML(owl) catch err error "The ontology is not a valid XML", err return false return owl _toTreeObject: (xml) -> ### Receives a valid xml, parses it and receives a valid tree ### print "Create Tree" tree = {} root = 0 $.each $(xml).find("Declaration"), (k, v) -> v = $(v).children().eq(0) name = v.attr("IRI") if name? # remove first character if it is "#" name = name.replace(/^#/, '') tree[name] = new Node({name: name}) else root_name = v.attr("abbreviatedIRI") # remove first characters until ":" # e.g.: owl:Thing -> Thing # e.g.: owl:owl:Thing -> owl:Thing root_name = root_name.replace(/.*?:/, '') if root_name tree[root_name] = new Root({name: root_name}) root = tree[root_name] true $.each $(xml).find("SubClassOf"), (k, v) -> v = $(v).children() name = v.eq(0).attr("IRI").replace(/^#/, '') parent_name = v.eq(1).attr("IRI") parent_name = if parent_name then parent_name.replace(/^#/, '') else v.eq(1).attr("abbreviatedIRI").replace(/.*?:/, '') tree[name].parent = tree[parent_name] tree[parent_name].children.push(tree[name]) true # the root has information about the whole tree root toSimpleJSON: (root) -> print "Create Simple JSON" ### Transforms the tree obtained from parsing the xml into an expressive object The tree will be an object similar: root: { child1: { child1_1: {} } child2: {} } Can have any depth, the name of the Node is actually the key name If the key is a leaf, it's value would be an empty object Else it's value would be an object containing its children Probably the easiest way to represent a Tree as a javascript object ### json = {} json[root.name] = {} traversal = (node, json) -> # check if it is a leaf # console.log node if (node.children?) if node.children.length is 0 {} else for child in node.children json[node.name][child.name] = {} traversal(child, json[node.name]) traversal(root, json) return json toJSON: (root) -> ### Transforms the tree obtained from parsing the xml into an expressive object The tree will be an object similar: { name: "root" children: [ { name: "child1" children: [ { name: "child1_1" children: [] } ] }, { name: "child2" children: [] } ] } Can have any depth It's harder to manually create a JSON like this (than the JSON returned by Simple JSON function) but can be more useful because it can store more data ### print "Create JSON" json = name: root.name id: root.name children: [] traversal = (node, json) -> # check if it is a leaf if (node.children?) if node.children.length is 0 return { name: node.name id: node.name children: [] } else node.children.forEach( (child, index) -> json.push( name: child.name id: child.name children: [] ) traversal(child, json[index].children) ) traversal(root, json.children) return json
true
# author PI:NAME:<NAME>END_PI # Converts a valid XML ontology generated in *Protege* into a JSON # First it creates the ontology's tree defined by root and children nodes # Then, it creates a proper json from this tree define ['cs!log', 'cs!tree'], (log, Tree) -> # set debug to true or false log.debug(false) print = log.info warn = log.warn error = log.error Node = Tree.Node Root = Tree.Root class Ontology type = Object.prototype.toString constructor: (owl) -> print "Initialize Ontology" # receives a string and checks if it is # a valid XML so it can return a proper JSON # after parsing it if not (xml = @_isValidXML?(owl)) return { status: "Error" message: "The parameter is not a valid XML" } else root = @_toTreeObject(xml) if not type.call(root) == "[object Object]" return false return [@toSimpleJSON(root), @toJSON(root)] _isValidXML: (owl) -> print "Test if XML is valid" # tries to see if ontology is a valid XML document # return false if the document is not a XML # else returns the document try owl = $.parseXML(owl) catch err error "The ontology is not a valid XML", err return false return owl _toTreeObject: (xml) -> ### Receives a valid xml, parses it and receives a valid tree ### print "Create Tree" tree = {} root = 0 $.each $(xml).find("Declaration"), (k, v) -> v = $(v).children().eq(0) name = v.attr("IRI") if name? # remove first character if it is "#" name = name.replace(/^#/, '') tree[name] = new Node({name: name}) else root_name = v.attr("abbreviatedIRI") # remove first characters until ":" # e.g.: owl:Thing -> Thing # e.g.: owl:owl:Thing -> owl:Thing root_name = root_name.replace(/.*?:/, '') if root_name tree[root_name] = new Root({name: root_name}) root = tree[root_name] true $.each $(xml).find("SubClassOf"), (k, v) -> v = $(v).children() name = v.eq(0).attr("IRI").replace(/^#/, '') parent_name = v.eq(1).attr("IRI") parent_name = if parent_name then parent_name.replace(/^#/, '') else v.eq(1).attr("abbreviatedIRI").replace(/.*?:/, '') tree[name].parent = tree[parent_name] tree[parent_name].children.push(tree[name]) true # the root has information about the whole tree root toSimpleJSON: (root) -> print "Create Simple JSON" ### Transforms the tree obtained from parsing the xml into an expressive object The tree will be an object similar: root: { child1: { child1_1: {} } child2: {} } Can have any depth, the name of the Node is actually the key name If the key is a leaf, it's value would be an empty object Else it's value would be an object containing its children Probably the easiest way to represent a Tree as a javascript object ### json = {} json[root.name] = {} traversal = (node, json) -> # check if it is a leaf # console.log node if (node.children?) if node.children.length is 0 {} else for child in node.children json[node.name][child.name] = {} traversal(child, json[node.name]) traversal(root, json) return json toJSON: (root) -> ### Transforms the tree obtained from parsing the xml into an expressive object The tree will be an object similar: { name: "root" children: [ { name: "child1" children: [ { name: "child1_1" children: [] } ] }, { name: "child2" children: [] } ] } Can have any depth It's harder to manually create a JSON like this (than the JSON returned by Simple JSON function) but can be more useful because it can store more data ### print "Create JSON" json = name: root.name id: root.name children: [] traversal = (node, json) -> # check if it is a leaf if (node.children?) if node.children.length is 0 return { name: node.name id: node.name children: [] } else node.children.forEach( (child, index) -> json.push( name: child.name id: child.name children: [] ) traversal(child, json[index].children) ) traversal(root, json.children) return json
[ { "context": ").Strategy\n\nUSERS =\n 1:\n id: 1\n username: 'admin'\n password: bcrypt.hashSync('secure', 10)\n 2:", "end": 201, "score": 0.9946960210800171, "start": 196, "tag": "USERNAME", "value": "admin" }, { "context": " username: 'admin'\n password: bcrypt.hashSy...
example/server.coffee
mattinsler/trojan
8
path = require 'path' bcrypt = require 'bcrypt' express = require 'express' passport = require 'passport' LocalStrategy = require('passport-local').Strategy USERS = 1: id: 1 username: 'admin' password: bcrypt.hashSync('secure', 10) 2: id: 2 username: 'foo' password: bcrypt.hashSync('barbaz', 10) USERS_BY_USERNAME = Object.keys(USERS).reduce (o, k) -> o[USERS[k].username] = USERS[k] o , {} passport.use new LocalStrategy( (username, password, done) -> user = USERS_BY_USERNAME[username] return done(null, false) unless user? return done(null, false) unless bcrypt.compareSync(password, user.password) done(null, user) ) passport.serializeUser (user, done) -> done(null, user.id) passport.deserializeUser (id, done) -> done(null, USERS[id]) app = express() app.set('view engine', 'ejs') app.set('views', path.join(__dirname, 'templates')) app.use express.logger() app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session(secret: 'shhhhhhhhhhhhhhhh') app.use passport.initialize() app.use passport.session() app.use app.router app.engine('html', require('ejs').renderFile) app.get '/', (req, res, next) -> return res.redirect('/login') unless req.user? res.render('index.html.ejs', user: req.user) app.get '/login', (req, res, next) -> res.render('login.html') app.post '/login', passport.authenticate('local', successRedirect: '/', failureRedirect: '/login') app.get '/logout', (req, res, next) -> req.logout() res.redirect('/') module.exports = app
179629
path = require 'path' bcrypt = require 'bcrypt' express = require 'express' passport = require 'passport' LocalStrategy = require('passport-local').Strategy USERS = 1: id: 1 username: 'admin' password: bcrypt.hashSync('<PASSWORD>', 10) 2: id: 2 username: 'foo' password: bcrypt.hashSync('<PASSWORD>', 10) USERS_BY_USERNAME = Object.keys(USERS).reduce (o, k) -> o[USERS[k].username] = USERS[k] o , {} passport.use new LocalStrategy( (username, password, done) -> user = USERS_BY_USERNAME[username] return done(null, false) unless user? return done(null, false) unless bcrypt.compareSync(password, user.password) done(null, user) ) passport.serializeUser (user, done) -> done(null, user.id) passport.deserializeUser (id, done) -> done(null, USERS[id]) app = express() app.set('view engine', 'ejs') app.set('views', path.join(__dirname, 'templates')) app.use express.logger() app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session(secret: 'shhhhhhhhhhhhhhhh') app.use passport.initialize() app.use passport.session() app.use app.router app.engine('html', require('ejs').renderFile) app.get '/', (req, res, next) -> return res.redirect('/login') unless req.user? res.render('index.html.ejs', user: req.user) app.get '/login', (req, res, next) -> res.render('login.html') app.post '/login', passport.authenticate('local', successRedirect: '/', failureRedirect: '/login') app.get '/logout', (req, res, next) -> req.logout() res.redirect('/') module.exports = app
true
path = require 'path' bcrypt = require 'bcrypt' express = require 'express' passport = require 'passport' LocalStrategy = require('passport-local').Strategy USERS = 1: id: 1 username: 'admin' password: bcrypt.hashSync('PI:PASSWORD:<PASSWORD>END_PI', 10) 2: id: 2 username: 'foo' password: bcrypt.hashSync('PI:PASSWORD:<PASSWORD>END_PI', 10) USERS_BY_USERNAME = Object.keys(USERS).reduce (o, k) -> o[USERS[k].username] = USERS[k] o , {} passport.use new LocalStrategy( (username, password, done) -> user = USERS_BY_USERNAME[username] return done(null, false) unless user? return done(null, false) unless bcrypt.compareSync(password, user.password) done(null, user) ) passport.serializeUser (user, done) -> done(null, user.id) passport.deserializeUser (id, done) -> done(null, USERS[id]) app = express() app.set('view engine', 'ejs') app.set('views', path.join(__dirname, 'templates')) app.use express.logger() app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session(secret: 'shhhhhhhhhhhhhhhh') app.use passport.initialize() app.use passport.session() app.use app.router app.engine('html', require('ejs').renderFile) app.get '/', (req, res, next) -> return res.redirect('/login') unless req.user? res.render('index.html.ejs', user: req.user) app.get '/login', (req, res, next) -> res.render('login.html') app.post '/login', passport.authenticate('local', successRedirect: '/', failureRedirect: '/login') app.get '/logout', (req, res, next) -> req.logout() res.redirect('/') module.exports = app
[ { "context": "o.surname}' <#{@options.to.email}>\"\n from: \"'Kindzy.com' <no-reply@kindzy.com>\"\n subject: @options.s", "end": 513, "score": 0.9207475781440735, "start": 503, "tag": "EMAIL", "value": "Kindzy.com" }, { "context": "#{@options.to.email}>\"\n from: \"'Ki...
lib/emailer.coffee
doomhz/daycare_social_platform
3
emailer = require("nodemailer") fs = require("fs") _ = require("underscore") class Emailer options: {} data: {} attachments: [ fileName: "logo.png" filePath: "./public/images/email/logo.png" cid: "logo@kindzy" ] constructor: (@options, @data)-> send: (callback)-> html = @getHtml(@options.template, @data) attachments = @getAttachments(html) messageData = to: "'#{@options.to.name} #{@options.to.surname}' <#{@options.to.email}>" from: "'Kindzy.com' <no-reply@kindzy.com>" subject: @options.subject html: html generateTextFromHTML: true attachments: attachments transport = @getTransport() transport.sendMail messageData, callback getTransport: ()-> emailer.createTransport "SMTP", service: "Gmail" auth: user: "email" pass: "pass" getHtml: (templateName, data)-> templatePath = "./views/emails/#{templateName}.html" templateContent = fs.readFileSync(templatePath, encoding="utf8") _.template templateContent, data, {interpolate: /\{\{(.+?)\}\}/g} getAttachments: (html)-> attachments = [] for attachment in @attachments attachments.push(attachment) if html.search("cid:#{attachment.cid}") > -1 attachments exports = module.exports = Emailer
211140
emailer = require("nodemailer") fs = require("fs") _ = require("underscore") class Emailer options: {} data: {} attachments: [ fileName: "logo.png" filePath: "./public/images/email/logo.png" cid: "logo@kindzy" ] constructor: (@options, @data)-> send: (callback)-> html = @getHtml(@options.template, @data) attachments = @getAttachments(html) messageData = to: "'#{@options.to.name} #{@options.to.surname}' <#{@options.to.email}>" from: "'<EMAIL>' <<EMAIL>>" subject: @options.subject html: html generateTextFromHTML: true attachments: attachments transport = @getTransport() transport.sendMail messageData, callback getTransport: ()-> emailer.createTransport "SMTP", service: "Gmail" auth: user: "email" pass: "<PASSWORD>" getHtml: (templateName, data)-> templatePath = "./views/emails/#{templateName}.html" templateContent = fs.readFileSync(templatePath, encoding="utf8") _.template templateContent, data, {interpolate: /\{\{(.+?)\}\}/g} getAttachments: (html)-> attachments = [] for attachment in @attachments attachments.push(attachment) if html.search("cid:#{attachment.cid}") > -1 attachments exports = module.exports = Emailer
true
emailer = require("nodemailer") fs = require("fs") _ = require("underscore") class Emailer options: {} data: {} attachments: [ fileName: "logo.png" filePath: "./public/images/email/logo.png" cid: "logo@kindzy" ] constructor: (@options, @data)-> send: (callback)-> html = @getHtml(@options.template, @data) attachments = @getAttachments(html) messageData = to: "'#{@options.to.name} #{@options.to.surname}' <#{@options.to.email}>" from: "'PI:EMAIL:<EMAIL>END_PI' <PI:EMAIL:<EMAIL>END_PI>" subject: @options.subject html: html generateTextFromHTML: true attachments: attachments transport = @getTransport() transport.sendMail messageData, callback getTransport: ()-> emailer.createTransport "SMTP", service: "Gmail" auth: user: "email" pass: "PI:PASSWORD:<PASSWORD>END_PI" getHtml: (templateName, data)-> templatePath = "./views/emails/#{templateName}.html" templateContent = fs.readFileSync(templatePath, encoding="utf8") _.template templateContent, data, {interpolate: /\{\{(.+?)\}\}/g} getAttachments: (html)-> attachments = [] for attachment in @attachments attachments.push(attachment) if html.search("cid:#{attachment.cid}") > -1 attachments exports = module.exports = Emailer
[ { "context": " and, optionally, one or more users.\n#\n# Thanks, Brian Eno.\n#\n# Author:\n# hakanensari\n\nmodule.exports = (r", "end": 391, "score": 0.9998964071273804, "start": 382, "tag": "NAME", "value": "Brian Eno" }, { "context": "re users.\n#\n# Thanks, Brian Eno.\n#\n#...
src/scripts/oblique.coffee
contolini/hubot-scripts
9
# Description: # Suggests an oblique strategy # # Dependencies: # None # # Configuration: # None # # Commands: # hubot strategy - Suggests a strategy # hubot a strategy for <user> - Suggests a strategy to user # # Notes: # You can be as verbose as you want as long as you address Hubot and mention # the word strategy and, optionally, one or more users. # # Thanks, Brian Eno. # # Author: # hakanensari module.exports = (robot) -> robot.respond /.*strategy/i, (msg) -> mentions = msg.message.text.match(/(@\w+)/g) robot.http('http://oblique.io') .get() (err, res, body) -> strategy = JSON.parse body strategy = "#{mentions.join(', ')}: #{strategy}" if mentions msg.send strategy
81370
# Description: # Suggests an oblique strategy # # Dependencies: # None # # Configuration: # None # # Commands: # hubot strategy - Suggests a strategy # hubot a strategy for <user> - Suggests a strategy to user # # Notes: # You can be as verbose as you want as long as you address Hubot and mention # the word strategy and, optionally, one or more users. # # Thanks, <NAME>. # # Author: # hakanensari module.exports = (robot) -> robot.respond /.*strategy/i, (msg) -> mentions = msg.message.text.match(/(@\w+)/g) robot.http('http://oblique.io') .get() (err, res, body) -> strategy = JSON.parse body strategy = "#{mentions.join(', ')}: #{strategy}" if mentions msg.send strategy
true
# Description: # Suggests an oblique strategy # # Dependencies: # None # # Configuration: # None # # Commands: # hubot strategy - Suggests a strategy # hubot a strategy for <user> - Suggests a strategy to user # # Notes: # You can be as verbose as you want as long as you address Hubot and mention # the word strategy and, optionally, one or more users. # # Thanks, PI:NAME:<NAME>END_PI. # # Author: # hakanensari module.exports = (robot) -> robot.respond /.*strategy/i, (msg) -> mentions = msg.message.text.match(/(@\w+)/g) robot.http('http://oblique.io') .get() (err, res, body) -> strategy = JSON.parse body strategy = "#{mentions.join(', ')}: #{strategy}" if mentions msg.send strategy
[ { "context": " false\n\n return true\n\n\n\n\nword = \"hello\"\nword2 = \"racecar\"\nconsole.log \"#{word}\", isPalindrome(word)\ncon", "end": 239, "score": 0.8045269846916199, "start": 235, "tag": "KEY", "value": "race" }, { "context": "se\n\n return true\n\n\n\n\nword = \"hello\"...
stack/test/isPalindrome.coffee
youqingkui/DataStructure
0
Stack = require('../stack') isPalindrome = (word) -> s = new Stack() for i in word s.push i rword = '' while s.length() rword += s.pop() if word != rword return false return true word = "hello" word2 = "racecar" console.log "#{word}", isPalindrome(word) console.log "#{word2}", isPalindrome(word2)
211871
Stack = require('../stack') isPalindrome = (word) -> s = new Stack() for i in word s.push i rword = '' while s.length() rword += s.pop() if word != rword return false return true word = "hello" word2 = "<KEY> <PASSWORD>" console.log "#{word}", isPalindrome(word) console.log "#{word2}", isPalindrome(word2)
true
Stack = require('../stack') isPalindrome = (word) -> s = new Stack() for i in word s.push i rword = '' while s.length() rword += s.pop() if word != rword return false return true word = "hello" word2 = "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" console.log "#{word}", isPalindrome(word) console.log "#{word2}", isPalindrome(word2)
[ { "context": "Client:=> \n\t\t\t\treturn @rclient\n\t\t@emailAddress = \"bob@smith\"\n\t\t@sessionId = \"sess:123456\"\n\t\t@stubbedKey", "end": 672, "score": 0.9244333505630493, "start": 669, "tag": "EMAIL", "value": "bob" }, { "context": "ent:=> \n\t\t\t\treturn @rclient\n\t\t@emai...
test/UnitTests/coffee/Security/SessionInvalidatorTests.coffee
mickaobrien/web-sharelatex
1
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Security/SessionInvalidator" expect = require("chai").expect describe "SessionInvaildator", -> beforeEach -> @settings = redis: web:{} @rclient = del:sinon.stub() set:sinon.stub().callsArgWith(2) get:sinon.stub() @SessionInvaildator = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> "redis-sharelatex": createClient:=> return @rclient @emailAddress = "bob@smith" @sessionId = "sess:123456" @stubbedKey = "e_sess:7890" describe "_getEmailKey", -> it "should get the email key by hashing it", -> result = @SessionInvaildator._getEmailKey "bob@smith.com" result.should.equal "e_sess:6815b961bfb8f83dd4cecd357e55e62d" describe "tracksession", -> it "should save the session in redis", (done)-> @SessionInvaildator._getEmailKey = sinon.stub().returns(@stubbedKey) @SessionInvaildator.tracksession @sessionId, @emailAddress, => @rclient.set.calledWith(@stubbedKey).should.equal true done() describe "invalidateSession", (done)-> beforeEach -> @SessionInvaildator._getEmailKey = sinon.stub().returns(@stubbedKey) @rclient.del.callsArgWith(1) it "get the session key and delete it", (done)-> @rclient.get.callsArgWith 1, null, @sessionId @SessionInvaildator.invalidateSession @emailAddress, => @rclient.del.calledWith(@sessionId).should.equal true @rclient.del.calledWith(@stubbedKey).should.equal true done()
144495
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Security/SessionInvalidator" expect = require("chai").expect describe "SessionInvaildator", -> beforeEach -> @settings = redis: web:{} @rclient = del:sinon.stub() set:sinon.stub().callsArgWith(2) get:sinon.stub() @SessionInvaildator = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> "redis-sharelatex": createClient:=> return @rclient @emailAddress = "<EMAIL> <PASSWORD>" @sessionId = "sess:123456" @stubbedKey = "<KEY>" describe "_getEmailKey", -> it "should get the email key by hashing it", -> result = @SessionInvaildator._getEmailKey "<EMAIL>" result.should.equal "e_sess:6815b961bfb8f83dd4cecd357e55e62d" describe "tracksession", -> it "should save the session in redis", (done)-> @SessionInvaildator._getEmailKey = sinon.stub().returns(@stubbedKey) @SessionInvaildator.tracksession @sessionId, @emailAddress, => @rclient.set.calledWith(@stubbedKey).should.equal true done() describe "invalidateSession", (done)-> beforeEach -> @SessionInvaildator._getEmailKey = sinon.stub().returns(@stubbedKey) @rclient.del.callsArgWith(1) it "get the session key and delete it", (done)-> @rclient.get.callsArgWith 1, null, @sessionId @SessionInvaildator.invalidateSession @emailAddress, => @rclient.del.calledWith(@sessionId).should.equal true @rclient.del.calledWith(@stubbedKey).should.equal true done()
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Security/SessionInvalidator" expect = require("chai").expect describe "SessionInvaildator", -> beforeEach -> @settings = redis: web:{} @rclient = del:sinon.stub() set:sinon.stub().callsArgWith(2) get:sinon.stub() @SessionInvaildator = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> "redis-sharelatex": createClient:=> return @rclient @emailAddress = "PI:EMAIL:<EMAIL>END_PI PI:PASSWORD:<PASSWORD>END_PI" @sessionId = "sess:123456" @stubbedKey = "PI:KEY:<KEY>END_PI" describe "_getEmailKey", -> it "should get the email key by hashing it", -> result = @SessionInvaildator._getEmailKey "PI:EMAIL:<EMAIL>END_PI" result.should.equal "e_sess:6815b961bfb8f83dd4cecd357e55e62d" describe "tracksession", -> it "should save the session in redis", (done)-> @SessionInvaildator._getEmailKey = sinon.stub().returns(@stubbedKey) @SessionInvaildator.tracksession @sessionId, @emailAddress, => @rclient.set.calledWith(@stubbedKey).should.equal true done() describe "invalidateSession", (done)-> beforeEach -> @SessionInvaildator._getEmailKey = sinon.stub().returns(@stubbedKey) @rclient.del.callsArgWith(1) it "get the session key and delete it", (done)-> @rclient.get.callsArgWith 1, null, @sessionId @SessionInvaildator.invalidateSession @emailAddress, => @rclient.del.calledWith(@sessionId).should.equal true @rclient.del.calledWith(@stubbedKey).should.equal true done()
[ { "context": " return yes if key is '$$hashKey' and x is hashKey\n ", "end": 6689, "score": 0.9408197402954102, "start": 6680, "tag": "KEY", "value": "$$hashKey" } ]
src/directive.coffee
efacilitation/angular-validator
0
$ = angular.element angular.module 'validator.directive', ['validator.provider'] .directive 'validator', ['$injector', ($injector) -> restrict: 'A' require: 'ngModel' link: (scope, element, attrs, ctrl) -> # ---------------------------------------- # providers # ---------------------------------------- $validator = $injector.get '$validator' $parse = $injector.get '$parse' # ---------------------------------------- # valuables # ---------------------------------------- model = $parse attrs.ngModel rules = [] # ---------------------------------------- # private methods # ---------------------------------------- validate = (from, args={}) -> ### Validate this element with all rules. @param from: 'watch', 'blur' or 'broadcast' @param args: success(): success callback (this callback will return success count) error(): error callback (this callback will return error count) oldValue: the old value of $watch ### successCount = 0 errorCount = 0 increaseSuccessCount = -> if ++successCount is rules.length ctrl.$setValidity attrs.ngModel, yes rule.success model(scope), scope, element, attrs, $injector for rule in rules args.success?() return for rule in rules switch from when 'blur' continue if rule.invoke isnt 'blur' rule.enableError = yes when 'watch' if rule.invoke isnt 'watch' and not rule.enableError increaseSuccessCount() continue when 'broadcast' then rule.enableError = yes else # validate do (rule) -> # success() and error() call back will run in other thread rule.validator model(scope), scope, element, attrs, success: -> increaseSuccessCount() error: -> if rule.enableError and ++errorCount is 1 ctrl.$setValidity attrs.ngModel, no rule.error model(scope), scope, element, attrs, $injector if args.error?() is 1 # scroll to the first element try element[0].scrollIntoViewIfNeeded() element[0].select() registerRequired = -> rule = $validator.getRule 'required' rule ?= $validator.convertRule 'required', validator: /^.+$/ invoke: 'watch' rules.push rule removeRule = (name) -> ### Remove the rule in rules by the name. ### for index in [0...rules.length] by 1 when rules[index]?.name is name rules[index].success model(scope), scope, element, attrs, $injector rules.splice index, 1 index-- # ---------------------------------------- # attrs.$observe # ---------------------------------------- attrs.$observe 'validator', (value) -> # remove old rule rules.length = 0 registerRequired() if observerRequired.validatorRequired or observerRequired.required # validat by RegExp match = value.match /^\/(.*)\/$/ if match rule = $validator.convertRule 'dynamic', validator: RegExp match[1] invoke: attrs.validatorInvoke error: attrs.validatorError rules.push rule return # validat by rules match = value.match /^\[(.*)\]$/ if match ruleNames = match[1].split ',' for name in ruleNames # stupid browser has no .trim() rule = $validator.getRule name.replace(/^\s+|\s+$/g, '') rule.init? scope, element, attrs, $injector rules.push rule if rule attrs.$observe 'validatorError', (value) -> match = attrs.validator.match /^\/(.*)\/$/ if match removeRule 'dynamic' rule = $validator.convertRule 'dynamic', validator: RegExp match[1] invoke: attrs.validatorInvoke error: value rules.push rule # validate by required attribute observerRequired = validatorRequired: no required: no attrs.$observe 'validatorRequired', (value) -> if value and value isnt 'false' # register required registerRequired() observerRequired.validatorRequired = yes else if observerRequired.validatorRequired # remove required removeRule 'required' observerRequired.validatorRequired = no attrs.$observe 'required', (value) -> if value and value isnt 'false' # register required registerRequired() observerRequired.required = yes else if observerRequired.required # remove required removeRule 'required' observerRequired.required = no # ---------------------------------------- # listen # ---------------------------------------- isAcceptTheBroadcast = (broadcast, modelName) -> if modelName # is match validator-group? return yes if attrs.validatorGroup is modelName if broadcast.targetScope is scope # check ngModel and validate model are same. return attrs.ngModel.indexOf(modelName) is 0 else # current scope is different maybe create by scope.$new() or in the ng-repeat anyHashKey = (targetModel, hashKey) -> for key of targetModel x = targetModel[key] switch typeof x when 'string' return yes if key is '$$hashKey' and x is hashKey when 'object' return yes if anyHashKey x, hashKey else no # the model of the scope in ng-repeat dotIndex = attrs.ngModel.indexOf '.' itemExpression = if dotIndex >= 0 then attrs.ngModel.substr(0, dotIndex) else attrs.ngModel itemModel = $parse(itemExpression) scope return anyHashKey $parse(modelName)(broadcast.targetScope), itemModel.$$hashKey yes scope.$on $validator.broadcastChannel.prepare, (self, object) -> return if not isAcceptTheBroadcast self, object.model object.accept() scope.$on $validator.broadcastChannel.start, (self, object) -> return if not isAcceptTheBroadcast self, object.model validate 'broadcast', success: object.success error: object.error scope.$on $validator.broadcastChannel.reset, (self, object) -> return if not isAcceptTheBroadcast self, object.model for rule in rules rule.success model(scope), scope, element, attrs, $injector rule.enableError = no if rule.invoke isnt 'watch' return # ---------------------------------------- # watch # ---------------------------------------- scope.$watch attrs.ngModel, (newValue, oldValue) -> return if newValue is oldValue # first validate 'watch', oldValue: oldValue # ---------------------------------------- # blur # ---------------------------------------- $(element).bind 'blur', -> scope.$apply -> validate 'blur' ]
98103
$ = angular.element angular.module 'validator.directive', ['validator.provider'] .directive 'validator', ['$injector', ($injector) -> restrict: 'A' require: 'ngModel' link: (scope, element, attrs, ctrl) -> # ---------------------------------------- # providers # ---------------------------------------- $validator = $injector.get '$validator' $parse = $injector.get '$parse' # ---------------------------------------- # valuables # ---------------------------------------- model = $parse attrs.ngModel rules = [] # ---------------------------------------- # private methods # ---------------------------------------- validate = (from, args={}) -> ### Validate this element with all rules. @param from: 'watch', 'blur' or 'broadcast' @param args: success(): success callback (this callback will return success count) error(): error callback (this callback will return error count) oldValue: the old value of $watch ### successCount = 0 errorCount = 0 increaseSuccessCount = -> if ++successCount is rules.length ctrl.$setValidity attrs.ngModel, yes rule.success model(scope), scope, element, attrs, $injector for rule in rules args.success?() return for rule in rules switch from when 'blur' continue if rule.invoke isnt 'blur' rule.enableError = yes when 'watch' if rule.invoke isnt 'watch' and not rule.enableError increaseSuccessCount() continue when 'broadcast' then rule.enableError = yes else # validate do (rule) -> # success() and error() call back will run in other thread rule.validator model(scope), scope, element, attrs, success: -> increaseSuccessCount() error: -> if rule.enableError and ++errorCount is 1 ctrl.$setValidity attrs.ngModel, no rule.error model(scope), scope, element, attrs, $injector if args.error?() is 1 # scroll to the first element try element[0].scrollIntoViewIfNeeded() element[0].select() registerRequired = -> rule = $validator.getRule 'required' rule ?= $validator.convertRule 'required', validator: /^.+$/ invoke: 'watch' rules.push rule removeRule = (name) -> ### Remove the rule in rules by the name. ### for index in [0...rules.length] by 1 when rules[index]?.name is name rules[index].success model(scope), scope, element, attrs, $injector rules.splice index, 1 index-- # ---------------------------------------- # attrs.$observe # ---------------------------------------- attrs.$observe 'validator', (value) -> # remove old rule rules.length = 0 registerRequired() if observerRequired.validatorRequired or observerRequired.required # validat by RegExp match = value.match /^\/(.*)\/$/ if match rule = $validator.convertRule 'dynamic', validator: RegExp match[1] invoke: attrs.validatorInvoke error: attrs.validatorError rules.push rule return # validat by rules match = value.match /^\[(.*)\]$/ if match ruleNames = match[1].split ',' for name in ruleNames # stupid browser has no .trim() rule = $validator.getRule name.replace(/^\s+|\s+$/g, '') rule.init? scope, element, attrs, $injector rules.push rule if rule attrs.$observe 'validatorError', (value) -> match = attrs.validator.match /^\/(.*)\/$/ if match removeRule 'dynamic' rule = $validator.convertRule 'dynamic', validator: RegExp match[1] invoke: attrs.validatorInvoke error: value rules.push rule # validate by required attribute observerRequired = validatorRequired: no required: no attrs.$observe 'validatorRequired', (value) -> if value and value isnt 'false' # register required registerRequired() observerRequired.validatorRequired = yes else if observerRequired.validatorRequired # remove required removeRule 'required' observerRequired.validatorRequired = no attrs.$observe 'required', (value) -> if value and value isnt 'false' # register required registerRequired() observerRequired.required = yes else if observerRequired.required # remove required removeRule 'required' observerRequired.required = no # ---------------------------------------- # listen # ---------------------------------------- isAcceptTheBroadcast = (broadcast, modelName) -> if modelName # is match validator-group? return yes if attrs.validatorGroup is modelName if broadcast.targetScope is scope # check ngModel and validate model are same. return attrs.ngModel.indexOf(modelName) is 0 else # current scope is different maybe create by scope.$new() or in the ng-repeat anyHashKey = (targetModel, hashKey) -> for key of targetModel x = targetModel[key] switch typeof x when 'string' return yes if key is '<KEY>' and x is hashKey when 'object' return yes if anyHashKey x, hashKey else no # the model of the scope in ng-repeat dotIndex = attrs.ngModel.indexOf '.' itemExpression = if dotIndex >= 0 then attrs.ngModel.substr(0, dotIndex) else attrs.ngModel itemModel = $parse(itemExpression) scope return anyHashKey $parse(modelName)(broadcast.targetScope), itemModel.$$hashKey yes scope.$on $validator.broadcastChannel.prepare, (self, object) -> return if not isAcceptTheBroadcast self, object.model object.accept() scope.$on $validator.broadcastChannel.start, (self, object) -> return if not isAcceptTheBroadcast self, object.model validate 'broadcast', success: object.success error: object.error scope.$on $validator.broadcastChannel.reset, (self, object) -> return if not isAcceptTheBroadcast self, object.model for rule in rules rule.success model(scope), scope, element, attrs, $injector rule.enableError = no if rule.invoke isnt 'watch' return # ---------------------------------------- # watch # ---------------------------------------- scope.$watch attrs.ngModel, (newValue, oldValue) -> return if newValue is oldValue # first validate 'watch', oldValue: oldValue # ---------------------------------------- # blur # ---------------------------------------- $(element).bind 'blur', -> scope.$apply -> validate 'blur' ]
true
$ = angular.element angular.module 'validator.directive', ['validator.provider'] .directive 'validator', ['$injector', ($injector) -> restrict: 'A' require: 'ngModel' link: (scope, element, attrs, ctrl) -> # ---------------------------------------- # providers # ---------------------------------------- $validator = $injector.get '$validator' $parse = $injector.get '$parse' # ---------------------------------------- # valuables # ---------------------------------------- model = $parse attrs.ngModel rules = [] # ---------------------------------------- # private methods # ---------------------------------------- validate = (from, args={}) -> ### Validate this element with all rules. @param from: 'watch', 'blur' or 'broadcast' @param args: success(): success callback (this callback will return success count) error(): error callback (this callback will return error count) oldValue: the old value of $watch ### successCount = 0 errorCount = 0 increaseSuccessCount = -> if ++successCount is rules.length ctrl.$setValidity attrs.ngModel, yes rule.success model(scope), scope, element, attrs, $injector for rule in rules args.success?() return for rule in rules switch from when 'blur' continue if rule.invoke isnt 'blur' rule.enableError = yes when 'watch' if rule.invoke isnt 'watch' and not rule.enableError increaseSuccessCount() continue when 'broadcast' then rule.enableError = yes else # validate do (rule) -> # success() and error() call back will run in other thread rule.validator model(scope), scope, element, attrs, success: -> increaseSuccessCount() error: -> if rule.enableError and ++errorCount is 1 ctrl.$setValidity attrs.ngModel, no rule.error model(scope), scope, element, attrs, $injector if args.error?() is 1 # scroll to the first element try element[0].scrollIntoViewIfNeeded() element[0].select() registerRequired = -> rule = $validator.getRule 'required' rule ?= $validator.convertRule 'required', validator: /^.+$/ invoke: 'watch' rules.push rule removeRule = (name) -> ### Remove the rule in rules by the name. ### for index in [0...rules.length] by 1 when rules[index]?.name is name rules[index].success model(scope), scope, element, attrs, $injector rules.splice index, 1 index-- # ---------------------------------------- # attrs.$observe # ---------------------------------------- attrs.$observe 'validator', (value) -> # remove old rule rules.length = 0 registerRequired() if observerRequired.validatorRequired or observerRequired.required # validat by RegExp match = value.match /^\/(.*)\/$/ if match rule = $validator.convertRule 'dynamic', validator: RegExp match[1] invoke: attrs.validatorInvoke error: attrs.validatorError rules.push rule return # validat by rules match = value.match /^\[(.*)\]$/ if match ruleNames = match[1].split ',' for name in ruleNames # stupid browser has no .trim() rule = $validator.getRule name.replace(/^\s+|\s+$/g, '') rule.init? scope, element, attrs, $injector rules.push rule if rule attrs.$observe 'validatorError', (value) -> match = attrs.validator.match /^\/(.*)\/$/ if match removeRule 'dynamic' rule = $validator.convertRule 'dynamic', validator: RegExp match[1] invoke: attrs.validatorInvoke error: value rules.push rule # validate by required attribute observerRequired = validatorRequired: no required: no attrs.$observe 'validatorRequired', (value) -> if value and value isnt 'false' # register required registerRequired() observerRequired.validatorRequired = yes else if observerRequired.validatorRequired # remove required removeRule 'required' observerRequired.validatorRequired = no attrs.$observe 'required', (value) -> if value and value isnt 'false' # register required registerRequired() observerRequired.required = yes else if observerRequired.required # remove required removeRule 'required' observerRequired.required = no # ---------------------------------------- # listen # ---------------------------------------- isAcceptTheBroadcast = (broadcast, modelName) -> if modelName # is match validator-group? return yes if attrs.validatorGroup is modelName if broadcast.targetScope is scope # check ngModel and validate model are same. return attrs.ngModel.indexOf(modelName) is 0 else # current scope is different maybe create by scope.$new() or in the ng-repeat anyHashKey = (targetModel, hashKey) -> for key of targetModel x = targetModel[key] switch typeof x when 'string' return yes if key is 'PI:KEY:<KEY>END_PI' and x is hashKey when 'object' return yes if anyHashKey x, hashKey else no # the model of the scope in ng-repeat dotIndex = attrs.ngModel.indexOf '.' itemExpression = if dotIndex >= 0 then attrs.ngModel.substr(0, dotIndex) else attrs.ngModel itemModel = $parse(itemExpression) scope return anyHashKey $parse(modelName)(broadcast.targetScope), itemModel.$$hashKey yes scope.$on $validator.broadcastChannel.prepare, (self, object) -> return if not isAcceptTheBroadcast self, object.model object.accept() scope.$on $validator.broadcastChannel.start, (self, object) -> return if not isAcceptTheBroadcast self, object.model validate 'broadcast', success: object.success error: object.error scope.$on $validator.broadcastChannel.reset, (self, object) -> return if not isAcceptTheBroadcast self, object.model for rule in rules rule.success model(scope), scope, element, attrs, $injector rule.enableError = no if rule.invoke isnt 'watch' return # ---------------------------------------- # watch # ---------------------------------------- scope.$watch attrs.ngModel, (newValue, oldValue) -> return if newValue is oldValue # first validate 'watch', oldValue: oldValue # ---------------------------------------- # blur # ---------------------------------------- $(element).bind 'blur', -> scope.$apply -> validate 'blur' ]
[ { "context": "alue' for i in [0..9]\n models[3].key = 'specialValue'\n\n collection = new Luca.Collection models\n\n ", "end": 2722, "score": 0.6264151930809021, "start": 2717, "tag": "KEY", "value": "Value" }, { "context": "collection = new Luca.Collection [],\n name: \"...
spec/javascripts/core/collection_spec.coffee
datapimp/luca
4
#### Luca.Collection setupCollection = ()-> window.cachedMethodOne = 0 window.cachedMethodTwo = 0 window.CachedMethodCollection = Luca.Collection.extend cachedMethods:["cachedMethodOne","cachedMethodTwo"] cachedMethodOne: ()-> window.cachedMethodOne += 1 cachedMethodTwo: ()-> window.cachedMethodTwo += 1 describe "Method Caching", -> beforeEach -> setupCollection() @collection = new CachedMethodCollection() afterEach -> @collection = undefined window.CachedMethodCollection = undefined it "should call the method", -> expect( @collection.cachedMethodOne() ).toEqual 1 it "should cache the value of the method", -> _( 5 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 1 it "should refresh the method cache upon reset of the models", -> _( 3 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 1 @collection.reset() _( 3 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 2 it "should restore the collection to the original configuration", -> @collection.restoreMethodCache() _( 5 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 6 describe "Luca.Collection", -> it "should accept a name and collection manager", -> mgr = Luca.CollectionManager.get?('collection-spec') || new Luca.CollectionManager(name:"collection-spec") collection = new Luca.Collection([], name:"booya",manager:mgr) expect( collection.name ).toEqual("booya") expect( collection.manager ).toEqual(mgr) it "should allow me to specify my own fetch method on a per collection basis", -> spy = sinon.spy() collection = new Luca.Collection([],fetch:spy) collection.fetch() expect( spy.called ).toBeTruthy() it "should trigger before:fetch", -> collection = new Luca.Collection([], url:"/models") spy = sinon.spy() collection.bind "before:fetch", spy collection.fetch() expect( spy.called ).toBeTruthy() it "should automatically parse a response with a root in it", -> collection = new Luca.Collection([], root:"root",url:"/rooted/models") collection.fetch() @server.respond() expect( collection.length ).toEqual(2) it "should attempt to register with a collection manager", -> registerSpy = sinon.spy() collection = new Luca.Collection [], name:"registered" register: registerSpy expect( registerSpy ).toHaveBeenCalled() it "should query collection with filter", -> models = [] models.push id: i, key: 'value' for i in [0..9] models[3].key = 'specialValue' collection = new Luca.Collection models collection.applyFilter key: 'specialValue' expect(collection.length).toBe 1 expect(collection.first().get('key')).toBe 'specialValue' describe "The ifLoaded helper", -> it "should fire the passed callback automatically if there are models", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}]) collection.ifLoaded(spy) expect( spy.callCount ).toEqual(1) it "should fire the passed callback any time the collection resets", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}], url:"/models") collection.ifLoaded ()-> spy.call() collection.fetch() @server.respond() expect( spy.callCount ).toEqual(2) it "should not fire the callback if there are no models", -> spy = sinon.spy() collection = new Luca.Collection() collection.ifLoaded(spy) expect( spy.called ).toBeFalsy() it "should automatically call fetch on the collection", -> spy = sinon.spy() collection = new Luca.Collection([],url:"/models",blah:true) collection.ifLoaded(spy) @server.respond() expect( spy.called ).toBeTruthy() it "should allow me to not automatically call fetch on the collection", -> collection = new Luca.Collection([],url:"/models") spy = sinon.spy( collection.fetch ) fn = ()-> true collection.ifLoaded(fn, autoFetch:false) expect( spy.called ).toBeFalsy() describe "The onceLoaded helper", -> it "should fire the passed callback once if there are models", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}]) collection.onceLoaded(spy) expect( spy.callCount ).toEqual(1) it "should fire the passed callback only once", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}],url:"/models") collection.onceLoaded(spy) expect( spy.callCount ).toEqual(1) collection.fetch() @server.respond() expect( spy.callCount ).toEqual(1) it "should not fire the callback if there are no models", -> spy = sinon.spy() collection = new Luca.Collection() collection.onceLoaded(spy) expect( spy.called ).toBeFalsy() it "should automatically call fetch on the collection", -> spy = sinon.spy() collection = new Luca.Collection([],url:"/models") collection.onceLoaded(spy) @server.respond() expect( spy.called ).toBeTruthy() it "should allow me to not automatically call fetch on the collection", -> collection = new Luca.Collection([],url:"/models") spy = sinon.spy( collection.fetch ) fn = ()-> true collection.onceLoaded(fn, autoFetch:false) expect( spy.called ).toBeFalsy() describe "Registering with the collection manager", -> it "should be able to find a default collection manager", -> mgr = Luca.CollectionManager.get() || new Luca.CollectionManager() expect( Luca.CollectionManager.get() ).toEqual(mgr) it "should automatically register with the manager if I specify a name", -> mgr = Luca.CollectionManager.get() || new Luca.CollectionManager() collection = new Luca.Collection([],name:"auto_register") expect( mgr.get("auto_register") ).toEqual(collection) it "should register with a specific manager", -> window.other_manager = new Luca.CollectionManager(name:"other_manager") collection = new Luca.Collection [], name: "other_collection" manager: window.other_manager expect( window.other_manager.get("other_collection") ).toEqual(collection) it "should find a collection manager by string", -> window.find_mgr_by_string = new Luca.CollectionManager(name:"find_by_string") collection = new Luca.Collection [], name: "biggie" manager: "find_mgr_by_string" expect( collection.manager ).toBeDefined() it "should not register with a collection manager if it is marked as private", -> manager = new Luca.CollectionManager(name:"private") registerSpy = sinon.spy() privateCollection = new Luca.Collection [], name: "private" manager: manager private: true register: registerSpy expect( registerSpy ).not.toHaveBeenCalled() describe "The Model Bootstrap", -> window.ModelBootstrap = sample: [] _(5).times (n)-> window.ModelBootstrap.sample.push id: n key: "value" it "should add an object into the models cache", -> Luca.Collection.bootstrap( window.ModelBootstrap ) expect( Luca.Collection.cache("sample").length ).toEqual(5) it "should fetch the cached models from the bootstrap", -> collection = new Luca.Collection [], cache_key: ()-> "sample" collection.fetch() expect( collection.length ).toEqual(5) expect( collection.pluck('id') ).toEqual([0,1,2,3,4]) it "should reference the cached models", -> collection = new Luca.Collection [], cache_key: ()-> "sample" expect( collection.cached_models().length ).toEqual(5) it "should avoid making an API call", -> spy = sinon.spy( Backbone.Collection.prototype.fetch ) collection = new Luca.Collection [], cache_key: ()-> "sample" collection.fetch() expect( spy.called ).toBeFalsy() it "should make an API call if specifically asked", -> spy = sinon.spy() collection = new Luca.Collection [], cache_key: ()-> "sample" url: ()-> "/models" collection.bind "after:response", spy collection.fetch(refresh:true) @server.respond() expect( spy.called ).toBeTruthy() describe "Base Params on the URL Method", -> beforeEach -> @collection = new Luca.Collection [], url: ()-> "/url/to/endpoint" afterEach -> Luca.Collection.resetBaseParams() it "should work with strings too", -> collection = new Luca.Collection [], url: "/string/based/url" expect( collection.url ).toEqual "/string/based/url" it "should include base params in the url", -> Luca.Collection.baseParams(base:"value") expect( @collection.url() ).toEqual '/url/to/endpoint?base=value' it "should include params in the url", -> @collection.applyParams(param:"value") expect( @collection.url() ).toEqual '/url/to/endpoint?param=value' it "should include one time params, in addition to base params", -> Luca.Collection.baseParams(base:"value") @collection.applyParams(one:"time") expect( @collection.url() ).toEqual "/url/to/endpoint?base=value&one=time"
52886
#### Luca.Collection setupCollection = ()-> window.cachedMethodOne = 0 window.cachedMethodTwo = 0 window.CachedMethodCollection = Luca.Collection.extend cachedMethods:["cachedMethodOne","cachedMethodTwo"] cachedMethodOne: ()-> window.cachedMethodOne += 1 cachedMethodTwo: ()-> window.cachedMethodTwo += 1 describe "Method Caching", -> beforeEach -> setupCollection() @collection = new CachedMethodCollection() afterEach -> @collection = undefined window.CachedMethodCollection = undefined it "should call the method", -> expect( @collection.cachedMethodOne() ).toEqual 1 it "should cache the value of the method", -> _( 5 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 1 it "should refresh the method cache upon reset of the models", -> _( 3 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 1 @collection.reset() _( 3 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 2 it "should restore the collection to the original configuration", -> @collection.restoreMethodCache() _( 5 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 6 describe "Luca.Collection", -> it "should accept a name and collection manager", -> mgr = Luca.CollectionManager.get?('collection-spec') || new Luca.CollectionManager(name:"collection-spec") collection = new Luca.Collection([], name:"booya",manager:mgr) expect( collection.name ).toEqual("booya") expect( collection.manager ).toEqual(mgr) it "should allow me to specify my own fetch method on a per collection basis", -> spy = sinon.spy() collection = new Luca.Collection([],fetch:spy) collection.fetch() expect( spy.called ).toBeTruthy() it "should trigger before:fetch", -> collection = new Luca.Collection([], url:"/models") spy = sinon.spy() collection.bind "before:fetch", spy collection.fetch() expect( spy.called ).toBeTruthy() it "should automatically parse a response with a root in it", -> collection = new Luca.Collection([], root:"root",url:"/rooted/models") collection.fetch() @server.respond() expect( collection.length ).toEqual(2) it "should attempt to register with a collection manager", -> registerSpy = sinon.spy() collection = new Luca.Collection [], name:"registered" register: registerSpy expect( registerSpy ).toHaveBeenCalled() it "should query collection with filter", -> models = [] models.push id: i, key: 'value' for i in [0..9] models[3].key = 'special<KEY>' collection = new Luca.Collection models collection.applyFilter key: 'specialValue' expect(collection.length).toBe 1 expect(collection.first().get('key')).toBe 'specialValue' describe "The ifLoaded helper", -> it "should fire the passed callback automatically if there are models", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}]) collection.ifLoaded(spy) expect( spy.callCount ).toEqual(1) it "should fire the passed callback any time the collection resets", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}], url:"/models") collection.ifLoaded ()-> spy.call() collection.fetch() @server.respond() expect( spy.callCount ).toEqual(2) it "should not fire the callback if there are no models", -> spy = sinon.spy() collection = new Luca.Collection() collection.ifLoaded(spy) expect( spy.called ).toBeFalsy() it "should automatically call fetch on the collection", -> spy = sinon.spy() collection = new Luca.Collection([],url:"/models",blah:true) collection.ifLoaded(spy) @server.respond() expect( spy.called ).toBeTruthy() it "should allow me to not automatically call fetch on the collection", -> collection = new Luca.Collection([],url:"/models") spy = sinon.spy( collection.fetch ) fn = ()-> true collection.ifLoaded(fn, autoFetch:false) expect( spy.called ).toBeFalsy() describe "The onceLoaded helper", -> it "should fire the passed callback once if there are models", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}]) collection.onceLoaded(spy) expect( spy.callCount ).toEqual(1) it "should fire the passed callback only once", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}],url:"/models") collection.onceLoaded(spy) expect( spy.callCount ).toEqual(1) collection.fetch() @server.respond() expect( spy.callCount ).toEqual(1) it "should not fire the callback if there are no models", -> spy = sinon.spy() collection = new Luca.Collection() collection.onceLoaded(spy) expect( spy.called ).toBeFalsy() it "should automatically call fetch on the collection", -> spy = sinon.spy() collection = new Luca.Collection([],url:"/models") collection.onceLoaded(spy) @server.respond() expect( spy.called ).toBeTruthy() it "should allow me to not automatically call fetch on the collection", -> collection = new Luca.Collection([],url:"/models") spy = sinon.spy( collection.fetch ) fn = ()-> true collection.onceLoaded(fn, autoFetch:false) expect( spy.called ).toBeFalsy() describe "Registering with the collection manager", -> it "should be able to find a default collection manager", -> mgr = Luca.CollectionManager.get() || new Luca.CollectionManager() expect( Luca.CollectionManager.get() ).toEqual(mgr) it "should automatically register with the manager if I specify a name", -> mgr = Luca.CollectionManager.get() || new Luca.CollectionManager() collection = new Luca.Collection([],name:"auto_register") expect( mgr.get("auto_register") ).toEqual(collection) it "should register with a specific manager", -> window.other_manager = new Luca.CollectionManager(name:"other_manager") collection = new Luca.Collection [], name: "other_collection" manager: window.other_manager expect( window.other_manager.get("other_collection") ).toEqual(collection) it "should find a collection manager by string", -> window.find_mgr_by_string = new Luca.CollectionManager(name:"find_by_string") collection = new Luca.Collection [], name: "biggie" manager: "find_mgr_by_string" expect( collection.manager ).toBeDefined() it "should not register with a collection manager if it is marked as private", -> manager = new Luca.CollectionManager(name:"private") registerSpy = sinon.spy() privateCollection = new Luca.Collection [], name: "private" manager: manager private: true register: registerSpy expect( registerSpy ).not.toHaveBeenCalled() describe "The Model Bootstrap", -> window.ModelBootstrap = sample: [] _(5).times (n)-> window.ModelBootstrap.sample.push id: n key: "value" it "should add an object into the models cache", -> Luca.Collection.bootstrap( window.ModelBootstrap ) expect( Luca.Collection.cache("sample").length ).toEqual(5) it "should fetch the cached models from the bootstrap", -> collection = new Luca.Collection [], cache_key: ()-> "sample" collection.fetch() expect( collection.length ).toEqual(5) expect( collection.pluck('id') ).toEqual([0,1,2,3,4]) it "should reference the cached models", -> collection = new Luca.Collection [], cache_key: ()-> "sample" expect( collection.cached_models().length ).toEqual(5) it "should avoid making an API call", -> spy = sinon.spy( Backbone.Collection.prototype.fetch ) collection = new Luca.Collection [], cache_key: ()-> "sample" collection.fetch() expect( spy.called ).toBeFalsy() it "should make an API call if specifically asked", -> spy = sinon.spy() collection = new Luca.Collection [], cache_key: ()-> "sample" url: ()-> "/models" collection.bind "after:response", spy collection.fetch(refresh:true) @server.respond() expect( spy.called ).toBeTruthy() describe "Base Params on the URL Method", -> beforeEach -> @collection = new Luca.Collection [], url: ()-> "/url/to/endpoint" afterEach -> Luca.Collection.resetBaseParams() it "should work with strings too", -> collection = new Luca.Collection [], url: "/string/based/url" expect( collection.url ).toEqual "/string/based/url" it "should include base params in the url", -> Luca.Collection.baseParams(base:"value") expect( @collection.url() ).toEqual '/url/to/endpoint?base=value' it "should include params in the url", -> @collection.applyParams(param:"value") expect( @collection.url() ).toEqual '/url/to/endpoint?param=value' it "should include one time params, in addition to base params", -> Luca.Collection.baseParams(base:"value") @collection.applyParams(one:"time") expect( @collection.url() ).toEqual "/url/to/endpoint?base=value&one=time"
true
#### Luca.Collection setupCollection = ()-> window.cachedMethodOne = 0 window.cachedMethodTwo = 0 window.CachedMethodCollection = Luca.Collection.extend cachedMethods:["cachedMethodOne","cachedMethodTwo"] cachedMethodOne: ()-> window.cachedMethodOne += 1 cachedMethodTwo: ()-> window.cachedMethodTwo += 1 describe "Method Caching", -> beforeEach -> setupCollection() @collection = new CachedMethodCollection() afterEach -> @collection = undefined window.CachedMethodCollection = undefined it "should call the method", -> expect( @collection.cachedMethodOne() ).toEqual 1 it "should cache the value of the method", -> _( 5 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 1 it "should refresh the method cache upon reset of the models", -> _( 3 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 1 @collection.reset() _( 3 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 2 it "should restore the collection to the original configuration", -> @collection.restoreMethodCache() _( 5 ).times ()=> @collection.cachedMethodOne() expect( @collection.cachedMethodOne() ).toEqual 6 describe "Luca.Collection", -> it "should accept a name and collection manager", -> mgr = Luca.CollectionManager.get?('collection-spec') || new Luca.CollectionManager(name:"collection-spec") collection = new Luca.Collection([], name:"booya",manager:mgr) expect( collection.name ).toEqual("booya") expect( collection.manager ).toEqual(mgr) it "should allow me to specify my own fetch method on a per collection basis", -> spy = sinon.spy() collection = new Luca.Collection([],fetch:spy) collection.fetch() expect( spy.called ).toBeTruthy() it "should trigger before:fetch", -> collection = new Luca.Collection([], url:"/models") spy = sinon.spy() collection.bind "before:fetch", spy collection.fetch() expect( spy.called ).toBeTruthy() it "should automatically parse a response with a root in it", -> collection = new Luca.Collection([], root:"root",url:"/rooted/models") collection.fetch() @server.respond() expect( collection.length ).toEqual(2) it "should attempt to register with a collection manager", -> registerSpy = sinon.spy() collection = new Luca.Collection [], name:"registered" register: registerSpy expect( registerSpy ).toHaveBeenCalled() it "should query collection with filter", -> models = [] models.push id: i, key: 'value' for i in [0..9] models[3].key = 'specialPI:KEY:<KEY>END_PI' collection = new Luca.Collection models collection.applyFilter key: 'specialValue' expect(collection.length).toBe 1 expect(collection.first().get('key')).toBe 'specialValue' describe "The ifLoaded helper", -> it "should fire the passed callback automatically if there are models", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}]) collection.ifLoaded(spy) expect( spy.callCount ).toEqual(1) it "should fire the passed callback any time the collection resets", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}], url:"/models") collection.ifLoaded ()-> spy.call() collection.fetch() @server.respond() expect( spy.callCount ).toEqual(2) it "should not fire the callback if there are no models", -> spy = sinon.spy() collection = new Luca.Collection() collection.ifLoaded(spy) expect( spy.called ).toBeFalsy() it "should automatically call fetch on the collection", -> spy = sinon.spy() collection = new Luca.Collection([],url:"/models",blah:true) collection.ifLoaded(spy) @server.respond() expect( spy.called ).toBeTruthy() it "should allow me to not automatically call fetch on the collection", -> collection = new Luca.Collection([],url:"/models") spy = sinon.spy( collection.fetch ) fn = ()-> true collection.ifLoaded(fn, autoFetch:false) expect( spy.called ).toBeFalsy() describe "The onceLoaded helper", -> it "should fire the passed callback once if there are models", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}]) collection.onceLoaded(spy) expect( spy.callCount ).toEqual(1) it "should fire the passed callback only once", -> spy = sinon.spy() collection = new Luca.Collection([{attr:"value"}],url:"/models") collection.onceLoaded(spy) expect( spy.callCount ).toEqual(1) collection.fetch() @server.respond() expect( spy.callCount ).toEqual(1) it "should not fire the callback if there are no models", -> spy = sinon.spy() collection = new Luca.Collection() collection.onceLoaded(spy) expect( spy.called ).toBeFalsy() it "should automatically call fetch on the collection", -> spy = sinon.spy() collection = new Luca.Collection([],url:"/models") collection.onceLoaded(spy) @server.respond() expect( spy.called ).toBeTruthy() it "should allow me to not automatically call fetch on the collection", -> collection = new Luca.Collection([],url:"/models") spy = sinon.spy( collection.fetch ) fn = ()-> true collection.onceLoaded(fn, autoFetch:false) expect( spy.called ).toBeFalsy() describe "Registering with the collection manager", -> it "should be able to find a default collection manager", -> mgr = Luca.CollectionManager.get() || new Luca.CollectionManager() expect( Luca.CollectionManager.get() ).toEqual(mgr) it "should automatically register with the manager if I specify a name", -> mgr = Luca.CollectionManager.get() || new Luca.CollectionManager() collection = new Luca.Collection([],name:"auto_register") expect( mgr.get("auto_register") ).toEqual(collection) it "should register with a specific manager", -> window.other_manager = new Luca.CollectionManager(name:"other_manager") collection = new Luca.Collection [], name: "other_collection" manager: window.other_manager expect( window.other_manager.get("other_collection") ).toEqual(collection) it "should find a collection manager by string", -> window.find_mgr_by_string = new Luca.CollectionManager(name:"find_by_string") collection = new Luca.Collection [], name: "biggie" manager: "find_mgr_by_string" expect( collection.manager ).toBeDefined() it "should not register with a collection manager if it is marked as private", -> manager = new Luca.CollectionManager(name:"private") registerSpy = sinon.spy() privateCollection = new Luca.Collection [], name: "private" manager: manager private: true register: registerSpy expect( registerSpy ).not.toHaveBeenCalled() describe "The Model Bootstrap", -> window.ModelBootstrap = sample: [] _(5).times (n)-> window.ModelBootstrap.sample.push id: n key: "value" it "should add an object into the models cache", -> Luca.Collection.bootstrap( window.ModelBootstrap ) expect( Luca.Collection.cache("sample").length ).toEqual(5) it "should fetch the cached models from the bootstrap", -> collection = new Luca.Collection [], cache_key: ()-> "sample" collection.fetch() expect( collection.length ).toEqual(5) expect( collection.pluck('id') ).toEqual([0,1,2,3,4]) it "should reference the cached models", -> collection = new Luca.Collection [], cache_key: ()-> "sample" expect( collection.cached_models().length ).toEqual(5) it "should avoid making an API call", -> spy = sinon.spy( Backbone.Collection.prototype.fetch ) collection = new Luca.Collection [], cache_key: ()-> "sample" collection.fetch() expect( spy.called ).toBeFalsy() it "should make an API call if specifically asked", -> spy = sinon.spy() collection = new Luca.Collection [], cache_key: ()-> "sample" url: ()-> "/models" collection.bind "after:response", spy collection.fetch(refresh:true) @server.respond() expect( spy.called ).toBeTruthy() describe "Base Params on the URL Method", -> beforeEach -> @collection = new Luca.Collection [], url: ()-> "/url/to/endpoint" afterEach -> Luca.Collection.resetBaseParams() it "should work with strings too", -> collection = new Luca.Collection [], url: "/string/based/url" expect( collection.url ).toEqual "/string/based/url" it "should include base params in the url", -> Luca.Collection.baseParams(base:"value") expect( @collection.url() ).toEqual '/url/to/endpoint?base=value' it "should include params in the url", -> @collection.applyParams(param:"value") expect( @collection.url() ).toEqual '/url/to/endpoint?param=value' it "should include one time params, in addition to base params", -> Luca.Collection.baseParams(base:"value") @collection.applyParams(one:"time") expect( @collection.url() ).toEqual "/url/to/endpoint?base=value&one=time"
[ { "context": "-> {\n id: this.id\n name: this.alias || 'John Doe'\n mode: this.mode || { video: '2d', audio: t", "end": 1336, "score": 0.9997653961181641, "start": 1328, "tag": "NAME", "value": "John Doe" } ]
lib/chat.coffee
lugati-eu/altexo-signal-server
1
request = require 'request' JsonRpc = require './utils/json-rpc.coffee' ListenerMixin = require './utils/listener.coffee' Registry = require './registry.coffee' module.exports = (config, logger, KurentoRoom, P2pRoom) -> class ChatRpc extends JsonRpc Object.assign( @::, ListenerMixin ) registry = new Registry() rooms = new Map() ChatError = { NOT_AUTHENTICATED: { code: 1001, message: 'not authenticated' } PEER_NOT_FOUND: { code: 1002, message: 'peer is not found'} ROOM_NOT_FOUND: { code: 1003, message: 'room is not found' } CURRENT_ROOM_PRESENT: { code: 1004, message: 'current room is already present' } NO_CURRENT_ROOM: { code: 1005, message: 'no current room' } ROOM_NAME_OCCUPIED: { code: 1006, message: 'room name occupied' } NOT_AUTHORIZED: { code: 1007, message: 'not authorized' } REQUEST_AUTH_ERROR: \ (e) -> { code: - 32000, message: "#{e.toString()}" } } _rawError = (e) -> unless e.code and e.message Promise.reject { code: -32001, message: "#{e.message}" } else Promise.reject(e) id: null isAuthenticated: false room: null alias: null mode: null getContactInfo: -> { id: this.id name: this.alias || 'John Doe' mode: this.mode || { video: '2d', audio: true } } rpc: { 'id': -> this.id 'authenticate': (token) -> auth = new Promise (resolve, reject) -> authRequest = { url: config.get('auth:me') headers: { 'Authorization': "Token #{token}" # NOTE: needed to turn off debug mode in django # 'Host': 'localhost' } } request authRequest, (error, response, body) -> if error return reject(ChatError.REQUEST_AUTH_ERROR(error)) unless response.statusCode == 200 return reject(ChatError.NOT_AUTHENTICATED) resolve(true) return auth.then => this.isAuthenticated = true 'room/open': (name, p2p) -> # unless this.isAuthenticated # return Promise.reject(ChatError.NOT_AUTHENTICATED) if this.room return Promise.reject(ChatError.CURRENT_ROOM_PRESENT) if rooms.has(name) return Promise.reject(ChatError.ROOM_NAME_OCCUPIED) # TODO: make this decision based on payment unless p2p # room = new KurentoRoom(name) return Promise.reject(ChatError.NOT_AUTHENTICATED) else room = new P2pRoom(name) room.create(this) .then => this.connectRoom(rooms.set(name, room).get(name)) .then => logger.info({ p2p, room: name, user: this.id }, 'room created') .then => this.room.getProfile() .then null, _rawError 'room/enter': (name) -> if this.room return Promise.reject(ChatError.CURRENT_ROOM_PRESENT) unless rooms.has(name) return Promise.reject(ChatError.ROOM_NOT_FOUND) rooms.get(name).addUser(this) .then => this.connectRoom(rooms.get(name)) .then => logger.info({ room: name, user: this.id }, 'room entered') .then => this.room.getProfile() .then null, _rawError 'room/close': -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) unless this is this.room.creator return Promise.reject(ChatError.NOT_AUTHORIZED) this.disconnectRoom() .then -> true .then null, _rawError 'room/leave': -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) this.disconnectRoom() .then -> true .then null, _rawError 'room/offer': (offerSdp) -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) this.room.processOffer(this, offerSdp) .then null, _rawError 'peer/restart': -> unless this.room return Promise.reject(ChatRpc.NO_CURRENT_ROOM) this.room.restartPeer(this) } rpcNotify: { 'user/alias': (name) -> this.alias = "#{name}" if this.room this.room.members.forEach (user) -> user.sendContactList() return 'user/mode': (value) -> this.mode = value if this.room this.room.members.forEach (user) => user.sendContactList() return 'room/text': (text) -> if this.room contact = this.getContactInfo() this.room.members.forEach (user) -> user.notify('room/text', [text, contact]) return 'room/ice-candidate': (candidate) -> if this.room this.room.processIceCandidate(this, candidate) return } onAttach: -> this.id = registry.add(this) this.remoteAddr = this._ws.upgradeReq.headers['x-real-ip'] || '=/=' this.userAgent = this._ws.upgradeReq.headers['user-agent'] || '=/=' onDetach: -> if this.room this.disconnectRoom() registry.remove(this.id) this.id = null sendCandidate: (candidate) -> this.notify('ice-candidate', [candidate]) sendOffer: (offerSdp) -> this.request('offer', [offerSdp]) sendContactList: -> this.notify('room/contacts', [this.room.getContacts()]) sendRestart: -> this.request('restart').then -> true connectRoom: (room) -> this.listenTo(room, 'user:enter', => this.sendContactList()) this.listenTo(room, 'user:leave', => this.sendContactList()) unless this is room.creator this.listenTo(room, 'destroy', => this.notify('room/destroy')) this.room = room disconnectRoom: -> room = this.room this.room = null this.stopListening(room) if this is room.creator logger.info({ room: room.name }, 'room closed') rooms.delete(room.name) return room.destroy() else logger.info({ room: room.name, user: this.id }, 'user quit room') return room.removeUser(this) notifyPeer: (id, method, params) -> peer = registry.getPeer(id) unless peer return peer.notify(method, params) requestPeer: (id, method, params) -> peer = registry.getPeer(id) unless peer return Promise.reject(ChatError.PEER_NOT_FOUND) peer.request(method, params)
158569
request = require 'request' JsonRpc = require './utils/json-rpc.coffee' ListenerMixin = require './utils/listener.coffee' Registry = require './registry.coffee' module.exports = (config, logger, KurentoRoom, P2pRoom) -> class ChatRpc extends JsonRpc Object.assign( @::, ListenerMixin ) registry = new Registry() rooms = new Map() ChatError = { NOT_AUTHENTICATED: { code: 1001, message: 'not authenticated' } PEER_NOT_FOUND: { code: 1002, message: 'peer is not found'} ROOM_NOT_FOUND: { code: 1003, message: 'room is not found' } CURRENT_ROOM_PRESENT: { code: 1004, message: 'current room is already present' } NO_CURRENT_ROOM: { code: 1005, message: 'no current room' } ROOM_NAME_OCCUPIED: { code: 1006, message: 'room name occupied' } NOT_AUTHORIZED: { code: 1007, message: 'not authorized' } REQUEST_AUTH_ERROR: \ (e) -> { code: - 32000, message: "#{e.toString()}" } } _rawError = (e) -> unless e.code and e.message Promise.reject { code: -32001, message: "#{e.message}" } else Promise.reject(e) id: null isAuthenticated: false room: null alias: null mode: null getContactInfo: -> { id: this.id name: this.alias || '<NAME>' mode: this.mode || { video: '2d', audio: true } } rpc: { 'id': -> this.id 'authenticate': (token) -> auth = new Promise (resolve, reject) -> authRequest = { url: config.get('auth:me') headers: { 'Authorization': "Token #{token}" # NOTE: needed to turn off debug mode in django # 'Host': 'localhost' } } request authRequest, (error, response, body) -> if error return reject(ChatError.REQUEST_AUTH_ERROR(error)) unless response.statusCode == 200 return reject(ChatError.NOT_AUTHENTICATED) resolve(true) return auth.then => this.isAuthenticated = true 'room/open': (name, p2p) -> # unless this.isAuthenticated # return Promise.reject(ChatError.NOT_AUTHENTICATED) if this.room return Promise.reject(ChatError.CURRENT_ROOM_PRESENT) if rooms.has(name) return Promise.reject(ChatError.ROOM_NAME_OCCUPIED) # TODO: make this decision based on payment unless p2p # room = new KurentoRoom(name) return Promise.reject(ChatError.NOT_AUTHENTICATED) else room = new P2pRoom(name) room.create(this) .then => this.connectRoom(rooms.set(name, room).get(name)) .then => logger.info({ p2p, room: name, user: this.id }, 'room created') .then => this.room.getProfile() .then null, _rawError 'room/enter': (name) -> if this.room return Promise.reject(ChatError.CURRENT_ROOM_PRESENT) unless rooms.has(name) return Promise.reject(ChatError.ROOM_NOT_FOUND) rooms.get(name).addUser(this) .then => this.connectRoom(rooms.get(name)) .then => logger.info({ room: name, user: this.id }, 'room entered') .then => this.room.getProfile() .then null, _rawError 'room/close': -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) unless this is this.room.creator return Promise.reject(ChatError.NOT_AUTHORIZED) this.disconnectRoom() .then -> true .then null, _rawError 'room/leave': -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) this.disconnectRoom() .then -> true .then null, _rawError 'room/offer': (offerSdp) -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) this.room.processOffer(this, offerSdp) .then null, _rawError 'peer/restart': -> unless this.room return Promise.reject(ChatRpc.NO_CURRENT_ROOM) this.room.restartPeer(this) } rpcNotify: { 'user/alias': (name) -> this.alias = "#{name}" if this.room this.room.members.forEach (user) -> user.sendContactList() return 'user/mode': (value) -> this.mode = value if this.room this.room.members.forEach (user) => user.sendContactList() return 'room/text': (text) -> if this.room contact = this.getContactInfo() this.room.members.forEach (user) -> user.notify('room/text', [text, contact]) return 'room/ice-candidate': (candidate) -> if this.room this.room.processIceCandidate(this, candidate) return } onAttach: -> this.id = registry.add(this) this.remoteAddr = this._ws.upgradeReq.headers['x-real-ip'] || '=/=' this.userAgent = this._ws.upgradeReq.headers['user-agent'] || '=/=' onDetach: -> if this.room this.disconnectRoom() registry.remove(this.id) this.id = null sendCandidate: (candidate) -> this.notify('ice-candidate', [candidate]) sendOffer: (offerSdp) -> this.request('offer', [offerSdp]) sendContactList: -> this.notify('room/contacts', [this.room.getContacts()]) sendRestart: -> this.request('restart').then -> true connectRoom: (room) -> this.listenTo(room, 'user:enter', => this.sendContactList()) this.listenTo(room, 'user:leave', => this.sendContactList()) unless this is room.creator this.listenTo(room, 'destroy', => this.notify('room/destroy')) this.room = room disconnectRoom: -> room = this.room this.room = null this.stopListening(room) if this is room.creator logger.info({ room: room.name }, 'room closed') rooms.delete(room.name) return room.destroy() else logger.info({ room: room.name, user: this.id }, 'user quit room') return room.removeUser(this) notifyPeer: (id, method, params) -> peer = registry.getPeer(id) unless peer return peer.notify(method, params) requestPeer: (id, method, params) -> peer = registry.getPeer(id) unless peer return Promise.reject(ChatError.PEER_NOT_FOUND) peer.request(method, params)
true
request = require 'request' JsonRpc = require './utils/json-rpc.coffee' ListenerMixin = require './utils/listener.coffee' Registry = require './registry.coffee' module.exports = (config, logger, KurentoRoom, P2pRoom) -> class ChatRpc extends JsonRpc Object.assign( @::, ListenerMixin ) registry = new Registry() rooms = new Map() ChatError = { NOT_AUTHENTICATED: { code: 1001, message: 'not authenticated' } PEER_NOT_FOUND: { code: 1002, message: 'peer is not found'} ROOM_NOT_FOUND: { code: 1003, message: 'room is not found' } CURRENT_ROOM_PRESENT: { code: 1004, message: 'current room is already present' } NO_CURRENT_ROOM: { code: 1005, message: 'no current room' } ROOM_NAME_OCCUPIED: { code: 1006, message: 'room name occupied' } NOT_AUTHORIZED: { code: 1007, message: 'not authorized' } REQUEST_AUTH_ERROR: \ (e) -> { code: - 32000, message: "#{e.toString()}" } } _rawError = (e) -> unless e.code and e.message Promise.reject { code: -32001, message: "#{e.message}" } else Promise.reject(e) id: null isAuthenticated: false room: null alias: null mode: null getContactInfo: -> { id: this.id name: this.alias || 'PI:NAME:<NAME>END_PI' mode: this.mode || { video: '2d', audio: true } } rpc: { 'id': -> this.id 'authenticate': (token) -> auth = new Promise (resolve, reject) -> authRequest = { url: config.get('auth:me') headers: { 'Authorization': "Token #{token}" # NOTE: needed to turn off debug mode in django # 'Host': 'localhost' } } request authRequest, (error, response, body) -> if error return reject(ChatError.REQUEST_AUTH_ERROR(error)) unless response.statusCode == 200 return reject(ChatError.NOT_AUTHENTICATED) resolve(true) return auth.then => this.isAuthenticated = true 'room/open': (name, p2p) -> # unless this.isAuthenticated # return Promise.reject(ChatError.NOT_AUTHENTICATED) if this.room return Promise.reject(ChatError.CURRENT_ROOM_PRESENT) if rooms.has(name) return Promise.reject(ChatError.ROOM_NAME_OCCUPIED) # TODO: make this decision based on payment unless p2p # room = new KurentoRoom(name) return Promise.reject(ChatError.NOT_AUTHENTICATED) else room = new P2pRoom(name) room.create(this) .then => this.connectRoom(rooms.set(name, room).get(name)) .then => logger.info({ p2p, room: name, user: this.id }, 'room created') .then => this.room.getProfile() .then null, _rawError 'room/enter': (name) -> if this.room return Promise.reject(ChatError.CURRENT_ROOM_PRESENT) unless rooms.has(name) return Promise.reject(ChatError.ROOM_NOT_FOUND) rooms.get(name).addUser(this) .then => this.connectRoom(rooms.get(name)) .then => logger.info({ room: name, user: this.id }, 'room entered') .then => this.room.getProfile() .then null, _rawError 'room/close': -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) unless this is this.room.creator return Promise.reject(ChatError.NOT_AUTHORIZED) this.disconnectRoom() .then -> true .then null, _rawError 'room/leave': -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) this.disconnectRoom() .then -> true .then null, _rawError 'room/offer': (offerSdp) -> unless this.room return Promise.reject(ChatError.NO_CURRENT_ROOM) this.room.processOffer(this, offerSdp) .then null, _rawError 'peer/restart': -> unless this.room return Promise.reject(ChatRpc.NO_CURRENT_ROOM) this.room.restartPeer(this) } rpcNotify: { 'user/alias': (name) -> this.alias = "#{name}" if this.room this.room.members.forEach (user) -> user.sendContactList() return 'user/mode': (value) -> this.mode = value if this.room this.room.members.forEach (user) => user.sendContactList() return 'room/text': (text) -> if this.room contact = this.getContactInfo() this.room.members.forEach (user) -> user.notify('room/text', [text, contact]) return 'room/ice-candidate': (candidate) -> if this.room this.room.processIceCandidate(this, candidate) return } onAttach: -> this.id = registry.add(this) this.remoteAddr = this._ws.upgradeReq.headers['x-real-ip'] || '=/=' this.userAgent = this._ws.upgradeReq.headers['user-agent'] || '=/=' onDetach: -> if this.room this.disconnectRoom() registry.remove(this.id) this.id = null sendCandidate: (candidate) -> this.notify('ice-candidate', [candidate]) sendOffer: (offerSdp) -> this.request('offer', [offerSdp]) sendContactList: -> this.notify('room/contacts', [this.room.getContacts()]) sendRestart: -> this.request('restart').then -> true connectRoom: (room) -> this.listenTo(room, 'user:enter', => this.sendContactList()) this.listenTo(room, 'user:leave', => this.sendContactList()) unless this is room.creator this.listenTo(room, 'destroy', => this.notify('room/destroy')) this.room = room disconnectRoom: -> room = this.room this.room = null this.stopListening(room) if this is room.creator logger.info({ room: room.name }, 'room closed') rooms.delete(room.name) return room.destroy() else logger.info({ room: room.name, user: this.id }, 'user quit room') return room.removeUser(this) notifyPeer: (id, method, params) -> peer = registry.getPeer(id) unless peer return peer.notify(method, params) requestPeer: (id, method, params) -> peer = registry.getPeer(id) unless peer return Promise.reject(ChatError.PEER_NOT_FOUND) peer.request(method, params)
[ { "context": "t-11.coffee\n# Commandment11 widget for Übersicht\n# Chris Scharff (http://tenlions.com)\n# Adapted from Wojciech Rut", "end": 76, "score": 0.9998754262924194, "start": 63, "tag": "NAME", "value": "Chris Scharff" }, { "context": "Chris Scharff (http://tenlions.com)\n# A...
commandment-11.coffee
cscharff/commandment-11
0
# commandment-11.coffee # Commandment11 widget for Übersicht # Chris Scharff (http://tenlions.com) # Adapted from Wojciech Rutkowski (http://wojciech-rutkowski.com/) and # Raphael Hanneken (behoernchen.github.io) code used from Time Words widget # both of whom did *all* the heavy lifting. # # Idea shamelessly borrowed from the folks at http://www.itstactical.com # They make some fine EDC gear if you happen to be in the market. # # Todo - clean up the hackjob of highlighting values by using a random selection function. # Todo - pupulate the text values from a OTP genrator style: """ top: auto bottom: 10% right: 10px width: 20% font-family: 'Andale Mono', sans-serif color: rgba(145, 145, 145, .8) font-weight: 50 text-align: left text-transform: uppercase font-size: 2vw letter-spacing: 0.535em font-smoothing: antialiased line-height: 1.1em text-shadow: 1px 1px 0px rgba(0, 0, 0, .1) .active color: rgba(245, 245, 245, 1) text-shadow: 1px 1px 0px rgba(105, 105, 105, .4) .cursor-on color: rgba(245, 245, 245, 1) animation: blink 1s cubic-bezier(0.950, 0.050, 0.795, 0.035) infinite alternate """ # Get the current hour as word. command: "" # Lower the frequency for more accuracy. refreshFrequency: (1000 * 95) # (1000 * n) seconds render: (o) -> """ <div id="content"> <style> @-webkit-keyframes blink { from { opacity: 1; } to { opacity: 0.2; } } </style> <span id="A01">A</span><span id="A02">5</span><span id="A03">Q</span><span id="A04">F</span><span id="A05">O</span><span id="A06">8</span><span id="A07">K</span><span id="A08">9</span><br> <span id="B01">N</span><span id="B02">7</span><span id="B03">U</span><span id="B04">5</span><span id="thou">THOU</span><br> <span id="C01">9</span><span id="C02">4</span><span id="C03">J</span><span id="C04">A</span><span id="C05">Q</span><span id="C06">F</span><span id="C07">A</span><span id="C08">O</span><br> <span id="shalt">SHALT</span><span id="D06">8</span><span id="D07">9</span><span id="D08">D</span><br> <span id="E01">A</span><span id="E02">J</span><span id="E03">C</span><span id="E04">5</span><span id="E05">4</span><span id="E06">S</span><span id="E07">2</span><span id="E08">C</span><br> <span id="F01">H</span><span id="F02">1</span><span id="F03">V</span><span id="F04">3</span><span id="F05">X</span><span id="not">NOT</span><br> <span id="G01">K</span><span id="G02">8</span><span id="G03">Q</span><span id="G04">5</span><span id="G05">2</span><span id="G06">8</span><span id="G07">O</span><span id="G08">4</span><br> <span id="H01">F</span><span id="get">GET</span><span id="H05">J</span><span id="H06">S</span><span id="H07">9</span><span id="H08">V</span> <span id="I01">U</span><span id="I02">5</span><span id="I03">O</span><span id="I04>3</span><span id="I05">H</span><span id="I06">C</span><span id="I07">P</span><span id="I08">7</span><br> <span id="J01">4</span><span id="J02">1</span><span id="caught">CAUGHT</span> <span id="K01">X</span><span id="K02">9</span><span id="K03">N</span><span id="K04">Q</span><span id="K05">B</span><span id="K06">5</span><span id="cursor">&#9646</span> </div> """ update: (output, dom) -> date = new Date() minute = date.getMinutes() hours = date.getHours() $(dom).find(".active").removeClass("active") span_ids = ['A01', 'A02', 'A03', 'A04', 'A05', 'A06', 'A07', 'A08', 'B02', 'B02', 'B04', 'C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'C07', 'C08', 'D06', 'D07', 'D08', 'E01', 'E02', 'E03', 'E04', 'E05', 'E06', 'E07', 'E08','F01', 'F02', 'F03', 'F04', 'F05','G01', 'G02', 'G03', 'G04', 'G05', 'G06', 'G07', 'G08','H01', 'H05', 'H06', 'H07', 'H08','I01', 'I02', 'I03', 'I04', 'I05', 'I06', 'I07', 'I08','J01', 'J02','K01', 'K02', 'K03', 'K04', 'K05', 'K06', 'cursor'] if minute <= 2 || minute >= 58 $(dom).find("#thou").addClass("active") $(dom).find("#shalt").addClass("active") $(dom).find("#not").addClass("active") $(dom).find("#get").addClass("active") $(dom).find("#caught").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 3 && minute <= 7 || minute >= 53 && minute <= 57 $(dom).find("#A01").addClass("active") $(dom).find("#B04").addClass("active") $(dom).find("#C05").addClass("active") $(dom).find("#G06").addClass("active") else if minute >= 8 && minute <= 12 || minute >= 48 && minute <= 52 $(dom).find("#B04").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#I03").addClass("active") $(dom).find("#K06").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 13 && minute <= 17 || minute >= 43 && minute <= 47 $(dom).find("#A09").addClass("active") $(dom).find("#B02").addClass("active") $(dom).find("#C06").addClass("active") $(dom).find("#G01").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#H07").addClass("active") $(dom).find("#I01").addClass("active") $(dom).find("#J04").addClass("active") else if minute >= 18 && minute <= 22 || minute >= 38 && minute <= 42 $(dom).find("#C01").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#H08").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 23 && minute <= 27 || minute >= 33 && minute <= 37 $(dom).find("#A07").addClass("active") $(dom).find("#B04").addClass("active") $(dom).find("#B05").addClass("active") $(dom).find("#E01").addClass("active") $(dom).find("#E08").addClass("active") $(dom).find("#H01").addClass("active") $(dom).find("#H05").addClass("active") $(dom).find("#J04").addClass("active") else if minute >= 28 && minute <= 32 $(dom).find("#B04").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#I03").addClass("active") $(dom).find("#K06").addClass("active") $(dom).find("#A09").addClass("active") $(dom).find("#B02").addClass("active") $(dom).find("#C06").addClass("active") $(dom).find("#G01").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#H07").addClass("active") $(dom).find("#I01").addClass("active") $(dom).find("#J04").addClass("active") $(dom).find("#cursor").addClass("cursor-on")
84847
# commandment-11.coffee # Commandment11 widget for Übersicht # <NAME> (http://tenlions.com) # Adapted from <NAME> (http://wojciech-rutkowski.com/) and # <NAME> (behoernchen.github.io) code used from Time Words widget # both of whom did *all* the heavy lifting. # # Idea shamelessly borrowed from the folks at http://www.itstactical.com # They make some fine EDC gear if you happen to be in the market. # # Todo - clean up the hackjob of highlighting values by using a random selection function. # Todo - pupulate the text values from a OTP genrator style: """ top: auto bottom: 10% right: 10px width: 20% font-family: 'Andale Mono', sans-serif color: rgba(145, 145, 145, .8) font-weight: 50 text-align: left text-transform: uppercase font-size: 2vw letter-spacing: 0.535em font-smoothing: antialiased line-height: 1.1em text-shadow: 1px 1px 0px rgba(0, 0, 0, .1) .active color: rgba(245, 245, 245, 1) text-shadow: 1px 1px 0px rgba(105, 105, 105, .4) .cursor-on color: rgba(245, 245, 245, 1) animation: blink 1s cubic-bezier(0.950, 0.050, 0.795, 0.035) infinite alternate """ # Get the current hour as word. command: "" # Lower the frequency for more accuracy. refreshFrequency: (1000 * 95) # (1000 * n) seconds render: (o) -> """ <div id="content"> <style> @-webkit-keyframes blink { from { opacity: 1; } to { opacity: 0.2; } } </style> <span id="A01">A</span><span id="A02">5</span><span id="A03">Q</span><span id="A04">F</span><span id="A05">O</span><span id="A06">8</span><span id="A07">K</span><span id="A08">9</span><br> <span id="B01">N</span><span id="B02">7</span><span id="B03">U</span><span id="B04">5</span><span id="thou">THOU</span><br> <span id="C01">9</span><span id="C02">4</span><span id="C03">J</span><span id="C04">A</span><span id="C05">Q</span><span id="C06">F</span><span id="C07">A</span><span id="C08">O</span><br> <span id="shalt">SHALT</span><span id="D06">8</span><span id="D07">9</span><span id="D08">D</span><br> <span id="E01">A</span><span id="E02">J</span><span id="E03">C</span><span id="E04">5</span><span id="E05">4</span><span id="E06">S</span><span id="E07">2</span><span id="E08">C</span><br> <span id="F01">H</span><span id="F02">1</span><span id="F03">V</span><span id="F04">3</span><span id="F05">X</span><span id="not">NOT</span><br> <span id="G01">K</span><span id="G02">8</span><span id="G03">Q</span><span id="G04">5</span><span id="G05">2</span><span id="G06">8</span><span id="G07">O</span><span id="G08">4</span><br> <span id="H01">F</span><span id="get">GET</span><span id="H05">J</span><span id="H06">S</span><span id="H07">9</span><span id="H08">V</span> <span id="I01">U</span><span id="I02">5</span><span id="I03">O</span><span id="I04>3</span><span id="I05">H</span><span id="I06">C</span><span id="I07">P</span><span id="I08">7</span><br> <span id="J01">4</span><span id="J02">1</span><span id="caught">CAUGHT</span> <span id="K01">X</span><span id="K02">9</span><span id="K03">N</span><span id="K04">Q</span><span id="K05">B</span><span id="K06">5</span><span id="cursor">&#9646</span> </div> """ update: (output, dom) -> date = new Date() minute = date.getMinutes() hours = date.getHours() $(dom).find(".active").removeClass("active") span_ids = ['A01', 'A02', 'A03', 'A04', 'A05', 'A06', 'A07', 'A08', 'B02', 'B02', 'B04', 'C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'C07', 'C08', 'D06', 'D07', 'D08', 'E01', 'E02', 'E03', 'E04', 'E05', 'E06', 'E07', 'E08','F01', 'F02', 'F03', 'F04', 'F05','G01', 'G02', 'G03', 'G04', 'G05', 'G06', 'G07', 'G08','H01', 'H05', 'H06', 'H07', 'H08','I01', 'I02', 'I03', 'I04', 'I05', 'I06', 'I07', 'I08','J01', 'J02','K01', 'K02', 'K03', 'K04', 'K05', 'K06', 'cursor'] if minute <= 2 || minute >= 58 $(dom).find("#thou").addClass("active") $(dom).find("#shalt").addClass("active") $(dom).find("#not").addClass("active") $(dom).find("#get").addClass("active") $(dom).find("#caught").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 3 && minute <= 7 || minute >= 53 && minute <= 57 $(dom).find("#A01").addClass("active") $(dom).find("#B04").addClass("active") $(dom).find("#C05").addClass("active") $(dom).find("#G06").addClass("active") else if minute >= 8 && minute <= 12 || minute >= 48 && minute <= 52 $(dom).find("#B04").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#I03").addClass("active") $(dom).find("#K06").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 13 && minute <= 17 || minute >= 43 && minute <= 47 $(dom).find("#A09").addClass("active") $(dom).find("#B02").addClass("active") $(dom).find("#C06").addClass("active") $(dom).find("#G01").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#H07").addClass("active") $(dom).find("#I01").addClass("active") $(dom).find("#J04").addClass("active") else if minute >= 18 && minute <= 22 || minute >= 38 && minute <= 42 $(dom).find("#C01").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#H08").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 23 && minute <= 27 || minute >= 33 && minute <= 37 $(dom).find("#A07").addClass("active") $(dom).find("#B04").addClass("active") $(dom).find("#B05").addClass("active") $(dom).find("#E01").addClass("active") $(dom).find("#E08").addClass("active") $(dom).find("#H01").addClass("active") $(dom).find("#H05").addClass("active") $(dom).find("#J04").addClass("active") else if minute >= 28 && minute <= 32 $(dom).find("#B04").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#I03").addClass("active") $(dom).find("#K06").addClass("active") $(dom).find("#A09").addClass("active") $(dom).find("#B02").addClass("active") $(dom).find("#C06").addClass("active") $(dom).find("#G01").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#H07").addClass("active") $(dom).find("#I01").addClass("active") $(dom).find("#J04").addClass("active") $(dom).find("#cursor").addClass("cursor-on")
true
# commandment-11.coffee # Commandment11 widget for Übersicht # PI:NAME:<NAME>END_PI (http://tenlions.com) # Adapted from PI:NAME:<NAME>END_PI (http://wojciech-rutkowski.com/) and # PI:NAME:<NAME>END_PI (behoernchen.github.io) code used from Time Words widget # both of whom did *all* the heavy lifting. # # Idea shamelessly borrowed from the folks at http://www.itstactical.com # They make some fine EDC gear if you happen to be in the market. # # Todo - clean up the hackjob of highlighting values by using a random selection function. # Todo - pupulate the text values from a OTP genrator style: """ top: auto bottom: 10% right: 10px width: 20% font-family: 'Andale Mono', sans-serif color: rgba(145, 145, 145, .8) font-weight: 50 text-align: left text-transform: uppercase font-size: 2vw letter-spacing: 0.535em font-smoothing: antialiased line-height: 1.1em text-shadow: 1px 1px 0px rgba(0, 0, 0, .1) .active color: rgba(245, 245, 245, 1) text-shadow: 1px 1px 0px rgba(105, 105, 105, .4) .cursor-on color: rgba(245, 245, 245, 1) animation: blink 1s cubic-bezier(0.950, 0.050, 0.795, 0.035) infinite alternate """ # Get the current hour as word. command: "" # Lower the frequency for more accuracy. refreshFrequency: (1000 * 95) # (1000 * n) seconds render: (o) -> """ <div id="content"> <style> @-webkit-keyframes blink { from { opacity: 1; } to { opacity: 0.2; } } </style> <span id="A01">A</span><span id="A02">5</span><span id="A03">Q</span><span id="A04">F</span><span id="A05">O</span><span id="A06">8</span><span id="A07">K</span><span id="A08">9</span><br> <span id="B01">N</span><span id="B02">7</span><span id="B03">U</span><span id="B04">5</span><span id="thou">THOU</span><br> <span id="C01">9</span><span id="C02">4</span><span id="C03">J</span><span id="C04">A</span><span id="C05">Q</span><span id="C06">F</span><span id="C07">A</span><span id="C08">O</span><br> <span id="shalt">SHALT</span><span id="D06">8</span><span id="D07">9</span><span id="D08">D</span><br> <span id="E01">A</span><span id="E02">J</span><span id="E03">C</span><span id="E04">5</span><span id="E05">4</span><span id="E06">S</span><span id="E07">2</span><span id="E08">C</span><br> <span id="F01">H</span><span id="F02">1</span><span id="F03">V</span><span id="F04">3</span><span id="F05">X</span><span id="not">NOT</span><br> <span id="G01">K</span><span id="G02">8</span><span id="G03">Q</span><span id="G04">5</span><span id="G05">2</span><span id="G06">8</span><span id="G07">O</span><span id="G08">4</span><br> <span id="H01">F</span><span id="get">GET</span><span id="H05">J</span><span id="H06">S</span><span id="H07">9</span><span id="H08">V</span> <span id="I01">U</span><span id="I02">5</span><span id="I03">O</span><span id="I04>3</span><span id="I05">H</span><span id="I06">C</span><span id="I07">P</span><span id="I08">7</span><br> <span id="J01">4</span><span id="J02">1</span><span id="caught">CAUGHT</span> <span id="K01">X</span><span id="K02">9</span><span id="K03">N</span><span id="K04">Q</span><span id="K05">B</span><span id="K06">5</span><span id="cursor">&#9646</span> </div> """ update: (output, dom) -> date = new Date() minute = date.getMinutes() hours = date.getHours() $(dom).find(".active").removeClass("active") span_ids = ['A01', 'A02', 'A03', 'A04', 'A05', 'A06', 'A07', 'A08', 'B02', 'B02', 'B04', 'C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'C07', 'C08', 'D06', 'D07', 'D08', 'E01', 'E02', 'E03', 'E04', 'E05', 'E06', 'E07', 'E08','F01', 'F02', 'F03', 'F04', 'F05','G01', 'G02', 'G03', 'G04', 'G05', 'G06', 'G07', 'G08','H01', 'H05', 'H06', 'H07', 'H08','I01', 'I02', 'I03', 'I04', 'I05', 'I06', 'I07', 'I08','J01', 'J02','K01', 'K02', 'K03', 'K04', 'K05', 'K06', 'cursor'] if minute <= 2 || minute >= 58 $(dom).find("#thou").addClass("active") $(dom).find("#shalt").addClass("active") $(dom).find("#not").addClass("active") $(dom).find("#get").addClass("active") $(dom).find("#caught").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 3 && minute <= 7 || minute >= 53 && minute <= 57 $(dom).find("#A01").addClass("active") $(dom).find("#B04").addClass("active") $(dom).find("#C05").addClass("active") $(dom).find("#G06").addClass("active") else if minute >= 8 && minute <= 12 || minute >= 48 && minute <= 52 $(dom).find("#B04").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#I03").addClass("active") $(dom).find("#K06").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 13 && minute <= 17 || minute >= 43 && minute <= 47 $(dom).find("#A09").addClass("active") $(dom).find("#B02").addClass("active") $(dom).find("#C06").addClass("active") $(dom).find("#G01").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#H07").addClass("active") $(dom).find("#I01").addClass("active") $(dom).find("#J04").addClass("active") else if minute >= 18 && minute <= 22 || minute >= 38 && minute <= 42 $(dom).find("#C01").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#H08").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#cursor").addClass("cursor-on") else if minute >= 23 && minute <= 27 || minute >= 33 && minute <= 37 $(dom).find("#A07").addClass("active") $(dom).find("#B04").addClass("active") $(dom).find("#B05").addClass("active") $(dom).find("#E01").addClass("active") $(dom).find("#E08").addClass("active") $(dom).find("#H01").addClass("active") $(dom).find("#H05").addClass("active") $(dom).find("#J04").addClass("active") else if minute >= 28 && minute <= 32 $(dom).find("#B04").addClass("active") $(dom).find("#C03").addClass("active") $(dom).find("#I06").addClass("active") $(dom).find("#I03").addClass("active") $(dom).find("#K06").addClass("active") $(dom).find("#A09").addClass("active") $(dom).find("#B02").addClass("active") $(dom).find("#C06").addClass("active") $(dom).find("#G01").addClass("active") $(dom).find("#G04").addClass("active") $(dom).find("#H07").addClass("active") $(dom).find("#I01").addClass("active") $(dom).find("#J04").addClass("active") $(dom).find("#cursor").addClass("cursor-on")
[ { "context": "f they've played a card this round\n#\n# Author:\n# MattRick and KevinBehrens\n\nUtil = require \"util\"\n\nblack_ca", "end": 1057, "score": 0.9997667074203491, "start": 1049, "tag": "NAME", "value": "MattRick" }, { "context": "yed a card this round\n#\n# Author:\n# ...
src/devops-against-humanity.coffee
dev-null-matt/devops-against-humanity
3
# Description: # The robot can run a game of devops against humanity using cards from # http://devopsagainsthumanity.com # # An editorial pass was made at the crowd-sourced cards. YMMV. # # Dependencies: # None # # Configuration: # HUBOT_HIPCHAT_TOKEN # # Commands: # hubot devops card me - Returns a random devops against humanity card pair. # hubot devops start game - Starts a new devops agains humanity game # hubot devops join - Joins an existing game # hubot devops who is the dealer - Mentions the dealer # hubot devops black card - Reveals the black card for the round if you're the dealer # hubot devops current black card - Display the black card for the round # hubot devops play card <n> <m> <o> - Plays cards from your hand # hubot devops reveal cards - Reveals all the card combinations # hubot devops <n> won - Announces the winner of the round # hubot devops score - Reports the score # hubot devops list players - Lists the players in the game and if they've played a card this round # # Author: # MattRick and KevinBehrens Util = require "util" black_cards = require('./blackcards.coffee') white_cards = require('./whitecards.coffee') dahGameStorage = require('./dah-game-storage.coffee') theRobot = undefined module.exports = (robot) -> theRobot = robot robot.respond /devops card( me)?/i, (message) -> randomCompletion(message) robot.respond /devops (draw )?black card/i, (message) -> revealBlackCard(message) robot.respond /devops reveal cards/i, (message) -> revealCards(message) robot.respond /devops (what is (the )?)?current black card/i, (message) -> findCurrentBlackCard(message) robot.respond /devops ([0-9]+) won/i, (message) -> declareWinner(message) robot.respond /devops (start( new)?|new) game/i, (message) -> startNewGame(message) robot.respond /devops (I'm )?join(ing)?/i, (message) -> addSenderToGame(message) robot.respond /devops (what are )?my cards/i, (message) -> checkHand(message) robot.respond /devops play card (\d+)( \d+)?( \d+)?/i, (message) -> playCards(message) robot.respond /devops (who is the )?dealer/i, (message) -> checkDealer(message) robot.respond /devops (top |bottom )?([0-9]+ )?score/i, (message) -> reportScore(message) robot.respond /devops list players/i, (message) -> listPlayers(message) # Called directly by robot.respond()s ########################################## addSenderToGame = (message) -> sender = getSenderName(message) room = getRoomName(message) if (dahGameStorage.isSenderDealer(sender, room)) response = "You're the currently the devops dealer. Maybe ask for a black card?" else if (!dahGameStorage.getCards(sender, room).length) giveUserCards(sender, room) dahGameStorage.setUserJid(sender, room, message.message.user.jid) response = getCards(sender, room) else response = "You're already playing. Do you want to know what devops cards you have?" pmPlayer(message.message.user.jid, response) checkDealer = (message) -> dealer = dahGameStorage.getDealer(getRoomName(message)) if dealer? message.send "@#{dealer.name} is currently the devops dealer." else message.reply "there is no devops dealer currently. Maybe you should start a game?" checkHand = (message) -> cards = getCards(getSenderName(message), getRoomName(message)) pmPlayer(message.message.user.jid, cards) declareWinner = (message) -> sender = getSenderName(message) room = getRoomName(message) if dahGameStorage.getDealer(room) && dahGameStorage.isSenderDealer(sender, room) && dahGameStorage.getBlackCard(room) playedCardInfo = dahGameStorage.getAllPlayedCards(room) winnerIndex = message.match[1] players = Object.keys(playedCardInfo) if winnerIndex > 0 && winnerIndex <= players.length winningPlayer = undefined for player, play of playedCardInfo if "#{play['index']}" is "#{winnerIndex}" winningPlayer = player if winningPlayer dahGameStorage.scorePoint(winningPlayer, room) dahGameStorage.setDealer(players[randomIndex(players)], room) for player in players giveUserCards(player, room) pmPlayer(player.jid, getCards(player.name, room)) dahGameStorage.clearRoundData(room) message.send "@#{winningPlayer} won. #{winningPlayer}'s score is now #{dahGameStorage.getScore(winningPlayer, room)}." message.send "@#{dahGameStorage.getDealer(room)['name']} is the new dealer." else message.reply "I couldn't find that card combination. Have white cards been revealed?" else message.reply "there were only #{Object.keys(playedCardInfo).length} cards played. Maybe pick one of those?" else if !dahGameStorage.getDealer(room) message.reply "there is no devops dealer currently. Maybe you should start a game?" else if !dahGameStorage.isSenderDealer(sender, room) message.reply "you have to be the dealer to award points. Stop trying to cheat." else if !dahGameStorage.getBlackCard(room) message.reply "you haven't drawn a black card yet. How can you know who won?" findCurrentBlackCard = (message) -> blackCard = dahGameStorage.getBlackCard(getRoomName(message)) if (blackCard) message.send blackCard else dealer = dahGameStorage.getDealer(getRoomName(message)) if (dealer) message.send "There is no current black card. Maybe @#{dealer['name']} should draw one?" else message.reply "there isn't a black card currently. Maybe you should start a game?" listPlayers = (message) -> room = getRoomName(message) dealer = dahGameStorage.getDealer() players = [] response = [] for player, play of dahGameStorage.getAllPlayedCards(room) players.push(player) for name, player of dahGameStorage.roomData(getRoomName(message))['users'] if name in players && (! dealer? || !(dealer['name'] is name)) response.push("#{name} has played a card this round.") else if ! dealer? || !(dealer['name'] is name) response.push("#{name} has not yet played a card this round.") message.send response.join("\n") playCards = (message) -> cardIndices = [message.match[1], message.match[2], message.match[3]] sender = getSenderName(message) room = getRoomName(message) cards = dahGameStorage.getCards(sender, room) blackCard = dahGameStorage.getBlackCard(getRoomName(message)) if (dahGameStorage.getCardsPlayed(sender, room)) cardWord = "card" if (blanks > 1) cardWord = "cards" message.reply "increase your calm. You've already played your #{cardWord} this round." else if dahGameStorage.isSenderDealer(sender, room) if (blackCard) message.reply "you're currently the devops dealer. Maybe you should reveal the responses?" else message.reply "you're currently the devops dealer. Maybe ask for a black card?" else if cards.length if (blackCard) blanks = countBlackCardBlanks(blackCard) plays = [] # Get all the cards played for index in cardIndices if index? && index > 0 && index < 6 plays.push cards[index-1] else if index? message.reply "you only have 5 cards in your hand. You can't play card \##{index}." plays = undefined break else cardIndices.splice(index,cardIndices.length - index) break # Play the cards if (plays? && plays.length and plays.length == blanks) newHand = [] for card in cards if !(card in plays) newHand.push card dahGameStorage.setCards(sender, room, newHand) dahGameStorage.setCardsPlayed(sender, room, getCombinedText(blackCard, plays)) else if (plays? && plays.length) verb = "is" if (blanks > 1) verb = "are" message.reply "you specified the wrong number of cards. There #{verb} #{countBlackCardBlanks(blackCard)} blanks." cards.splice(0,0,plays) else message.reply "you're getting ahead of yourself. There is no black card in play." else message.reply "you don't have any cards. Maybe you should join the game?" randomCompletion = (message) -> black_card = drawBlackCard() random_white_cards = [] blanks = countBlackCardBlanks(black_card) for num in [1..blanks] white_card = drawWhiteCard() random_white_cards.push white_card message.send getCombinedText(black_card, random_white_cards) reportScore = (message) -> report = ["There are no scores to report."] scores = [] asc = true amount = 5 for name, player of dahGameStorage.roomData(getRoomName(message))['users'] scores.push player if scores.length > 0 report = ["The current score is:"] if (message.match[1]?) asc = message.match[1].trim().toLowerCase() == 'top' if (message.match[2]?) amount = message.match[2] scores.sort((a,b) -> if asc then b.score - a.score else a.score - b.score) scores = scores.slice(0, amount) for score in scores report.push "\t #{score['name']}: #{score['score']} points" message.send report.join("\n") revealBlackCard = (message) -> blackCard = drawBlackCard() room = getRoomName(message) if dahGameStorage.isSenderDealer(getSenderName(message),room) && !dahGameStorage.getBlackCard(room) dahGameStorage.setBlackCard(room, blackCard) message.send "Setting black card to:\n#{blackCard}" else if dahGameStorage.isSenderDealer(getSenderName(message),room) message.reply "you've already revealed the black card!" else message.reply "only the dealer can reveal the black card." revealCards = (message) -> room = getRoomName(message) if dahGameStorage.isSenderDealer(getSenderName(message), room) && dahGameStorage.getBlackCard(room) playedCardInfo = dahGameStorage.getAllPlayedCards(room) players = [] response = [] for player, play of playedCardInfo players.splice(randomIndex(players), 0, player) for player in players response.push("#{_i+1}) #{playedCardInfo[player]['completion']}") playedCardInfo[player]['index'] = _i+1 message.send response.join("\n") else dealer = dahGameStorage.getDealer(room) if dahGameStorage.isSenderDealer(getSenderName(message), room) message.reply "maybe you should set the black card before revealing white cards." else if dealer message.reply "only the dealer can reveal the combinations." message.send "@#{dealer.name}, is it time for the big reveal?" else message.reply "there is no dealer currently. Perhaps it's time to start a game?" startNewGame = (message) -> sender = getSenderName(message) room = getRoomName(message) dahGameStorage.clearRoomData(room) dahGameStorage.isSenderDealer(sender, room, true) dahGameStorage.setUserJid(sender, room, message.message.user.jid) message.send "Starting a new devops game." # Game logic helpers ########################################################### getCards = (sender, room) -> cards = [] for card in dahGameStorage.getCards(sender, room) cards.push "#{_i+1}) #{card}" if cards.length > 0 cards.join("\n") else "You have no devops cards. Maybe you should join the game?" getRoomName = (message) -> message.message.room getSenderName = (message) -> name = message.message.user.mention_name if (!name) name = message.message.user.name name giveUserCards = (sender, room) -> cards = dahGameStorage.getCards(sender, room) for num in [cards.length..4] cards.push drawWhiteCard() dahGameStorage.setCards(sender, room, cards) # Card completion helpers ###################################################### capitalizeFirstLetter = (text) -> if text.charAt(0) is '"' white_card = text.charAt(0) + text.charAt(1).toUpperCase() + text.slice(2) else white_card = text.charAt(0).toUpperCase() + text.slice(1) white_card countBlackCardBlanks = (black_card) -> (black_card.match(/__________/g) || []).length drawBlackCard = -> black_cards[randomIndex(black_cards)] drawWhiteCard = -> white_cards[randomIndex(white_cards)] getCombinedText = (black_card, random_white_cards) -> black_card_tokens = black_card.split('__________') currentWhiteCard = random_white_cards.shift() for word in black_card_tokens shouldCapitalize = ".?".indexOf(black_card_tokens[_i].trim().slice(-1)) > -1 if currentWhiteCard? if shouldCapitalize currentWhiteCard = capitalizeFirstLetter(currentWhiteCard) black_card_tokens[_i] = "#{black_card_tokens[_i]}#{currentWhiteCard}" currentWhiteCard = random_white_cards.shift() black_card_tokens.join "" # Utility ###################################################################### pmPlayer = (jid, text) -> theRobot.send({'user': jid}, text) randomIndex = (array) -> Math.floor(Math.random() * array.length)
69999
# Description: # The robot can run a game of devops against humanity using cards from # http://devopsagainsthumanity.com # # An editorial pass was made at the crowd-sourced cards. YMMV. # # Dependencies: # None # # Configuration: # HUBOT_HIPCHAT_TOKEN # # Commands: # hubot devops card me - Returns a random devops against humanity card pair. # hubot devops start game - Starts a new devops agains humanity game # hubot devops join - Joins an existing game # hubot devops who is the dealer - Mentions the dealer # hubot devops black card - Reveals the black card for the round if you're the dealer # hubot devops current black card - Display the black card for the round # hubot devops play card <n> <m> <o> - Plays cards from your hand # hubot devops reveal cards - Reveals all the card combinations # hubot devops <n> won - Announces the winner of the round # hubot devops score - Reports the score # hubot devops list players - Lists the players in the game and if they've played a card this round # # Author: # <NAME> and <NAME> Util = require "util" black_cards = require('./blackcards.coffee') white_cards = require('./whitecards.coffee') dahGameStorage = require('./dah-game-storage.coffee') theRobot = undefined module.exports = (robot) -> theRobot = robot robot.respond /devops card( me)?/i, (message) -> randomCompletion(message) robot.respond /devops (draw )?black card/i, (message) -> revealBlackCard(message) robot.respond /devops reveal cards/i, (message) -> revealCards(message) robot.respond /devops (what is (the )?)?current black card/i, (message) -> findCurrentBlackCard(message) robot.respond /devops ([0-9]+) won/i, (message) -> declareWinner(message) robot.respond /devops (start( new)?|new) game/i, (message) -> startNewGame(message) robot.respond /devops (I'm )?join(ing)?/i, (message) -> addSenderToGame(message) robot.respond /devops (what are )?my cards/i, (message) -> checkHand(message) robot.respond /devops play card (\d+)( \d+)?( \d+)?/i, (message) -> playCards(message) robot.respond /devops (who is the )?dealer/i, (message) -> checkDealer(message) robot.respond /devops (top |bottom )?([0-9]+ )?score/i, (message) -> reportScore(message) robot.respond /devops list players/i, (message) -> listPlayers(message) # Called directly by robot.respond()s ########################################## addSenderToGame = (message) -> sender = getSenderName(message) room = getRoomName(message) if (dahGameStorage.isSenderDealer(sender, room)) response = "You're the currently the devops dealer. Maybe ask for a black card?" else if (!dahGameStorage.getCards(sender, room).length) giveUserCards(sender, room) dahGameStorage.setUserJid(sender, room, message.message.user.jid) response = getCards(sender, room) else response = "You're already playing. Do you want to know what devops cards you have?" pmPlayer(message.message.user.jid, response) checkDealer = (message) -> dealer = dahGameStorage.getDealer(getRoomName(message)) if dealer? message.send "@#{dealer.name} is currently the devops dealer." else message.reply "there is no devops dealer currently. Maybe you should start a game?" checkHand = (message) -> cards = getCards(getSenderName(message), getRoomName(message)) pmPlayer(message.message.user.jid, cards) declareWinner = (message) -> sender = getSenderName(message) room = getRoomName(message) if dahGameStorage.getDealer(room) && dahGameStorage.isSenderDealer(sender, room) && dahGameStorage.getBlackCard(room) playedCardInfo = dahGameStorage.getAllPlayedCards(room) winnerIndex = message.match[1] players = Object.keys(playedCardInfo) if winnerIndex > 0 && winnerIndex <= players.length winningPlayer = undefined for player, play of playedCardInfo if "#{play['index']}" is "#{winnerIndex}" winningPlayer = player if winningPlayer dahGameStorage.scorePoint(winningPlayer, room) dahGameStorage.setDealer(players[randomIndex(players)], room) for player in players giveUserCards(player, room) pmPlayer(player.jid, getCards(player.name, room)) dahGameStorage.clearRoundData(room) message.send "@#{winningPlayer} won. #{winningPlayer}'s score is now #{dahGameStorage.getScore(winningPlayer, room)}." message.send "@#{dahGameStorage.getDealer(room)['name']} is the new dealer." else message.reply "I couldn't find that card combination. Have white cards been revealed?" else message.reply "there were only #{Object.keys(playedCardInfo).length} cards played. Maybe pick one of those?" else if !dahGameStorage.getDealer(room) message.reply "there is no devops dealer currently. Maybe you should start a game?" else if !dahGameStorage.isSenderDealer(sender, room) message.reply "you have to be the dealer to award points. Stop trying to cheat." else if !dahGameStorage.getBlackCard(room) message.reply "you haven't drawn a black card yet. How can you know who won?" findCurrentBlackCard = (message) -> blackCard = dahGameStorage.getBlackCard(getRoomName(message)) if (blackCard) message.send blackCard else dealer = dahGameStorage.getDealer(getRoomName(message)) if (dealer) message.send "There is no current black card. Maybe @#{dealer['name']} should draw one?" else message.reply "there isn't a black card currently. Maybe you should start a game?" listPlayers = (message) -> room = getRoomName(message) dealer = dahGameStorage.getDealer() players = [] response = [] for player, play of dahGameStorage.getAllPlayedCards(room) players.push(player) for name, player of dahGameStorage.roomData(getRoomName(message))['users'] if name in players && (! dealer? || !(dealer['name'] is name)) response.push("#{name} has played a card this round.") else if ! dealer? || !(dealer['name'] is name) response.push("#{name} has not yet played a card this round.") message.send response.join("\n") playCards = (message) -> cardIndices = [message.match[1], message.match[2], message.match[3]] sender = getSenderName(message) room = getRoomName(message) cards = dahGameStorage.getCards(sender, room) blackCard = dahGameStorage.getBlackCard(getRoomName(message)) if (dahGameStorage.getCardsPlayed(sender, room)) cardWord = "card" if (blanks > 1) cardWord = "cards" message.reply "increase your calm. You've already played your #{cardWord} this round." else if dahGameStorage.isSenderDealer(sender, room) if (blackCard) message.reply "you're currently the devops dealer. Maybe you should reveal the responses?" else message.reply "you're currently the devops dealer. Maybe ask for a black card?" else if cards.length if (blackCard) blanks = countBlackCardBlanks(blackCard) plays = [] # Get all the cards played for index in cardIndices if index? && index > 0 && index < 6 plays.push cards[index-1] else if index? message.reply "you only have 5 cards in your hand. You can't play card \##{index}." plays = undefined break else cardIndices.splice(index,cardIndices.length - index) break # Play the cards if (plays? && plays.length and plays.length == blanks) newHand = [] for card in cards if !(card in plays) newHand.push card dahGameStorage.setCards(sender, room, newHand) dahGameStorage.setCardsPlayed(sender, room, getCombinedText(blackCard, plays)) else if (plays? && plays.length) verb = "is" if (blanks > 1) verb = "are" message.reply "you specified the wrong number of cards. There #{verb} #{countBlackCardBlanks(blackCard)} blanks." cards.splice(0,0,plays) else message.reply "you're getting ahead of yourself. There is no black card in play." else message.reply "you don't have any cards. Maybe you should join the game?" randomCompletion = (message) -> black_card = drawBlackCard() random_white_cards = [] blanks = countBlackCardBlanks(black_card) for num in [1..blanks] white_card = drawWhiteCard() random_white_cards.push white_card message.send getCombinedText(black_card, random_white_cards) reportScore = (message) -> report = ["There are no scores to report."] scores = [] asc = true amount = 5 for name, player of dahGameStorage.roomData(getRoomName(message))['users'] scores.push player if scores.length > 0 report = ["The current score is:"] if (message.match[1]?) asc = message.match[1].trim().toLowerCase() == 'top' if (message.match[2]?) amount = message.match[2] scores.sort((a,b) -> if asc then b.score - a.score else a.score - b.score) scores = scores.slice(0, amount) for score in scores report.push "\t #{score['name']}: #{score['score']} points" message.send report.join("\n") revealBlackCard = (message) -> blackCard = drawBlackCard() room = getRoomName(message) if dahGameStorage.isSenderDealer(getSenderName(message),room) && !dahGameStorage.getBlackCard(room) dahGameStorage.setBlackCard(room, blackCard) message.send "Setting black card to:\n#{blackCard}" else if dahGameStorage.isSenderDealer(getSenderName(message),room) message.reply "you've already revealed the black card!" else message.reply "only the dealer can reveal the black card." revealCards = (message) -> room = getRoomName(message) if dahGameStorage.isSenderDealer(getSenderName(message), room) && dahGameStorage.getBlackCard(room) playedCardInfo = dahGameStorage.getAllPlayedCards(room) players = [] response = [] for player, play of playedCardInfo players.splice(randomIndex(players), 0, player) for player in players response.push("#{_i+1}) #{playedCardInfo[player]['completion']}") playedCardInfo[player]['index'] = _i+1 message.send response.join("\n") else dealer = dahGameStorage.getDealer(room) if dahGameStorage.isSenderDealer(getSenderName(message), room) message.reply "maybe you should set the black card before revealing white cards." else if dealer message.reply "only the dealer can reveal the combinations." message.send "@#{dealer.name}, is it time for the big reveal?" else message.reply "there is no dealer currently. Perhaps it's time to start a game?" startNewGame = (message) -> sender = getSenderName(message) room = getRoomName(message) dahGameStorage.clearRoomData(room) dahGameStorage.isSenderDealer(sender, room, true) dahGameStorage.setUserJid(sender, room, message.message.user.jid) message.send "Starting a new devops game." # Game logic helpers ########################################################### getCards = (sender, room) -> cards = [] for card in dahGameStorage.getCards(sender, room) cards.push "#{_i+1}) #{card}" if cards.length > 0 cards.join("\n") else "You have no devops cards. Maybe you should join the game?" getRoomName = (message) -> message.message.room getSenderName = (message) -> name = message.message.user.mention_name if (!name) name = message.message.user.name name giveUserCards = (sender, room) -> cards = dahGameStorage.getCards(sender, room) for num in [cards.length..4] cards.push drawWhiteCard() dahGameStorage.setCards(sender, room, cards) # Card completion helpers ###################################################### capitalizeFirstLetter = (text) -> if text.charAt(0) is '"' white_card = text.charAt(0) + text.charAt(1).toUpperCase() + text.slice(2) else white_card = text.charAt(0).toUpperCase() + text.slice(1) white_card countBlackCardBlanks = (black_card) -> (black_card.match(/__________/g) || []).length drawBlackCard = -> black_cards[randomIndex(black_cards)] drawWhiteCard = -> white_cards[randomIndex(white_cards)] getCombinedText = (black_card, random_white_cards) -> black_card_tokens = black_card.split('__________') currentWhiteCard = random_white_cards.shift() for word in black_card_tokens shouldCapitalize = ".?".indexOf(black_card_tokens[_i].trim().slice(-1)) > -1 if currentWhiteCard? if shouldCapitalize currentWhiteCard = capitalizeFirstLetter(currentWhiteCard) black_card_tokens[_i] = "#{black_card_tokens[_i]}#{currentWhiteCard}" currentWhiteCard = random_white_cards.shift() black_card_tokens.join "" # Utility ###################################################################### pmPlayer = (jid, text) -> theRobot.send({'user': jid}, text) randomIndex = (array) -> Math.floor(Math.random() * array.length)
true
# Description: # The robot can run a game of devops against humanity using cards from # http://devopsagainsthumanity.com # # An editorial pass was made at the crowd-sourced cards. YMMV. # # Dependencies: # None # # Configuration: # HUBOT_HIPCHAT_TOKEN # # Commands: # hubot devops card me - Returns a random devops against humanity card pair. # hubot devops start game - Starts a new devops agains humanity game # hubot devops join - Joins an existing game # hubot devops who is the dealer - Mentions the dealer # hubot devops black card - Reveals the black card for the round if you're the dealer # hubot devops current black card - Display the black card for the round # hubot devops play card <n> <m> <o> - Plays cards from your hand # hubot devops reveal cards - Reveals all the card combinations # hubot devops <n> won - Announces the winner of the round # hubot devops score - Reports the score # hubot devops list players - Lists the players in the game and if they've played a card this round # # Author: # PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI Util = require "util" black_cards = require('./blackcards.coffee') white_cards = require('./whitecards.coffee') dahGameStorage = require('./dah-game-storage.coffee') theRobot = undefined module.exports = (robot) -> theRobot = robot robot.respond /devops card( me)?/i, (message) -> randomCompletion(message) robot.respond /devops (draw )?black card/i, (message) -> revealBlackCard(message) robot.respond /devops reveal cards/i, (message) -> revealCards(message) robot.respond /devops (what is (the )?)?current black card/i, (message) -> findCurrentBlackCard(message) robot.respond /devops ([0-9]+) won/i, (message) -> declareWinner(message) robot.respond /devops (start( new)?|new) game/i, (message) -> startNewGame(message) robot.respond /devops (I'm )?join(ing)?/i, (message) -> addSenderToGame(message) robot.respond /devops (what are )?my cards/i, (message) -> checkHand(message) robot.respond /devops play card (\d+)( \d+)?( \d+)?/i, (message) -> playCards(message) robot.respond /devops (who is the )?dealer/i, (message) -> checkDealer(message) robot.respond /devops (top |bottom )?([0-9]+ )?score/i, (message) -> reportScore(message) robot.respond /devops list players/i, (message) -> listPlayers(message) # Called directly by robot.respond()s ########################################## addSenderToGame = (message) -> sender = getSenderName(message) room = getRoomName(message) if (dahGameStorage.isSenderDealer(sender, room)) response = "You're the currently the devops dealer. Maybe ask for a black card?" else if (!dahGameStorage.getCards(sender, room).length) giveUserCards(sender, room) dahGameStorage.setUserJid(sender, room, message.message.user.jid) response = getCards(sender, room) else response = "You're already playing. Do you want to know what devops cards you have?" pmPlayer(message.message.user.jid, response) checkDealer = (message) -> dealer = dahGameStorage.getDealer(getRoomName(message)) if dealer? message.send "@#{dealer.name} is currently the devops dealer." else message.reply "there is no devops dealer currently. Maybe you should start a game?" checkHand = (message) -> cards = getCards(getSenderName(message), getRoomName(message)) pmPlayer(message.message.user.jid, cards) declareWinner = (message) -> sender = getSenderName(message) room = getRoomName(message) if dahGameStorage.getDealer(room) && dahGameStorage.isSenderDealer(sender, room) && dahGameStorage.getBlackCard(room) playedCardInfo = dahGameStorage.getAllPlayedCards(room) winnerIndex = message.match[1] players = Object.keys(playedCardInfo) if winnerIndex > 0 && winnerIndex <= players.length winningPlayer = undefined for player, play of playedCardInfo if "#{play['index']}" is "#{winnerIndex}" winningPlayer = player if winningPlayer dahGameStorage.scorePoint(winningPlayer, room) dahGameStorage.setDealer(players[randomIndex(players)], room) for player in players giveUserCards(player, room) pmPlayer(player.jid, getCards(player.name, room)) dahGameStorage.clearRoundData(room) message.send "@#{winningPlayer} won. #{winningPlayer}'s score is now #{dahGameStorage.getScore(winningPlayer, room)}." message.send "@#{dahGameStorage.getDealer(room)['name']} is the new dealer." else message.reply "I couldn't find that card combination. Have white cards been revealed?" else message.reply "there were only #{Object.keys(playedCardInfo).length} cards played. Maybe pick one of those?" else if !dahGameStorage.getDealer(room) message.reply "there is no devops dealer currently. Maybe you should start a game?" else if !dahGameStorage.isSenderDealer(sender, room) message.reply "you have to be the dealer to award points. Stop trying to cheat." else if !dahGameStorage.getBlackCard(room) message.reply "you haven't drawn a black card yet. How can you know who won?" findCurrentBlackCard = (message) -> blackCard = dahGameStorage.getBlackCard(getRoomName(message)) if (blackCard) message.send blackCard else dealer = dahGameStorage.getDealer(getRoomName(message)) if (dealer) message.send "There is no current black card. Maybe @#{dealer['name']} should draw one?" else message.reply "there isn't a black card currently. Maybe you should start a game?" listPlayers = (message) -> room = getRoomName(message) dealer = dahGameStorage.getDealer() players = [] response = [] for player, play of dahGameStorage.getAllPlayedCards(room) players.push(player) for name, player of dahGameStorage.roomData(getRoomName(message))['users'] if name in players && (! dealer? || !(dealer['name'] is name)) response.push("#{name} has played a card this round.") else if ! dealer? || !(dealer['name'] is name) response.push("#{name} has not yet played a card this round.") message.send response.join("\n") playCards = (message) -> cardIndices = [message.match[1], message.match[2], message.match[3]] sender = getSenderName(message) room = getRoomName(message) cards = dahGameStorage.getCards(sender, room) blackCard = dahGameStorage.getBlackCard(getRoomName(message)) if (dahGameStorage.getCardsPlayed(sender, room)) cardWord = "card" if (blanks > 1) cardWord = "cards" message.reply "increase your calm. You've already played your #{cardWord} this round." else if dahGameStorage.isSenderDealer(sender, room) if (blackCard) message.reply "you're currently the devops dealer. Maybe you should reveal the responses?" else message.reply "you're currently the devops dealer. Maybe ask for a black card?" else if cards.length if (blackCard) blanks = countBlackCardBlanks(blackCard) plays = [] # Get all the cards played for index in cardIndices if index? && index > 0 && index < 6 plays.push cards[index-1] else if index? message.reply "you only have 5 cards in your hand. You can't play card \##{index}." plays = undefined break else cardIndices.splice(index,cardIndices.length - index) break # Play the cards if (plays? && plays.length and plays.length == blanks) newHand = [] for card in cards if !(card in plays) newHand.push card dahGameStorage.setCards(sender, room, newHand) dahGameStorage.setCardsPlayed(sender, room, getCombinedText(blackCard, plays)) else if (plays? && plays.length) verb = "is" if (blanks > 1) verb = "are" message.reply "you specified the wrong number of cards. There #{verb} #{countBlackCardBlanks(blackCard)} blanks." cards.splice(0,0,plays) else message.reply "you're getting ahead of yourself. There is no black card in play." else message.reply "you don't have any cards. Maybe you should join the game?" randomCompletion = (message) -> black_card = drawBlackCard() random_white_cards = [] blanks = countBlackCardBlanks(black_card) for num in [1..blanks] white_card = drawWhiteCard() random_white_cards.push white_card message.send getCombinedText(black_card, random_white_cards) reportScore = (message) -> report = ["There are no scores to report."] scores = [] asc = true amount = 5 for name, player of dahGameStorage.roomData(getRoomName(message))['users'] scores.push player if scores.length > 0 report = ["The current score is:"] if (message.match[1]?) asc = message.match[1].trim().toLowerCase() == 'top' if (message.match[2]?) amount = message.match[2] scores.sort((a,b) -> if asc then b.score - a.score else a.score - b.score) scores = scores.slice(0, amount) for score in scores report.push "\t #{score['name']}: #{score['score']} points" message.send report.join("\n") revealBlackCard = (message) -> blackCard = drawBlackCard() room = getRoomName(message) if dahGameStorage.isSenderDealer(getSenderName(message),room) && !dahGameStorage.getBlackCard(room) dahGameStorage.setBlackCard(room, blackCard) message.send "Setting black card to:\n#{blackCard}" else if dahGameStorage.isSenderDealer(getSenderName(message),room) message.reply "you've already revealed the black card!" else message.reply "only the dealer can reveal the black card." revealCards = (message) -> room = getRoomName(message) if dahGameStorage.isSenderDealer(getSenderName(message), room) && dahGameStorage.getBlackCard(room) playedCardInfo = dahGameStorage.getAllPlayedCards(room) players = [] response = [] for player, play of playedCardInfo players.splice(randomIndex(players), 0, player) for player in players response.push("#{_i+1}) #{playedCardInfo[player]['completion']}") playedCardInfo[player]['index'] = _i+1 message.send response.join("\n") else dealer = dahGameStorage.getDealer(room) if dahGameStorage.isSenderDealer(getSenderName(message), room) message.reply "maybe you should set the black card before revealing white cards." else if dealer message.reply "only the dealer can reveal the combinations." message.send "@#{dealer.name}, is it time for the big reveal?" else message.reply "there is no dealer currently. Perhaps it's time to start a game?" startNewGame = (message) -> sender = getSenderName(message) room = getRoomName(message) dahGameStorage.clearRoomData(room) dahGameStorage.isSenderDealer(sender, room, true) dahGameStorage.setUserJid(sender, room, message.message.user.jid) message.send "Starting a new devops game." # Game logic helpers ########################################################### getCards = (sender, room) -> cards = [] for card in dahGameStorage.getCards(sender, room) cards.push "#{_i+1}) #{card}" if cards.length > 0 cards.join("\n") else "You have no devops cards. Maybe you should join the game?" getRoomName = (message) -> message.message.room getSenderName = (message) -> name = message.message.user.mention_name if (!name) name = message.message.user.name name giveUserCards = (sender, room) -> cards = dahGameStorage.getCards(sender, room) for num in [cards.length..4] cards.push drawWhiteCard() dahGameStorage.setCards(sender, room, cards) # Card completion helpers ###################################################### capitalizeFirstLetter = (text) -> if text.charAt(0) is '"' white_card = text.charAt(0) + text.charAt(1).toUpperCase() + text.slice(2) else white_card = text.charAt(0).toUpperCase() + text.slice(1) white_card countBlackCardBlanks = (black_card) -> (black_card.match(/__________/g) || []).length drawBlackCard = -> black_cards[randomIndex(black_cards)] drawWhiteCard = -> white_cards[randomIndex(white_cards)] getCombinedText = (black_card, random_white_cards) -> black_card_tokens = black_card.split('__________') currentWhiteCard = random_white_cards.shift() for word in black_card_tokens shouldCapitalize = ".?".indexOf(black_card_tokens[_i].trim().slice(-1)) > -1 if currentWhiteCard? if shouldCapitalize currentWhiteCard = capitalizeFirstLetter(currentWhiteCard) black_card_tokens[_i] = "#{black_card_tokens[_i]}#{currentWhiteCard}" currentWhiteCard = random_white_cards.shift() black_card_tokens.join "" # Utility ###################################################################### pmPlayer = (jid, text) -> theRobot.send({'user': jid}, text) randomIndex = (array) -> Math.floor(Math.random() * array.length)
[ { "context": "cribe 'client and call apis', ->\n\n _userId = '53be41be138556909068769f'\n token = '5e7f8ead-47fa-4256-9", "end": 588, "score": 0.42220282554626465, "start": 580, "tag": "PASSWORD", "value": "3be41be1" }, { "context": "_userId = '53be41be138556909068769f'\n to...
test/main.coffee
jianliaoim/talk-node-sdk
4
http = require 'http' should = require 'should' express = require 'express' supertest = require 'supertest' Promise = require 'bluebird' talk = require '../src/talk' logger = require('graceful-logger').mute() app = require './app' describe 'Talk#Main', -> talk.init(app.config) describe 'retry connecting', -> it 'should work when api server is started after the client', (done) -> talk.call 'ping', (err, data) -> data.should.eql 'pong' done err setTimeout app.fakeServer, 500 describe 'client and call apis', -> _userId = '53be41be138556909068769f' token = '5e7f8ead-47fa-4256-9a27-4e2166cfcfac' it 'should get an NO_PERMISSIONT error without authorization', (done) -> talk.call 'user.readOne', _id: _userId, (err) -> should(err).not.eql null done() it 'should call the user.readOne with authorization', (done) -> authClient = talk.client(token) authClient.call 'user.readOne', _id: _userId, (err, user) -> user.should.have.properties 'name' done err describe 'service and listen for events', -> exApp = express() # Express application service = talk.service(exApp) it 'should intialize the express server and call the api', (done) -> supertest(exApp).post('/').end (err, res) -> res.text.should.eql '{"pong":1}' done err it 'should listen for the user.readOne event', (done) -> service.once 'user.readOne', (data) -> data.should.eql 'ok' done() supertest(exApp).post('/') .set "Content-Type": "application/json" .send JSON.stringify(event: 'user.readOne', data: 'ok') .end(->) it 'should listen for the wildcard * event', (done) -> service.once '*', (data) -> data.should.eql 'ok' done() supertest(exApp).post '/' .set "Content-Type": "application/json" .send JSON.stringify(event: 'user.readOne', data: 'ok') .end(->) describe 'worker and test for what he should do', -> @timeout 3000 it 'should run the tasks every 100ms', (done) -> ticks = 0 testTask = (task) -> worker.tasks.should.have.keys '2.00abc_mention', '2.00def_mention', '2.00def_repost' task.should.have.properties 'token', 'event' if task.token is '2.00abc' task.event.should.eql 'mention' worker = talk.worker interval: 100 # Execute task every 100 ms runner: (task) -> # Task runner new Promise (resolve, reject) -> ticks += 1 testTask task if ticks is 6 # Stop work after 2 * 3 times worker.stop() done() resolve() worker.run() it 'should execute the tasks each second by cron-like schedule', (done) -> ticks = 0 textTask = (task) -> worker.tasks.should.have.keys '' worker = talk.worker cron: '* * * * * *' taskInterval: 0 runner: (task) -> ticks += 1 if ticks is 6 worker.stop() done() worker.run() it 'should not bother the other tasks when a task crashed', (done) -> ticks = 0 worker = talk.worker interval: 100 runner: (task) -> num = ticks += 1 new Promise (resolve, reject) -> setTimeout -> # The first task will crash return reject(new Error('something error')) if num is 1 # The second task will also work if num is 2 worker.stop() task.token.should.eql '2.00def' done() , 20 * num worker.run() it 'should send a error integration to server when task failed', (done) -> worker = talk.worker interval: 100 maxErrorTimes: 1 runner: (task) -> new Promise (resolve, reject) -> return reject(new Error('OMG, they killed kenny!')) if task.token is '2.00abc' resolve() app.test = (req, res) -> req.body.should.have.properties 'appToken', 'errorInfo' req.url.should.containEql '54533b3ac4cc9aa41acc3cf6' app.test = -> setTimeout -> # Should not have the invalid task worker.tasks.should.have.keys '2.00def_mention', '2.00def_repost' worker.stop() done() , 100 worker.run()
144160
http = require 'http' should = require 'should' express = require 'express' supertest = require 'supertest' Promise = require 'bluebird' talk = require '../src/talk' logger = require('graceful-logger').mute() app = require './app' describe 'Talk#Main', -> talk.init(app.config) describe 'retry connecting', -> it 'should work when api server is started after the client', (done) -> talk.call 'ping', (err, data) -> data.should.eql 'pong' done err setTimeout app.fakeServer, 500 describe 'client and call apis', -> _userId = '5<PASSWORD>38556909068769f' token = '<PASSWORD>' it 'should get an NO_PERMISSIONT error without authorization', (done) -> talk.call 'user.readOne', _id: _userId, (err) -> should(err).not.eql null done() it 'should call the user.readOne with authorization', (done) -> authClient = talk.client(token) authClient.call 'user.readOne', _id: _userId, (err, user) -> user.should.have.properties 'name' done err describe 'service and listen for events', -> exApp = express() # Express application service = talk.service(exApp) it 'should intialize the express server and call the api', (done) -> supertest(exApp).post('/').end (err, res) -> res.text.should.eql '{"pong":1}' done err it 'should listen for the user.readOne event', (done) -> service.once 'user.readOne', (data) -> data.should.eql 'ok' done() supertest(exApp).post('/') .set "Content-Type": "application/json" .send JSON.stringify(event: 'user.readOne', data: 'ok') .end(->) it 'should listen for the wildcard * event', (done) -> service.once '*', (data) -> data.should.eql 'ok' done() supertest(exApp).post '/' .set "Content-Type": "application/json" .send JSON.stringify(event: 'user.readOne', data: 'ok') .end(->) describe 'worker and test for what he should do', -> @timeout 3000 it 'should run the tasks every 100ms', (done) -> ticks = 0 testTask = (task) -> worker.tasks.should.have.keys '2.00abc_mention', '2.00def_mention', '2.00def_repost' task.should.have.properties 'token', 'event' if task.token is '<KEY>.<PASSWORD>' task.event.should.eql 'mention' worker = talk.worker interval: 100 # Execute task every 100 ms runner: (task) -> # Task runner new Promise (resolve, reject) -> ticks += 1 testTask task if ticks is 6 # Stop work after 2 * 3 times worker.stop() done() resolve() worker.run() it 'should execute the tasks each second by cron-like schedule', (done) -> ticks = 0 textTask = (task) -> worker.tasks.should.have.keys '' worker = talk.worker cron: '* * * * * *' taskInterval: 0 runner: (task) -> ticks += 1 if ticks is 6 worker.stop() done() worker.run() it 'should not bother the other tasks when a task crashed', (done) -> ticks = 0 worker = talk.worker interval: 100 runner: (task) -> num = ticks += 1 new Promise (resolve, reject) -> setTimeout -> # The first task will crash return reject(new Error('something error')) if num is 1 # The second task will also work if num is 2 worker.stop() task.token.should.eql '<KEY>.<PASSWORD>0def' done() , 20 * num worker.run() it 'should send a error integration to server when task failed', (done) -> worker = talk.worker interval: 100 maxErrorTimes: 1 runner: (task) -> new Promise (resolve, reject) -> return reject(new Error('OMG, they killed kenny!')) if task.token is '<PASSWORD>' resolve() app.test = (req, res) -> req.body.should.have.properties 'appToken', 'errorInfo' req.url.should.containEql '54533b3ac4cc9aa41acc3cf6' app.test = -> setTimeout -> # Should not have the invalid task worker.tasks.should.have.keys '2.00def_mention', '2.00def_repost' worker.stop() done() , 100 worker.run()
true
http = require 'http' should = require 'should' express = require 'express' supertest = require 'supertest' Promise = require 'bluebird' talk = require '../src/talk' logger = require('graceful-logger').mute() app = require './app' describe 'Talk#Main', -> talk.init(app.config) describe 'retry connecting', -> it 'should work when api server is started after the client', (done) -> talk.call 'ping', (err, data) -> data.should.eql 'pong' done err setTimeout app.fakeServer, 500 describe 'client and call apis', -> _userId = '5PI:PASSWORD:<PASSWORD>END_PI38556909068769f' token = 'PI:PASSWORD:<PASSWORD>END_PI' it 'should get an NO_PERMISSIONT error without authorization', (done) -> talk.call 'user.readOne', _id: _userId, (err) -> should(err).not.eql null done() it 'should call the user.readOne with authorization', (done) -> authClient = talk.client(token) authClient.call 'user.readOne', _id: _userId, (err, user) -> user.should.have.properties 'name' done err describe 'service and listen for events', -> exApp = express() # Express application service = talk.service(exApp) it 'should intialize the express server and call the api', (done) -> supertest(exApp).post('/').end (err, res) -> res.text.should.eql '{"pong":1}' done err it 'should listen for the user.readOne event', (done) -> service.once 'user.readOne', (data) -> data.should.eql 'ok' done() supertest(exApp).post('/') .set "Content-Type": "application/json" .send JSON.stringify(event: 'user.readOne', data: 'ok') .end(->) it 'should listen for the wildcard * event', (done) -> service.once '*', (data) -> data.should.eql 'ok' done() supertest(exApp).post '/' .set "Content-Type": "application/json" .send JSON.stringify(event: 'user.readOne', data: 'ok') .end(->) describe 'worker and test for what he should do', -> @timeout 3000 it 'should run the tasks every 100ms', (done) -> ticks = 0 testTask = (task) -> worker.tasks.should.have.keys '2.00abc_mention', '2.00def_mention', '2.00def_repost' task.should.have.properties 'token', 'event' if task.token is 'PI:KEY:<KEY>END_PI.PI:PASSWORD:<PASSWORD>END_PI' task.event.should.eql 'mention' worker = talk.worker interval: 100 # Execute task every 100 ms runner: (task) -> # Task runner new Promise (resolve, reject) -> ticks += 1 testTask task if ticks is 6 # Stop work after 2 * 3 times worker.stop() done() resolve() worker.run() it 'should execute the tasks each second by cron-like schedule', (done) -> ticks = 0 textTask = (task) -> worker.tasks.should.have.keys '' worker = talk.worker cron: '* * * * * *' taskInterval: 0 runner: (task) -> ticks += 1 if ticks is 6 worker.stop() done() worker.run() it 'should not bother the other tasks when a task crashed', (done) -> ticks = 0 worker = talk.worker interval: 100 runner: (task) -> num = ticks += 1 new Promise (resolve, reject) -> setTimeout -> # The first task will crash return reject(new Error('something error')) if num is 1 # The second task will also work if num is 2 worker.stop() task.token.should.eql 'PI:KEY:<KEY>END_PI.PI:PASSWORD:<PASSWORD>END_PI0def' done() , 20 * num worker.run() it 'should send a error integration to server when task failed', (done) -> worker = talk.worker interval: 100 maxErrorTimes: 1 runner: (task) -> new Promise (resolve, reject) -> return reject(new Error('OMG, they killed kenny!')) if task.token is 'PI:PASSWORD:<PASSWORD>END_PI' resolve() app.test = (req, res) -> req.body.should.have.properties 'appToken', 'errorInfo' req.url.should.containEql '54533b3ac4cc9aa41acc3cf6' app.test = -> setTimeout -> # Should not have the invalid task worker.tasks.should.have.keys '2.00def_mention', '2.00def_repost' worker.stop() done() , 100 worker.run()
[ { "context": " context = Serenade(items: [{ valid: true, name: 'foo' }, { name: 'bar' }])\n @render '''\n ul\n ", "end": 2588, "score": 0.9265750646591187, "start": 2585, "tag": "NAME", "value": "foo" }, { "context": "de(items: [{ valid: true, name: 'foo' }, { name: 'bar' }]...
test/integration/if.spec.coffee
jnicklas/serenade.js
1
require './../spec_helper' Serenade = require('../../lib/serenade') describe 'If', -> beforeEach -> @setupDom() it 'shows the content if the context value is truthy', -> context = { valid: true, visible: "true" } @render ''' ul - if $valid li[id="valid"] - if $visible li[id="visible"] ''', context expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') it 'can have multiple children', -> context = { valid: true, visible: "true" } @render ''' ul - if $valid li[id="valid"] li[id="visible"] li[id="monkey"] ''', context expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') expect(@body).to.have.element('ul > li#monkey') it 'does not show the content if the context value is falsy', -> context = { valid: false, visible: 0 } @render ''' ul - if $valid li[id="valid"] - if $visible li[id="visible"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') it 'updates the existence of content based on context value truthiness', -> context = Serenade(valid: false, visible: 0) @render ''' ul - if @valid li[id="valid"] - if @visible li[id="visible"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') context.valid = "yes" expect(@body).to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') context.valid = "" context.visible = "Cool" expect(@body).not.to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') context.valid = "Blah" context.visible = {} expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') it 'can have else statement', -> context = Serenade(valid: false) @render ''' ul - if @valid li[id="valid"] - else li[id="invalid"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#invalid') context.valid = true expect(@body).to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#invalid') it 'peacefully coexists with collections', -> context = Serenade(items: [{ valid: true, name: 'foo' }, { name: 'bar' }]) @render ''' ul - collection @items - if $valid li[id=name] ''', context expect(@body).to.have.element('ul > li#foo') expect(@body).not.to.have.element('ul > li#bar') it "can be nested", -> context = Serenade(show: true, details: "test") @render """ div - if @show - if @details p#test """, context context.show = false context.show = true expect(@body).to.have.element('#test') it 'can be a root node', -> context = Serenade(valid: false) @render ''' - if @valid p[id="valid"] - else p[id="invalid"] ''', context expect(@body).not.to.have.element('p#valid') expect(@body).to.have.element('p#invalid') context.valid = true expect(@body).to.have.element('p#valid') expect(@body).not.to.have.element('p#invalid') it 'it does not lose listeners on re-render', -> context = Serenade(shown: true, name: "Jonas") @render ''' - if @shown p[id="name"] @name ''', context expect(@body.querySelector("#name").textContent).to.eql("Jonas") context.shown = true context.name = "Kim" expect(@body.querySelector("#name").textContent).to.eql("Kim")
147865
require './../spec_helper' Serenade = require('../../lib/serenade') describe 'If', -> beforeEach -> @setupDom() it 'shows the content if the context value is truthy', -> context = { valid: true, visible: "true" } @render ''' ul - if $valid li[id="valid"] - if $visible li[id="visible"] ''', context expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') it 'can have multiple children', -> context = { valid: true, visible: "true" } @render ''' ul - if $valid li[id="valid"] li[id="visible"] li[id="monkey"] ''', context expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') expect(@body).to.have.element('ul > li#monkey') it 'does not show the content if the context value is falsy', -> context = { valid: false, visible: 0 } @render ''' ul - if $valid li[id="valid"] - if $visible li[id="visible"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') it 'updates the existence of content based on context value truthiness', -> context = Serenade(valid: false, visible: 0) @render ''' ul - if @valid li[id="valid"] - if @visible li[id="visible"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') context.valid = "yes" expect(@body).to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') context.valid = "" context.visible = "Cool" expect(@body).not.to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') context.valid = "Blah" context.visible = {} expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') it 'can have else statement', -> context = Serenade(valid: false) @render ''' ul - if @valid li[id="valid"] - else li[id="invalid"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#invalid') context.valid = true expect(@body).to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#invalid') it 'peacefully coexists with collections', -> context = Serenade(items: [{ valid: true, name: '<NAME>' }, { name: '<NAME>' }]) @render ''' ul - collection @items - if $valid li[id=name] ''', context expect(@body).to.have.element('ul > li#foo') expect(@body).not.to.have.element('ul > li#bar') it "can be nested", -> context = Serenade(show: true, details: "test") @render """ div - if @show - if @details p#test """, context context.show = false context.show = true expect(@body).to.have.element('#test') it 'can be a root node', -> context = Serenade(valid: false) @render ''' - if @valid p[id="valid"] - else p[id="invalid"] ''', context expect(@body).not.to.have.element('p#valid') expect(@body).to.have.element('p#invalid') context.valid = true expect(@body).to.have.element('p#valid') expect(@body).not.to.have.element('p#invalid') it 'it does not lose listeners on re-render', -> context = Serenade(shown: true, name: "<NAME>") @render ''' - if @shown p[id="name"] @name ''', context expect(@body.querySelector("#name").textContent).to.eql("<NAME>") context.shown = true context.name = "<NAME>" expect(@body.querySelector("#name").textContent).to.eql("<NAME>")
true
require './../spec_helper' Serenade = require('../../lib/serenade') describe 'If', -> beforeEach -> @setupDom() it 'shows the content if the context value is truthy', -> context = { valid: true, visible: "true" } @render ''' ul - if $valid li[id="valid"] - if $visible li[id="visible"] ''', context expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') it 'can have multiple children', -> context = { valid: true, visible: "true" } @render ''' ul - if $valid li[id="valid"] li[id="visible"] li[id="monkey"] ''', context expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') expect(@body).to.have.element('ul > li#monkey') it 'does not show the content if the context value is falsy', -> context = { valid: false, visible: 0 } @render ''' ul - if $valid li[id="valid"] - if $visible li[id="visible"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') it 'updates the existence of content based on context value truthiness', -> context = Serenade(valid: false, visible: 0) @render ''' ul - if @valid li[id="valid"] - if @visible li[id="visible"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') context.valid = "yes" expect(@body).to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#visible') context.valid = "" context.visible = "Cool" expect(@body).not.to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') context.valid = "Blah" context.visible = {} expect(@body).to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#visible') it 'can have else statement', -> context = Serenade(valid: false) @render ''' ul - if @valid li[id="valid"] - else li[id="invalid"] ''', context expect(@body).not.to.have.element('ul > li#valid') expect(@body).to.have.element('ul > li#invalid') context.valid = true expect(@body).to.have.element('ul > li#valid') expect(@body).not.to.have.element('ul > li#invalid') it 'peacefully coexists with collections', -> context = Serenade(items: [{ valid: true, name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }]) @render ''' ul - collection @items - if $valid li[id=name] ''', context expect(@body).to.have.element('ul > li#foo') expect(@body).not.to.have.element('ul > li#bar') it "can be nested", -> context = Serenade(show: true, details: "test") @render """ div - if @show - if @details p#test """, context context.show = false context.show = true expect(@body).to.have.element('#test') it 'can be a root node', -> context = Serenade(valid: false) @render ''' - if @valid p[id="valid"] - else p[id="invalid"] ''', context expect(@body).not.to.have.element('p#valid') expect(@body).to.have.element('p#invalid') context.valid = true expect(@body).to.have.element('p#valid') expect(@body).not.to.have.element('p#invalid') it 'it does not lose listeners on re-render', -> context = Serenade(shown: true, name: "PI:NAME:<NAME>END_PI") @render ''' - if @shown p[id="name"] @name ''', context expect(@body.querySelector("#name").textContent).to.eql("PI:NAME:<NAME>END_PI") context.shown = true context.name = "PI:NAME:<NAME>END_PI" expect(@body.querySelector("#name").textContent).to.eql("PI:NAME:<NAME>END_PI")
[ { "context": "sName=\"font-weight-bold\" href=\"https://github.com/edemaine/cocreate\">Cocreate</a> for a shared whiteboard.</", "end": 544, "score": 0.9947441220283508, "start": 536, "tag": "USERNAME", "value": "edemaine" }, { "context": "/#{zoomID}\" +\n if zoomPwd then \"?p...
client/TabNew.coffee
diomidov/comingle
0
import React, {useState, useEffect, useRef} from 'react' import {Form} from 'react-bootstrap' import {validURL, tabTypes, categories, mangleTab, zoomRegExp} from '/lib/tabs' import {useDebounce} from './lib/useDebounce' import {getCreator} from './lib/presenceId' import {capitalize} from './lib/capitalize' export tabTypePage = iframe: topDescription: <p>Paste the URL for any embeddable website, e.g., Wikipedia:</p> cocreate: topDescription: <p>This server uses <a className="font-weight-bold" href="https://github.com/edemaine/cocreate">Cocreate</a> for a shared whiteboard.</p> jitsi: topDescription: <p>This server recommends <a className="font-weight-bold" href="https://meet.jit.si/">Jitsi Meet</a> for video conferencing, because it allows free creation of unlimited rooms.</p> youtube: topDescription: <p>Paste a <a className="font-weight-bold" href="https://www.youtube.com/">YouTube</a> link and we'll turn it into its embeddable form:</p> zoom: topDescription: <p>If you create a <a className="font-weight-bold" href="https://zoom.us/">Zoom</a> meeting yourself, you can embed it here.</p> bottomDescription: <p>Or paste a Zoom invitation link:</p> tabTypesByCategory = {} do -> # avoid namespace pollution for tabType, tabData of tabTypes category = tabData.category ? tabData.title tabTypesByCategory[category] ?= {} tabTypesByCategory[category][tabType] = tabData export TabNew = ({node, meetingId, roomId, replaceTabNew, existingTabTypes}) -> [url, setUrl] = useState '' [title, setTitle] = useState '' [category, setCategory] = useState 'Web' [type, setType] = useState 'iframe' [manualTitle, setManualTitle] = useState false [submit, setSubmit] = useState false submitButton = useRef() ## Zoom [zoomID, setZoomID] = useState '' [zoomPwd, setZoomPwd] = useState '' useEffect -> return unless type == 'zoom' if zoomID match = zoomRegExp.exec url setUrl "#{match?[1] ? 'https://zoom.us/'}j/#{zoomID}" + if zoomPwd then "?pwd=#{zoomPwd}" else '' , [zoomID, zoomPwd, type] useEffect -> return unless type == 'zoom' match = zoomRegExp.exec url setZoomID match[2] if match?[2] setZoomPwd match[3] if match?[3] , [url, type] ## Automatic mangling after a little idle time urlDebounce = useDebounce url, 100 titleDebounce = useDebounce title, 100 useEffect -> tab = mangleTab {url, title, type, manualTitle} setUrl tab.url if tab.url != url setTitle tab.title if tab.title != title setType tab.type if tab.type != type setManualTitle tab.manualTitle if tab.manualTitle != manualTitle if submit setSubmit false setTimeout (-> submitButton.current?.click()), 0 undefined , [urlDebounce, titleDebounce, submit] onCategory = (categoryName) -> (e) -> e.preventDefault() unless category == categoryName setCategory categoryName for tabType of tabTypesByCategory[categoryName] break # choose first tabType within category setType tabType onType = (tabType) -> (e) -> e.preventDefault() setType tabType onSubmit = (e) -> e.preventDefault() return unless validURL url ## One last mangle (in case didn't reach idle threshold) tab = mangleTab meeting: meetingId room: roomId title: title.trim() type: type url: url manualTitle: manualTitle creator: getCreator() , true id = Meteor.apply 'tabNew', [tab], returnStubValue: true replaceTabNew {id, node} <div className="card"> <div className="card-body"> <h3 className="card-title">Add Shared Tab to Room</h3> <p className="card-text"> Create/embed a widget for everyone in this room to use. </p> <div className="card form-group"> <div className="card-header"> <ul className="nav nav-tabs card-header-tabs" role="tablist"> {for categoryName, categoryTabTypes of tabTypesByCategory selected = (category == categoryName) <li key={categoryName} className="nav-item" role="presentation"> <a className="nav-link #{if selected then 'active'}" href="#" role="tab" aria-selected="#{selected}" onClick={onCategory categoryName}> {categoryName} </a> </li> } </ul> </div> {if (tabType for tabType of tabTypesByCategory[category]).length > 1 <div className="card-header"> <ul className="nav nav-tabs card-header-tabs" role="tablist"> {for tabType, tabData of tabTypesByCategory[category] selected = (type == tabType) disabled = tabData.onePerRoom and existingTabTypes[tabType] <li key={tabType} disabled={disabled} className="nav-item" role="presentation"> <a className="nav-link #{if selected then 'active'}" href="#" role="tab" aria-selected="#{selected}" onClick={onType tabType}> {tabData.title} </a> </li> } </ul> </div> } <div className="card-body"> <form className="newTab" onSubmit={onSubmit}> {if categories[category]?.onePerRoom and (tabType for tabType of tabTypesByCategory[category] \ when existingTabTypes[tabType]).length <div className="alert alert-warning"> WARNING: This room already has a {category} tab. Do you really want another? </div> } {tabTypePage[type].topDescription} {if tabTypes[type].onePerRoom and existingTabTypes[type] <div className="alert alert-warning"> WARNING: This room already has a {tabTypes[type].longTitle ? tabTypes[type].title} tab. Do you really want another? </div> } {if tabTypes[type].createNew onClick = -> url = tabTypes[type].createNew() url = await url if url.then? setUrl url setSubmit true <> <div className="form-group"> <button className="btn btn-primary btn-lg btn-block" onClick={onClick}> New {tabTypes[type].longTitle ? tabTypes[type].title} {capitalize tabTypes[type].instance} </button> </div> <p>Or paste the URL for an existing {tabTypes[type].instance}:</p> </> } {if type == 'zoom' <> <Form.Group> <Form.Label>Room number</Form.Label> <Form.Control type="text" placeholder="123456789" value={zoomID} onChange={(e) -> setZoomID e.target.value}/> </Form.Group> <Form.Group> <Form.Label>Room password / hash (if needed)</Form.Label> <Form.Control type="text" placeholder="MzN..." value={zoomPwd} onChange={(e) -> setZoomPwd e.target.value}/> </Form.Group> </> } {tabTypePage[type].bottomDescription} <div className="form-group"> <label>URL</label> <input type="url" placeholder="https://..." className="form-control" value={url} required onChange={(e) -> setUrl e.target.value}/> </div> <div className="form-group"> <label>Tab title (can be renamed later)</label> <input type="text" placeholder="Cool Site" className="form-control" value={title} required pattern=".*\S.*" onChange={(e) -> setTitle e.target.value; setManualTitle true}/> </div> <button ref={submitButton} type="submit" className="btn btn-primary btn-lg btn-block mb-1"> Embed This URL </button> </form> </div> </div> </div> </div> TabNew.displayName = 'TabNew'
201646
import React, {useState, useEffect, useRef} from 'react' import {Form} from 'react-bootstrap' import {validURL, tabTypes, categories, mangleTab, zoomRegExp} from '/lib/tabs' import {useDebounce} from './lib/useDebounce' import {getCreator} from './lib/presenceId' import {capitalize} from './lib/capitalize' export tabTypePage = iframe: topDescription: <p>Paste the URL for any embeddable website, e.g., Wikipedia:</p> cocreate: topDescription: <p>This server uses <a className="font-weight-bold" href="https://github.com/edemaine/cocreate">Cocreate</a> for a shared whiteboard.</p> jitsi: topDescription: <p>This server recommends <a className="font-weight-bold" href="https://meet.jit.si/">Jitsi Meet</a> for video conferencing, because it allows free creation of unlimited rooms.</p> youtube: topDescription: <p>Paste a <a className="font-weight-bold" href="https://www.youtube.com/">YouTube</a> link and we'll turn it into its embeddable form:</p> zoom: topDescription: <p>If you create a <a className="font-weight-bold" href="https://zoom.us/">Zoom</a> meeting yourself, you can embed it here.</p> bottomDescription: <p>Or paste a Zoom invitation link:</p> tabTypesByCategory = {} do -> # avoid namespace pollution for tabType, tabData of tabTypes category = tabData.category ? tabData.title tabTypesByCategory[category] ?= {} tabTypesByCategory[category][tabType] = tabData export TabNew = ({node, meetingId, roomId, replaceTabNew, existingTabTypes}) -> [url, setUrl] = useState '' [title, setTitle] = useState '' [category, setCategory] = useState 'Web' [type, setType] = useState 'iframe' [manualTitle, setManualTitle] = useState false [submit, setSubmit] = useState false submitButton = useRef() ## Zoom [zoomID, setZoomID] = useState '' [zoomPwd, setZoomPwd] = useState '' useEffect -> return unless type == 'zoom' if zoomID match = zoomRegExp.exec url setUrl "#{match?[1] ? 'https://zoom.us/'}j/#{zoomID}" + if zoomPwd then "?pwd=#{zoom<PASSWORD>}" else '' , [zoomID, zoomPwd, type] useEffect -> return unless type == 'zoom' match = zoomRegExp.exec url setZoomID match[2] if match?[2] setZoomPwd match[3] if match?[3] , [url, type] ## Automatic mangling after a little idle time urlDebounce = useDebounce url, 100 titleDebounce = useDebounce title, 100 useEffect -> tab = mangleTab {url, title, type, manualTitle} setUrl tab.url if tab.url != url setTitle tab.title if tab.title != title setType tab.type if tab.type != type setManualTitle tab.manualTitle if tab.manualTitle != manualTitle if submit setSubmit false setTimeout (-> submitButton.current?.click()), 0 undefined , [urlDebounce, titleDebounce, submit] onCategory = (categoryName) -> (e) -> e.preventDefault() unless category == categoryName setCategory categoryName for tabType of tabTypesByCategory[categoryName] break # choose first tabType within category setType tabType onType = (tabType) -> (e) -> e.preventDefault() setType tabType onSubmit = (e) -> e.preventDefault() return unless validURL url ## One last mangle (in case didn't reach idle threshold) tab = mangleTab meeting: meetingId room: roomId title: title.trim() type: type url: url manualTitle: manualTitle creator: getCreator() , true id = Meteor.apply 'tabNew', [tab], returnStubValue: true replaceTabNew {id, node} <div className="card"> <div className="card-body"> <h3 className="card-title">Add Shared Tab to Room</h3> <p className="card-text"> Create/embed a widget for everyone in this room to use. </p> <div className="card form-group"> <div className="card-header"> <ul className="nav nav-tabs card-header-tabs" role="tablist"> {for categoryName, categoryTabTypes of tabTypesByCategory selected = (category == categoryName) <li key={categoryName} className="nav-item" role="presentation"> <a className="nav-link #{if selected then 'active'}" href="#" role="tab" aria-selected="#{selected}" onClick={onCategory categoryName}> {categoryName} </a> </li> } </ul> </div> {if (tabType for tabType of tabTypesByCategory[category]).length > 1 <div className="card-header"> <ul className="nav nav-tabs card-header-tabs" role="tablist"> {for tabType, tabData of tabTypesByCategory[category] selected = (type == tabType) disabled = tabData.onePerRoom and existingTabTypes[tabType] <li key={tabType} disabled={disabled} className="nav-item" role="presentation"> <a className="nav-link #{if selected then 'active'}" href="#" role="tab" aria-selected="#{selected}" onClick={onType tabType}> {tabData.title} </a> </li> } </ul> </div> } <div className="card-body"> <form className="newTab" onSubmit={onSubmit}> {if categories[category]?.onePerRoom and (tabType for tabType of tabTypesByCategory[category] \ when existingTabTypes[tabType]).length <div className="alert alert-warning"> WARNING: This room already has a {category} tab. Do you really want another? </div> } {tabTypePage[type].topDescription} {if tabTypes[type].onePerRoom and existingTabTypes[type] <div className="alert alert-warning"> WARNING: This room already has a {tabTypes[type].longTitle ? tabTypes[type].title} tab. Do you really want another? </div> } {if tabTypes[type].createNew onClick = -> url = tabTypes[type].createNew() url = await url if url.then? setUrl url setSubmit true <> <div className="form-group"> <button className="btn btn-primary btn-lg btn-block" onClick={onClick}> New {tabTypes[type].longTitle ? tabTypes[type].title} {capitalize tabTypes[type].instance} </button> </div> <p>Or paste the URL for an existing {tabTypes[type].instance}:</p> </> } {if type == 'zoom' <> <Form.Group> <Form.Label>Room number</Form.Label> <Form.Control type="text" placeholder="123456789" value={zoomID} onChange={(e) -> setZoomID e.target.value}/> </Form.Group> <Form.Group> <Form.Label>Room password / hash (if needed)</Form.Label> <Form.Control type="text" placeholder="MzN..." value={zoomPwd} onChange={(e) -> setZoomPwd e.target.value}/> </Form.Group> </> } {tabTypePage[type].bottomDescription} <div className="form-group"> <label>URL</label> <input type="url" placeholder="https://..." className="form-control" value={url} required onChange={(e) -> setUrl e.target.value}/> </div> <div className="form-group"> <label>Tab title (can be renamed later)</label> <input type="text" placeholder="Cool Site" className="form-control" value={title} required pattern=".*\S.*" onChange={(e) -> setTitle e.target.value; setManualTitle true}/> </div> <button ref={submitButton} type="submit" className="btn btn-primary btn-lg btn-block mb-1"> Embed This URL </button> </form> </div> </div> </div> </div> TabNew.displayName = 'TabNew'
true
import React, {useState, useEffect, useRef} from 'react' import {Form} from 'react-bootstrap' import {validURL, tabTypes, categories, mangleTab, zoomRegExp} from '/lib/tabs' import {useDebounce} from './lib/useDebounce' import {getCreator} from './lib/presenceId' import {capitalize} from './lib/capitalize' export tabTypePage = iframe: topDescription: <p>Paste the URL for any embeddable website, e.g., Wikipedia:</p> cocreate: topDescription: <p>This server uses <a className="font-weight-bold" href="https://github.com/edemaine/cocreate">Cocreate</a> for a shared whiteboard.</p> jitsi: topDescription: <p>This server recommends <a className="font-weight-bold" href="https://meet.jit.si/">Jitsi Meet</a> for video conferencing, because it allows free creation of unlimited rooms.</p> youtube: topDescription: <p>Paste a <a className="font-weight-bold" href="https://www.youtube.com/">YouTube</a> link and we'll turn it into its embeddable form:</p> zoom: topDescription: <p>If you create a <a className="font-weight-bold" href="https://zoom.us/">Zoom</a> meeting yourself, you can embed it here.</p> bottomDescription: <p>Or paste a Zoom invitation link:</p> tabTypesByCategory = {} do -> # avoid namespace pollution for tabType, tabData of tabTypes category = tabData.category ? tabData.title tabTypesByCategory[category] ?= {} tabTypesByCategory[category][tabType] = tabData export TabNew = ({node, meetingId, roomId, replaceTabNew, existingTabTypes}) -> [url, setUrl] = useState '' [title, setTitle] = useState '' [category, setCategory] = useState 'Web' [type, setType] = useState 'iframe' [manualTitle, setManualTitle] = useState false [submit, setSubmit] = useState false submitButton = useRef() ## Zoom [zoomID, setZoomID] = useState '' [zoomPwd, setZoomPwd] = useState '' useEffect -> return unless type == 'zoom' if zoomID match = zoomRegExp.exec url setUrl "#{match?[1] ? 'https://zoom.us/'}j/#{zoomID}" + if zoomPwd then "?pwd=#{zoomPI:PASSWORD:<PASSWORD>END_PI}" else '' , [zoomID, zoomPwd, type] useEffect -> return unless type == 'zoom' match = zoomRegExp.exec url setZoomID match[2] if match?[2] setZoomPwd match[3] if match?[3] , [url, type] ## Automatic mangling after a little idle time urlDebounce = useDebounce url, 100 titleDebounce = useDebounce title, 100 useEffect -> tab = mangleTab {url, title, type, manualTitle} setUrl tab.url if tab.url != url setTitle tab.title if tab.title != title setType tab.type if tab.type != type setManualTitle tab.manualTitle if tab.manualTitle != manualTitle if submit setSubmit false setTimeout (-> submitButton.current?.click()), 0 undefined , [urlDebounce, titleDebounce, submit] onCategory = (categoryName) -> (e) -> e.preventDefault() unless category == categoryName setCategory categoryName for tabType of tabTypesByCategory[categoryName] break # choose first tabType within category setType tabType onType = (tabType) -> (e) -> e.preventDefault() setType tabType onSubmit = (e) -> e.preventDefault() return unless validURL url ## One last mangle (in case didn't reach idle threshold) tab = mangleTab meeting: meetingId room: roomId title: title.trim() type: type url: url manualTitle: manualTitle creator: getCreator() , true id = Meteor.apply 'tabNew', [tab], returnStubValue: true replaceTabNew {id, node} <div className="card"> <div className="card-body"> <h3 className="card-title">Add Shared Tab to Room</h3> <p className="card-text"> Create/embed a widget for everyone in this room to use. </p> <div className="card form-group"> <div className="card-header"> <ul className="nav nav-tabs card-header-tabs" role="tablist"> {for categoryName, categoryTabTypes of tabTypesByCategory selected = (category == categoryName) <li key={categoryName} className="nav-item" role="presentation"> <a className="nav-link #{if selected then 'active'}" href="#" role="tab" aria-selected="#{selected}" onClick={onCategory categoryName}> {categoryName} </a> </li> } </ul> </div> {if (tabType for tabType of tabTypesByCategory[category]).length > 1 <div className="card-header"> <ul className="nav nav-tabs card-header-tabs" role="tablist"> {for tabType, tabData of tabTypesByCategory[category] selected = (type == tabType) disabled = tabData.onePerRoom and existingTabTypes[tabType] <li key={tabType} disabled={disabled} className="nav-item" role="presentation"> <a className="nav-link #{if selected then 'active'}" href="#" role="tab" aria-selected="#{selected}" onClick={onType tabType}> {tabData.title} </a> </li> } </ul> </div> } <div className="card-body"> <form className="newTab" onSubmit={onSubmit}> {if categories[category]?.onePerRoom and (tabType for tabType of tabTypesByCategory[category] \ when existingTabTypes[tabType]).length <div className="alert alert-warning"> WARNING: This room already has a {category} tab. Do you really want another? </div> } {tabTypePage[type].topDescription} {if tabTypes[type].onePerRoom and existingTabTypes[type] <div className="alert alert-warning"> WARNING: This room already has a {tabTypes[type].longTitle ? tabTypes[type].title} tab. Do you really want another? </div> } {if tabTypes[type].createNew onClick = -> url = tabTypes[type].createNew() url = await url if url.then? setUrl url setSubmit true <> <div className="form-group"> <button className="btn btn-primary btn-lg btn-block" onClick={onClick}> New {tabTypes[type].longTitle ? tabTypes[type].title} {capitalize tabTypes[type].instance} </button> </div> <p>Or paste the URL for an existing {tabTypes[type].instance}:</p> </> } {if type == 'zoom' <> <Form.Group> <Form.Label>Room number</Form.Label> <Form.Control type="text" placeholder="123456789" value={zoomID} onChange={(e) -> setZoomID e.target.value}/> </Form.Group> <Form.Group> <Form.Label>Room password / hash (if needed)</Form.Label> <Form.Control type="text" placeholder="MzN..." value={zoomPwd} onChange={(e) -> setZoomPwd e.target.value}/> </Form.Group> </> } {tabTypePage[type].bottomDescription} <div className="form-group"> <label>URL</label> <input type="url" placeholder="https://..." className="form-control" value={url} required onChange={(e) -> setUrl e.target.value}/> </div> <div className="form-group"> <label>Tab title (can be renamed later)</label> <input type="text" placeholder="Cool Site" className="form-control" value={title} required pattern=".*\S.*" onChange={(e) -> setTitle e.target.value; setManualTitle true}/> </div> <button ref={submitButton} type="submit" className="btn btn-primary btn-lg btn-block mb-1"> Embed This URL </button> </form> </div> </div> </div> </div> TabNew.displayName = 'TabNew'
[ { "context": "#options.username or= null\n #options.password or= null\n options.authdb or= 'admin'\n return options\n\ncl", "end": 553, "score": 0.9404250383377075, "start": 549, "tag": "PASSWORD", "value": "null" } ]
lib/main.coffee
classdojo/mongo-watch
0
{EventEmitter} = require 'events' formats = require './formats' getOplogStream = require './getOplogStream' {walk, convertObjectID} = require './util' applyDefaults = (options) -> options or= {} options.port or= 27017 options.host or= 'localhost' options.dbOpts or= {w: 1} options.format or= 'raw' options.useMasterOplog or= false options.convertObjectIDs ?= true options.onError or= (error) -> console.log 'Error - MongoWatch:', (error?.stack or error) options.onDebug or= -> #options.username or= null #options.password or= null options.authdb or= 'admin' return options class MongoWatch status: 'connecting' watching: [] constructor: (options) -> @options = applyDefaults options @channel = new EventEmitter @channel.on 'error', @options.onError @channel.on 'connected', => @status = 'connected' @debug = @options.onDebug getOplogStream @options, (err, @stream, @oplogClient) => @channel.emit 'error', err if err @debug "Emiting 'connected'. Stream exists:", @stream? @channel.emit 'connected' ready: (done) -> isReady = @status is 'connected' @debug 'Ready:', isReady if isReady return done() else @channel.once 'connected', done watch: (collection, notify) -> collection ||= 'all' notify ||= console.log @ready => unless @watching[collection]? watcher = (data) => relevant = (collection is 'all') or (data.ns is collection) @debug 'Data changed:', {data: data, watching: collection, relevant: relevant} return unless relevant channel = if collection then "change:#{collection}" else 'change' formatter = formats[@options.format] or formats['raw'] event = formatter data # convert ObjectIDs to strings if @options.convertObjectIDs is true event = walk event, convertObjectID @debug 'Emitting event:', {channel: channel, event: event} @channel.emit collection, event # watch user model @debug 'Adding emitter for:', {collection: collection} @stream.on 'data', watcher @watching[collection] = watcher @debug 'Adding listener on:', {collection: collection} @channel.on collection, notify stop: (collection) -> @debug 'Removing listeners for:', collection collection ||= 'all' @channel.removeAllListeners collection @stream.removeListener 'data', @watching[collection] delete @watching[collection] stopAll: -> @stop coll for coll of @watching module.exports = MongoWatch
121094
{EventEmitter} = require 'events' formats = require './formats' getOplogStream = require './getOplogStream' {walk, convertObjectID} = require './util' applyDefaults = (options) -> options or= {} options.port or= 27017 options.host or= 'localhost' options.dbOpts or= {w: 1} options.format or= 'raw' options.useMasterOplog or= false options.convertObjectIDs ?= true options.onError or= (error) -> console.log 'Error - MongoWatch:', (error?.stack or error) options.onDebug or= -> #options.username or= null #options.password or= <PASSWORD> options.authdb or= 'admin' return options class MongoWatch status: 'connecting' watching: [] constructor: (options) -> @options = applyDefaults options @channel = new EventEmitter @channel.on 'error', @options.onError @channel.on 'connected', => @status = 'connected' @debug = @options.onDebug getOplogStream @options, (err, @stream, @oplogClient) => @channel.emit 'error', err if err @debug "Emiting 'connected'. Stream exists:", @stream? @channel.emit 'connected' ready: (done) -> isReady = @status is 'connected' @debug 'Ready:', isReady if isReady return done() else @channel.once 'connected', done watch: (collection, notify) -> collection ||= 'all' notify ||= console.log @ready => unless @watching[collection]? watcher = (data) => relevant = (collection is 'all') or (data.ns is collection) @debug 'Data changed:', {data: data, watching: collection, relevant: relevant} return unless relevant channel = if collection then "change:#{collection}" else 'change' formatter = formats[@options.format] or formats['raw'] event = formatter data # convert ObjectIDs to strings if @options.convertObjectIDs is true event = walk event, convertObjectID @debug 'Emitting event:', {channel: channel, event: event} @channel.emit collection, event # watch user model @debug 'Adding emitter for:', {collection: collection} @stream.on 'data', watcher @watching[collection] = watcher @debug 'Adding listener on:', {collection: collection} @channel.on collection, notify stop: (collection) -> @debug 'Removing listeners for:', collection collection ||= 'all' @channel.removeAllListeners collection @stream.removeListener 'data', @watching[collection] delete @watching[collection] stopAll: -> @stop coll for coll of @watching module.exports = MongoWatch
true
{EventEmitter} = require 'events' formats = require './formats' getOplogStream = require './getOplogStream' {walk, convertObjectID} = require './util' applyDefaults = (options) -> options or= {} options.port or= 27017 options.host or= 'localhost' options.dbOpts or= {w: 1} options.format or= 'raw' options.useMasterOplog or= false options.convertObjectIDs ?= true options.onError or= (error) -> console.log 'Error - MongoWatch:', (error?.stack or error) options.onDebug or= -> #options.username or= null #options.password or= PI:PASSWORD:<PASSWORD>END_PI options.authdb or= 'admin' return options class MongoWatch status: 'connecting' watching: [] constructor: (options) -> @options = applyDefaults options @channel = new EventEmitter @channel.on 'error', @options.onError @channel.on 'connected', => @status = 'connected' @debug = @options.onDebug getOplogStream @options, (err, @stream, @oplogClient) => @channel.emit 'error', err if err @debug "Emiting 'connected'. Stream exists:", @stream? @channel.emit 'connected' ready: (done) -> isReady = @status is 'connected' @debug 'Ready:', isReady if isReady return done() else @channel.once 'connected', done watch: (collection, notify) -> collection ||= 'all' notify ||= console.log @ready => unless @watching[collection]? watcher = (data) => relevant = (collection is 'all') or (data.ns is collection) @debug 'Data changed:', {data: data, watching: collection, relevant: relevant} return unless relevant channel = if collection then "change:#{collection}" else 'change' formatter = formats[@options.format] or formats['raw'] event = formatter data # convert ObjectIDs to strings if @options.convertObjectIDs is true event = walk event, convertObjectID @debug 'Emitting event:', {channel: channel, event: event} @channel.emit collection, event # watch user model @debug 'Adding emitter for:', {collection: collection} @stream.on 'data', watcher @watching[collection] = watcher @debug 'Adding listener on:', {collection: collection} @channel.on collection, notify stop: (collection) -> @debug 'Removing listeners for:', collection collection ||= 'all' @channel.removeAllListeners collection @stream.removeListener 'data', @watching[collection] delete @watching[collection] stopAll: -> @stop coll for coll of @watching module.exports = MongoWatch
[ { "context": "e' : (test) ->\n message = \"<presence from='thing@clayster.com/imc'\n to='discovery.clayster.com'\n ", "end": 824, "score": 0.9985742568969727, "start": 806, "tag": "EMAIL", "value": "thing@clayster.com" }, { "context": "resence'\n test....
test/presence-handler.test.coffee
TNO-IoT/ekster
3
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # Some test cases refer to paragraphs and / or examples from the spec. {EventEmitter} = require 'events' PresenceHandler = require '../src/presence-handler.coffee' Backend = require '../src/backend.coffee' Processor = require '../src/processor.coffee' Thing = require '../src/thing.coffee' ltx = require('node-xmpp-core').ltx Q = require 'q' class Connection extends EventEmitter constructor: () -> class TestBackend extends Backend constructor: (@callback) -> super 'test' get: (jid) -> return @callback('get', jid) update: (thing) -> return @callback('update', thing) exports.PresenceHandlerTest = 'test subscribe' : (test) -> message = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='0' type='subscribe'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'subscribe' test.expect 5 test.done() handler.handle ltx.parse(message) 'test unsubscribe' : (test) -> test.expect 9 message = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='0' type='unsubscribe'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' if stanza.attrs.type isnt 'unsubscribed' test.equal stanza.attrs.type, 'unsubscribe' test.done() handler.handle ltx.parse(message) 'test subscribed' : (test) -> message = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='0' type='subscribed'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'subscribed' test.expect 5 test.done() handler.handle ltx.parse(message) 'test unfriend' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> received++ if stanza.attrs.type is 'unsubscribe' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribe' if stanza.attrs.type is 'unsubscribed' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribed' if received is 2 test.expect 8 test.done() handler.unfriend 'thing@clayster.com' 'test online - user is offline' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = () -> test.equal true, false, 'do not call this' test.done() onFailure = () -> test.expect 4 test.done() promise = handler.whenOnline 'thing@clayster.com', 100 promise.then onSuccess, onFailure 'test online - user is online' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = (jid) -> test.equal jid, 'thing@clayster.com/imc' test.expect 5 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise = handler.whenOnline 'thing@clayster.com', 1000 promise.then onSuccess, onFailure presence = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='1' type='available'/>" handler.handlePresence 'thing@clayster.com', ltx.parse(presence) 'test online - user is online - no status' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = (jid) -> test.equal jid, 'thing@clayster.com/imc' test.expect 5 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise = handler.whenOnline 'thing@clayster.com', 1000 promise.then onSuccess, onFailure presence = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='1'/>" handler.handlePresence 'thing@clayster.com', ltx.parse(presence) 'test online - multiple request for same user' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' count = 0 onSuccess = () -> count++ if count > 1 test.expect 4 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise1 = handler.whenOnline 'thing@clayster.com', 1000 promise1.then onSuccess, onFailure promise2 = handler.whenOnline 'thing@clayster.com', 1000 promise2.then onSuccess, onFailure presence = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='1' type='available'/>" handler.handlePresence 'thing@clayster.com', ltx.parse(presence) 'test online - unavailable' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = () -> test.equal true, false, 'do not call this' test.done() onFailure = () -> test.expect 4 test.done() promise = handler.whenOnline 'thing@clayster.com', 100 promise.then onSuccess, onFailure presence = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com' id='1' type='unavailable'/>" handler.handlePresence 'thing@clayster.com', ltx.parse(presence) 'test came online - has messages' : (test) -> message = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, undefined test.equal stanza.name, 'iq' test.equal stanza.attrs.to, 'thing@clayster.com/imc' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'set' test.equal stanza.children.length, 1 test.equal stanza.children[0].name, 'claimed' test.equal stanza.children[0].attrs.jid, 'owner@clayster.com' response = "<iq type='result' from='thing@clayster.com/imc' to='discovery.clayster.com' id='#{ stanza.attrs.id }'/>" connection.emit 'stanza', ltx.parse(response) processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'thing@clayster.com' return Q.fcall -> thing.owner = 'owner@clayster.com' thing.needsNotification = true thing2 = new Thing thing.jid thing2.owner = 'owner@clayster.com' thing2.needsNotification = false return [ thing, thing2 ] else if method is 'update' test.equal thing.jid, 'thing@clayster.com' test.equal thing.needsNotification, '' thing.needsNofication = undefined test.expect 11 test.done() return Q.fcall -> return thing handler.handle ltx.parse(message) 'test came online - no messages' : (test) -> message = "<presence from='thing@clayster.com/imc' to='discovery.clayster.com'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'thing@clayster.com' test.expect 1 test.done() return Q.fcall -> thing.owner = 'owner@clayster.com' thing.needsNotification = false return [ thing1, thing2 ] test.equal true, false, 'do not get here' test.done() handler.handle ltx.parse(message) 'test unfriend if possible - it is possible' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> received++ if stanza.attrs.type is 'unsubscribe' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribe' if stanza.attrs.type is 'unsubscribed' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'thing@clayster.com' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribed' if received is 2 test.expect 9 test.done() processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'thing@clayster.com' return Q.fcall -> return [ ] test.equal true, false, 'do not get here' test.done() handler.unfriendIfPossible 'thing@clayster.com' 'test unfriend if possible - it is not possible' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> test.equal true, false, 'should not be called' processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'thing@clayster.com' test.expect 1 test.done() return Q.fcall -> return [ thing ] handler.unfriendIfPossible 'thing@clayster.com'
66339
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # Some test cases refer to paragraphs and / or examples from the spec. {EventEmitter} = require 'events' PresenceHandler = require '../src/presence-handler.coffee' Backend = require '../src/backend.coffee' Processor = require '../src/processor.coffee' Thing = require '../src/thing.coffee' ltx = require('node-xmpp-core').ltx Q = require 'q' class Connection extends EventEmitter constructor: () -> class TestBackend extends Backend constructor: (@callback) -> super 'test' get: (jid) -> return @callback('get', jid) update: (thing) -> return @callback('update', thing) exports.PresenceHandlerTest = 'test subscribe' : (test) -> message = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='0' type='subscribe'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'subscribe' test.expect 5 test.done() handler.handle ltx.parse(message) 'test unsubscribe' : (test) -> test.expect 9 message = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='0' type='unsubscribe'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' if stanza.attrs.type isnt 'unsubscribed' test.equal stanza.attrs.type, 'unsubscribe' test.done() handler.handle ltx.parse(message) 'test subscribed' : (test) -> message = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='0' type='subscribed'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'subscribed' test.expect 5 test.done() handler.handle ltx.parse(message) 'test unfriend' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> received++ if stanza.attrs.type is 'unsubscribe' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribe' if stanza.attrs.type is 'unsubscribed' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribed' if received is 2 test.expect 8 test.done() handler.unfriend '<EMAIL>' 'test online - user is offline' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = () -> test.equal true, false, 'do not call this' test.done() onFailure = () -> test.expect 4 test.done() promise = handler.whenOnline '<EMAIL>', 100 promise.then onSuccess, onFailure 'test online - user is online' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = (jid) -> test.equal jid, '<EMAIL>/imc' test.expect 5 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise = handler.whenOnline '<EMAIL>', 1000 promise.then onSuccess, onFailure presence = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='1' type='available'/>" handler.handlePresence '<EMAIL>', ltx.parse(presence) 'test online - user is online - no status' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = (jid) -> test.equal jid, '<EMAIL>/imc' test.expect 5 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise = handler.whenOnline '<EMAIL>', 1000 promise.then onSuccess, onFailure presence = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='1'/>" handler.handlePresence '<EMAIL>', ltx.parse(presence) 'test online - multiple request for same user' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' count = 0 onSuccess = () -> count++ if count > 1 test.expect 4 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise1 = handler.whenOnline '<EMAIL>', 1000 promise1.then onSuccess, onFailure promise2 = handler.whenOnline '<EMAIL>', 1000 promise2.then onSuccess, onFailure presence = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='1' type='available'/>" handler.handlePresence '<EMAIL>', ltx.parse(presence) 'test online - unavailable' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = () -> test.equal true, false, 'do not call this' test.done() onFailure = () -> test.expect 4 test.done() promise = handler.whenOnline '<EMAIL>', 100 promise.then onSuccess, onFailure presence = "<presence from='<EMAIL>/imc' to='discovery.clayster.com' id='1' type='unavailable'/>" handler.handlePresence '<EMAIL>', ltx.parse(presence) 'test came online - has messages' : (test) -> message = "<presence from='<EMAIL>/imc' to='discovery.clayster.com'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, undefined test.equal stanza.name, 'iq' test.equal stanza.attrs.to, '<EMAIL>.com/imc' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'set' test.equal stanza.children.length, 1 test.equal stanza.children[0].name, 'claimed' test.equal stanza.children[0].attrs.jid, '<EMAIL>' response = "<iq type='result' from='<EMAIL>/imc' to='discovery.clayster.com' id='#{ stanza.attrs.id }'/>" connection.emit 'stanza', ltx.parse(response) processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, '<EMAIL>' return Q.fcall -> thing.owner = '<EMAIL>' thing.needsNotification = true thing2 = new Thing thing.jid thing2.owner = '<EMAIL>' thing2.needsNotification = false return [ thing, thing2 ] else if method is 'update' test.equal thing.jid, '<EMAIL>' test.equal thing.needsNotification, '' thing.needsNofication = undefined test.expect 11 test.done() return Q.fcall -> return thing handler.handle ltx.parse(message) 'test came online - no messages' : (test) -> message = "<presence from='<EMAIL>/imc' to='discovery.clayster.com'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, '<EMAIL>' test.expect 1 test.done() return Q.fcall -> thing.owner = '<EMAIL>' thing.needsNotification = false return [ thing1, thing2 ] test.equal true, false, 'do not get here' test.done() handler.handle ltx.parse(message) 'test unfriend if possible - it is possible' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> received++ if stanza.attrs.type is 'unsubscribe' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribe' if stanza.attrs.type is 'unsubscribed' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, '<EMAIL>' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribed' if received is 2 test.expect 9 test.done() processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, '<EMAIL>' return Q.fcall -> return [ ] test.equal true, false, 'do not get here' test.done() handler.unfriendIfPossible '<EMAIL>' 'test unfriend if possible - it is not possible' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> test.equal true, false, 'should not be called' processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, '<EMAIL>' test.expect 1 test.done() return Q.fcall -> return [ thing ] handler.unfriendIfPossible '<EMAIL>'
true
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # Some test cases refer to paragraphs and / or examples from the spec. {EventEmitter} = require 'events' PresenceHandler = require '../src/presence-handler.coffee' Backend = require '../src/backend.coffee' Processor = require '../src/processor.coffee' Thing = require '../src/thing.coffee' ltx = require('node-xmpp-core').ltx Q = require 'q' class Connection extends EventEmitter constructor: () -> class TestBackend extends Backend constructor: (@callback) -> super 'test' get: (jid) -> return @callback('get', jid) update: (thing) -> return @callback('update', thing) exports.PresenceHandlerTest = 'test subscribe' : (test) -> message = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='0' type='subscribe'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'subscribe' test.expect 5 test.done() handler.handle ltx.parse(message) 'test unsubscribe' : (test) -> test.expect 9 message = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='0' type='unsubscribe'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' if stanza.attrs.type isnt 'unsubscribed' test.equal stanza.attrs.type, 'unsubscribe' test.done() handler.handle ltx.parse(message) 'test subscribed' : (test) -> message = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='0' type='subscribed'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, '0', 'should generate a new id' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'subscribed' test.expect 5 test.done() handler.handle ltx.parse(message) 'test unfriend' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> received++ if stanza.attrs.type is 'unsubscribe' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribe' if stanza.attrs.type is 'unsubscribed' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribed' if received is 2 test.expect 8 test.done() handler.unfriend 'PI:EMAIL:<EMAIL>END_PI' 'test online - user is offline' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = () -> test.equal true, false, 'do not call this' test.done() onFailure = () -> test.expect 4 test.done() promise = handler.whenOnline 'PI:EMAIL:<EMAIL>END_PI', 100 promise.then onSuccess, onFailure 'test online - user is online' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = (jid) -> test.equal jid, 'PI:EMAIL:<EMAIL>END_PI/imc' test.expect 5 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise = handler.whenOnline 'PI:EMAIL:<EMAIL>END_PI', 1000 promise.then onSuccess, onFailure presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='1' type='available'/>" handler.handlePresence 'PI:EMAIL:<EMAIL>END_PI', ltx.parse(presence) 'test online - user is online - no status' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = (jid) -> test.equal jid, 'PI:EMAIL:<EMAIL>END_PI/imc' test.expect 5 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise = handler.whenOnline 'PI:EMAIL:<EMAIL>END_PI', 1000 promise.then onSuccess, onFailure presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='1'/>" handler.handlePresence 'PI:EMAIL:<EMAIL>END_PI', ltx.parse(presence) 'test online - multiple request for same user' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' return Q.fcall -> return [ thing ] connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' count = 0 onSuccess = () -> count++ if count > 1 test.expect 4 test.done() onFailure = () -> test.equal true, false, 'do not call this' test.done() promise1 = handler.whenOnline 'PI:EMAIL:<EMAIL>END_PI', 1000 promise1.then onSuccess, onFailure promise2 = handler.whenOnline 'PI:EMAIL:<EMAIL>END_PI', 1000 promise2.then onSuccess, onFailure presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='1' type='available'/>" handler.handlePresence 'PI:EMAIL:<EMAIL>END_PI', ltx.parse(presence) 'test online - unavailable' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'probe' onSuccess = () -> test.equal true, false, 'do not call this' test.done() onFailure = () -> test.expect 4 test.done() promise = handler.whenOnline 'PI:EMAIL:<EMAIL>END_PI', 100 promise.then onSuccess, onFailure presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='1' type='unavailable'/>" handler.handlePresence 'PI:EMAIL:<EMAIL>END_PI', ltx.parse(presence) 'test came online - has messages' : (test) -> message = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) connection.send = (stanza) -> test.notEqual stanza.attrs.id, undefined test.equal stanza.name, 'iq' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI.com/imc' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'set' test.equal stanza.children.length, 1 test.equal stanza.children[0].name, 'claimed' test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI' response = "<iq type='result' from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com' id='#{ stanza.attrs.id }'/>" connection.emit 'stanza', ltx.parse(response) processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI' return Q.fcall -> thing.owner = 'PI:EMAIL:<EMAIL>END_PI' thing.needsNotification = true thing2 = new Thing thing.jid thing2.owner = 'PI:EMAIL:<EMAIL>END_PI' thing2.needsNotification = false return [ thing, thing2 ] else if method is 'update' test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI' test.equal thing.needsNotification, '' thing.needsNofication = undefined test.expect 11 test.done() return Q.fcall -> return thing handler.handle ltx.parse(message) 'test came online - no messages' : (test) -> message = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc' to='discovery.clayster.com'/>" connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI' test.expect 1 test.done() return Q.fcall -> thing.owner = 'PI:EMAIL:<EMAIL>END_PI' thing.needsNotification = false return [ thing1, thing2 ] test.equal true, false, 'do not get here' test.done() handler.handle ltx.parse(message) 'test unfriend if possible - it is possible' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> received++ if stanza.attrs.type is 'unsubscribe' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribe' if stanza.attrs.type is 'unsubscribed' test.equal stanza.name, 'presence' test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI' test.equal stanza.attrs.from, 'discovery.clayster.com' test.equal stanza.attrs.type, 'unsubscribed' if received is 2 test.expect 9 test.done() processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI' return Q.fcall -> return [ ] test.equal true, false, 'do not get here' test.done() handler.unfriendIfPossible 'PI:EMAIL:<EMAIL>END_PI' 'test unfriend if possible - it is not possible' : (test) -> connection = new Connection processor = new Processor(connection, 'discovery.clayster.com') handler = new PresenceHandler(processor) received = 0 connection.send = (stanza) -> test.equal true, false, 'should not be called' processor.backend = new TestBackend (method, thing) -> if method is 'get' test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI' test.expect 1 test.done() return Q.fcall -> return [ thing ] handler.unfriendIfPossible 'PI:EMAIL:<EMAIL>END_PI'
[ { "context": "xedDB = require \"fake-indexeddb\"\n\n###\nimport_key \"1.2.15\" \"5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zk", "end": 1327, "score": 0.9926398396492004, "start": 1321, "tag": "KEY", "value": "1.2.15" }, { "context": "equire \"fake-indexeddb\"\n\n###\nimport_key \"...
dl/test/tr_tests.coffee
ttcoinofficial/ttshares-ui
0
PrivateKey = require '../src/ecc/key_private' PublicKey = require '../src/ecc/key_public' Signature = require '../src/ecc/signature' Aes = require 'ecc/aes' WebSocketRpc = require '../src/rpc_api/WebSocketRpc' GrapheneApi = require '../src/rpc_api/GrapheneApi' Promise = require '../src/common/Promise' ByteBuffer = require '../src/common/bytebuffer' secureRandom = require 'secure-random' assert = require 'assert' tr_helper = require '../src/chain/transaction_helper' th = require './test_helper' hash = require 'common/hash' so_type = require '../src/chain/serializer_operation_types' account_create_type = so_type.account_create transaction_type = so_type.transaction signed_transaction_type = so_type.signed_transaction tr_op = require '../src/chain/signed_transaction' signed_transaction = tr_op.signed_transaction key_create = tr_op.key_create account_create = tr_op.account_create ApiInstances = require('../src/rpc_api/ApiInstances') WalletApi = require '../src/rpc_api/WalletApi' WalletDb = require 'stores/WalletDb' PrivateKeyStore = require "stores/PrivateKeyStore" ApplicationApi = require '../src/rpc_api/ApplicationApi' wallet = new WalletApi() app = new ApplicationApi() helper = require "./test_helper" iDB = require "../src/idb-instance" fakeIndexedDB = require "fake-indexeddb" ### import_key "1.2.15" "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3" ### describe "tr_tests", -> # broadcast with confirmation waits for a block this.timeout(8 * 1000) broadcast = process.env.GPH_TEST_NO_BROADCAST is undefined genesis_private = PrivateKey.fromWif "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3" api = null before (done)-> iDB.init_instance(fakeIndexedDB).init_promise.then () -> api = ApiInstances.instance() api.init_promise.then ()-> done() .catch th.log_error after (done)-> iDB.instance().db().close() # Does Not delete the database ??? fakeIndexedDB.deleteDatabase("graphene_db") api.close() done() #it "update account transaction", -> it "wallet.transfer nomemo", (done)-> helper.test_wallet().then (suffix)=> wallet.transfer( "1.2.15", "1.2.14", 1, "1.3.0", memo = null broadcast, encrypt_memo = no ).then (result)-> #th.print_result result #th.print_hex "" done() .catch th.log_error return it "wallet.transfer encmemo", (done)-> helper.test_wallet().then (suffix)=> wallet.transfer( "1.2.15", "1.2.14", 1, "1.3.0", memo = "memo" broadcast ).then (result)-> #th.print_result result #th.print_hex "" done() .catch th.log_error return # Aes.encrypt data is not matching c++ it "wallet encmemo_format", ()-> sender = PrivateKey.fromSeed("1") receiver = PrivateKey.fromSeed("2") enc_hex = Aes.encrypt_with_checksum( sender receiver.toPublicKey() nonce = 12345 "Hello, world!" ) #console.log('... enc_hex',enc_hex.toString('hex')) memo={ from: sender.toPublicKey() to: receiver.toPublicKey() nonce: 12345 message: new Buffer(enc_hex, 'hex') } enc_buffer = hash.sha256 so_type.memo_data.toBuffer memo assert.equal( enc_buffer.toString('hex') "8de72a07d093a589f574460deb19023b4aff354b561eb34590d9f4629f51dbf3" ) assert.equal( Aes.decrypt_with_checksum( receiver sender.toPublicKey() nonce = 12345 enc_hex ) "Hello, world!" ) return ### assertHexEqual=(x1, x2, msg)-> return if x1 is x2 console.log "ERROR: Unmatched binary\t", msg console.log "Original Transaction" ByteBuffer.fromHex(x1).printDebug() console.log "New Transaction" ByteBuffer.fromHex(x2).printDebug() throw new Error "Unmatched Transaction" check_trx=(description, trx)-> # Match Transaction fromHex -> toHex transaction = transaction_so.fromHex trx.hex #console.log JSON.stringify transaction_so.toObject(transaction),null,4 assertHexEqual trx.hex,transaction_so.toHex(transaction),"initial construction\t" + description # Match Transaction toObject -> fromObject then match to the original hex trx_object = transaction_so.toObject transaction #console.log '... trx_object',JSON.stringify trx_object,null,2 transaction2 = transaction_so.fromObject trx_object assertHexEqual trx.hex,transaction_so.toHex(transaction2),"re-construction\t" + description # readability only (technically redundant) if trx.json try transaction3 = transaction_so.fromObject trx.json assertHexEqual trx.hex,transaction_so.toHex(transaction3),"'json' object\t" + description catch error console.log 'WARNING',error,error.stack transaction check_object=(description, transaction_object)-> transaction = transaction_so.fromObject transaction_object #console.log JSON.stringify transaction_so.toObject(transaction),null,4 hex1 = transaction_so.toHex(transaction) #console.log '... transaction_hex', hex1 transaction2 = transaction_so.fromHex(hex1) hex2 = transaction_so.toHex(transaction2) assertHexEqual hex1, hex2, "hex\t" + description serilized_object = transaction_so.toObject(transaction) #console.log '... transaction', JSON.stringify serilized_object,null,2 transaction3 = transaction_so.fromObject serilized_object hex3 = transaction_so.toHex transaction3 assertHexEqual hex1, hex3, "object\t" + description ###
135644
PrivateKey = require '../src/ecc/key_private' PublicKey = require '../src/ecc/key_public' Signature = require '../src/ecc/signature' Aes = require 'ecc/aes' WebSocketRpc = require '../src/rpc_api/WebSocketRpc' GrapheneApi = require '../src/rpc_api/GrapheneApi' Promise = require '../src/common/Promise' ByteBuffer = require '../src/common/bytebuffer' secureRandom = require 'secure-random' assert = require 'assert' tr_helper = require '../src/chain/transaction_helper' th = require './test_helper' hash = require 'common/hash' so_type = require '../src/chain/serializer_operation_types' account_create_type = so_type.account_create transaction_type = so_type.transaction signed_transaction_type = so_type.signed_transaction tr_op = require '../src/chain/signed_transaction' signed_transaction = tr_op.signed_transaction key_create = tr_op.key_create account_create = tr_op.account_create ApiInstances = require('../src/rpc_api/ApiInstances') WalletApi = require '../src/rpc_api/WalletApi' WalletDb = require 'stores/WalletDb' PrivateKeyStore = require "stores/PrivateKeyStore" ApplicationApi = require '../src/rpc_api/ApplicationApi' wallet = new WalletApi() app = new ApplicationApi() helper = require "./test_helper" iDB = require "../src/idb-instance" fakeIndexedDB = require "fake-indexeddb" ### import_key "<KEY>" "<KEY>" ### describe "tr_tests", -> # broadcast with confirmation waits for a block this.timeout(8 * 1000) broadcast = process.env.GPH_TEST_NO_BROADCAST is undefined genesis_private = PrivateKey.fromWif "<KEY>JiwsST4cqQzDeyXtP79zkvFD3" api = null before (done)-> iDB.init_instance(fakeIndexedDB).init_promise.then () -> api = ApiInstances.instance() api.init_promise.then ()-> done() .catch th.log_error after (done)-> iDB.instance().db().close() # Does Not delete the database ??? fakeIndexedDB.deleteDatabase("graphene_db") api.close() done() #it "update account transaction", -> it "wallet.transfer nomemo", (done)-> helper.test_wallet().then (suffix)=> wallet.transfer( "1.2.15", "1.2.14", 1, "1.3.0", memo = null broadcast, encrypt_memo = no ).then (result)-> #th.print_result result #th.print_hex "" done() .catch th.log_error return it "wallet.transfer encmemo", (done)-> helper.test_wallet().then (suffix)=> wallet.transfer( "1.2.15", "1.2.14", 1, "1.3.0", memo = "memo" broadcast ).then (result)-> #th.print_result result #th.print_hex "" done() .catch th.log_error return # Aes.encrypt data is not matching c++ it "wallet encmemo_format", ()-> sender = PrivateKey.fromSeed("1") receiver = PrivateKey.fromSeed("2") enc_hex = Aes.encrypt_with_checksum( sender receiver.toPublicKey() nonce = 12345 "Hello, world!" ) #console.log('... enc_hex',enc_hex.toString('hex')) memo={ from: sender.toPublicKey() to: receiver.toPublicKey() nonce: 12345 message: new Buffer(enc_hex, 'hex') } enc_buffer = hash.sha256 so_type.memo_data.toBuffer memo assert.equal( enc_buffer.toString('hex') "8de72a07d093a589f574460deb19023b4aff354b561eb34590d9f4629f51dbf3" ) assert.equal( Aes.decrypt_with_checksum( receiver sender.toPublicKey() nonce = 12345 enc_hex ) "Hello, world!" ) return ### assertHexEqual=(x1, x2, msg)-> return if x1 is x2 console.log "ERROR: Unmatched binary\t", msg console.log "Original Transaction" ByteBuffer.fromHex(x1).printDebug() console.log "New Transaction" ByteBuffer.fromHex(x2).printDebug() throw new Error "Unmatched Transaction" check_trx=(description, trx)-> # Match Transaction fromHex -> toHex transaction = transaction_so.fromHex trx.hex #console.log JSON.stringify transaction_so.toObject(transaction),null,4 assertHexEqual trx.hex,transaction_so.toHex(transaction),"initial construction\t" + description # Match Transaction toObject -> fromObject then match to the original hex trx_object = transaction_so.toObject transaction #console.log '... trx_object',JSON.stringify trx_object,null,2 transaction2 = transaction_so.fromObject trx_object assertHexEqual trx.hex,transaction_so.toHex(transaction2),"re-construction\t" + description # readability only (technically redundant) if trx.json try transaction3 = transaction_so.fromObject trx.json assertHexEqual trx.hex,transaction_so.toHex(transaction3),"'json' object\t" + description catch error console.log 'WARNING',error,error.stack transaction check_object=(description, transaction_object)-> transaction = transaction_so.fromObject transaction_object #console.log JSON.stringify transaction_so.toObject(transaction),null,4 hex1 = transaction_so.toHex(transaction) #console.log '... transaction_hex', hex1 transaction2 = transaction_so.fromHex(hex1) hex2 = transaction_so.toHex(transaction2) assertHexEqual hex1, hex2, "hex\t" + description serilized_object = transaction_so.toObject(transaction) #console.log '... transaction', JSON.stringify serilized_object,null,2 transaction3 = transaction_so.fromObject serilized_object hex3 = transaction_so.toHex transaction3 assertHexEqual hex1, hex3, "object\t" + description ###
true
PrivateKey = require '../src/ecc/key_private' PublicKey = require '../src/ecc/key_public' Signature = require '../src/ecc/signature' Aes = require 'ecc/aes' WebSocketRpc = require '../src/rpc_api/WebSocketRpc' GrapheneApi = require '../src/rpc_api/GrapheneApi' Promise = require '../src/common/Promise' ByteBuffer = require '../src/common/bytebuffer' secureRandom = require 'secure-random' assert = require 'assert' tr_helper = require '../src/chain/transaction_helper' th = require './test_helper' hash = require 'common/hash' so_type = require '../src/chain/serializer_operation_types' account_create_type = so_type.account_create transaction_type = so_type.transaction signed_transaction_type = so_type.signed_transaction tr_op = require '../src/chain/signed_transaction' signed_transaction = tr_op.signed_transaction key_create = tr_op.key_create account_create = tr_op.account_create ApiInstances = require('../src/rpc_api/ApiInstances') WalletApi = require '../src/rpc_api/WalletApi' WalletDb = require 'stores/WalletDb' PrivateKeyStore = require "stores/PrivateKeyStore" ApplicationApi = require '../src/rpc_api/ApplicationApi' wallet = new WalletApi() app = new ApplicationApi() helper = require "./test_helper" iDB = require "../src/idb-instance" fakeIndexedDB = require "fake-indexeddb" ### import_key "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" ### describe "tr_tests", -> # broadcast with confirmation waits for a block this.timeout(8 * 1000) broadcast = process.env.GPH_TEST_NO_BROADCAST is undefined genesis_private = PrivateKey.fromWif "PI:KEY:<KEY>END_PIJiwsST4cqQzDeyXtP79zkvFD3" api = null before (done)-> iDB.init_instance(fakeIndexedDB).init_promise.then () -> api = ApiInstances.instance() api.init_promise.then ()-> done() .catch th.log_error after (done)-> iDB.instance().db().close() # Does Not delete the database ??? fakeIndexedDB.deleteDatabase("graphene_db") api.close() done() #it "update account transaction", -> it "wallet.transfer nomemo", (done)-> helper.test_wallet().then (suffix)=> wallet.transfer( "1.2.15", "1.2.14", 1, "1.3.0", memo = null broadcast, encrypt_memo = no ).then (result)-> #th.print_result result #th.print_hex "" done() .catch th.log_error return it "wallet.transfer encmemo", (done)-> helper.test_wallet().then (suffix)=> wallet.transfer( "1.2.15", "1.2.14", 1, "1.3.0", memo = "memo" broadcast ).then (result)-> #th.print_result result #th.print_hex "" done() .catch th.log_error return # Aes.encrypt data is not matching c++ it "wallet encmemo_format", ()-> sender = PrivateKey.fromSeed("1") receiver = PrivateKey.fromSeed("2") enc_hex = Aes.encrypt_with_checksum( sender receiver.toPublicKey() nonce = 12345 "Hello, world!" ) #console.log('... enc_hex',enc_hex.toString('hex')) memo={ from: sender.toPublicKey() to: receiver.toPublicKey() nonce: 12345 message: new Buffer(enc_hex, 'hex') } enc_buffer = hash.sha256 so_type.memo_data.toBuffer memo assert.equal( enc_buffer.toString('hex') "8de72a07d093a589f574460deb19023b4aff354b561eb34590d9f4629f51dbf3" ) assert.equal( Aes.decrypt_with_checksum( receiver sender.toPublicKey() nonce = 12345 enc_hex ) "Hello, world!" ) return ### assertHexEqual=(x1, x2, msg)-> return if x1 is x2 console.log "ERROR: Unmatched binary\t", msg console.log "Original Transaction" ByteBuffer.fromHex(x1).printDebug() console.log "New Transaction" ByteBuffer.fromHex(x2).printDebug() throw new Error "Unmatched Transaction" check_trx=(description, trx)-> # Match Transaction fromHex -> toHex transaction = transaction_so.fromHex trx.hex #console.log JSON.stringify transaction_so.toObject(transaction),null,4 assertHexEqual trx.hex,transaction_so.toHex(transaction),"initial construction\t" + description # Match Transaction toObject -> fromObject then match to the original hex trx_object = transaction_so.toObject transaction #console.log '... trx_object',JSON.stringify trx_object,null,2 transaction2 = transaction_so.fromObject trx_object assertHexEqual trx.hex,transaction_so.toHex(transaction2),"re-construction\t" + description # readability only (technically redundant) if trx.json try transaction3 = transaction_so.fromObject trx.json assertHexEqual trx.hex,transaction_so.toHex(transaction3),"'json' object\t" + description catch error console.log 'WARNING',error,error.stack transaction check_object=(description, transaction_object)-> transaction = transaction_so.fromObject transaction_object #console.log JSON.stringify transaction_so.toObject(transaction),null,4 hex1 = transaction_so.toHex(transaction) #console.log '... transaction_hex', hex1 transaction2 = transaction_so.fromHex(hex1) hex2 = transaction_so.toHex(transaction2) assertHexEqual hex1, hex2, "hex\t" + description serilized_object = transaction_so.toObject(transaction) #console.log '... transaction', JSON.stringify serilized_object,null,2 transaction3 = transaction_so.fromObject serilized_object hex3 = transaction_so.toHex transaction3 assertHexEqual hex1, hex3, "object\t" + description ###
[ { "context": "ng\" and has a referrer-restriction set\napi_key = \"AIzaSyDNunorfrD4Wp21oL0F96Ov_L8mb9rdw_s\"\n\nyoutube_api_endpoint = 'https://www.googleapis.", "end": 150, "score": 0.9997512102127075, "start": 111, "tag": "KEY", "value": "AIzaSyDNunorfrD4Wp21oL0F96Ov_L8mb9rdw_s" }, { ...
web/js/make.coffee
andychase/radmontage
2
# The api key below is a public key # It set to be "user-facing" and has a referrer-restriction set api_key = "AIzaSyDNunorfrD4Wp21oL0F96Ov_L8mb9rdw_s" youtube_api_endpoint = 'https://www.googleapis.com/youtube/v3/videos' youtube_video_link = "https://www.youtube.com/watch?v=" youtube_channel_link = "https://www.youtube.com/channel/" my_host_url = "" get_endpoint = "#{my_host_url}/get.php" save_endpoint = "#{my_host_url}/save.php" new_endpoint = "#{my_host_url}/new.php" watch_link = "#{my_host_url}/watch/" montage_id = null montage_secret = null disable_saving = false allowed_in_time_field = /[^0-9:]/g ## External Functions and Helpers ## $.fn.moveUp = -> $.each this, -> $(this).after $(this).prev() $.fn.moveDown = -> $.each this, -> $(this).before $(this).next() edit_id_matcher = new RegExp("/edit/(new|[0-9a-z]+)") get_edit_id = -> matches = window.location.pathname.match(edit_id_matcher) if matches? and matches.length > 1 and matches[1].length > 0 return matches[1] # # Check if input string is a valid YouTube URL # and try to extract the YouTube Video ID from it. # @author Stephan Schmitz <eyecatchup@gmail.com> # @param $url string The string that shall be checked. # @return mixed Returns YouTube Video ID, or (boolean) false. # yt_matcher = do -> pattern = '(?:https?://)?'; # Optional URL scheme. Either http or https. pattern += '(?:www\\.|m\\.)?'; # Optional www or m subdomain. pattern += '(?:'; # Group host alternatives: pattern += 'youtu\\.be/'; # Either youtu.be, pattern += '|youtube\\.com'; # or youtube.com pattern += '|youtube\\.com'; # or youtube.com pattern += '|i\\.ytimg\\.com'; # or youtube.com pattern += ')'; # End path alternatives. pattern += '(?:'; # Group path alternatives: pattern += '/embed/'; # Either /embed/, pattern += '|/v/'; # or /v/, pattern += '|/vi/'; # or /v/, pattern += '|/watch\\?v='; # or /watch?v=, pattern += '|/watch\\?.+&v='; # or /watch?other_param&v= pattern += ')'; # End host alternatives. (https://i.ytimg.com/vi/5e_AjgKbceQ/mqdefault.jpg) pattern += '([A-Za-z0-9_\\- ]{11,})'; # 11 characters (Length of Youtube video ids). pattern += '(?:.+)?'; # Optional other ending URL parameters. return new RegExp(pattern) yt_link_to_id = (url) -> matches = url.match(yt_matcher) if matches? and matches.length > 1 and matches[1].length > 0 return matches[1] ## ajax_channel_and_title = (id, func) -> $.ajax( url: youtube_api_endpoint data: part: 'snippet' id: id key: api_key localCache: true cacheTTL: 5 dataType: 'json' cacheKey: id ).done (response) -> func(response) link_to_img = (id) -> "https://i.ytimg.com/vi/#{id}/mqdefault.jpg" set_video_image = (target, url) -> target.css("background-image", "url('/img/testCard.gif')") img = new Image img.onload = -> target.css("background-image", "") target.attr("src", url) img.src = url clear_video_image = (target) -> target.css("background-image", "") video_title_markup = (channel_id, channel_title, title, id) -> "<a href='#{youtube_channel_link}#{channel_id}'>#{channel_title}</a>" + "<span>/</span><a href='#{youtube_video_link}#{id}'>#{title}</a>" set_video_title = (target, id) -> ajax_channel_and_title id, (response) -> title = response.items[0].snippet.title channel_id = response.items[0].snippet.channelId channel_title = response.items[0].snippet.channelTitle target.html(video_title_markup(channel_id, channel_title, title, id)) clear_video_title = (target) -> target.html("&nbsp;") get_montage_title = -> if $("#montageName").val()? $("#montageName").val().replace(":", "") else "" text_to_time = (value) -> value = value.replace(allowed_in_time_field, "") output = 0 parts = value.split(":") if parts.length > 0 output += parseInt(parts.pop()) if parts.length > 0 output += parseInt(parts.pop()) * 60 if parts.length > 0 output += parseInt(parts.pop()) * 60 * 60 output time_to_text = (value) -> if not parseInt(value) return 0 value = parseInt(value) hours = value // (60 * 60) minutes = (value - (hours * 60 * 60)) // 60 seconds = value - (hours * 60 * 60) - (minutes * 60) if hours and minutes < 10 minutes = "0" + minutes if minutes and seconds < 10 seconds = "0" + seconds if hours [hours, minutes, seconds].join(":") else if minutes [minutes, seconds].join(":") else seconds make_link_container = """ <div class="row-container row montage-row"> <img class="thumb img-responsive col-xs-4 col-lg-5" /> <div class="row-box info-box-space col-xs-8 col-lg-7"> <div class="montage-form-group"> <h4 class="montageTitle">&nbsp;</h4> <div class="form-group"> <label for="montageUrl1"></label> <input type="text" id="montageUrl1" class="form-control montageUrl" placeholder="Paste a Youtube link here"/> </div> <div class="form-inline"> <div class="form-group"> <label>Start:</label> <input type="text" class="form-control montageStart" placeholder="0:00" maxlength="6"/> </div> <div class="form-group"> <label>Stop:</label> <input type="text" class="form-control montageEnd" placeholder="99:99" maxlength="6"/> </div> <div class="form-group"> <div class="btn-group montage-link-buttons" role="group"> <a href="#" title="Delete this video" class="montage-delete btn btn-default"><i class="fa fa-times"></i></a> <a href="#" title="Move this video up" class="montage-up btn btn-default"><i class="fa fa-chevron-up"></i></a> <a href="#" title="Move this video down" class="montage-down btn btn-default"><i class="fa fa-chevron-down"></i></a> <a href="#" title="Insert video spot above" class="montage-add-here btn btn-default"><i class="fa fa-plus"></i></a> </div> </div> </div> </div> </div> </div> """ montage_link_container = undefined get_link_from_montage_container = (container) -> container.find(".montageUrl") do_action_button_with_save = (container, selector, action) -> container.find(selector).click (e) -> e.preventDefault() action() serializeAndSave() append_new_video_container = (target) -> # Make and add container new_container = $(make_link_container) new_container.hide() if target? target.before(new_container) else montage_link_container.append(new_container) new_container.slideDown 100 url_target = get_link_from_montage_container(new_container) url_target.change(montage_link_entered) url_target.keyup(montage_link_entered) new_container.find(".montageStart").change -> serializeAndSave() new_container.find(".montageEnd").change -> serializeAndSave() new_container.find(".montage-add-here").click (e)-> e.preventDefault() append_new_video_container(new_container) new_container.find(".montage-delete").click (e) -> e.preventDefault() new_container.slideUp 100, -> new_container.remove() serializeAndSave() append_new_video_container_if_none_left() do_action_button_with_save new_container, ".montage-up", -> if new_container.index() != 1 new_container.moveUp() do_action_button_with_save new_container, ".montage-down", -> new_container.moveDown() $(url_target).on("paste", (e) -> setTimeout(-> $(e.target).trigger('change'); , 1); ) new_container.find(".montageEnd, .montageStart").on("paste keydown", (e) -> setTimeout(-> $(e.target).trigger('change'); , 1); ) url_target append_new_video_container_if_none_left = -> if montage_link_container if montage_link_container.children().length > 1 last = get_link_from_montage_container(montage_link_container.children().last()) if last.val()? and last.val().trim().length append_new_video_container() else append_new_video_container() montage_links = {} montage_link_entered = (e) -> link_index = $(e.target.parentNode.parentNode.parentNode.parentNode).index() image_target = $(e.target.parentNode.parentNode.parentNode.parentNode).children(".thumb").first() title_target = $(e.target.parentNode.parentNode).children(".montageTitle").first() link_target = e.target.value if montage_links[link_index] == link_target and title_target.html() != "&nbsp;" return else montage_links[link_index] = link_target youtube_id = yt_link_to_id(link_target) if youtube_id? serializeAndSave() $(e.target.parentNode).addClass("has-success") set_video_image(image_target, link_to_img(youtube_id)) set_video_title(title_target, youtube_id) append_new_video_container_if_none_left() return $(e.target.parentNode).removeClass("has-success") serializeAndSave() clear_video_image(image_target) clear_video_title(title_target) unserialize = (data) -> if data? and data != "" data = data.split(":") montage_secret = data[0] montage_link_container.find("#montageName").val(data[1]) data = data.slice(2) number_of_videos = data.length / 3 else data = [] if number_of_videos > 0 for video_index in [0..number_of_videos - 1] link = append_new_video_container() start = link.parent().parent().find(".montageStart") stop = link.parent().parent().find(".montageEnd") link.attr("value", youtube_video_link + data[video_index * 3]) if data[video_index * 3 + 1] != "0" start.attr("value", time_to_text(data[video_index * 3 + 1])) if data[video_index * 3 + 2] != "0" stop.attr("value", time_to_text(data[video_index * 3 + 2])) montage_link_container.children().each (i, container) -> get_link_from_montage_container($(container)).trigger('change') serialize = () -> data = [] montage_name = get_montage_title() data.push(montage_secret) data.push(montage_name) montage_link_container.children().each (i, container) -> link = get_link_from_montage_container($(container)) youtube_id = null if link? and link.val()? youtube_id = yt_link_to_id(link.val().trim()) if youtube_id? start = link.parent().parent().find(".montageStart") stop = link.parent().parent().find(".montageEnd") data.push(youtube_id) start_time = 0 if start.val()? and start.val() != "" start_time = text_to_time(start.val()) if start_time > 0 start.parent().addClass("has-success") else start.parent().removeClass("has-success") data.push(start_time) else start.parent().removeClass("has-success") data.push(0) if stop.val()? and stop.val() != "" end_time = text_to_time(stop.val()) if end_time > 0 if end_time > start_time stop.parent().removeClass("has-error") stop.parent().addClass("has-success") else end_time = 0 stop.parent().removeClass("has-success") stop.parent().addClass("has-error") else stop.parent().removeClass("has-error") stop.parent().removeClass("has-success") data.push(end_time) else stop.parent().removeClass("has-error") stop.parent().removeClass("has-success") data.push(0) data.join(":") update_previous_montages = (link_data, remove_this_id) -> list_location = $("#previous-montages .dest") data = window.localStorage.getItem("data") if data? and data != "" data = data.split("||") else data = [] previous_titles = {} for record_string in data record = record_string.split(":") previous_titles[record[0]] = record[1] # Id => title if montage_id? date = new Date() previous_titles["" + montage_id] = "#{get_montage_title()} #{date.getMonth() + 1}/#{date.getDate()}/#{date.getFullYear()}" if link_data? and link_data.split(":").length == 2 delete previous_titles["" + montage_id] if remove_this_id delete previous_titles["" + remove_this_id] output = for id, title of previous_titles [id, title].join(":") window.localStorage.setItem("data", output.join("||")) previous_ids = Object.keys(previous_titles).sort().reverse() if previous_ids.length > 0 list_location.empty() for id in previous_ids list_location.append($("<li><a href='/edit/#{id}'>#{previous_titles[id]}</a></li>")) finishedSerializing = () -> rel_url = "#{watch_link}#{montage_id}" full_url = "https://radmontage.com#{watch_link}#{montage_id}" link_to_montage_html = """ <a href="#{rel_url}" class="btn btn-default btn-sm" id="montage-play-button"><i class="fa fa-play"></i> Play</a> <span id="montage-manual-link"> Link to share: <a href='#{rel_url}'>#{full_url}</a> </span> """ $("#montage-link").html(link_to_montage_html) last_saved = "" serializeAndSave = () -> if disable_saving return data = serialize() anything_to_save = data? and data != "" and data.split(":").length > 2 # Get new id and secret if we don't have one if anything_to_save and data != last_saved $("#montage-link").html("Saving...") if not montage_secret? or montage_secret == "" disable_saving = true # We have to disable saving otherwise the call for a new id/secret gets spammed return $.get(new_endpoint, { }, (result) -> disable_saving = false montage_id = result.id montage_secret = result.secret history.replaceState(null, "", "/edit/#{montage_id}"); serializeAndSave() , 'json' ) # Persist locally if possible if (window.localStorage) window.localStorage.setItem(montage_id, data) window.localStorage.setItem("last_worked_on", montage_id) if montage_secret? and montage_secret $.post(save_endpoint, { id: montage_id secret: montage_secret data: data }, -> last_saved = data finishedSerializing() , 'json' ).fail (xhr) -> if xhr.status == 403 montage_secret = null update_previous_montages(null, montage_id) serializeAndSave() update_previous_montages(data) $ -> update_previous_montages() montage_link_container = $("#montage-links-container") if get_edit_id()? montage_id = get_edit_id() if montage_id == "new" montage_id = null window.localStorage.setItem("last_worked_on", "") last_worked_on = window.localStorage.getItem("last_worked_on") if not montage_id? and last_worked_on? and last_worked_on != "" montage_id = last_worked_on if montage_id? saved_data = window.localStorage.getItem(montage_id) if saved_data? and saved_data != "" unserialize(saved_data) history.replaceState(null, "", "/edit/#{montage_id}"); else $.get(get_endpoint, { id: montage_id }, (result) -> unserialize(":" + result.join(":")) serializeAndSave() , 'json' ) append_new_video_container_if_none_left() else append_new_video_container() $("#montageName").change -> serializeAndSave()
102179
# The api key below is a public key # It set to be "user-facing" and has a referrer-restriction set api_key = "<KEY>" youtube_api_endpoint = 'https://www.googleapis.com/youtube/v3/videos' youtube_video_link = "https://www.youtube.com/watch?v=" youtube_channel_link = "https://www.youtube.com/channel/" my_host_url = "" get_endpoint = "#{my_host_url}/get.php" save_endpoint = "#{my_host_url}/save.php" new_endpoint = "#{my_host_url}/new.php" watch_link = "#{my_host_url}/watch/" montage_id = null montage_secret = null disable_saving = false allowed_in_time_field = /[^0-9:]/g ## External Functions and Helpers ## $.fn.moveUp = -> $.each this, -> $(this).after $(this).prev() $.fn.moveDown = -> $.each this, -> $(this).before $(this).next() edit_id_matcher = new RegExp("/edit/(new|[0-9a-z]+)") get_edit_id = -> matches = window.location.pathname.match(edit_id_matcher) if matches? and matches.length > 1 and matches[1].length > 0 return matches[1] # # Check if input string is a valid YouTube URL # and try to extract the YouTube Video ID from it. # @author <NAME> <<EMAIL>> # @param $url string The string that shall be checked. # @return mixed Returns YouTube Video ID, or (boolean) false. # yt_matcher = do -> pattern = '(?:https?://)?'; # Optional URL scheme. Either http or https. pattern += '(?:www\\.|m\\.)?'; # Optional www or m subdomain. pattern += '(?:'; # Group host alternatives: pattern += 'youtu\\.be/'; # Either youtu.be, pattern += '|youtube\\.com'; # or youtube.com pattern += '|youtube\\.com'; # or youtube.com pattern += '|i\\.ytimg\\.com'; # or youtube.com pattern += ')'; # End path alternatives. pattern += '(?:'; # Group path alternatives: pattern += '/embed/'; # Either /embed/, pattern += '|/v/'; # or /v/, pattern += '|/vi/'; # or /v/, pattern += '|/watch\\?v='; # or /watch?v=, pattern += '|/watch\\?.+&v='; # or /watch?other_param&v= pattern += ')'; # End host alternatives. (https://i.ytimg.com/vi/5e_AjgKbceQ/mqdefault.jpg) pattern += '([A-Za-z0-9_\\- ]{11,})'; # 11 characters (Length of Youtube video ids). pattern += '(?:.+)?'; # Optional other ending URL parameters. return new RegExp(pattern) yt_link_to_id = (url) -> matches = url.match(yt_matcher) if matches? and matches.length > 1 and matches[1].length > 0 return matches[1] ## ajax_channel_and_title = (id, func) -> $.ajax( url: youtube_api_endpoint data: part: 'snippet' id: id key: api_key localCache: true cacheTTL: 5 dataType: 'json' cacheKey: id ).done (response) -> func(response) link_to_img = (id) -> "https://i.ytimg.com/vi/#{id}/mqdefault.jpg" set_video_image = (target, url) -> target.css("background-image", "url('/img/testCard.gif')") img = new Image img.onload = -> target.css("background-image", "") target.attr("src", url) img.src = url clear_video_image = (target) -> target.css("background-image", "") video_title_markup = (channel_id, channel_title, title, id) -> "<a href='#{youtube_channel_link}#{channel_id}'>#{channel_title}</a>" + "<span>/</span><a href='#{youtube_video_link}#{id}'>#{title}</a>" set_video_title = (target, id) -> ajax_channel_and_title id, (response) -> title = response.items[0].snippet.title channel_id = response.items[0].snippet.channelId channel_title = response.items[0].snippet.channelTitle target.html(video_title_markup(channel_id, channel_title, title, id)) clear_video_title = (target) -> target.html("&nbsp;") get_montage_title = -> if $("#montageName").val()? $("#montageName").val().replace(":", "") else "" text_to_time = (value) -> value = value.replace(allowed_in_time_field, "") output = 0 parts = value.split(":") if parts.length > 0 output += parseInt(parts.pop()) if parts.length > 0 output += parseInt(parts.pop()) * 60 if parts.length > 0 output += parseInt(parts.pop()) * 60 * 60 output time_to_text = (value) -> if not parseInt(value) return 0 value = parseInt(value) hours = value // (60 * 60) minutes = (value - (hours * 60 * 60)) // 60 seconds = value - (hours * 60 * 60) - (minutes * 60) if hours and minutes < 10 minutes = "0" + minutes if minutes and seconds < 10 seconds = "0" + seconds if hours [hours, minutes, seconds].join(":") else if minutes [minutes, seconds].join(":") else seconds make_link_container = """ <div class="row-container row montage-row"> <img class="thumb img-responsive col-xs-4 col-lg-5" /> <div class="row-box info-box-space col-xs-8 col-lg-7"> <div class="montage-form-group"> <h4 class="montageTitle">&nbsp;</h4> <div class="form-group"> <label for="montageUrl1"></label> <input type="text" id="montageUrl1" class="form-control montageUrl" placeholder="Paste a Youtube link here"/> </div> <div class="form-inline"> <div class="form-group"> <label>Start:</label> <input type="text" class="form-control montageStart" placeholder="0:00" maxlength="6"/> </div> <div class="form-group"> <label>Stop:</label> <input type="text" class="form-control montageEnd" placeholder="99:99" maxlength="6"/> </div> <div class="form-group"> <div class="btn-group montage-link-buttons" role="group"> <a href="#" title="Delete this video" class="montage-delete btn btn-default"><i class="fa fa-times"></i></a> <a href="#" title="Move this video up" class="montage-up btn btn-default"><i class="fa fa-chevron-up"></i></a> <a href="#" title="Move this video down" class="montage-down btn btn-default"><i class="fa fa-chevron-down"></i></a> <a href="#" title="Insert video spot above" class="montage-add-here btn btn-default"><i class="fa fa-plus"></i></a> </div> </div> </div> </div> </div> </div> """ montage_link_container = undefined get_link_from_montage_container = (container) -> container.find(".montageUrl") do_action_button_with_save = (container, selector, action) -> container.find(selector).click (e) -> e.preventDefault() action() serializeAndSave() append_new_video_container = (target) -> # Make and add container new_container = $(make_link_container) new_container.hide() if target? target.before(new_container) else montage_link_container.append(new_container) new_container.slideDown 100 url_target = get_link_from_montage_container(new_container) url_target.change(montage_link_entered) url_target.keyup(montage_link_entered) new_container.find(".montageStart").change -> serializeAndSave() new_container.find(".montageEnd").change -> serializeAndSave() new_container.find(".montage-add-here").click (e)-> e.preventDefault() append_new_video_container(new_container) new_container.find(".montage-delete").click (e) -> e.preventDefault() new_container.slideUp 100, -> new_container.remove() serializeAndSave() append_new_video_container_if_none_left() do_action_button_with_save new_container, ".montage-up", -> if new_container.index() != 1 new_container.moveUp() do_action_button_with_save new_container, ".montage-down", -> new_container.moveDown() $(url_target).on("paste", (e) -> setTimeout(-> $(e.target).trigger('change'); , 1); ) new_container.find(".montageEnd, .montageStart").on("paste keydown", (e) -> setTimeout(-> $(e.target).trigger('change'); , 1); ) url_target append_new_video_container_if_none_left = -> if montage_link_container if montage_link_container.children().length > 1 last = get_link_from_montage_container(montage_link_container.children().last()) if last.val()? and last.val().trim().length append_new_video_container() else append_new_video_container() montage_links = {} montage_link_entered = (e) -> link_index = $(e.target.parentNode.parentNode.parentNode.parentNode).index() image_target = $(e.target.parentNode.parentNode.parentNode.parentNode).children(".thumb").first() title_target = $(e.target.parentNode.parentNode).children(".montageTitle").first() link_target = e.target.value if montage_links[link_index] == link_target and title_target.html() != "&nbsp;" return else montage_links[link_index] = link_target youtube_id = yt_link_to_id(link_target) if youtube_id? serializeAndSave() $(e.target.parentNode).addClass("has-success") set_video_image(image_target, link_to_img(youtube_id)) set_video_title(title_target, youtube_id) append_new_video_container_if_none_left() return $(e.target.parentNode).removeClass("has-success") serializeAndSave() clear_video_image(image_target) clear_video_title(title_target) unserialize = (data) -> if data? and data != "" data = data.split(":") montage_secret = data[0] montage_link_container.find("#montageName").val(data[1]) data = data.slice(2) number_of_videos = data.length / 3 else data = [] if number_of_videos > 0 for video_index in [0..number_of_videos - 1] link = append_new_video_container() start = link.parent().parent().find(".montageStart") stop = link.parent().parent().find(".montageEnd") link.attr("value", youtube_video_link + data[video_index * 3]) if data[video_index * 3 + 1] != "0" start.attr("value", time_to_text(data[video_index * 3 + 1])) if data[video_index * 3 + 2] != "0" stop.attr("value", time_to_text(data[video_index * 3 + 2])) montage_link_container.children().each (i, container) -> get_link_from_montage_container($(container)).trigger('change') serialize = () -> data = [] montage_name = get_montage_title() data.push(montage_secret) data.push(montage_name) montage_link_container.children().each (i, container) -> link = get_link_from_montage_container($(container)) youtube_id = null if link? and link.val()? youtube_id = yt_link_to_id(link.val().trim()) if youtube_id? start = link.parent().parent().find(".montageStart") stop = link.parent().parent().find(".montageEnd") data.push(youtube_id) start_time = 0 if start.val()? and start.val() != "" start_time = text_to_time(start.val()) if start_time > 0 start.parent().addClass("has-success") else start.parent().removeClass("has-success") data.push(start_time) else start.parent().removeClass("has-success") data.push(0) if stop.val()? and stop.val() != "" end_time = text_to_time(stop.val()) if end_time > 0 if end_time > start_time stop.parent().removeClass("has-error") stop.parent().addClass("has-success") else end_time = 0 stop.parent().removeClass("has-success") stop.parent().addClass("has-error") else stop.parent().removeClass("has-error") stop.parent().removeClass("has-success") data.push(end_time) else stop.parent().removeClass("has-error") stop.parent().removeClass("has-success") data.push(0) data.join(":") update_previous_montages = (link_data, remove_this_id) -> list_location = $("#previous-montages .dest") data = window.localStorage.getItem("data") if data? and data != "" data = data.split("||") else data = [] previous_titles = {} for record_string in data record = record_string.split(":") previous_titles[record[0]] = record[1] # Id => title if montage_id? date = new Date() previous_titles["" + montage_id] = "#{get_montage_title()} #{date.getMonth() + 1}/#{date.getDate()}/#{date.getFullYear()}" if link_data? and link_data.split(":").length == 2 delete previous_titles["" + montage_id] if remove_this_id delete previous_titles["" + remove_this_id] output = for id, title of previous_titles [id, title].join(":") window.localStorage.setItem("data", output.join("||")) previous_ids = Object.keys(previous_titles).sort().reverse() if previous_ids.length > 0 list_location.empty() for id in previous_ids list_location.append($("<li><a href='/edit/#{id}'>#{previous_titles[id]}</a></li>")) finishedSerializing = () -> rel_url = "#{watch_link}#{montage_id}" full_url = "https://radmontage.com#{watch_link}#{montage_id}" link_to_montage_html = """ <a href="#{rel_url}" class="btn btn-default btn-sm" id="montage-play-button"><i class="fa fa-play"></i> Play</a> <span id="montage-manual-link"> Link to share: <a href='#{rel_url}'>#{full_url}</a> </span> """ $("#montage-link").html(link_to_montage_html) last_saved = "" serializeAndSave = () -> if disable_saving return data = serialize() anything_to_save = data? and data != "" and data.split(":").length > 2 # Get new id and secret if we don't have one if anything_to_save and data != last_saved $("#montage-link").html("Saving...") if not montage_secret? or montage_secret == "" disable_saving = true # We have to disable saving otherwise the call for a new id/secret gets spammed return $.get(new_endpoint, { }, (result) -> disable_saving = false montage_id = result.id montage_secret = result.secret history.replaceState(null, "", "/edit/#{montage_id}"); serializeAndSave() , 'json' ) # Persist locally if possible if (window.localStorage) window.localStorage.setItem(montage_id, data) window.localStorage.setItem("last_worked_on", montage_id) if montage_secret? and montage_secret $.post(save_endpoint, { id: montage_id secret: montage_secret data: data }, -> last_saved = data finishedSerializing() , 'json' ).fail (xhr) -> if xhr.status == 403 montage_secret = null update_previous_montages(null, montage_id) serializeAndSave() update_previous_montages(data) $ -> update_previous_montages() montage_link_container = $("#montage-links-container") if get_edit_id()? montage_id = get_edit_id() if montage_id == "new" montage_id = null window.localStorage.setItem("last_worked_on", "") last_worked_on = window.localStorage.getItem("last_worked_on") if not montage_id? and last_worked_on? and last_worked_on != "" montage_id = last_worked_on if montage_id? saved_data = window.localStorage.getItem(montage_id) if saved_data? and saved_data != "" unserialize(saved_data) history.replaceState(null, "", "/edit/#{montage_id}"); else $.get(get_endpoint, { id: montage_id }, (result) -> unserialize(":" + result.join(":")) serializeAndSave() , 'json' ) append_new_video_container_if_none_left() else append_new_video_container() $("#montageName").change -> serializeAndSave()
true
# The api key below is a public key # It set to be "user-facing" and has a referrer-restriction set api_key = "PI:KEY:<KEY>END_PI" youtube_api_endpoint = 'https://www.googleapis.com/youtube/v3/videos' youtube_video_link = "https://www.youtube.com/watch?v=" youtube_channel_link = "https://www.youtube.com/channel/" my_host_url = "" get_endpoint = "#{my_host_url}/get.php" save_endpoint = "#{my_host_url}/save.php" new_endpoint = "#{my_host_url}/new.php" watch_link = "#{my_host_url}/watch/" montage_id = null montage_secret = null disable_saving = false allowed_in_time_field = /[^0-9:]/g ## External Functions and Helpers ## $.fn.moveUp = -> $.each this, -> $(this).after $(this).prev() $.fn.moveDown = -> $.each this, -> $(this).before $(this).next() edit_id_matcher = new RegExp("/edit/(new|[0-9a-z]+)") get_edit_id = -> matches = window.location.pathname.match(edit_id_matcher) if matches? and matches.length > 1 and matches[1].length > 0 return matches[1] # # Check if input string is a valid YouTube URL # and try to extract the YouTube Video ID from it. # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # @param $url string The string that shall be checked. # @return mixed Returns YouTube Video ID, or (boolean) false. # yt_matcher = do -> pattern = '(?:https?://)?'; # Optional URL scheme. Either http or https. pattern += '(?:www\\.|m\\.)?'; # Optional www or m subdomain. pattern += '(?:'; # Group host alternatives: pattern += 'youtu\\.be/'; # Either youtu.be, pattern += '|youtube\\.com'; # or youtube.com pattern += '|youtube\\.com'; # or youtube.com pattern += '|i\\.ytimg\\.com'; # or youtube.com pattern += ')'; # End path alternatives. pattern += '(?:'; # Group path alternatives: pattern += '/embed/'; # Either /embed/, pattern += '|/v/'; # or /v/, pattern += '|/vi/'; # or /v/, pattern += '|/watch\\?v='; # or /watch?v=, pattern += '|/watch\\?.+&v='; # or /watch?other_param&v= pattern += ')'; # End host alternatives. (https://i.ytimg.com/vi/5e_AjgKbceQ/mqdefault.jpg) pattern += '([A-Za-z0-9_\\- ]{11,})'; # 11 characters (Length of Youtube video ids). pattern += '(?:.+)?'; # Optional other ending URL parameters. return new RegExp(pattern) yt_link_to_id = (url) -> matches = url.match(yt_matcher) if matches? and matches.length > 1 and matches[1].length > 0 return matches[1] ## ajax_channel_and_title = (id, func) -> $.ajax( url: youtube_api_endpoint data: part: 'snippet' id: id key: api_key localCache: true cacheTTL: 5 dataType: 'json' cacheKey: id ).done (response) -> func(response) link_to_img = (id) -> "https://i.ytimg.com/vi/#{id}/mqdefault.jpg" set_video_image = (target, url) -> target.css("background-image", "url('/img/testCard.gif')") img = new Image img.onload = -> target.css("background-image", "") target.attr("src", url) img.src = url clear_video_image = (target) -> target.css("background-image", "") video_title_markup = (channel_id, channel_title, title, id) -> "<a href='#{youtube_channel_link}#{channel_id}'>#{channel_title}</a>" + "<span>/</span><a href='#{youtube_video_link}#{id}'>#{title}</a>" set_video_title = (target, id) -> ajax_channel_and_title id, (response) -> title = response.items[0].snippet.title channel_id = response.items[0].snippet.channelId channel_title = response.items[0].snippet.channelTitle target.html(video_title_markup(channel_id, channel_title, title, id)) clear_video_title = (target) -> target.html("&nbsp;") get_montage_title = -> if $("#montageName").val()? $("#montageName").val().replace(":", "") else "" text_to_time = (value) -> value = value.replace(allowed_in_time_field, "") output = 0 parts = value.split(":") if parts.length > 0 output += parseInt(parts.pop()) if parts.length > 0 output += parseInt(parts.pop()) * 60 if parts.length > 0 output += parseInt(parts.pop()) * 60 * 60 output time_to_text = (value) -> if not parseInt(value) return 0 value = parseInt(value) hours = value // (60 * 60) minutes = (value - (hours * 60 * 60)) // 60 seconds = value - (hours * 60 * 60) - (minutes * 60) if hours and minutes < 10 minutes = "0" + minutes if minutes and seconds < 10 seconds = "0" + seconds if hours [hours, minutes, seconds].join(":") else if minutes [minutes, seconds].join(":") else seconds make_link_container = """ <div class="row-container row montage-row"> <img class="thumb img-responsive col-xs-4 col-lg-5" /> <div class="row-box info-box-space col-xs-8 col-lg-7"> <div class="montage-form-group"> <h4 class="montageTitle">&nbsp;</h4> <div class="form-group"> <label for="montageUrl1"></label> <input type="text" id="montageUrl1" class="form-control montageUrl" placeholder="Paste a Youtube link here"/> </div> <div class="form-inline"> <div class="form-group"> <label>Start:</label> <input type="text" class="form-control montageStart" placeholder="0:00" maxlength="6"/> </div> <div class="form-group"> <label>Stop:</label> <input type="text" class="form-control montageEnd" placeholder="99:99" maxlength="6"/> </div> <div class="form-group"> <div class="btn-group montage-link-buttons" role="group"> <a href="#" title="Delete this video" class="montage-delete btn btn-default"><i class="fa fa-times"></i></a> <a href="#" title="Move this video up" class="montage-up btn btn-default"><i class="fa fa-chevron-up"></i></a> <a href="#" title="Move this video down" class="montage-down btn btn-default"><i class="fa fa-chevron-down"></i></a> <a href="#" title="Insert video spot above" class="montage-add-here btn btn-default"><i class="fa fa-plus"></i></a> </div> </div> </div> </div> </div> </div> """ montage_link_container = undefined get_link_from_montage_container = (container) -> container.find(".montageUrl") do_action_button_with_save = (container, selector, action) -> container.find(selector).click (e) -> e.preventDefault() action() serializeAndSave() append_new_video_container = (target) -> # Make and add container new_container = $(make_link_container) new_container.hide() if target? target.before(new_container) else montage_link_container.append(new_container) new_container.slideDown 100 url_target = get_link_from_montage_container(new_container) url_target.change(montage_link_entered) url_target.keyup(montage_link_entered) new_container.find(".montageStart").change -> serializeAndSave() new_container.find(".montageEnd").change -> serializeAndSave() new_container.find(".montage-add-here").click (e)-> e.preventDefault() append_new_video_container(new_container) new_container.find(".montage-delete").click (e) -> e.preventDefault() new_container.slideUp 100, -> new_container.remove() serializeAndSave() append_new_video_container_if_none_left() do_action_button_with_save new_container, ".montage-up", -> if new_container.index() != 1 new_container.moveUp() do_action_button_with_save new_container, ".montage-down", -> new_container.moveDown() $(url_target).on("paste", (e) -> setTimeout(-> $(e.target).trigger('change'); , 1); ) new_container.find(".montageEnd, .montageStart").on("paste keydown", (e) -> setTimeout(-> $(e.target).trigger('change'); , 1); ) url_target append_new_video_container_if_none_left = -> if montage_link_container if montage_link_container.children().length > 1 last = get_link_from_montage_container(montage_link_container.children().last()) if last.val()? and last.val().trim().length append_new_video_container() else append_new_video_container() montage_links = {} montage_link_entered = (e) -> link_index = $(e.target.parentNode.parentNode.parentNode.parentNode).index() image_target = $(e.target.parentNode.parentNode.parentNode.parentNode).children(".thumb").first() title_target = $(e.target.parentNode.parentNode).children(".montageTitle").first() link_target = e.target.value if montage_links[link_index] == link_target and title_target.html() != "&nbsp;" return else montage_links[link_index] = link_target youtube_id = yt_link_to_id(link_target) if youtube_id? serializeAndSave() $(e.target.parentNode).addClass("has-success") set_video_image(image_target, link_to_img(youtube_id)) set_video_title(title_target, youtube_id) append_new_video_container_if_none_left() return $(e.target.parentNode).removeClass("has-success") serializeAndSave() clear_video_image(image_target) clear_video_title(title_target) unserialize = (data) -> if data? and data != "" data = data.split(":") montage_secret = data[0] montage_link_container.find("#montageName").val(data[1]) data = data.slice(2) number_of_videos = data.length / 3 else data = [] if number_of_videos > 0 for video_index in [0..number_of_videos - 1] link = append_new_video_container() start = link.parent().parent().find(".montageStart") stop = link.parent().parent().find(".montageEnd") link.attr("value", youtube_video_link + data[video_index * 3]) if data[video_index * 3 + 1] != "0" start.attr("value", time_to_text(data[video_index * 3 + 1])) if data[video_index * 3 + 2] != "0" stop.attr("value", time_to_text(data[video_index * 3 + 2])) montage_link_container.children().each (i, container) -> get_link_from_montage_container($(container)).trigger('change') serialize = () -> data = [] montage_name = get_montage_title() data.push(montage_secret) data.push(montage_name) montage_link_container.children().each (i, container) -> link = get_link_from_montage_container($(container)) youtube_id = null if link? and link.val()? youtube_id = yt_link_to_id(link.val().trim()) if youtube_id? start = link.parent().parent().find(".montageStart") stop = link.parent().parent().find(".montageEnd") data.push(youtube_id) start_time = 0 if start.val()? and start.val() != "" start_time = text_to_time(start.val()) if start_time > 0 start.parent().addClass("has-success") else start.parent().removeClass("has-success") data.push(start_time) else start.parent().removeClass("has-success") data.push(0) if stop.val()? and stop.val() != "" end_time = text_to_time(stop.val()) if end_time > 0 if end_time > start_time stop.parent().removeClass("has-error") stop.parent().addClass("has-success") else end_time = 0 stop.parent().removeClass("has-success") stop.parent().addClass("has-error") else stop.parent().removeClass("has-error") stop.parent().removeClass("has-success") data.push(end_time) else stop.parent().removeClass("has-error") stop.parent().removeClass("has-success") data.push(0) data.join(":") update_previous_montages = (link_data, remove_this_id) -> list_location = $("#previous-montages .dest") data = window.localStorage.getItem("data") if data? and data != "" data = data.split("||") else data = [] previous_titles = {} for record_string in data record = record_string.split(":") previous_titles[record[0]] = record[1] # Id => title if montage_id? date = new Date() previous_titles["" + montage_id] = "#{get_montage_title()} #{date.getMonth() + 1}/#{date.getDate()}/#{date.getFullYear()}" if link_data? and link_data.split(":").length == 2 delete previous_titles["" + montage_id] if remove_this_id delete previous_titles["" + remove_this_id] output = for id, title of previous_titles [id, title].join(":") window.localStorage.setItem("data", output.join("||")) previous_ids = Object.keys(previous_titles).sort().reverse() if previous_ids.length > 0 list_location.empty() for id in previous_ids list_location.append($("<li><a href='/edit/#{id}'>#{previous_titles[id]}</a></li>")) finishedSerializing = () -> rel_url = "#{watch_link}#{montage_id}" full_url = "https://radmontage.com#{watch_link}#{montage_id}" link_to_montage_html = """ <a href="#{rel_url}" class="btn btn-default btn-sm" id="montage-play-button"><i class="fa fa-play"></i> Play</a> <span id="montage-manual-link"> Link to share: <a href='#{rel_url}'>#{full_url}</a> </span> """ $("#montage-link").html(link_to_montage_html) last_saved = "" serializeAndSave = () -> if disable_saving return data = serialize() anything_to_save = data? and data != "" and data.split(":").length > 2 # Get new id and secret if we don't have one if anything_to_save and data != last_saved $("#montage-link").html("Saving...") if not montage_secret? or montage_secret == "" disable_saving = true # We have to disable saving otherwise the call for a new id/secret gets spammed return $.get(new_endpoint, { }, (result) -> disable_saving = false montage_id = result.id montage_secret = result.secret history.replaceState(null, "", "/edit/#{montage_id}"); serializeAndSave() , 'json' ) # Persist locally if possible if (window.localStorage) window.localStorage.setItem(montage_id, data) window.localStorage.setItem("last_worked_on", montage_id) if montage_secret? and montage_secret $.post(save_endpoint, { id: montage_id secret: montage_secret data: data }, -> last_saved = data finishedSerializing() , 'json' ).fail (xhr) -> if xhr.status == 403 montage_secret = null update_previous_montages(null, montage_id) serializeAndSave() update_previous_montages(data) $ -> update_previous_montages() montage_link_container = $("#montage-links-container") if get_edit_id()? montage_id = get_edit_id() if montage_id == "new" montage_id = null window.localStorage.setItem("last_worked_on", "") last_worked_on = window.localStorage.getItem("last_worked_on") if not montage_id? and last_worked_on? and last_worked_on != "" montage_id = last_worked_on if montage_id? saved_data = window.localStorage.getItem(montage_id) if saved_data? and saved_data != "" unserialize(saved_data) history.replaceState(null, "", "/edit/#{montage_id}"); else $.get(get_endpoint, { id: montage_id }, (result) -> unserialize(":" + result.join(":")) serializeAndSave() , 'json' ) append_new_video_container_if_none_left() else append_new_video_container() $("#montageName").change -> serializeAndSave()
[ { "context": " [\n key: 'series1'\n label: 'Hello'\n values: []\n ,\n key", "end": 278, "score": 0.949926495552063, "start": 273, "tag": "NAME", "value": "Hello" }, { "context": " ,\n key: 'series2'\n label: 'Wo...
test/data.coffee
robinfhu/forest-d3
58
describe 'Data API', -> it 'should have ability to get raw data', -> api = ForestD3.DataAPI [1,2,3] api.get().should.deep.equal [1,2,3] it 'has methods to show/hide data series`', -> data = [ key: 'series1' label: 'Hello' values: [] , key: 'series2' label: 'World' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.hide(['series1', 'series2']) visible = api.visible() visible.length.should.equal 1 api.show('series2') visible = api.visible() visible.length.should.equal 2 api.toggle('series2') visible = api.visible() visible.length.should.equal 1 it 'has methods for showOnly and showAll data', -> data = [ key: 'series1' label: 'Hello' values: [] , key: 'series2' label: 'World' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.showOnly 'series2' visible = api.visible() visible.length.should.equal 1 visible[0].key.should.equal 'series2' api.showAll() visible = api.visible() visible.length.should.equal 3 it 'showOnly accepts "onlyDataSeries" option', -> data = [ key: 'series1' label: 'Hello' values: [] , key: 'series2' label: 'World' values: [] , key: 'seriesMarker' type: 'marker' value: 0 , key: 'seriesRegion' type: 'region' values: [0,1] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.showOnly 'series2', {onlyDataSeries: true} visible = api.visible() visible.length.should.equal 3, '3 visible' visible[0].key.should.equal 'series2' visible[1].key.should.equal 'seriesMarker' visible[2].key.should.equal 'seriesRegion' it 'has method to get visible data only', -> data = [ key: 'series1' label: 'Hello' values: [] , key: 'series2' label: 'World' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) chart.data().hide(['series2','series3']) visible = chart.data().visible() visible.length.should.equal 1 visible[0].key.should.equal 'series1' it 'has method to get list of x values', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(false).data(data) chart.data().xValues().should.deep.equal [2, 80, 90] data = [ value: [1,2] ] chart.data(data) chart.data().xValues().should.deep.equal [] chart.getX (d,i)-> i data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart.data(data) chart.data().xValues().should.deep.equal [0,1,2] it 'can get raw x values for an ordinal chart', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) chart.data().xValuesRaw().should.deep.equal [2,80,90] it 'can get x value at certain index', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) chart.data().xValueAt(0).should.equal 2 chart.data().xValueAt(1).should.equal 80 chart.data().xValueAt(2).should.equal 90 should.not.exist chart.data().xValueAt(4) it 'makes a copy of the data', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] , key: 'line2' type: 'line' values: [ [0,7] [1,8] [2,9] ] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() (internalData is data).should.be.false (internalData[0].values is data[0].values).should.be.false (internalData[1].values is data[1].values).should.be.false it 'accepts an object of objects as chart data', -> data = 'line1': type: 'line' values: [ [0,0] [1,1] [2,4] ] 'bar1': type: 'bar' values: [ [0,0] [1,1] [2,4] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData.should.be.instanceof Array internalData[0].key.should.equal 'line1' internalData[0].type.should.equal 'line' internalData[1].key.should.equal 'bar1' internalData[1].type.should.equal 'bar' it 'converts data to consistent format internally', -> data = 'line1': type: 'line' values: [ [0,0] [1,1] [2,4] ] 'bar1': type: 'bar' values: [ [0,0] [1,1] [2,4] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData[0].values[0].x.should.equal 0 internalData[0].values[0].y.should.equal 0 internalData[1].values[2].x.should.equal 2 internalData[1].values[2].y.should.equal 4 internalData[1].values[2].data.should.deep.equal [2,4] it 'calculates the x,y extent of each series', -> data = [ type: 'line' values: [ [-3,4] [0,6] [4,8] ] , type: 'line' values: [ [4,-1] [5,3] [6,2] ] , type: 'marker' axis: 'x' value: 30 , type: 'marker' axis: 'y' value: 40 , type: 'region' axis: 'x' values: [3,10] , type: 'region' axis: 'y' values: [-10,11] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) internalData = chart.data().get() internalData[0].extent.should.deep.equal x: [0,2] y: [4,8] internalData[1].extent.should.deep.equal x: [0,2] y: [-1,3] internalData[2].extent.should.deep.equal x: [30] y: [] internalData[3].extent.should.deep.equal x: [] y: [40] internalData[4].extent.should.deep.equal x: [3,10] y: [] internalData[5].extent.should.deep.equal x: [] y: [-10,11] it 'fills in key and label if not defined', -> data = [ values: [] , values: [] , values: [] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData[0].key.should.equal 'series0' internalData[0].label.should.equal 'Series #0' internalData[1].key.should.equal 'series1' internalData[1].label.should.equal 'Series #1' internalData[2].key.should.equal 'series2' internalData[2].label.should.equal 'Series #2' internalData[2].type.should.equal 'scatter' it 'automatically adds color and index field to each series', -> data = [ values: [] , color: '#00f' values: [] , type: 'marker' value: 30 , values: [] , values: [] , values: [] ] colors = [ "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a" ] chart = new ForestD3.Chart() chart.colorPalette(colors).data(data) internalData = chart.data().get() internalData[0].color.should.equal '#1f77b4' internalData[1].color.should.equal '#00f' should.not.exist internalData[2].color internalData[3].color.should.equal '#aec7e8' internalData[4].color.should.equal '#ff7f0e' internalData[5].color.should.equal '#ffbb78' internalData[0].index.should.equal 0 internalData[1].index.should.equal 1 should.not.exist internalData[2].index internalData[3].index.should.equal 2 internalData[4].index.should.equal 3 internalData[5].index.should.equal 4 it 'auto sorts data by x value ascending', -> getPoints = -> points = [0...50].map (i)-> x: i y: Math.random() d3.shuffle points points data = series1: type: 'line' values: getPoints() series2: type: 'line' values: getPoints() chart = new ForestD3.Chart() chart .getX((d)->d.x) .getY((d)->d.y) .ordinal(false) .autoSortXValues(true) .data(data) internal = chart.data().get() internalXVals = internal[0].values.map (d)-> d.x internalXVals.should.deep.equal [0...50] internalXVals = internal[1].values.map (d)-> d.x internalXVals.should.deep.equal [0...50] describe 'Data Slice', -> it 'can get a slice of data at an index', -> data = [ key: 'series1' label: 'Foo' color: '#000' values: [ [70, 10] [80, 100] [90, 101] ] , key: 'series2' label: 'Bar' values: [ [70, 11] [80, 800] [90, 709] ] , key: 'series3' label: 'Maz' color: '#0f0' values: [ [70, 12] [80, 300] [90, 749] ] ] chart = new ForestD3.Chart() chart.data(data) slice = chart.data().sliced(0) slice.length.should.equal 3, '3 items' slice[0].y.should.equal 10 slice[0].series.label.should.equal 'Foo' slice[0].series.color.should.equal '#000' slice[1].y.should.equal 11 slice[2].y.should.equal 12 slice = chart.data().sliced(2) yData = slice.map (d)-> d.y yData.should.deep.equal [101, 709, 749] it 'keeps hidden data out of slice', -> it 'can get a slice of data at an index', -> data = [ key: 's1' values: [ [70, 10] [80, 100] [90, 101] ] , key: 's2' values: [ [70, 10] [80, 800] [90, 709] ] , key: 's3' values: [ [70, 12] [80, 300] [90, 749] ] ] chart = new ForestD3.Chart() chart.data(data) chart.data().hide(['s2','s3']) slice = chart.data().sliced(0) slice.length.should.equal 1, 'only one item' describe 'bar item api', -> data = [ key: 's1' type: 'line' values: [] , key: 's2' type: 'bar' values: [] , key: 's3' type: 'line' values: [] , key: 's4' type: 'bar' values: [] , key: 's5' type: 'bar' values: [] ] it 'can count number of bar items', -> chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.hide 's5' api.barCount().should.equal 2, 'two visible bars' api.show 's5' api.barCount().should.equal 3, 'three bars visible' it 'can get the relative bar index', -> chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.barIndex('s5').should.equal 2 api.barIndex('s4').should.equal 1 api.barIndex('s2').should.equal 0 should.not.exist api.barIndex('s1') api.hide 's2' api.barIndex('s4').should.equal 0 api.barIndex('s5').should.equal 1
89715
describe 'Data API', -> it 'should have ability to get raw data', -> api = ForestD3.DataAPI [1,2,3] api.get().should.deep.equal [1,2,3] it 'has methods to show/hide data series`', -> data = [ key: 'series1' label: '<NAME>' values: [] , key: 'series2' label: '<NAME>' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.hide(['series1', 'series2']) visible = api.visible() visible.length.should.equal 1 api.show('series2') visible = api.visible() visible.length.should.equal 2 api.toggle('series2') visible = api.visible() visible.length.should.equal 1 it 'has methods for showOnly and showAll data', -> data = [ key: 'series1' label: '<NAME>' values: [] , key: 'series2' label: '<NAME>' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.showOnly 'series2' visible = api.visible() visible.length.should.equal 1 visible[0].key.should.equal 'series2' api.showAll() visible = api.visible() visible.length.should.equal 3 it 'showOnly accepts "onlyDataSeries" option', -> data = [ key: 'series1' label: '<NAME>' values: [] , key: 'series2' label: '<NAME>' values: [] , key: 'seriesMarker' type: 'marker' value: 0 , key: 'seriesRegion' type: 'region' values: [0,1] , key: 'series3' color: '#00f' label: '<NAME>' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.showOnly 'series2', {onlyDataSeries: true} visible = api.visible() visible.length.should.equal 3, '3 visible' visible[0].key.should.equal 'series2' visible[1].key.should.equal 'seriesMarker' visible[2].key.should.equal 'seriesRegion' it 'has method to get visible data only', -> data = [ key: 'series1' label: '<NAME>' values: [] , key: 'series2' label: '<NAME>' values: [] , key: 'series3' color: '#00f' label: '<NAME>' values: [] ] chart = new ForestD3.Chart() chart.data(data) chart.data().hide(['series2','series3']) visible = chart.data().visible() visible.length.should.equal 1 visible[0].key.should.equal 'series1' it 'has method to get list of x values', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(false).data(data) chart.data().xValues().should.deep.equal [2, 80, 90] data = [ value: [1,2] ] chart.data(data) chart.data().xValues().should.deep.equal [] chart.getX (d,i)-> i data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart.data(data) chart.data().xValues().should.deep.equal [0,1,2] it 'can get raw x values for an ordinal chart', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) chart.data().xValuesRaw().should.deep.equal [2,80,90] it 'can get x value at certain index', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) chart.data().xValueAt(0).should.equal 2 chart.data().xValueAt(1).should.equal 80 chart.data().xValueAt(2).should.equal 90 should.not.exist chart.data().xValueAt(4) it 'makes a copy of the data', -> data = [ key: '<KEY>' type: 'line' values: [ [0,0] [1,1] [2,4] ] , key: '<KEY>' type: 'line' values: [ [0,7] [1,8] [2,9] ] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() (internalData is data).should.be.false (internalData[0].values is data[0].values).should.be.false (internalData[1].values is data[1].values).should.be.false it 'accepts an object of objects as chart data', -> data = 'line1': type: 'line' values: [ [0,0] [1,1] [2,4] ] 'bar1': type: 'bar' values: [ [0,0] [1,1] [2,4] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData.should.be.instanceof Array internalData[0].key.should.equal 'line1' internalData[0].type.should.equal 'line' internalData[1].key.should.equal '<KEY>' internalData[1].type.should.equal 'bar' it 'converts data to consistent format internally', -> data = 'line1': type: 'line' values: [ [0,0] [1,1] [2,4] ] 'bar1': type: 'bar' values: [ [0,0] [1,1] [2,4] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData[0].values[0].x.should.equal 0 internalData[0].values[0].y.should.equal 0 internalData[1].values[2].x.should.equal 2 internalData[1].values[2].y.should.equal 4 internalData[1].values[2].data.should.deep.equal [2,4] it 'calculates the x,y extent of each series', -> data = [ type: 'line' values: [ [-3,4] [0,6] [4,8] ] , type: 'line' values: [ [4,-1] [5,3] [6,2] ] , type: 'marker' axis: 'x' value: 30 , type: 'marker' axis: 'y' value: 40 , type: 'region' axis: 'x' values: [3,10] , type: 'region' axis: 'y' values: [-10,11] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) internalData = chart.data().get() internalData[0].extent.should.deep.equal x: [0,2] y: [4,8] internalData[1].extent.should.deep.equal x: [0,2] y: [-1,3] internalData[2].extent.should.deep.equal x: [30] y: [] internalData[3].extent.should.deep.equal x: [] y: [40] internalData[4].extent.should.deep.equal x: [3,10] y: [] internalData[5].extent.should.deep.equal x: [] y: [-10,11] it 'fills in key and label if not defined', -> data = [ values: [] , values: [] , values: [] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData[0].key.should.equal '<KEY>0' internalData[0].label.should.equal 'Series #0' internalData[1].key.should.equal '<KEY>1' internalData[1].label.should.equal 'Series #1' internalData[2].key.should.equal '<KEY>2' internalData[2].label.should.equal 'Series #2' internalData[2].type.should.equal 'scatter' it 'automatically adds color and index field to each series', -> data = [ values: [] , color: '#00f' values: [] , type: 'marker' value: 30 , values: [] , values: [] , values: [] ] colors = [ "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a" ] chart = new ForestD3.Chart() chart.colorPalette(colors).data(data) internalData = chart.data().get() internalData[0].color.should.equal '#1f77b4' internalData[1].color.should.equal '#00f' should.not.exist internalData[2].color internalData[3].color.should.equal '#aec7e8' internalData[4].color.should.equal '#ff7f0e' internalData[5].color.should.equal '#ffbb78' internalData[0].index.should.equal 0 internalData[1].index.should.equal 1 should.not.exist internalData[2].index internalData[3].index.should.equal 2 internalData[4].index.should.equal 3 internalData[5].index.should.equal 4 it 'auto sorts data by x value ascending', -> getPoints = -> points = [0...50].map (i)-> x: i y: Math.random() d3.shuffle points points data = series1: type: 'line' values: getPoints() series2: type: 'line' values: getPoints() chart = new ForestD3.Chart() chart .getX((d)->d.x) .getY((d)->d.y) .ordinal(false) .autoSortXValues(true) .data(data) internal = chart.data().get() internalXVals = internal[0].values.map (d)-> d.x internalXVals.should.deep.equal [0...50] internalXVals = internal[1].values.map (d)-> d.x internalXVals.should.deep.equal [0...50] describe 'Data Slice', -> it 'can get a slice of data at an index', -> data = [ key: 'series1' label: '<NAME>' color: '#000' values: [ [70, 10] [80, 100] [90, 101] ] , key: 'series2' label: 'Bar' values: [ [70, 11] [80, 800] [90, 709] ] , key: 'series3' label: '<NAME>az' color: '#0f0' values: [ [70, 12] [80, 300] [90, 749] ] ] chart = new ForestD3.Chart() chart.data(data) slice = chart.data().sliced(0) slice.length.should.equal 3, '3 items' slice[0].y.should.equal 10 slice[0].series.label.should.equal 'Foo' slice[0].series.color.should.equal '#000' slice[1].y.should.equal 11 slice[2].y.should.equal 12 slice = chart.data().sliced(2) yData = slice.map (d)-> d.y yData.should.deep.equal [101, 709, 749] it 'keeps hidden data out of slice', -> it 'can get a slice of data at an index', -> data = [ key: 's1' values: [ [70, 10] [80, 100] [90, 101] ] , key: 's2' values: [ [70, 10] [80, 800] [90, 709] ] , key: 's3' values: [ [70, 12] [80, 300] [90, 749] ] ] chart = new ForestD3.Chart() chart.data(data) chart.data().hide(['s2','s3']) slice = chart.data().sliced(0) slice.length.should.equal 1, 'only one item' describe 'bar item api', -> data = [ key: 's1' type: 'line' values: [] , key: 's2' type: 'bar' values: [] , key: 's3' type: 'line' values: [] , key: 's4' type: 'bar' values: [] , key: 's5' type: 'bar' values: [] ] it 'can count number of bar items', -> chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.hide 's5' api.barCount().should.equal 2, 'two visible bars' api.show 's5' api.barCount().should.equal 3, 'three bars visible' it 'can get the relative bar index', -> chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.barIndex('s5').should.equal 2 api.barIndex('s4').should.equal 1 api.barIndex('s2').should.equal 0 should.not.exist api.barIndex('s1') api.hide 's2' api.barIndex('s4').should.equal 0 api.barIndex('s5').should.equal 1
true
describe 'Data API', -> it 'should have ability to get raw data', -> api = ForestD3.DataAPI [1,2,3] api.get().should.deep.equal [1,2,3] it 'has methods to show/hide data series`', -> data = [ key: 'series1' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series2' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.hide(['series1', 'series2']) visible = api.visible() visible.length.should.equal 1 api.show('series2') visible = api.visible() visible.length.should.equal 2 api.toggle('series2') visible = api.visible() visible.length.should.equal 1 it 'has methods for showOnly and showAll data', -> data = [ key: 'series1' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series2' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series3' color: '#00f' label: 'Foo' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.showOnly 'series2' visible = api.visible() visible.length.should.equal 1 visible[0].key.should.equal 'series2' api.showAll() visible = api.visible() visible.length.should.equal 3 it 'showOnly accepts "onlyDataSeries" option', -> data = [ key: 'series1' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series2' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'seriesMarker' type: 'marker' value: 0 , key: 'seriesRegion' type: 'region' values: [0,1] , key: 'series3' color: '#00f' label: 'PI:NAME:<NAME>END_PI' values: [] ] chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.showOnly 'series2', {onlyDataSeries: true} visible = api.visible() visible.length.should.equal 3, '3 visible' visible[0].key.should.equal 'series2' visible[1].key.should.equal 'seriesMarker' visible[2].key.should.equal 'seriesRegion' it 'has method to get visible data only', -> data = [ key: 'series1' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series2' label: 'PI:NAME:<NAME>END_PI' values: [] , key: 'series3' color: '#00f' label: 'PI:NAME:<NAME>END_PI' values: [] ] chart = new ForestD3.Chart() chart.data(data) chart.data().hide(['series2','series3']) visible = chart.data().visible() visible.length.should.equal 1 visible[0].key.should.equal 'series1' it 'has method to get list of x values', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(false).data(data) chart.data().xValues().should.deep.equal [2, 80, 90] data = [ value: [1,2] ] chart.data(data) chart.data().xValues().should.deep.equal [] chart.getX (d,i)-> i data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart.data(data) chart.data().xValues().should.deep.equal [0,1,2] it 'can get raw x values for an ordinal chart', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) chart.data().xValuesRaw().should.deep.equal [2,80,90] it 'can get x value at certain index', -> data = [ values: [ [2, 10] [80, 100] [90, 101] ] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) chart.data().xValueAt(0).should.equal 2 chart.data().xValueAt(1).should.equal 80 chart.data().xValueAt(2).should.equal 90 should.not.exist chart.data().xValueAt(4) it 'makes a copy of the data', -> data = [ key: 'PI:KEY:<KEY>END_PI' type: 'line' values: [ [0,0] [1,1] [2,4] ] , key: 'PI:KEY:<KEY>END_PI' type: 'line' values: [ [0,7] [1,8] [2,9] ] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() (internalData is data).should.be.false (internalData[0].values is data[0].values).should.be.false (internalData[1].values is data[1].values).should.be.false it 'accepts an object of objects as chart data', -> data = 'line1': type: 'line' values: [ [0,0] [1,1] [2,4] ] 'bar1': type: 'bar' values: [ [0,0] [1,1] [2,4] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData.should.be.instanceof Array internalData[0].key.should.equal 'line1' internalData[0].type.should.equal 'line' internalData[1].key.should.equal 'PI:KEY:<KEY>END_PI' internalData[1].type.should.equal 'bar' it 'converts data to consistent format internally', -> data = 'line1': type: 'line' values: [ [0,0] [1,1] [2,4] ] 'bar1': type: 'bar' values: [ [0,0] [1,1] [2,4] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData[0].values[0].x.should.equal 0 internalData[0].values[0].y.should.equal 0 internalData[1].values[2].x.should.equal 2 internalData[1].values[2].y.should.equal 4 internalData[1].values[2].data.should.deep.equal [2,4] it 'calculates the x,y extent of each series', -> data = [ type: 'line' values: [ [-3,4] [0,6] [4,8] ] , type: 'line' values: [ [4,-1] [5,3] [6,2] ] , type: 'marker' axis: 'x' value: 30 , type: 'marker' axis: 'y' value: 40 , type: 'region' axis: 'x' values: [3,10] , type: 'region' axis: 'y' values: [-10,11] ] chart = new ForestD3.Chart() chart.ordinal(true).data(data) internalData = chart.data().get() internalData[0].extent.should.deep.equal x: [0,2] y: [4,8] internalData[1].extent.should.deep.equal x: [0,2] y: [-1,3] internalData[2].extent.should.deep.equal x: [30] y: [] internalData[3].extent.should.deep.equal x: [] y: [40] internalData[4].extent.should.deep.equal x: [3,10] y: [] internalData[5].extent.should.deep.equal x: [] y: [-10,11] it 'fills in key and label if not defined', -> data = [ values: [] , values: [] , values: [] ] chart = new ForestD3.Chart() chart.data(data) internalData = chart.data().get() internalData[0].key.should.equal 'PI:KEY:<KEY>END_PI0' internalData[0].label.should.equal 'Series #0' internalData[1].key.should.equal 'PI:KEY:<KEY>END_PI1' internalData[1].label.should.equal 'Series #1' internalData[2].key.should.equal 'PI:KEY:<KEY>END_PI2' internalData[2].label.should.equal 'Series #2' internalData[2].type.should.equal 'scatter' it 'automatically adds color and index field to each series', -> data = [ values: [] , color: '#00f' values: [] , type: 'marker' value: 30 , values: [] , values: [] , values: [] ] colors = [ "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a" ] chart = new ForestD3.Chart() chart.colorPalette(colors).data(data) internalData = chart.data().get() internalData[0].color.should.equal '#1f77b4' internalData[1].color.should.equal '#00f' should.not.exist internalData[2].color internalData[3].color.should.equal '#aec7e8' internalData[4].color.should.equal '#ff7f0e' internalData[5].color.should.equal '#ffbb78' internalData[0].index.should.equal 0 internalData[1].index.should.equal 1 should.not.exist internalData[2].index internalData[3].index.should.equal 2 internalData[4].index.should.equal 3 internalData[5].index.should.equal 4 it 'auto sorts data by x value ascending', -> getPoints = -> points = [0...50].map (i)-> x: i y: Math.random() d3.shuffle points points data = series1: type: 'line' values: getPoints() series2: type: 'line' values: getPoints() chart = new ForestD3.Chart() chart .getX((d)->d.x) .getY((d)->d.y) .ordinal(false) .autoSortXValues(true) .data(data) internal = chart.data().get() internalXVals = internal[0].values.map (d)-> d.x internalXVals.should.deep.equal [0...50] internalXVals = internal[1].values.map (d)-> d.x internalXVals.should.deep.equal [0...50] describe 'Data Slice', -> it 'can get a slice of data at an index', -> data = [ key: 'series1' label: 'PI:NAME:<NAME>END_PI' color: '#000' values: [ [70, 10] [80, 100] [90, 101] ] , key: 'series2' label: 'Bar' values: [ [70, 11] [80, 800] [90, 709] ] , key: 'series3' label: 'PI:NAME:<NAME>END_PIaz' color: '#0f0' values: [ [70, 12] [80, 300] [90, 749] ] ] chart = new ForestD3.Chart() chart.data(data) slice = chart.data().sliced(0) slice.length.should.equal 3, '3 items' slice[0].y.should.equal 10 slice[0].series.label.should.equal 'Foo' slice[0].series.color.should.equal '#000' slice[1].y.should.equal 11 slice[2].y.should.equal 12 slice = chart.data().sliced(2) yData = slice.map (d)-> d.y yData.should.deep.equal [101, 709, 749] it 'keeps hidden data out of slice', -> it 'can get a slice of data at an index', -> data = [ key: 's1' values: [ [70, 10] [80, 100] [90, 101] ] , key: 's2' values: [ [70, 10] [80, 800] [90, 709] ] , key: 's3' values: [ [70, 12] [80, 300] [90, 749] ] ] chart = new ForestD3.Chart() chart.data(data) chart.data().hide(['s2','s3']) slice = chart.data().sliced(0) slice.length.should.equal 1, 'only one item' describe 'bar item api', -> data = [ key: 's1' type: 'line' values: [] , key: 's2' type: 'bar' values: [] , key: 's3' type: 'line' values: [] , key: 's4' type: 'bar' values: [] , key: 's5' type: 'bar' values: [] ] it 'can count number of bar items', -> chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.hide 's5' api.barCount().should.equal 2, 'two visible bars' api.show 's5' api.barCount().should.equal 3, 'three bars visible' it 'can get the relative bar index', -> chart = new ForestD3.Chart() chart.data(data) api = chart.data() api.barIndex('s5').should.equal 2 api.barIndex('s4').should.equal 1 api.barIndex('s2').should.equal 0 should.not.exist api.barIndex('s1') api.hide 's2' api.barIndex('s4').should.equal 0 api.barIndex('s5').should.equal 1
[ { "context": "istory\"\n chat:\n name: \"People wax poetic about Jerry\"\n\nclass App.Views.Header extends App.Views.View\n ", "end": 99, "score": 0.9867845773696899, "start": 94, "tag": "NAME", "value": "Jerry" } ]
app/views/header.coffee
RelistenNet/relisten.net-original
2
otherPages = today: name: "Today in History" chat: name: "People wax poetic about Jerry" class App.Views.Header extends App.Views.View autoRender: true el: 'header' template: JST['header'] events: 'click .band': 'refreshBand' initialize: -> super render: (playlist) => @$el.html @template loggedIn: App.user.loggedIn() slug: App.router?.band bandName: App.bands[App.router?.band]?.name || otherPages[App.router?.band]?.name the: App.bands[App.router?.band]?.the refreshBand: -> if Backbone.history.fragment is App.router?.band Backbone.history.loadUrl '/' + App.router?.band else App.router.navigate '/' + App.router?.band, trigger: true
144976
otherPages = today: name: "Today in History" chat: name: "People wax poetic about <NAME>" class App.Views.Header extends App.Views.View autoRender: true el: 'header' template: JST['header'] events: 'click .band': 'refreshBand' initialize: -> super render: (playlist) => @$el.html @template loggedIn: App.user.loggedIn() slug: App.router?.band bandName: App.bands[App.router?.band]?.name || otherPages[App.router?.band]?.name the: App.bands[App.router?.band]?.the refreshBand: -> if Backbone.history.fragment is App.router?.band Backbone.history.loadUrl '/' + App.router?.band else App.router.navigate '/' + App.router?.band, trigger: true
true
otherPages = today: name: "Today in History" chat: name: "People wax poetic about PI:NAME:<NAME>END_PI" class App.Views.Header extends App.Views.View autoRender: true el: 'header' template: JST['header'] events: 'click .band': 'refreshBand' initialize: -> super render: (playlist) => @$el.html @template loggedIn: App.user.loggedIn() slug: App.router?.band bandName: App.bands[App.router?.band]?.name || otherPages[App.router?.band]?.name the: App.bands[App.router?.band]?.the refreshBand: -> if Backbone.history.fragment is App.router?.band Backbone.history.loadUrl '/' + App.router?.band else App.router.navigate '/' + App.router?.band, trigger: true
[ { "context": "response_data\":{\n \"account_id\":\"14449979\",\n \"name\": \"Choochee\"\n ", "end": 379, "score": 0.9591376781463623, "start": 371, "tag": "KEY", "value": "14449979" }, { "context": "count_id\":\"14449979\",\n ...
models/account/fixture/get_account.coffee
signonsridhar/sridhar_hbs
0
define(['can_fixture'], (can)-> can.fixture('GET /bss/account?action=getaccount',(req, res)-> return { "response":{ "service":"getaccount", "response_code":100, "execution_time":125, "timestamp":"2013-11-25T18:36:37+0000", "response_data":{ "account_id":"14449979", "name": "Choochee" "account_address_street1":"295 n bernado ave", "account_address_city":"mountain view", "account_address_state":"CA", "account_address_country":"US", "account_address_zip":"94043", "billing_address_street1":"295 n bernado ave", "billing_address_city":"mountain view", "billing_address_state":"CA", "billing_address_country":"US", "billing_address_zip":"94043", "primary_email":"sudha@choochee.com", "contact_first_name":"adminFirstname", "contact_last_name":"AdminLastname", "currencycode":"USD", "status":"ACTIVE", "credit_card_address1":"295 n bernado ave", "credit_card_city":"mountain view", "credit_card_country":"US", "credit_card_expiration_month":"3", "credit_card_expiration_year":"2016", "credit_card_mask_number":"XXXX-1111", "credit_card_postal_code":"94043", "credit_card_state":"CA", "credit_card_type":"Visa", "bill_cycle_day":"25", "master_plan_name":"General Aria Master Plan (Dev)", "master_plan_id":"10905223", "bill_period_start": "11/1/2013", "bill_period_end": "11/30/2013", "bill_cycle_date": "2013-11-28T00:00:00-0500", "last_bill_cycle_date": "10/31/2013", "last_paid_amount": 0.0, "total_recurring_charge": 0.0 }, "version":"1.0" } } ) )
136226
define(['can_fixture'], (can)-> can.fixture('GET /bss/account?action=getaccount',(req, res)-> return { "response":{ "service":"getaccount", "response_code":100, "execution_time":125, "timestamp":"2013-11-25T18:36:37+0000", "response_data":{ "account_id":"<KEY>", "name": "<NAME>" "account_address_street1":"295 n bernado ave", "account_address_city":"mountain view", "account_address_state":"CA", "account_address_country":"US", "account_address_zip":"94043", "billing_address_street1":"295 n bernado ave", "billing_address_city":"mountain view", "billing_address_state":"CA", "billing_address_country":"US", "billing_address_zip":"94043", "primary_email":"<EMAIL>", "contact_first_name":"<NAME>", "contact_last_name":"<NAME>", "currencycode":"USD", "status":"ACTIVE", "credit_card_address1":"295 n bernado ave", "credit_card_city":"mountain view", "credit_card_country":"US", "credit_card_expiration_month":"3", "credit_card_expiration_year":"2016", "credit_card_mask_number":"XXXX-1111", "credit_card_postal_code":"94043", "credit_card_state":"CA", "credit_card_type":"Visa", "bill_cycle_day":"25", "master_plan_name":"General Aria Master Plan (Dev)", "master_plan_id":"10905223", "bill_period_start": "11/1/2013", "bill_period_end": "11/30/2013", "bill_cycle_date": "2013-11-28T00:00:00-0500", "last_bill_cycle_date": "10/31/2013", "last_paid_amount": 0.0, "total_recurring_charge": 0.0 }, "version":"1.0" } } ) )
true
define(['can_fixture'], (can)-> can.fixture('GET /bss/account?action=getaccount',(req, res)-> return { "response":{ "service":"getaccount", "response_code":100, "execution_time":125, "timestamp":"2013-11-25T18:36:37+0000", "response_data":{ "account_id":"PI:KEY:<KEY>END_PI", "name": "PI:NAME:<NAME>END_PI" "account_address_street1":"295 n bernado ave", "account_address_city":"mountain view", "account_address_state":"CA", "account_address_country":"US", "account_address_zip":"94043", "billing_address_street1":"295 n bernado ave", "billing_address_city":"mountain view", "billing_address_state":"CA", "billing_address_country":"US", "billing_address_zip":"94043", "primary_email":"PI:EMAIL:<EMAIL>END_PI", "contact_first_name":"PI:NAME:<NAME>END_PI", "contact_last_name":"PI:NAME:<NAME>END_PI", "currencycode":"USD", "status":"ACTIVE", "credit_card_address1":"295 n bernado ave", "credit_card_city":"mountain view", "credit_card_country":"US", "credit_card_expiration_month":"3", "credit_card_expiration_year":"2016", "credit_card_mask_number":"XXXX-1111", "credit_card_postal_code":"94043", "credit_card_state":"CA", "credit_card_type":"Visa", "bill_cycle_day":"25", "master_plan_name":"General Aria Master Plan (Dev)", "master_plan_id":"10905223", "bill_period_start": "11/1/2013", "bill_period_end": "11/30/2013", "bill_cycle_date": "2013-11-28T00:00:00-0500", "last_bill_cycle_date": "10/31/2013", "last_paid_amount": 0.0, "total_recurring_charge": 0.0 }, "version":"1.0" } } ) )
[ { "context": " db:\n dbName: 'masons_test'\n login: 'masons'\n password: 'masons'\n host: \"#{process.", "end": 101, "score": 0.9995697736740112, "start": 95, "tag": "USERNAME", "value": "masons" }, { "context": "sons_test'\n login: 'masons'\n passwor...
src/server/conf.coffee
osboo/masonsmafia-db
0
if process.env.MASONS_ENV == 'TEST' conf = db: dbName: 'masons_test' login: 'masons' password: 'masons' host: "#{process.env.MYSQL_HOST}" else conf = db: dbName: 'masons' login: 'masons' password: 'masons' host: "#{process.env.MYSQL_HOST}" module.exports = (section) -> return conf[section]
72124
if process.env.MASONS_ENV == 'TEST' conf = db: dbName: 'masons_test' login: 'masons' password: '<PASSWORD>' host: "#{process.env.MYSQL_HOST}" else conf = db: dbName: 'masons' login: 'masons' password: '<PASSWORD>' host: "#{process.env.MYSQL_HOST}" module.exports = (section) -> return conf[section]
true
if process.env.MASONS_ENV == 'TEST' conf = db: dbName: 'masons_test' login: 'masons' password: 'PI:PASSWORD:<PASSWORD>END_PI' host: "#{process.env.MYSQL_HOST}" else conf = db: dbName: 'masons' login: 'masons' password: 'PI:PASSWORD:<PASSWORD>END_PI' host: "#{process.env.MYSQL_HOST}" module.exports = (section) -> return conf[section]
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.9888670444488525, "start": 16, "tag": "NAME", "value": "Konode" } ]
src/clientFilePage/modifySectionStatusDialog.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 # Dialog to change the status of a section within the client's plan (default/deactivated/completed) # TODO: Consolidate with ModifyTargetStatusDialog Persist = require '../persist' load = (win) -> Bootbox = win.bootbox React = win.React R = React.DOM CrashHandler = require('../crashHandler').load(win) Dialog = require('../dialog').load(win) ModifySectionStatusDialog = React.createFactory React.createClass mixins: [React.addons.PureRenderMixin] componentDidMount: -> @refs.statusReasonField.focus() getInitialState: -> { statusReason: '' } render: -> Dialog({ ref: 'dialog' title: @props.title onClose: @props.onClose }, R.div({className: 'modifyTargetStatusDialog'}, (if @props.dangerMessage R.div({className: 'alert alert-danger'}, @props.dangerMessage) ) R.div({className: 'alert alert-warning'}, @props.message) R.div({className: 'form-group'}, R.label({}, @props.reasonLabel), R.textarea({ className: 'form-control' style: {minWidth: 350, minHeight: 100} ref: 'statusReasonField' onChange: @_updateStatusReason value: @state.statusReason placeholder: "Please specify a reason..." }) ) R.div({className: 'btn-toolbar'}, R.button({ className: 'btn btn-default' onClick: @props.onCancel }, "Cancel") R.button({ className: 'btn btn-primary' onClick: @_submit disabled: not @state.statusReason }, "Confirm") ) ) ) _updateStatusReason: (event) -> @setState {statusReason: event.target.value} _submit: -> @refs.dialog.setIsLoading true clientFile = @props.parentData index = clientFile.getIn(['plan', 'sections']).indexOf @props.data revisedPlan = clientFile.get('plan') .setIn(['sections', index, 'status'], @props.newStatus) .setIn(['sections', index, 'statusReason'], @state.statusReason) revisedClientFile = clientFile.set 'plan', revisedPlan ActiveSession.persist.clientFiles.createRevision revisedClientFile, (err, updatedClientFile) => @refs.dialog.setIsLoading(false) if @refs.dialog? if err if err instanceof Persist.IOError Bootbox.alert """ An error occurred. Please check your network connection and try again. """ console.error err return CrashHandler.handle err return @props.onSuccess() return ModifySectionStatusDialog module.exports = {load}
103918
# 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 # Dialog to change the status of a section within the client's plan (default/deactivated/completed) # TODO: Consolidate with ModifyTargetStatusDialog Persist = require '../persist' load = (win) -> Bootbox = win.bootbox React = win.React R = React.DOM CrashHandler = require('../crashHandler').load(win) Dialog = require('../dialog').load(win) ModifySectionStatusDialog = React.createFactory React.createClass mixins: [React.addons.PureRenderMixin] componentDidMount: -> @refs.statusReasonField.focus() getInitialState: -> { statusReason: '' } render: -> Dialog({ ref: 'dialog' title: @props.title onClose: @props.onClose }, R.div({className: 'modifyTargetStatusDialog'}, (if @props.dangerMessage R.div({className: 'alert alert-danger'}, @props.dangerMessage) ) R.div({className: 'alert alert-warning'}, @props.message) R.div({className: 'form-group'}, R.label({}, @props.reasonLabel), R.textarea({ className: 'form-control' style: {minWidth: 350, minHeight: 100} ref: 'statusReasonField' onChange: @_updateStatusReason value: @state.statusReason placeholder: "Please specify a reason..." }) ) R.div({className: 'btn-toolbar'}, R.button({ className: 'btn btn-default' onClick: @props.onCancel }, "Cancel") R.button({ className: 'btn btn-primary' onClick: @_submit disabled: not @state.statusReason }, "Confirm") ) ) ) _updateStatusReason: (event) -> @setState {statusReason: event.target.value} _submit: -> @refs.dialog.setIsLoading true clientFile = @props.parentData index = clientFile.getIn(['plan', 'sections']).indexOf @props.data revisedPlan = clientFile.get('plan') .setIn(['sections', index, 'status'], @props.newStatus) .setIn(['sections', index, 'statusReason'], @state.statusReason) revisedClientFile = clientFile.set 'plan', revisedPlan ActiveSession.persist.clientFiles.createRevision revisedClientFile, (err, updatedClientFile) => @refs.dialog.setIsLoading(false) if @refs.dialog? if err if err instanceof Persist.IOError Bootbox.alert """ An error occurred. Please check your network connection and try again. """ console.error err return CrashHandler.handle err return @props.onSuccess() return ModifySectionStatusDialog 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 # Dialog to change the status of a section within the client's plan (default/deactivated/completed) # TODO: Consolidate with ModifyTargetStatusDialog Persist = require '../persist' load = (win) -> Bootbox = win.bootbox React = win.React R = React.DOM CrashHandler = require('../crashHandler').load(win) Dialog = require('../dialog').load(win) ModifySectionStatusDialog = React.createFactory React.createClass mixins: [React.addons.PureRenderMixin] componentDidMount: -> @refs.statusReasonField.focus() getInitialState: -> { statusReason: '' } render: -> Dialog({ ref: 'dialog' title: @props.title onClose: @props.onClose }, R.div({className: 'modifyTargetStatusDialog'}, (if @props.dangerMessage R.div({className: 'alert alert-danger'}, @props.dangerMessage) ) R.div({className: 'alert alert-warning'}, @props.message) R.div({className: 'form-group'}, R.label({}, @props.reasonLabel), R.textarea({ className: 'form-control' style: {minWidth: 350, minHeight: 100} ref: 'statusReasonField' onChange: @_updateStatusReason value: @state.statusReason placeholder: "Please specify a reason..." }) ) R.div({className: 'btn-toolbar'}, R.button({ className: 'btn btn-default' onClick: @props.onCancel }, "Cancel") R.button({ className: 'btn btn-primary' onClick: @_submit disabled: not @state.statusReason }, "Confirm") ) ) ) _updateStatusReason: (event) -> @setState {statusReason: event.target.value} _submit: -> @refs.dialog.setIsLoading true clientFile = @props.parentData index = clientFile.getIn(['plan', 'sections']).indexOf @props.data revisedPlan = clientFile.get('plan') .setIn(['sections', index, 'status'], @props.newStatus) .setIn(['sections', index, 'statusReason'], @state.statusReason) revisedClientFile = clientFile.set 'plan', revisedPlan ActiveSession.persist.clientFiles.createRevision revisedClientFile, (err, updatedClientFile) => @refs.dialog.setIsLoading(false) if @refs.dialog? if err if err instanceof Persist.IOError Bootbox.alert """ An error occurred. Please check your network connection and try again. """ console.error err return CrashHandler.handle err return @props.onSuccess() return ModifySectionStatusDialog module.exports = {load}
[ { "context": "email) ->\n doc =\n email: email\n password: '12345678'\n profile:\n first_name: faker.name.firstN", "end": 18846, "score": 0.9993749856948853, "start": 18838, "tag": "PASSWORD", "value": "12345678" }, { "context": "one, email) ->\n Meteor.loginWithPassw...
app_tests/client/sells.app-tests.coffee
Phaze1D/SA-Units
0
faker = require 'faker' { chai, assert, expect } = require 'meteor/practicalmeteor:chai' { Meteor } = require 'meteor/meteor' { Accounts } = require 'meteor/accounts-base' { resetDatabase } = require 'meteor/xolvio:cleaner' { Random } = require 'meteor/random' { _ } = require 'meteor/underscore' EventModule = require '../../imports/api/collections/events/events.coffee' InventoryModule = require '../../imports/api/collections/inventories/inventories.coffee' ProductModule = require '../../imports/api/collections/products/products.coffee' SellModule = require '../../imports/api/collections/sells/sells.coffee' EMethods = require '../../imports/api/collections/events/methods.coffee' OMethods = require '../../imports/api/collections/organizations/methods.coffee' PMethods = require '../../imports/api/collections/products/methods.coffee' IMethods = require '../../imports/api/collections/inventories/methods.coffee' InMethods = require '../../imports/api/collections/ingredients/methods.coffee' SMethods = require '../../imports/api/collections/sells/methods.coffee' sellIDs = [] organizationIDs = [] productIDs = [] inventoryIDs = [] ingredientIDs = [] describe "Sells Client Side Test", -> before -> resetDatabase(null); describe "Setup", -> after( (done) -> @timeout(5000) setTimeout(done, 3000) return ) it "Create User", (done) -> createUser(done, faker.internet.email()) it "Create Organization", (done) -> createOrgan(done) it "Create Ingredient",(done) -> createIngredient(done, 0) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Inventory", (done) -> createInventory(done, 0) it "Add to Inventory", (done) -> addToInventory(done, 0, 30) it "Create Inventory", (done) -> createInventory(done, 0) it "Add to Inventory", (done) -> addToInventory(done, 1, 30) it "Create Inventory", (done) -> createInventory(done, 1) it "Add to Inventory", (done) -> addToInventory(done, 2, 30) it "Create Inventory", (done) -> createInventory(done, 2) it "Add to Inventory", (done) -> addToInventory(done, 3, 30) it "Create Inventory", (done) -> createInventory(done, 2) it "Add to Inventory", (done) -> addToInventory(done, 4, 30) it "Subscribe to inventory", (done) -> subscribe(done, 'inventories') it "Subscribe to events", (done) -> subscribe(done, 'events') it "Subscribe to products", (done) -> subscribe(done, 'products') it "Subscribe to sells", (done) -> subscribe(done, 'sells') describe "Insert", -> it "Validate duplicate products", (done) -> details = [ { product_id: productIDs[0] quantity: 12 }, { product_id: productIDs[0] quantity: 1 } ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(err).to.have.property('error', 'duplicateError') done() it "Remove Zero Details ", (done) -> details = [ { product_id: productIDs[0] quantity: 12 }, { product_id: productIDs[1] quantity: 0 } ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(SellModule.Sells.findOne(res).details.length).to.equal(1) sellIDs.push res done() it "Remove un auth fields", (done) -> details = [ { product_id: productIDs[0] quantity: 12 inventories: [ inventory_id: inventoryIDs[0] quantity_taken: 12 ] } ] sell_doc = details: details status: 'preorder' paid: true discount: 12 payment_method: 'cash' organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> sell = SellModule.Sells.findOne(res) expect(sell.paid).to.equal(false) expect(sell.details[0].inventories.length).to.equal(0) sellIDs.push res done() describe "Add Items", -> it "Quantity over load", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 100 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'quantityError') done() it "Check new details", (done) -> expect(SellModule.Sells.findOne(sellIDs[1]).details[0].quantity).to.equal(12) old = InventoryModule.Inventories.findOne(inventoryIDs[0]).amount inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[2] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> sell = SellModule.Sells.findOne(sellIDs[1]) expect(de.quantity).to.equal(1) for de in sell.details expect(old).to.equal(InventoryModule.Inventories.findOne(inventoryIDs[0]).amount + 1) expect(EventModule.Events.findOne({for_id: inventoryIDs[0]}, sort: {createdAt: -1}).amount).to.equal(-1) done() it "Negative quantities", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[2] quantity_taken: -1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'validation-error') done() describe "Put Back", -> it "Check 0 details", (done) -> old = InventoryModule.Inventories.findOne(inventoryIDs[2]).amount expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) inventories = [ { inventory_id: inventoryIDs[2] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> sell = SellModule.Sells.findOne(sellIDs[1]) expect(sell.details.length).to.equal(1) expect(old).to.equal( InventoryModule.Inventories.findOne(inventoryIDs[2]).amount - 1) done() it "Over taking", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() it "Remove non existing product in sell", (done) -> inventories = [ { inventory_id: inventoryIDs[4] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() it "Remove non existing inventory in sell", (done) -> inventories = [ { inventory_id: inventoryIDs[1] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() describe "Update Un paid", -> it "Update details with new product", (done) -> console.log SellModule.Sells.findOne(sellIDs[1]) expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) details = [ product_id: productIDs[2] unit_price: 131 quantity: 23 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist console.log SellModule.Sells.findOne(sellIDs[1]) expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) done() it "Update removing detail without inventories", (done) -> expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) details = [ product_id: productIDs[2] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) done() it "Update detail with inventories to 0", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[1]) expect(sell.details.length).to.equal(1) expect(sell.details[0].quantity).to.equal(0) done() describe "Delete un paid", -> it "Delete with inventories", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('error', 'deleteError') done() it "Remove inventory", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> console.log err expect(err).to.not.exist done() it "update detail", (done) -> details = [ product_id: productIDs[2] unit_price: 131 quantity: 23 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> console.log err expect(err).to.not.exist expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) done() it "Delete without inventories", (done) -> expect(SellModule.Sells.find().count()).to.equal(2) organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(SellModule.Sells.find().count()).to.equal(1) expect(err).to.not.exist done() describe "Pay", -> it "No physical Items", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('reason', 'Cannot paid sell that has no physical items') done() it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "Update sell", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist done() it "No physical Items", (done) -> expect(SellModule.Sells.findOne().details.length).to.equal(1) organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('error', 'detailMismatch') done() it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "pay", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.not.exist expect( SellModule.Sells.findOne().paid ).to.equal(true) done() it "pay double", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('reason', 'sell has already been paid') done() describe "Update paid", -> it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.exist expect(err).to.have.property('error', 'itemError') done() it "Remove physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.exist expect(err).to.have.property('error', 'itemError') done() it "Update detail with inventories to 0", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details status: 'nono' organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[0]) expect(sell.details.length).to.equal(1) expect(sell.details[0].quantity).to.equal(4) expect(sell.status).to.equal('nono') done() describe "Delete paid", -> it "Delete paid", (done) -> expect(SellModule.Sells.find().count()).to.equal(1) organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(SellModule.Sells.find().count()).to.equal(1) expect(err).to.exist expect(err).to.have.property('error', 'deleteError') done() describe "Extra", (done) -> it "insert", (done) -> details = [ { product_id: productIDs[0] quantity: 32 }, { product_id: productIDs[1] quantity: 12 }, { product_id: productIDs[2] quantity: 13 }, { product_id: productIDs[3] quantity: 13 }, ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(err).to.not.exist sellIDs.push res done() it "Add inventories", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 20 }, { inventory_id: inventoryIDs[1] quantity_taken: 20 }, { inventory_id: inventoryIDs[2] quantity_taken: 12 }, { inventory_id: inventoryIDs[3] quantity_taken: 5 }, { inventory_id: inventoryIDs[4] quantity_taken: 23 } ] organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "pay", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.exist done() it "Update", (done)-> details = [ product_id: productIDs[3] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[2]) console.log sell expect(sell.details.length).to.equal(3) done() # ++++++++++++++++++++++++ Setup Methods addToInventory = (done, index, amount) -> event_doc = amount: amount for_type: 'inventory' for_id: inventoryIDs[index] organization_id: organizationIDs[0] EMethods.userEvent.call {event_doc}, (err, res) -> throw err if err? done() createUser = (done, email) -> doc = email: email password: '12345678' profile: first_name: faker.name.firstName() last_name: faker.name.lastName() Accounts.createUser doc, (err) -> throw err if err? done() login = (done, email) -> Meteor.loginWithPassword email, '12345678', (err) -> done() logout = (done) -> Meteor.logout( (err) -> done() ) createOrgan = (done) -> organization_doc = name: faker.company.companyName() email: faker.internet.email() OMethods.insert.call {organization_doc}, (err, res) -> throw err if err? organizationIDs.push res done() createInventory = (done, pIndex) -> inventory_doc = product_id: productIDs[pIndex] organization_id: organizationIDs[0] IMethods.insert.call {inventory_doc}, (err,res) -> throw err if err? inventoryIDs.push res done() createIngredient = (done, i) -> ingredient_doc = name: faker.name.firstName() measurement_unit: 'kg' organization_id: organizationIDs[i] InMethods.insert.call {ingredient_doc}, (err, res) -> throw err if err? ingredientIDs.push res done() createProduct = (done, ings) -> ingredientsL = [] for ing in ings ing_doc = ingredient_id: ing amount: (Random.fraction() * 100) ingredientsL.push ing_doc product_doc = name: faker.commerce.productName() sku: faker.random.uuid() unit_price: 12.23 currency: 'mxn' tax_rate: 16 ingredients: ingredientsL organization_id: organizationIDs[0] PMethods.insert.call {product_doc}, (err, res) -> throw err if err? productIDs.push res done() subscribe = (done, subto) -> callbacks = onStop: (err) -> throw err if err? onReady: () -> done() Meteor.subscribe(subto, organizationIDs[0], callbacks) inviteUse = (done, email) -> invited_user_doc = emails: [ address: email ] profile: first_name: faker.name.firstName() organization_id = organizationID permission = owner: false viewer: false expenses_manager: false sells_manager: false units_manager: false inventories_manager: true users_manager: false inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) -> throw err if err? done()
115958
faker = require 'faker' { chai, assert, expect } = require 'meteor/practicalmeteor:chai' { Meteor } = require 'meteor/meteor' { Accounts } = require 'meteor/accounts-base' { resetDatabase } = require 'meteor/xolvio:cleaner' { Random } = require 'meteor/random' { _ } = require 'meteor/underscore' EventModule = require '../../imports/api/collections/events/events.coffee' InventoryModule = require '../../imports/api/collections/inventories/inventories.coffee' ProductModule = require '../../imports/api/collections/products/products.coffee' SellModule = require '../../imports/api/collections/sells/sells.coffee' EMethods = require '../../imports/api/collections/events/methods.coffee' OMethods = require '../../imports/api/collections/organizations/methods.coffee' PMethods = require '../../imports/api/collections/products/methods.coffee' IMethods = require '../../imports/api/collections/inventories/methods.coffee' InMethods = require '../../imports/api/collections/ingredients/methods.coffee' SMethods = require '../../imports/api/collections/sells/methods.coffee' sellIDs = [] organizationIDs = [] productIDs = [] inventoryIDs = [] ingredientIDs = [] describe "Sells Client Side Test", -> before -> resetDatabase(null); describe "Setup", -> after( (done) -> @timeout(5000) setTimeout(done, 3000) return ) it "Create User", (done) -> createUser(done, faker.internet.email()) it "Create Organization", (done) -> createOrgan(done) it "Create Ingredient",(done) -> createIngredient(done, 0) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Inventory", (done) -> createInventory(done, 0) it "Add to Inventory", (done) -> addToInventory(done, 0, 30) it "Create Inventory", (done) -> createInventory(done, 0) it "Add to Inventory", (done) -> addToInventory(done, 1, 30) it "Create Inventory", (done) -> createInventory(done, 1) it "Add to Inventory", (done) -> addToInventory(done, 2, 30) it "Create Inventory", (done) -> createInventory(done, 2) it "Add to Inventory", (done) -> addToInventory(done, 3, 30) it "Create Inventory", (done) -> createInventory(done, 2) it "Add to Inventory", (done) -> addToInventory(done, 4, 30) it "Subscribe to inventory", (done) -> subscribe(done, 'inventories') it "Subscribe to events", (done) -> subscribe(done, 'events') it "Subscribe to products", (done) -> subscribe(done, 'products') it "Subscribe to sells", (done) -> subscribe(done, 'sells') describe "Insert", -> it "Validate duplicate products", (done) -> details = [ { product_id: productIDs[0] quantity: 12 }, { product_id: productIDs[0] quantity: 1 } ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(err).to.have.property('error', 'duplicateError') done() it "Remove Zero Details ", (done) -> details = [ { product_id: productIDs[0] quantity: 12 }, { product_id: productIDs[1] quantity: 0 } ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(SellModule.Sells.findOne(res).details.length).to.equal(1) sellIDs.push res done() it "Remove un auth fields", (done) -> details = [ { product_id: productIDs[0] quantity: 12 inventories: [ inventory_id: inventoryIDs[0] quantity_taken: 12 ] } ] sell_doc = details: details status: 'preorder' paid: true discount: 12 payment_method: 'cash' organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> sell = SellModule.Sells.findOne(res) expect(sell.paid).to.equal(false) expect(sell.details[0].inventories.length).to.equal(0) sellIDs.push res done() describe "Add Items", -> it "Quantity over load", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 100 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'quantityError') done() it "Check new details", (done) -> expect(SellModule.Sells.findOne(sellIDs[1]).details[0].quantity).to.equal(12) old = InventoryModule.Inventories.findOne(inventoryIDs[0]).amount inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[2] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> sell = SellModule.Sells.findOne(sellIDs[1]) expect(de.quantity).to.equal(1) for de in sell.details expect(old).to.equal(InventoryModule.Inventories.findOne(inventoryIDs[0]).amount + 1) expect(EventModule.Events.findOne({for_id: inventoryIDs[0]}, sort: {createdAt: -1}).amount).to.equal(-1) done() it "Negative quantities", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[2] quantity_taken: -1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'validation-error') done() describe "Put Back", -> it "Check 0 details", (done) -> old = InventoryModule.Inventories.findOne(inventoryIDs[2]).amount expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) inventories = [ { inventory_id: inventoryIDs[2] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> sell = SellModule.Sells.findOne(sellIDs[1]) expect(sell.details.length).to.equal(1) expect(old).to.equal( InventoryModule.Inventories.findOne(inventoryIDs[2]).amount - 1) done() it "Over taking", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() it "Remove non existing product in sell", (done) -> inventories = [ { inventory_id: inventoryIDs[4] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() it "Remove non existing inventory in sell", (done) -> inventories = [ { inventory_id: inventoryIDs[1] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() describe "Update Un paid", -> it "Update details with new product", (done) -> console.log SellModule.Sells.findOne(sellIDs[1]) expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) details = [ product_id: productIDs[2] unit_price: 131 quantity: 23 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist console.log SellModule.Sells.findOne(sellIDs[1]) expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) done() it "Update removing detail without inventories", (done) -> expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) details = [ product_id: productIDs[2] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) done() it "Update detail with inventories to 0", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[1]) expect(sell.details.length).to.equal(1) expect(sell.details[0].quantity).to.equal(0) done() describe "Delete un paid", -> it "Delete with inventories", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('error', 'deleteError') done() it "Remove inventory", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> console.log err expect(err).to.not.exist done() it "update detail", (done) -> details = [ product_id: productIDs[2] unit_price: 131 quantity: 23 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> console.log err expect(err).to.not.exist expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) done() it "Delete without inventories", (done) -> expect(SellModule.Sells.find().count()).to.equal(2) organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(SellModule.Sells.find().count()).to.equal(1) expect(err).to.not.exist done() describe "Pay", -> it "No physical Items", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('reason', 'Cannot paid sell that has no physical items') done() it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "Update sell", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist done() it "No physical Items", (done) -> expect(SellModule.Sells.findOne().details.length).to.equal(1) organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('error', 'detailMismatch') done() it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "pay", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.not.exist expect( SellModule.Sells.findOne().paid ).to.equal(true) done() it "pay double", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('reason', 'sell has already been paid') done() describe "Update paid", -> it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.exist expect(err).to.have.property('error', 'itemError') done() it "Remove physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.exist expect(err).to.have.property('error', 'itemError') done() it "Update detail with inventories to 0", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details status: 'nono' organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[0]) expect(sell.details.length).to.equal(1) expect(sell.details[0].quantity).to.equal(4) expect(sell.status).to.equal('nono') done() describe "Delete paid", -> it "Delete paid", (done) -> expect(SellModule.Sells.find().count()).to.equal(1) organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(SellModule.Sells.find().count()).to.equal(1) expect(err).to.exist expect(err).to.have.property('error', 'deleteError') done() describe "Extra", (done) -> it "insert", (done) -> details = [ { product_id: productIDs[0] quantity: 32 }, { product_id: productIDs[1] quantity: 12 }, { product_id: productIDs[2] quantity: 13 }, { product_id: productIDs[3] quantity: 13 }, ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(err).to.not.exist sellIDs.push res done() it "Add inventories", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 20 }, { inventory_id: inventoryIDs[1] quantity_taken: 20 }, { inventory_id: inventoryIDs[2] quantity_taken: 12 }, { inventory_id: inventoryIDs[3] quantity_taken: 5 }, { inventory_id: inventoryIDs[4] quantity_taken: 23 } ] organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "pay", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.exist done() it "Update", (done)-> details = [ product_id: productIDs[3] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[2]) console.log sell expect(sell.details.length).to.equal(3) done() # ++++++++++++++++++++++++ Setup Methods addToInventory = (done, index, amount) -> event_doc = amount: amount for_type: 'inventory' for_id: inventoryIDs[index] organization_id: organizationIDs[0] EMethods.userEvent.call {event_doc}, (err, res) -> throw err if err? done() createUser = (done, email) -> doc = email: email password: '<PASSWORD>' profile: first_name: faker.name.firstName() last_name: faker.name.lastName() Accounts.createUser doc, (err) -> throw err if err? done() login = (done, email) -> Meteor.loginWithPassword email, '<PASSWORD>', (err) -> done() logout = (done) -> Meteor.logout( (err) -> done() ) createOrgan = (done) -> organization_doc = name: faker.company.companyName() email: faker.internet.email() OMethods.insert.call {organization_doc}, (err, res) -> throw err if err? organizationIDs.push res done() createInventory = (done, pIndex) -> inventory_doc = product_id: productIDs[pIndex] organization_id: organizationIDs[0] IMethods.insert.call {inventory_doc}, (err,res) -> throw err if err? inventoryIDs.push res done() createIngredient = (done, i) -> ingredient_doc = name: faker.name.firstName() measurement_unit: 'kg' organization_id: organizationIDs[i] InMethods.insert.call {ingredient_doc}, (err, res) -> throw err if err? ingredientIDs.push res done() createProduct = (done, ings) -> ingredientsL = [] for ing in ings ing_doc = ingredient_id: ing amount: (Random.fraction() * 100) ingredientsL.push ing_doc product_doc = name: faker.commerce.productName() sku: faker.random.uuid() unit_price: 12.23 currency: 'mxn' tax_rate: 16 ingredients: ingredientsL organization_id: organizationIDs[0] PMethods.insert.call {product_doc}, (err, res) -> throw err if err? productIDs.push res done() subscribe = (done, subto) -> callbacks = onStop: (err) -> throw err if err? onReady: () -> done() Meteor.subscribe(subto, organizationIDs[0], callbacks) inviteUse = (done, email) -> invited_user_doc = emails: [ address: email ] profile: first_name: faker.name.firstName() organization_id = organizationID permission = owner: false viewer: false expenses_manager: false sells_manager: false units_manager: false inventories_manager: true users_manager: false inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) -> throw err if err? done()
true
faker = require 'faker' { chai, assert, expect } = require 'meteor/practicalmeteor:chai' { Meteor } = require 'meteor/meteor' { Accounts } = require 'meteor/accounts-base' { resetDatabase } = require 'meteor/xolvio:cleaner' { Random } = require 'meteor/random' { _ } = require 'meteor/underscore' EventModule = require '../../imports/api/collections/events/events.coffee' InventoryModule = require '../../imports/api/collections/inventories/inventories.coffee' ProductModule = require '../../imports/api/collections/products/products.coffee' SellModule = require '../../imports/api/collections/sells/sells.coffee' EMethods = require '../../imports/api/collections/events/methods.coffee' OMethods = require '../../imports/api/collections/organizations/methods.coffee' PMethods = require '../../imports/api/collections/products/methods.coffee' IMethods = require '../../imports/api/collections/inventories/methods.coffee' InMethods = require '../../imports/api/collections/ingredients/methods.coffee' SMethods = require '../../imports/api/collections/sells/methods.coffee' sellIDs = [] organizationIDs = [] productIDs = [] inventoryIDs = [] ingredientIDs = [] describe "Sells Client Side Test", -> before -> resetDatabase(null); describe "Setup", -> after( (done) -> @timeout(5000) setTimeout(done, 3000) return ) it "Create User", (done) -> createUser(done, faker.internet.email()) it "Create Organization", (done) -> createOrgan(done) it "Create Ingredient",(done) -> createIngredient(done, 0) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Product", (done) -> ings = [ingredientIDs[0]] createProduct(done, ings) it "Create Inventory", (done) -> createInventory(done, 0) it "Add to Inventory", (done) -> addToInventory(done, 0, 30) it "Create Inventory", (done) -> createInventory(done, 0) it "Add to Inventory", (done) -> addToInventory(done, 1, 30) it "Create Inventory", (done) -> createInventory(done, 1) it "Add to Inventory", (done) -> addToInventory(done, 2, 30) it "Create Inventory", (done) -> createInventory(done, 2) it "Add to Inventory", (done) -> addToInventory(done, 3, 30) it "Create Inventory", (done) -> createInventory(done, 2) it "Add to Inventory", (done) -> addToInventory(done, 4, 30) it "Subscribe to inventory", (done) -> subscribe(done, 'inventories') it "Subscribe to events", (done) -> subscribe(done, 'events') it "Subscribe to products", (done) -> subscribe(done, 'products') it "Subscribe to sells", (done) -> subscribe(done, 'sells') describe "Insert", -> it "Validate duplicate products", (done) -> details = [ { product_id: productIDs[0] quantity: 12 }, { product_id: productIDs[0] quantity: 1 } ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(err).to.have.property('error', 'duplicateError') done() it "Remove Zero Details ", (done) -> details = [ { product_id: productIDs[0] quantity: 12 }, { product_id: productIDs[1] quantity: 0 } ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(SellModule.Sells.findOne(res).details.length).to.equal(1) sellIDs.push res done() it "Remove un auth fields", (done) -> details = [ { product_id: productIDs[0] quantity: 12 inventories: [ inventory_id: inventoryIDs[0] quantity_taken: 12 ] } ] sell_doc = details: details status: 'preorder' paid: true discount: 12 payment_method: 'cash' organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> sell = SellModule.Sells.findOne(res) expect(sell.paid).to.equal(false) expect(sell.details[0].inventories.length).to.equal(0) sellIDs.push res done() describe "Add Items", -> it "Quantity over load", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 100 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'quantityError') done() it "Check new details", (done) -> expect(SellModule.Sells.findOne(sellIDs[1]).details[0].quantity).to.equal(12) old = InventoryModule.Inventories.findOne(inventoryIDs[0]).amount inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[2] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> sell = SellModule.Sells.findOne(sellIDs[1]) expect(de.quantity).to.equal(1) for de in sell.details expect(old).to.equal(InventoryModule.Inventories.findOne(inventoryIDs[0]).amount + 1) expect(EventModule.Events.findOne({for_id: inventoryIDs[0]}, sort: {createdAt: -1}).amount).to.equal(-1) done() it "Negative quantities", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[2] quantity_taken: -1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'validation-error') done() describe "Put Back", -> it "Check 0 details", (done) -> old = InventoryModule.Inventories.findOne(inventoryIDs[2]).amount expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) inventories = [ { inventory_id: inventoryIDs[2] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> sell = SellModule.Sells.findOne(sellIDs[1]) expect(sell.details.length).to.equal(1) expect(old).to.equal( InventoryModule.Inventories.findOne(inventoryIDs[2]).amount - 1) done() it "Over taking", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() it "Remove non existing product in sell", (done) -> inventories = [ { inventory_id: inventoryIDs[4] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() it "Remove non existing inventory in sell", (done) -> inventories = [ { inventory_id: inventoryIDs[1] quantity_taken: 4 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.have.property('error', 'putBackError') done() describe "Update Un paid", -> it "Update details with new product", (done) -> console.log SellModule.Sells.findOne(sellIDs[1]) expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) details = [ product_id: productIDs[2] unit_price: 131 quantity: 23 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist console.log SellModule.Sells.findOne(sellIDs[1]) expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) done() it "Update removing detail without inventories", (done) -> expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(2) details = [ product_id: productIDs[2] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) done() it "Update detail with inventories to 0", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[1]) expect(sell.details.length).to.equal(1) expect(sell.details[0].quantity).to.equal(0) done() describe "Delete un paid", -> it "Delete with inventories", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('error', 'deleteError') done() it "Remove inventory", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> console.log err expect(err).to.not.exist done() it "update detail", (done) -> details = [ product_id: productIDs[2] unit_price: 131 quantity: 23 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> console.log err expect(err).to.not.exist expect(SellModule.Sells.findOne(sellIDs[1]).details.length).to.equal(1) done() it "Delete without inventories", (done) -> expect(SellModule.Sells.find().count()).to.equal(2) organization_id = organizationIDs[0] sell_id = sellIDs[1] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(SellModule.Sells.find().count()).to.equal(1) expect(err).to.not.exist done() describe "Pay", -> it "No physical Items", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('reason', 'Cannot paid sell that has no physical items') done() it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "Update sell", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist done() it "No physical Items", (done) -> expect(SellModule.Sells.findOne().details.length).to.equal(1) organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('error', 'detailMismatch') done() it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "pay", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.not.exist expect( SellModule.Sells.findOne().paid ).to.equal(true) done() it "pay double", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.have.property('reason', 'sell has already been paid') done() describe "Update paid", -> it "Add physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.exist expect(err).to.have.property('error', 'itemError') done() it "Remove physical items", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 1 }, { inventory_id: inventoryIDs[1] quantity_taken: 1 } ] organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.putBackItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.exist expect(err).to.have.property('error', 'itemError') done() it "Update detail with inventories to 0", (done) -> details = [ product_id: productIDs[0] unit_price: 131 quantity: 0 ] sell_doc = details: details status: 'nono' organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[0]) expect(sell.details.length).to.equal(1) expect(sell.details[0].quantity).to.equal(4) expect(sell.status).to.equal('nono') done() describe "Delete paid", -> it "Delete paid", (done) -> expect(SellModule.Sells.find().count()).to.equal(1) organization_id = organizationIDs[0] sell_id = sellIDs[0] SMethods.deleteSell.call {organization_id, sell_id}, (err, res) -> expect(SellModule.Sells.find().count()).to.equal(1) expect(err).to.exist expect(err).to.have.property('error', 'deleteError') done() describe "Extra", (done) -> it "insert", (done) -> details = [ { product_id: productIDs[0] quantity: 32 }, { product_id: productIDs[1] quantity: 12 }, { product_id: productIDs[2] quantity: 13 }, { product_id: productIDs[3] quantity: 13 }, ] sell_doc = details: details status: 'preorder' total_price: 0 organization_id: organizationIDs[0] SMethods.insert.call {sell_doc}, (err, res) -> expect(err).to.not.exist sellIDs.push res done() it "Add inventories", (done) -> inventories = [ { inventory_id: inventoryIDs[0] quantity_taken: 20 }, { inventory_id: inventoryIDs[1] quantity_taken: 20 }, { inventory_id: inventoryIDs[2] quantity_taken: 12 }, { inventory_id: inventoryIDs[3] quantity_taken: 5 }, { inventory_id: inventoryIDs[4] quantity_taken: 23 } ] organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.addItems.call {organization_id, sell_id, inventories}, (err, res) -> expect(err).to.not.exist done() it "pay", (done) -> organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.pay.call {organization_id, sell_id}, (err, res) -> expect(err).to.exist done() it "Update", (done)-> details = [ product_id: productIDs[3] unit_price: 131 quantity: 0 ] sell_doc = details: details organization_id = organizationIDs[0] sell_id = sellIDs[2] SMethods.update.call {organization_id, sell_id, sell_doc}, (err, res) -> expect(err).to.not.exist sell = SellModule.Sells.findOne(sellIDs[2]) console.log sell expect(sell.details.length).to.equal(3) done() # ++++++++++++++++++++++++ Setup Methods addToInventory = (done, index, amount) -> event_doc = amount: amount for_type: 'inventory' for_id: inventoryIDs[index] organization_id: organizationIDs[0] EMethods.userEvent.call {event_doc}, (err, res) -> throw err if err? done() createUser = (done, email) -> doc = email: email password: 'PI:PASSWORD:<PASSWORD>END_PI' profile: first_name: faker.name.firstName() last_name: faker.name.lastName() Accounts.createUser doc, (err) -> throw err if err? done() login = (done, email) -> Meteor.loginWithPassword email, 'PI:PASSWORD:<PASSWORD>END_PI', (err) -> done() logout = (done) -> Meteor.logout( (err) -> done() ) createOrgan = (done) -> organization_doc = name: faker.company.companyName() email: faker.internet.email() OMethods.insert.call {organization_doc}, (err, res) -> throw err if err? organizationIDs.push res done() createInventory = (done, pIndex) -> inventory_doc = product_id: productIDs[pIndex] organization_id: organizationIDs[0] IMethods.insert.call {inventory_doc}, (err,res) -> throw err if err? inventoryIDs.push res done() createIngredient = (done, i) -> ingredient_doc = name: faker.name.firstName() measurement_unit: 'kg' organization_id: organizationIDs[i] InMethods.insert.call {ingredient_doc}, (err, res) -> throw err if err? ingredientIDs.push res done() createProduct = (done, ings) -> ingredientsL = [] for ing in ings ing_doc = ingredient_id: ing amount: (Random.fraction() * 100) ingredientsL.push ing_doc product_doc = name: faker.commerce.productName() sku: faker.random.uuid() unit_price: 12.23 currency: 'mxn' tax_rate: 16 ingredients: ingredientsL organization_id: organizationIDs[0] PMethods.insert.call {product_doc}, (err, res) -> throw err if err? productIDs.push res done() subscribe = (done, subto) -> callbacks = onStop: (err) -> throw err if err? onReady: () -> done() Meteor.subscribe(subto, organizationIDs[0], callbacks) inviteUse = (done, email) -> invited_user_doc = emails: [ address: email ] profile: first_name: faker.name.firstName() organization_id = organizationID permission = owner: false viewer: false expenses_manager: false sells_manager: false units_manager: false inventories_manager: true users_manager: false inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) -> throw err if err? done()
[ { "context": "nse object', -> co =>\n yield pretend.user('sam').send 'door 1'\n yield @path.match pretend", "end": 6868, "score": 0.8800855278968811, "start": 6865, "tag": "NAME", "value": "sam" }, { "context": "s the path', -> co =>\n yield pretend.user('sam').s...
test/unit/02-path_test.coffee
PropertyUX/nubot-playbook
0
sinon = require 'sinon' chai = require 'chai' should = chai.should() chai.use require 'sinon-chai' co = require 'co' _ = require 'lodash' pretend = require 'hubot-pretend' Path = require '../../lib/modules/path' resMatch = (value) -> responseKeys = [ 'robot', 'message', 'match', 'envelope' ] difference = _.difference responseKeys, _.keys value difference.length == 0 describe 'Path', -> beforeEach -> pretend.start() pretend.log.level = 'silent' afterEach -> pretend.shutdown() describe 'constructor', -> context 'with branches', -> it 'calls .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot, [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] path.addBranch.args.should.eql [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] Path.prototype.addBranch.restore() it 'is not closed', -> path = new Path pretend.robot, [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] path.closed.should.be.false context 'with a single branch', -> it 'calls .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot, [ /ok/, 'OK, ok!' ] path.addBranch.args.should.eql [ [ /ok/, 'OK, ok!' ] ] Path.prototype.addBranch.restore() it 'is not closed', -> path = new Path pretend.robot, [ /ok/, 'OK, ok!' ] path.closed.should.be.false context 'with undefined branches and options', -> it 'does not call .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot Path.prototype.addBranch.restore() it 'stays closed', -> path = new Path pretend.robot path.closed.should.be.true context 'with bad arguments for branch', -> it 'throws', -> try @path = new Path pretend.robot, 'breakme.jpg' Path.constructor.should.throw describe '.addBranch', -> beforeEach -> sinon.spy Path.prototype, 'addBranch' afterEach -> Path.prototype.addBranch.restore() it 'creates branch object', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.branches[0].should.be.an 'object' it 'branch has valid regex', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.branches[0].regex.should.be.instanceof RegExp it 'accepts a string that can be cast as RegExp', -> path = new Path pretend.robot path.addBranch '/.*/ig', 'foo', () -> path.branches[0].regex.should.be.instanceof RegExp it 'calls getHandler with strings and callback', -> path = new Path pretend.robot callback = -> sinon.stub path, 'getHandler' path.addBranch /.*/, 'foo', callback path.getHandler.should.have.calledWithExactly 'foo', callback it 'calls getHandler with just stirngs', -> path = new Path pretend.robot sinon.stub path, 'getHandler' path.addBranch /.*/, ['foo', 'bar'] path.getHandler.should.have.calledWithExactly ['foo', 'bar'], undefined it 'calls getHandler with just callback', -> path = new Path pretend.robot callback = -> sinon.stub path, 'getHandler' path.addBranch /.*/, callback path.getHandler.should.have.calledWithExactly undefined, callback it 'branch stores handler', -> path = new Path pretend.robot sinon.spy path, 'getHandler' path.addBranch /.*/, 'foo', () -> lasthandler = path.getHandler.returnValues[0] path.branches[0].handler.should.eql lasthandler it 'opens path', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.closed.should.be.false it 'throws with invalid regex', -> path = new Path pretend.robot try path.addBranch 'derp' path.addBranch.should.throw it 'throws with insufficient args', -> path = new Path pretend.robot try path.addBranch /.*/ path.addBranch.should.throw it 'throws with invalid message', -> path = new Path pretend.robot try path.addBranch /.*/, () -> path.addBranch.should.throw it 'throws with invalid callback', -> path = new Path pretend.robot try path.addBranch /.*/, 'foo', 'bar' path.addBranch.should.throw describe '.getHandler', -> it 'returns a function', -> path = new Path pretend.robot callback = sinon.spy() handler = path.getHandler ['foo', 'bar'], callback handler.should.be.a 'function' context 'when handler called with response', -> it 'calls the callback with the response', -> path = new Path pretend.robot callback = sinon.spy() handler = path.getHandler ['foo', 'bar'], callback mockRes = reply: sinon.spy() handler mockRes callback.should.have.calledWithExactly mockRes it 'sends strings with dialogue if it has one', -> path = new Path pretend.robot handler = path.getHandler ['foo', 'bar'] mockRes = reply: sinon.spy(), dialogue: send: sinon.spy() handler mockRes mockRes.dialogue.send.should.have.calledWith 'foo', 'bar' it 'uses response reply if there is no dialogue', -> path = new Path pretend.robot handler = path.getHandler ['foo', 'bar'] mockRes = reply: sinon.spy() handler mockRes mockRes.reply.should.have.calledWith 'foo', 'bar' it 'returns promise resolving with send results', -> co -> path = new Path pretend.robot handler = path.getHandler ['foo'], () -> bar: 'baz' mockRes = reply: sinon.spy() handlerSpy = sinon.spy handler yield handler mockRes handlerSpy.returned sinon.match resMatch it 'returns promise also merged with callback results', -> co -> path = new Path pretend.robot handler = path.getHandler ['foo'], () -> bar: 'baz' mockRes = reply: sinon.spy() handlerSpy = sinon.spy handler yield handler mockRes handlerSpy.returned sinon.match bar: 'baz' describe '.match', -> beforeEach -> pretend.robot.hear /door/, -> # listen to tests @path = new Path pretend.robot, [ [ /door 1/, 'you lost', -> winner: false ] [ /door 2/, 'you won', -> winner: true ] [ /door 3/, 'try again' ] ] @match = sinon.spy() @mismatch = sinon.spy() @catch = sinon.spy() @path.on 'match', @match @path.on 'mismatch', @mismatch @path.on 'catch', @catch context 'with string matching branch regex', -> it 'updates match in response object', -> co => yield pretend.user('sam').send 'door 1' yield @path.match pretend.lastListen() expectedMatch = 'door 1'.match @path.branches[0].regex pretend.lastListen().match.should.eql expectedMatch it 'closes the path', -> co => yield pretend.user('sam').send 'door 2' yield @path.match pretend.lastListen() @path.closed.should.be.true it 'calls the handler for matching branch with res', -> co => @path.branches[1].handler = sinon.stub() yield pretend.user('sam').send 'door 2' res = pretend.lastListen() yield @path.match res @path.branches[1].handler.should.have.calledWithExactly res it 'emits match with res', -> co => yield pretend.user('sam').send 'door 2' yield @path.match pretend.lastListen() @match.should.have.calledWith sinon.match resMatch context 'with string matching multiple branches', -> it 'updates match in response object', -> co => yield pretend.user('sam').send 'door 1 and door 2' yield @path.match pretend.lastListen() expectedMatch = 'door 1 and door 2'.match @path.branches[0].regex pretend.lastListen().match.should.eql expectedMatch it 'calls the first matching branch handler', -> co => yield pretend.user('sam').send 'door 1 and door 2' result = yield @path.match pretend.lastListen() result.should.have.property 'winner', false it 'closes the path', -> co => yield pretend.user('sam').send 'door 1 and door 2' yield @path.match pretend.lastListen() @path.closed.should.be.true context 'with mismatching string and no catch', -> it 'returns undefined', -> co => yield pretend.user('sam').send 'door X' result = yield @path.match pretend.lastListen() chai.expect(result).to.be.undefined it 'updates match to null in response object', -> co => yield pretend.user('sam').send 'door X' yield @path.match pretend.lastListen() chai.expect(pretend.lastListen().match).to.be.null it 'path stays open', -> co => yield pretend.user('sam').send 'door X' yield @path.match pretend.lastListen() @path.closed.should.be.false it 'emits mismatch with res', -> co => yield pretend.user('sam').send 'door X' yield @path.match pretend.lastListen() @mismatch.should.have.calledWith sinon.match resMatch context 'with mismatching string and catch message', -> it 'returns the response from send', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('sam').send 'door X' result = yield @path.match pretend.lastListen() result.strings.should.eql [ 'no, wrong door' ] it 'emits catch with res', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('sam').send 'door X' yield @path.match pretend.lastListen() @catch.should.have.calledWith sinon.match resMatch context 'with mismatching string and catch callback', -> it 'returns the result of the callback', -> co => @path.configure catchCallback: -> other: 'door fail' yield pretend.user('sam').send 'door X' result = yield @path.match pretend.lastListen() result.should.have.property 'other', 'door fail' it 'emits catch with res', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('sam').send 'door X' yield @path.match pretend.lastListen() @catch.should.have.calledWith sinon.match resMatch
34987
sinon = require 'sinon' chai = require 'chai' should = chai.should() chai.use require 'sinon-chai' co = require 'co' _ = require 'lodash' pretend = require 'hubot-pretend' Path = require '../../lib/modules/path' resMatch = (value) -> responseKeys = [ 'robot', 'message', 'match', 'envelope' ] difference = _.difference responseKeys, _.keys value difference.length == 0 describe 'Path', -> beforeEach -> pretend.start() pretend.log.level = 'silent' afterEach -> pretend.shutdown() describe 'constructor', -> context 'with branches', -> it 'calls .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot, [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] path.addBranch.args.should.eql [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] Path.prototype.addBranch.restore() it 'is not closed', -> path = new Path pretend.robot, [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] path.closed.should.be.false context 'with a single branch', -> it 'calls .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot, [ /ok/, 'OK, ok!' ] path.addBranch.args.should.eql [ [ /ok/, 'OK, ok!' ] ] Path.prototype.addBranch.restore() it 'is not closed', -> path = new Path pretend.robot, [ /ok/, 'OK, ok!' ] path.closed.should.be.false context 'with undefined branches and options', -> it 'does not call .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot Path.prototype.addBranch.restore() it 'stays closed', -> path = new Path pretend.robot path.closed.should.be.true context 'with bad arguments for branch', -> it 'throws', -> try @path = new Path pretend.robot, 'breakme.jpg' Path.constructor.should.throw describe '.addBranch', -> beforeEach -> sinon.spy Path.prototype, 'addBranch' afterEach -> Path.prototype.addBranch.restore() it 'creates branch object', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.branches[0].should.be.an 'object' it 'branch has valid regex', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.branches[0].regex.should.be.instanceof RegExp it 'accepts a string that can be cast as RegExp', -> path = new Path pretend.robot path.addBranch '/.*/ig', 'foo', () -> path.branches[0].regex.should.be.instanceof RegExp it 'calls getHandler with strings and callback', -> path = new Path pretend.robot callback = -> sinon.stub path, 'getHandler' path.addBranch /.*/, 'foo', callback path.getHandler.should.have.calledWithExactly 'foo', callback it 'calls getHandler with just stirngs', -> path = new Path pretend.robot sinon.stub path, 'getHandler' path.addBranch /.*/, ['foo', 'bar'] path.getHandler.should.have.calledWithExactly ['foo', 'bar'], undefined it 'calls getHandler with just callback', -> path = new Path pretend.robot callback = -> sinon.stub path, 'getHandler' path.addBranch /.*/, callback path.getHandler.should.have.calledWithExactly undefined, callback it 'branch stores handler', -> path = new Path pretend.robot sinon.spy path, 'getHandler' path.addBranch /.*/, 'foo', () -> lasthandler = path.getHandler.returnValues[0] path.branches[0].handler.should.eql lasthandler it 'opens path', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.closed.should.be.false it 'throws with invalid regex', -> path = new Path pretend.robot try path.addBranch 'derp' path.addBranch.should.throw it 'throws with insufficient args', -> path = new Path pretend.robot try path.addBranch /.*/ path.addBranch.should.throw it 'throws with invalid message', -> path = new Path pretend.robot try path.addBranch /.*/, () -> path.addBranch.should.throw it 'throws with invalid callback', -> path = new Path pretend.robot try path.addBranch /.*/, 'foo', 'bar' path.addBranch.should.throw describe '.getHandler', -> it 'returns a function', -> path = new Path pretend.robot callback = sinon.spy() handler = path.getHandler ['foo', 'bar'], callback handler.should.be.a 'function' context 'when handler called with response', -> it 'calls the callback with the response', -> path = new Path pretend.robot callback = sinon.spy() handler = path.getHandler ['foo', 'bar'], callback mockRes = reply: sinon.spy() handler mockRes callback.should.have.calledWithExactly mockRes it 'sends strings with dialogue if it has one', -> path = new Path pretend.robot handler = path.getHandler ['foo', 'bar'] mockRes = reply: sinon.spy(), dialogue: send: sinon.spy() handler mockRes mockRes.dialogue.send.should.have.calledWith 'foo', 'bar' it 'uses response reply if there is no dialogue', -> path = new Path pretend.robot handler = path.getHandler ['foo', 'bar'] mockRes = reply: sinon.spy() handler mockRes mockRes.reply.should.have.calledWith 'foo', 'bar' it 'returns promise resolving with send results', -> co -> path = new Path pretend.robot handler = path.getHandler ['foo'], () -> bar: 'baz' mockRes = reply: sinon.spy() handlerSpy = sinon.spy handler yield handler mockRes handlerSpy.returned sinon.match resMatch it 'returns promise also merged with callback results', -> co -> path = new Path pretend.robot handler = path.getHandler ['foo'], () -> bar: 'baz' mockRes = reply: sinon.spy() handlerSpy = sinon.spy handler yield handler mockRes handlerSpy.returned sinon.match bar: 'baz' describe '.match', -> beforeEach -> pretend.robot.hear /door/, -> # listen to tests @path = new Path pretend.robot, [ [ /door 1/, 'you lost', -> winner: false ] [ /door 2/, 'you won', -> winner: true ] [ /door 3/, 'try again' ] ] @match = sinon.spy() @mismatch = sinon.spy() @catch = sinon.spy() @path.on 'match', @match @path.on 'mismatch', @mismatch @path.on 'catch', @catch context 'with string matching branch regex', -> it 'updates match in response object', -> co => yield pretend.user('<NAME>').send 'door 1' yield @path.match pretend.lastListen() expectedMatch = 'door 1'.match @path.branches[0].regex pretend.lastListen().match.should.eql expectedMatch it 'closes the path', -> co => yield pretend.user('<NAME>').send 'door 2' yield @path.match pretend.lastListen() @path.closed.should.be.true it 'calls the handler for matching branch with res', -> co => @path.branches[1].handler = sinon.stub() yield pretend.user('<NAME>').send 'door 2' res = pretend.lastListen() yield @path.match res @path.branches[1].handler.should.have.calledWithExactly res it 'emits match with res', -> co => yield pretend.user('<NAME>').send 'door 2' yield @path.match pretend.lastListen() @match.should.have.calledWith sinon.match resMatch context 'with string matching multiple branches', -> it 'updates match in response object', -> co => yield pretend.user('sam').send 'door 1 and door 2' yield @path.match pretend.lastListen() expectedMatch = 'door 1 and door 2'.match @path.branches[0].regex pretend.lastListen().match.should.eql expectedMatch it 'calls the first matching branch handler', -> co => yield pretend.user('<NAME>').send 'door 1 and door 2' result = yield @path.match pretend.lastListen() result.should.have.property 'winner', false it 'closes the path', -> co => yield pretend.user('sam').send 'door 1 and door 2' yield @path.match pretend.lastListen() @path.closed.should.be.true context 'with mismatching string and no catch', -> it 'returns undefined', -> co => yield pretend.user('<NAME>').send 'door X' result = yield @path.match pretend.lastListen() chai.expect(result).to.be.undefined it 'updates match to null in response object', -> co => yield pretend.user('<NAME>').send 'door X' yield @path.match pretend.lastListen() chai.expect(pretend.lastListen().match).to.be.null it 'path stays open', -> co => yield pretend.user('<NAME>').send 'door X' yield @path.match pretend.lastListen() @path.closed.should.be.false it 'emits mismatch with res', -> co => yield pretend.user('<NAME>').send 'door X' yield @path.match pretend.lastListen() @mismatch.should.have.calledWith sinon.match resMatch context 'with mismatching string and catch message', -> it 'returns the response from send', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('<NAME>').send 'door X' result = yield @path.match pretend.lastListen() result.strings.should.eql [ 'no, wrong door' ] it 'emits catch with res', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('<NAME>').send 'door X' yield @path.match pretend.lastListen() @catch.should.have.calledWith sinon.match resMatch context 'with mismatching string and catch callback', -> it 'returns the result of the callback', -> co => @path.configure catchCallback: -> other: 'door fail' yield pretend.user('<NAME>').send 'door X' result = yield @path.match pretend.lastListen() result.should.have.property 'other', 'door fail' it 'emits catch with res', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('<NAME>').send 'door X' yield @path.match pretend.lastListen() @catch.should.have.calledWith sinon.match resMatch
true
sinon = require 'sinon' chai = require 'chai' should = chai.should() chai.use require 'sinon-chai' co = require 'co' _ = require 'lodash' pretend = require 'hubot-pretend' Path = require '../../lib/modules/path' resMatch = (value) -> responseKeys = [ 'robot', 'message', 'match', 'envelope' ] difference = _.difference responseKeys, _.keys value difference.length == 0 describe 'Path', -> beforeEach -> pretend.start() pretend.log.level = 'silent' afterEach -> pretend.shutdown() describe 'constructor', -> context 'with branches', -> it 'calls .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot, [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] path.addBranch.args.should.eql [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] Path.prototype.addBranch.restore() it 'is not closed', -> path = new Path pretend.robot, [ [ /left/, 'Ok, going left!' ] [ /right/, 'Ok, going right!' ] ] path.closed.should.be.false context 'with a single branch', -> it 'calls .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot, [ /ok/, 'OK, ok!' ] path.addBranch.args.should.eql [ [ /ok/, 'OK, ok!' ] ] Path.prototype.addBranch.restore() it 'is not closed', -> path = new Path pretend.robot, [ /ok/, 'OK, ok!' ] path.closed.should.be.false context 'with undefined branches and options', -> it 'does not call .addBranch', -> sinon.spy Path.prototype, 'addBranch' path = new Path pretend.robot Path.prototype.addBranch.restore() it 'stays closed', -> path = new Path pretend.robot path.closed.should.be.true context 'with bad arguments for branch', -> it 'throws', -> try @path = new Path pretend.robot, 'breakme.jpg' Path.constructor.should.throw describe '.addBranch', -> beforeEach -> sinon.spy Path.prototype, 'addBranch' afterEach -> Path.prototype.addBranch.restore() it 'creates branch object', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.branches[0].should.be.an 'object' it 'branch has valid regex', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.branches[0].regex.should.be.instanceof RegExp it 'accepts a string that can be cast as RegExp', -> path = new Path pretend.robot path.addBranch '/.*/ig', 'foo', () -> path.branches[0].regex.should.be.instanceof RegExp it 'calls getHandler with strings and callback', -> path = new Path pretend.robot callback = -> sinon.stub path, 'getHandler' path.addBranch /.*/, 'foo', callback path.getHandler.should.have.calledWithExactly 'foo', callback it 'calls getHandler with just stirngs', -> path = new Path pretend.robot sinon.stub path, 'getHandler' path.addBranch /.*/, ['foo', 'bar'] path.getHandler.should.have.calledWithExactly ['foo', 'bar'], undefined it 'calls getHandler with just callback', -> path = new Path pretend.robot callback = -> sinon.stub path, 'getHandler' path.addBranch /.*/, callback path.getHandler.should.have.calledWithExactly undefined, callback it 'branch stores handler', -> path = new Path pretend.robot sinon.spy path, 'getHandler' path.addBranch /.*/, 'foo', () -> lasthandler = path.getHandler.returnValues[0] path.branches[0].handler.should.eql lasthandler it 'opens path', -> path = new Path pretend.robot path.addBranch /.*/, 'foo', () -> path.closed.should.be.false it 'throws with invalid regex', -> path = new Path pretend.robot try path.addBranch 'derp' path.addBranch.should.throw it 'throws with insufficient args', -> path = new Path pretend.robot try path.addBranch /.*/ path.addBranch.should.throw it 'throws with invalid message', -> path = new Path pretend.robot try path.addBranch /.*/, () -> path.addBranch.should.throw it 'throws with invalid callback', -> path = new Path pretend.robot try path.addBranch /.*/, 'foo', 'bar' path.addBranch.should.throw describe '.getHandler', -> it 'returns a function', -> path = new Path pretend.robot callback = sinon.spy() handler = path.getHandler ['foo', 'bar'], callback handler.should.be.a 'function' context 'when handler called with response', -> it 'calls the callback with the response', -> path = new Path pretend.robot callback = sinon.spy() handler = path.getHandler ['foo', 'bar'], callback mockRes = reply: sinon.spy() handler mockRes callback.should.have.calledWithExactly mockRes it 'sends strings with dialogue if it has one', -> path = new Path pretend.robot handler = path.getHandler ['foo', 'bar'] mockRes = reply: sinon.spy(), dialogue: send: sinon.spy() handler mockRes mockRes.dialogue.send.should.have.calledWith 'foo', 'bar' it 'uses response reply if there is no dialogue', -> path = new Path pretend.robot handler = path.getHandler ['foo', 'bar'] mockRes = reply: sinon.spy() handler mockRes mockRes.reply.should.have.calledWith 'foo', 'bar' it 'returns promise resolving with send results', -> co -> path = new Path pretend.robot handler = path.getHandler ['foo'], () -> bar: 'baz' mockRes = reply: sinon.spy() handlerSpy = sinon.spy handler yield handler mockRes handlerSpy.returned sinon.match resMatch it 'returns promise also merged with callback results', -> co -> path = new Path pretend.robot handler = path.getHandler ['foo'], () -> bar: 'baz' mockRes = reply: sinon.spy() handlerSpy = sinon.spy handler yield handler mockRes handlerSpy.returned sinon.match bar: 'baz' describe '.match', -> beforeEach -> pretend.robot.hear /door/, -> # listen to tests @path = new Path pretend.robot, [ [ /door 1/, 'you lost', -> winner: false ] [ /door 2/, 'you won', -> winner: true ] [ /door 3/, 'try again' ] ] @match = sinon.spy() @mismatch = sinon.spy() @catch = sinon.spy() @path.on 'match', @match @path.on 'mismatch', @mismatch @path.on 'catch', @catch context 'with string matching branch regex', -> it 'updates match in response object', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door 1' yield @path.match pretend.lastListen() expectedMatch = 'door 1'.match @path.branches[0].regex pretend.lastListen().match.should.eql expectedMatch it 'closes the path', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door 2' yield @path.match pretend.lastListen() @path.closed.should.be.true it 'calls the handler for matching branch with res', -> co => @path.branches[1].handler = sinon.stub() yield pretend.user('PI:NAME:<NAME>END_PI').send 'door 2' res = pretend.lastListen() yield @path.match res @path.branches[1].handler.should.have.calledWithExactly res it 'emits match with res', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door 2' yield @path.match pretend.lastListen() @match.should.have.calledWith sinon.match resMatch context 'with string matching multiple branches', -> it 'updates match in response object', -> co => yield pretend.user('sam').send 'door 1 and door 2' yield @path.match pretend.lastListen() expectedMatch = 'door 1 and door 2'.match @path.branches[0].regex pretend.lastListen().match.should.eql expectedMatch it 'calls the first matching branch handler', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door 1 and door 2' result = yield @path.match pretend.lastListen() result.should.have.property 'winner', false it 'closes the path', -> co => yield pretend.user('sam').send 'door 1 and door 2' yield @path.match pretend.lastListen() @path.closed.should.be.true context 'with mismatching string and no catch', -> it 'returns undefined', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' result = yield @path.match pretend.lastListen() chai.expect(result).to.be.undefined it 'updates match to null in response object', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' yield @path.match pretend.lastListen() chai.expect(pretend.lastListen().match).to.be.null it 'path stays open', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' yield @path.match pretend.lastListen() @path.closed.should.be.false it 'emits mismatch with res', -> co => yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' yield @path.match pretend.lastListen() @mismatch.should.have.calledWith sinon.match resMatch context 'with mismatching string and catch message', -> it 'returns the response from send', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' result = yield @path.match pretend.lastListen() result.strings.should.eql [ 'no, wrong door' ] it 'emits catch with res', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' yield @path.match pretend.lastListen() @catch.should.have.calledWith sinon.match resMatch context 'with mismatching string and catch callback', -> it 'returns the result of the callback', -> co => @path.configure catchCallback: -> other: 'door fail' yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' result = yield @path.match pretend.lastListen() result.should.have.property 'other', 'door fail' it 'emits catch with res', -> co => @path.configure catchMessage: 'no, wrong door' yield pretend.user('PI:NAME:<NAME>END_PI').send 'door X' yield @path.match pretend.lastListen() @catch.should.have.calledWith sinon.match resMatch
[ { "context": "ld just work\", -> \n validators.validateUser(\"anton\", \"anton@circuithub.com\").isValid().should.be.tru", "end": 216, "score": 0.9994896650314331, "start": 211, "tag": "USERNAME", "value": "anton" }, { "context": "ork\", -> \n validators.validateUser(\"anto...
test/input.validators.coffee
circuithub/massive-git
6
should = require "should" validators = require "../lib/validators/input.validators" describe "user validation", -> describe "with valid user", -> it "should just work", -> validators.validateUser("anton", "anton@circuithub.com").isValid().should.be.true describe "with null username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(null, "anton@circuithub.com").errorMessage.should.equal "Invalid parameters" describe "with undefined username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(undefined, "anton@circuithub.com").errorMessage.should.equal "Invalid parameters" describe "with empty username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("", "anton@circuithub.com").errorMessage.should.equal "Invalid parameters" describe "with blank username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(" ", "anton@circuithub.com").errorMessage.should.equal "Invalid parameters" describe "with short username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("bc", "anton@circuithub.com").errorMessage.should.equal "Username is out of range" describe "with long username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("123456789azwsxedcrfcrfvtgb", "anton@circuithub.com").errorMessage.should.equal "Username is out of range" describe "with null email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", null).errorMessage.should.equal "Invalid parameters" describe "with undefined email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", undefined).errorMessage.should.equal "Invalid parameters" describe "with empty email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", "").errorMessage.should.equal "Invalid parameters" describe "with blank email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", " ").errorMessage.should.equal "Invalid parameters" describe "with invalid email", -> it "should return 'Email address is invalid' error", -> validators.validateUser("anton", "anton@com").errorMessage.should.equal "Email address is invalid" describe "repo validation", -> describe "with valid repo", -> it "should work fine", -> validators.validateRepo("project-one", "anton").isValid().should.be.true describe "with null repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(null, "anton").errorMessage.should.equal "Invalid parameters" describe "with undefined repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(undefined, "anton").errorMessage.should.equal "Invalid parameters" describe "with empty repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("", "anton").errorMessage.should.equal "Invalid parameters" describe "with blank repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(" ", "anton").errorMessage.should.equal "Invalid parameters" describe "with short repo name", -> it "should return 'Repository name is out of range' error", -> validators.validateRepo("bc", "anton").errorMessage.should.equal "Repository name is out of range" describe "with long repo name", -> it "should return 'Repository name is out of range' error", -> validators.validateRepo("123456789azwsxedcrfcrfvtgb", "anton").errorMessage.should.equal "Repository name is out of range" describe "with null author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", null).errorMessage.should.equal "Invalid parameters" describe "with undefined author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", undefined).errorMessage.should.equal "Invalid parameters" describe "with empty author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", "").errorMessage.should.equal "Invalid parameters" describe "with blank author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", " ").errorMessage.should.equal "Invalid parameters"
104633
should = require "should" validators = require "../lib/validators/input.validators" describe "user validation", -> describe "with valid user", -> it "should just work", -> validators.validateUser("anton", "<EMAIL>").isValid().should.be.true describe "with null username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(null, "<EMAIL>").errorMessage.should.equal "Invalid parameters" describe "with undefined username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(undefined, "<EMAIL>").errorMessage.should.equal "Invalid parameters" describe "with empty username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("", "<EMAIL>").errorMessage.should.equal "Invalid parameters" describe "with blank username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(" ", "<EMAIL>").errorMessage.should.equal "Invalid parameters" describe "with short username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("bc", "<EMAIL>").errorMessage.should.equal "Username is out of range" describe "with long username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("123456789azwsxedcrfcrfvtgb", "<EMAIL>").errorMessage.should.equal "Username is out of range" describe "with null email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", null).errorMessage.should.equal "Invalid parameters" describe "with undefined email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", undefined).errorMessage.should.equal "Invalid parameters" describe "with empty email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", "").errorMessage.should.equal "Invalid parameters" describe "with blank email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", " ").errorMessage.should.equal "Invalid parameters" describe "with invalid email", -> it "should return 'Email address is invalid' error", -> validators.validateUser("anton", "<EMAIL>").errorMessage.should.equal "Email address is invalid" describe "repo validation", -> describe "with valid repo", -> it "should work fine", -> validators.validateRepo("project-one", "anton").isValid().should.be.true describe "with null repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(null, "anton").errorMessage.should.equal "Invalid parameters" describe "with undefined repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(undefined, "anton").errorMessage.should.equal "Invalid parameters" describe "with empty repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("", "anton").errorMessage.should.equal "Invalid parameters" describe "with blank repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(" ", "anton").errorMessage.should.equal "Invalid parameters" describe "with short repo name", -> it "should return 'Repository name is out of range' error", -> validators.validateRepo("bc", "anton").errorMessage.should.equal "Repository name is out of range" describe "with long repo name", -> it "should return 'Repository name is out of range' error", -> validators.validateRepo("123456789azwsxedcrfcrfvtgb", "anton").errorMessage.should.equal "Repository name is out of range" describe "with null author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", null).errorMessage.should.equal "Invalid parameters" describe "with undefined author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", undefined).errorMessage.should.equal "Invalid parameters" describe "with empty author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", "").errorMessage.should.equal "Invalid parameters" describe "with blank author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", " ").errorMessage.should.equal "Invalid parameters"
true
should = require "should" validators = require "../lib/validators/input.validators" describe "user validation", -> describe "with valid user", -> it "should just work", -> validators.validateUser("anton", "PI:EMAIL:<EMAIL>END_PI").isValid().should.be.true describe "with null username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(null, "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Invalid parameters" describe "with undefined username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(undefined, "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Invalid parameters" describe "with empty username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("", "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Invalid parameters" describe "with blank username", -> it "should return 'Invalid parameters' error", -> validators.validateUser(" ", "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Invalid parameters" describe "with short username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("bc", "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Username is out of range" describe "with long username", -> it "should return 'Invalid parameters' error", -> validators.validateUser("123456789azwsxedcrfcrfvtgb", "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Username is out of range" describe "with null email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", null).errorMessage.should.equal "Invalid parameters" describe "with undefined email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", undefined).errorMessage.should.equal "Invalid parameters" describe "with empty email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", "").errorMessage.should.equal "Invalid parameters" describe "with blank email", -> it "should return 'Invalid parameters' error", -> validators.validateUser("anton", " ").errorMessage.should.equal "Invalid parameters" describe "with invalid email", -> it "should return 'Email address is invalid' error", -> validators.validateUser("anton", "PI:EMAIL:<EMAIL>END_PI").errorMessage.should.equal "Email address is invalid" describe "repo validation", -> describe "with valid repo", -> it "should work fine", -> validators.validateRepo("project-one", "anton").isValid().should.be.true describe "with null repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(null, "anton").errorMessage.should.equal "Invalid parameters" describe "with undefined repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(undefined, "anton").errorMessage.should.equal "Invalid parameters" describe "with empty repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("", "anton").errorMessage.should.equal "Invalid parameters" describe "with blank repo name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo(" ", "anton").errorMessage.should.equal "Invalid parameters" describe "with short repo name", -> it "should return 'Repository name is out of range' error", -> validators.validateRepo("bc", "anton").errorMessage.should.equal "Repository name is out of range" describe "with long repo name", -> it "should return 'Repository name is out of range' error", -> validators.validateRepo("123456789azwsxedcrfcrfvtgb", "anton").errorMessage.should.equal "Repository name is out of range" describe "with null author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", null).errorMessage.should.equal "Invalid parameters" describe "with undefined author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", undefined).errorMessage.should.equal "Invalid parameters" describe "with empty author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", "").errorMessage.should.equal "Invalid parameters" describe "with blank author name", -> it "should return 'Invalid parameters' error", -> validators.validateRepo("project-one", " ").errorMessage.should.equal "Invalid parameters"
[ { "context": " message.pid, 38324\n assert.equal message.key, 1717739733\n\n\ndescribe 'BackendMessage.ReadyForQuery', ->\n i", "end": 1883, "score": 0.9964934587478638, "start": 1873, "tag": "KEY", "value": "1717739733" } ]
test/unit/backend_message_test.coffee
gauravbansal74/node-vertica
25
assert = require 'assert' BackendMessage = require('../../src/backend_message') Buffer = require('../../src/buffer').Buffer describe 'BackendMessage.Authentication', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 0 it "should read a message correctly when using MD5_PASSWORD", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x10])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 5 assert.equal message.salt, 16 it "should read a message correctly when using CRYPT_PASSWORD", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x10])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 4 assert.equal message.salt, 16 describe 'BackendMessage.ParameterStatus', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x53, 0x00, 0x00, 0x00, 0x16, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00])) assert.ok message instanceof BackendMessage.ParameterStatus assert.equal message.name, 'application_name' assert.equal message.value, '' describe 'BackendMessage.BackendKeyData', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x4b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x95, 0xb4, 0x66, 0x62, 0xa0, 0xd5])) assert.ok message instanceof BackendMessage.BackendKeyData assert.equal message.pid, 38324 assert.equal message.key, 1717739733 describe 'BackendMessage.ReadyForQuery', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x5a, 0x00, 0x00, 0x00, 0x05, 0x49])) assert.ok message instanceof BackendMessage.ReadyForQuery assert.equal message.transactionStatus, 0x49 describe 'BackendMessage.EmptyQueryResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x49, 0x00, 0x00, 0x00, 0x04])) assert.ok message instanceof BackendMessage.EmptyQueryResponse describe 'BackendMessage.RowDescription', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x54, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x01, 0x69, 0x64, 0x00, 0x00, 0x00, 0x75, 0x9e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00])) assert.ok message instanceof BackendMessage.RowDescription assert.equal message.columns.length, 1 assert.equal message.columns[0].tableOID, 30110 assert.equal message.columns[0].tableFieldIndex, 1 assert.equal message.columns[0].typeOID, 6 assert.equal message.columns[0].type, "integer" describe 'BackendMessage.DataRow', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x44, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x70, 0x61, 0x69, 0x64])) assert.ok message instanceof BackendMessage.DataRow assert.equal message.values.length, 1 assert.equal String(message.values[0]), 'paid' describe 'BackendMessage.CommandComplete', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x43, 0x00, 0x00, 0x00, 0x0b, 0x53, 0x45, 0x4c, 0x45, 0x43, 0x54, 0x00])) assert.ok message instanceof BackendMessage.CommandComplete assert.equal message.status, 'SELECT' describe 'BackendMessage.ErrorResponse', -> it "ishould read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([ 0x45, 0x00, 0x00, 0x00, 0x67, 0x53, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x00, 0x43, 0x30, 0x41, 0x30, 0x30, 0x30, 0x00, 0x4d, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x46, 0x76, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x2e, 0x63, 0x00, 0x4c, 0x32, 0x33, 0x38, 0x30, 0x00, 0x52, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x74, 0x6d, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x00 ])) assert.ok message instanceof BackendMessage.ErrorResponse assert.equal message.information['Severity'], 'ERROR' assert.equal message.information['Code'], '0A000' assert.equal message.information['Message'], 'command NOTIFY is not supported' assert.equal message.information['File'], 'vertica.c' assert.equal message.information['Line'], '2380' assert.equal message.information['Routine'], 'checkVerticaUtilityStmtSupported' assert.equal message.message, 'command NOTIFY is not supported' describe 'BackendMessage.NoticeResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([ 0x4e, 0x00, 0x00, 0x00, 0x67, 0x53, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x00, 0x43, 0x30, 0x41, 0x30, 0x30, 0x30, 0x00, 0x4d, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x46, 0x76, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x2e, 0x63, 0x00, 0x4c, 0x32, 0x33, 0x38, 0x30, 0x00, 0x52, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x74, 0x6d, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x00 ])) assert.ok message instanceof BackendMessage.NoticeResponse assert.equal message.information['Severity'], 'NOTICE' assert.equal message.information['Code'], '0A000' assert.equal message.information['Message'], 'command NOTIFY is not supported' assert.equal message.information['File'], 'vertica.c' assert.equal message.information['Line'], '2380' assert.equal message.information['Routine'], 'checkVerticaUtilityStmtSupported' assert.equal message.message, 'command NOTIFY is not supported' describe 'BackendMessage.CopyInResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([71, 0, 0, 0, 7, 0, 0, 0])) assert.ok message instanceof BackendMessage.CopyInResponse assert.equal message.globalFormatType, 0 assert.deepEqual message.fieldFormatTypes, []
58538
assert = require 'assert' BackendMessage = require('../../src/backend_message') Buffer = require('../../src/buffer').Buffer describe 'BackendMessage.Authentication', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 0 it "should read a message correctly when using MD5_PASSWORD", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x10])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 5 assert.equal message.salt, 16 it "should read a message correctly when using CRYPT_PASSWORD", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x10])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 4 assert.equal message.salt, 16 describe 'BackendMessage.ParameterStatus', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x53, 0x00, 0x00, 0x00, 0x16, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00])) assert.ok message instanceof BackendMessage.ParameterStatus assert.equal message.name, 'application_name' assert.equal message.value, '' describe 'BackendMessage.BackendKeyData', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x4b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x95, 0xb4, 0x66, 0x62, 0xa0, 0xd5])) assert.ok message instanceof BackendMessage.BackendKeyData assert.equal message.pid, 38324 assert.equal message.key, <KEY> describe 'BackendMessage.ReadyForQuery', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x5a, 0x00, 0x00, 0x00, 0x05, 0x49])) assert.ok message instanceof BackendMessage.ReadyForQuery assert.equal message.transactionStatus, 0x49 describe 'BackendMessage.EmptyQueryResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x49, 0x00, 0x00, 0x00, 0x04])) assert.ok message instanceof BackendMessage.EmptyQueryResponse describe 'BackendMessage.RowDescription', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x54, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x01, 0x69, 0x64, 0x00, 0x00, 0x00, 0x75, 0x9e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00])) assert.ok message instanceof BackendMessage.RowDescription assert.equal message.columns.length, 1 assert.equal message.columns[0].tableOID, 30110 assert.equal message.columns[0].tableFieldIndex, 1 assert.equal message.columns[0].typeOID, 6 assert.equal message.columns[0].type, "integer" describe 'BackendMessage.DataRow', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x44, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x70, 0x61, 0x69, 0x64])) assert.ok message instanceof BackendMessage.DataRow assert.equal message.values.length, 1 assert.equal String(message.values[0]), 'paid' describe 'BackendMessage.CommandComplete', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x43, 0x00, 0x00, 0x00, 0x0b, 0x53, 0x45, 0x4c, 0x45, 0x43, 0x54, 0x00])) assert.ok message instanceof BackendMessage.CommandComplete assert.equal message.status, 'SELECT' describe 'BackendMessage.ErrorResponse', -> it "ishould read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([ 0x45, 0x00, 0x00, 0x00, 0x67, 0x53, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x00, 0x43, 0x30, 0x41, 0x30, 0x30, 0x30, 0x00, 0x4d, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x46, 0x76, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x2e, 0x63, 0x00, 0x4c, 0x32, 0x33, 0x38, 0x30, 0x00, 0x52, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x74, 0x6d, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x00 ])) assert.ok message instanceof BackendMessage.ErrorResponse assert.equal message.information['Severity'], 'ERROR' assert.equal message.information['Code'], '0A000' assert.equal message.information['Message'], 'command NOTIFY is not supported' assert.equal message.information['File'], 'vertica.c' assert.equal message.information['Line'], '2380' assert.equal message.information['Routine'], 'checkVerticaUtilityStmtSupported' assert.equal message.message, 'command NOTIFY is not supported' describe 'BackendMessage.NoticeResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([ 0x4e, 0x00, 0x00, 0x00, 0x67, 0x53, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x00, 0x43, 0x30, 0x41, 0x30, 0x30, 0x30, 0x00, 0x4d, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x46, 0x76, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x2e, 0x63, 0x00, 0x4c, 0x32, 0x33, 0x38, 0x30, 0x00, 0x52, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x74, 0x6d, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x00 ])) assert.ok message instanceof BackendMessage.NoticeResponse assert.equal message.information['Severity'], 'NOTICE' assert.equal message.information['Code'], '0A000' assert.equal message.information['Message'], 'command NOTIFY is not supported' assert.equal message.information['File'], 'vertica.c' assert.equal message.information['Line'], '2380' assert.equal message.information['Routine'], 'checkVerticaUtilityStmtSupported' assert.equal message.message, 'command NOTIFY is not supported' describe 'BackendMessage.CopyInResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([71, 0, 0, 0, 7, 0, 0, 0])) assert.ok message instanceof BackendMessage.CopyInResponse assert.equal message.globalFormatType, 0 assert.deepEqual message.fieldFormatTypes, []
true
assert = require 'assert' BackendMessage = require('../../src/backend_message') Buffer = require('../../src/buffer').Buffer describe 'BackendMessage.Authentication', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 0 it "should read a message correctly when using MD5_PASSWORD", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x10])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 5 assert.equal message.salt, 16 it "should read a message correctly when using CRYPT_PASSWORD", -> message = BackendMessage.fromBuffer(new Buffer([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x10])) assert.ok message instanceof BackendMessage.Authentication assert.equal message.method, 4 assert.equal message.salt, 16 describe 'BackendMessage.ParameterStatus', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x53, 0x00, 0x00, 0x00, 0x16, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00])) assert.ok message instanceof BackendMessage.ParameterStatus assert.equal message.name, 'application_name' assert.equal message.value, '' describe 'BackendMessage.BackendKeyData', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x4b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x95, 0xb4, 0x66, 0x62, 0xa0, 0xd5])) assert.ok message instanceof BackendMessage.BackendKeyData assert.equal message.pid, 38324 assert.equal message.key, PI:KEY:<KEY>END_PI describe 'BackendMessage.ReadyForQuery', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x5a, 0x00, 0x00, 0x00, 0x05, 0x49])) assert.ok message instanceof BackendMessage.ReadyForQuery assert.equal message.transactionStatus, 0x49 describe 'BackendMessage.EmptyQueryResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x49, 0x00, 0x00, 0x00, 0x04])) assert.ok message instanceof BackendMessage.EmptyQueryResponse describe 'BackendMessage.RowDescription', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x54, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x01, 0x69, 0x64, 0x00, 0x00, 0x00, 0x75, 0x9e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00])) assert.ok message instanceof BackendMessage.RowDescription assert.equal message.columns.length, 1 assert.equal message.columns[0].tableOID, 30110 assert.equal message.columns[0].tableFieldIndex, 1 assert.equal message.columns[0].typeOID, 6 assert.equal message.columns[0].type, "integer" describe 'BackendMessage.DataRow', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x44, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x70, 0x61, 0x69, 0x64])) assert.ok message instanceof BackendMessage.DataRow assert.equal message.values.length, 1 assert.equal String(message.values[0]), 'paid' describe 'BackendMessage.CommandComplete', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([0x43, 0x00, 0x00, 0x00, 0x0b, 0x53, 0x45, 0x4c, 0x45, 0x43, 0x54, 0x00])) assert.ok message instanceof BackendMessage.CommandComplete assert.equal message.status, 'SELECT' describe 'BackendMessage.ErrorResponse', -> it "ishould read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([ 0x45, 0x00, 0x00, 0x00, 0x67, 0x53, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x00, 0x43, 0x30, 0x41, 0x30, 0x30, 0x30, 0x00, 0x4d, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x46, 0x76, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x2e, 0x63, 0x00, 0x4c, 0x32, 0x33, 0x38, 0x30, 0x00, 0x52, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x74, 0x6d, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x00 ])) assert.ok message instanceof BackendMessage.ErrorResponse assert.equal message.information['Severity'], 'ERROR' assert.equal message.information['Code'], '0A000' assert.equal message.information['Message'], 'command NOTIFY is not supported' assert.equal message.information['File'], 'vertica.c' assert.equal message.information['Line'], '2380' assert.equal message.information['Routine'], 'checkVerticaUtilityStmtSupported' assert.equal message.message, 'command NOTIFY is not supported' describe 'BackendMessage.NoticeResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([ 0x4e, 0x00, 0x00, 0x00, 0x67, 0x53, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x00, 0x43, 0x30, 0x41, 0x30, 0x30, 0x30, 0x00, 0x4d, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x46, 0x59, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x46, 0x76, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x2e, 0x63, 0x00, 0x4c, 0x32, 0x33, 0x38, 0x30, 0x00, 0x52, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x74, 0x69, 0x63, 0x61, 0x55, 0x74, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x74, 0x6d, 0x74, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00, 0x00 ])) assert.ok message instanceof BackendMessage.NoticeResponse assert.equal message.information['Severity'], 'NOTICE' assert.equal message.information['Code'], '0A000' assert.equal message.information['Message'], 'command NOTIFY is not supported' assert.equal message.information['File'], 'vertica.c' assert.equal message.information['Line'], '2380' assert.equal message.information['Routine'], 'checkVerticaUtilityStmtSupported' assert.equal message.message, 'command NOTIFY is not supported' describe 'BackendMessage.CopyInResponse', -> it "should read a message correctly", -> message = BackendMessage.fromBuffer(new Buffer([71, 0, 0, 0, 7, 0, 0, 0])) assert.ok message instanceof BackendMessage.CopyInResponse assert.equal message.globalFormatType, 0 assert.deepEqual message.fieldFormatTypes, []
[ { "context": " expect(headers.meshblu_auth_token).to.equal 'treachery'\n ).respond()\n @httpBackend.flush()", "end": 3809, "score": 0.9933910369873047, "start": 3800, "tag": "PASSWORD", "value": "treachery" } ]
test/trigger-service-spec.coffee
octoblu/blu-web
3
describe 'TriggerService', => beforeEach -> module 'blu', => inject (_$httpBackend_, TriggerService) => @httpBackend = _$httpBackend_ @sut = TriggerService it 'should exist', -> expect(@sut).to.exist describe '->trigger', -> it 'should exist', -> expect(@sut.trigger).to.exist describe 'when it is called with a uuid and token present', -> it 'should message meshblu using those credentials and data', -> @httpBackend.expectPOST('https://meshblu.octoblu.com/messages', { devices: ['flow-uuid'] topic: 'button' payload: from: 'trigger-id' },{ meshblu_auth_uuid: 'device-uuid' meshblu_auth_token: 'device-token' Accept: "application/json, text/plain, */*" "Content-Type": "application/json;charset=utf-8" } ).respond() @sut.trigger 'flow-uuid', 'trigger-id', 'device-uuid', 'device-token' @httpBackend.flush() describe '->getTriggers', -> it 'should exist', -> expect(@sut.getTriggers).to.exist describe 'when getTriggers is called with a uuid and token', -> beforeEach -> @sut.getTriggers 'device-uuid', 'device-token', 'owner-uuid' return null it 'should query meshblu using those credentials', -> @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid', (headers)=> expect(headers.meshblu_auth_uuid).to.equal 'device-uuid' expect(headers.meshblu_auth_token).to.equal 'device-token' ).respond() @httpBackend.flush() describe 'when meshblu returns some flows', -> beforeEach -> flow = { flow: [ { type: 'trigger', name: 'Women Trigger', id: 1234 } { type: 'bacon', id: 4321 } { type: 'not-something-important', id: 2341 } ], uuid: 6789 } @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid').respond devices: [ flow ] it 'should return a list containing one trigger', -> @sut.getTriggers(null, null, 'owner-uuid').then (triggers) => expect(triggers.length).to.equal 1 @httpBackend.flush() it 'should return a correctly formatted trigger', -> @sut.getTriggers(null, null, 'owner-uuid').then (triggers) => expect(triggers).to.deep.equal [{flow: 6789, name: 'Women Trigger', id: 1234 }] @httpBackend.flush() describe 'when meshblu returns a different flow', -> beforeEach -> flow = { flow: [ { type: 'bacon', id: 12345 } { type: 'trigger', name: 'Monster Trigger', id: 128937 } { type: 'not-something-important', id: 90123 } ], uuid: 1589 } @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid').respond devices: [ flow ] it 'should return a correctly formatted trigger', -> @sut.getTriggers(@uuid, @token, 'owner-uuid').then (triggers) => expect(triggers).to.deep.equal [{flow: 1589, name: 'Monster Trigger', id: 128937 }] @httpBackend.flush() describe 'when getTriggers is called with a different uuid and token present', -> beforeEach -> @sut.getTriggers 'bludgeoned-with-trophy', 'treachery', 'owner-uuid' return null it 'should query meshblu using those credentials', -> @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid', (headers)=> expect(headers.meshblu_auth_uuid).to.equal 'bludgeoned-with-trophy' expect(headers.meshblu_auth_token).to.equal 'treachery' ).respond() @httpBackend.flush()
124900
describe 'TriggerService', => beforeEach -> module 'blu', => inject (_$httpBackend_, TriggerService) => @httpBackend = _$httpBackend_ @sut = TriggerService it 'should exist', -> expect(@sut).to.exist describe '->trigger', -> it 'should exist', -> expect(@sut.trigger).to.exist describe 'when it is called with a uuid and token present', -> it 'should message meshblu using those credentials and data', -> @httpBackend.expectPOST('https://meshblu.octoblu.com/messages', { devices: ['flow-uuid'] topic: 'button' payload: from: 'trigger-id' },{ meshblu_auth_uuid: 'device-uuid' meshblu_auth_token: 'device-token' Accept: "application/json, text/plain, */*" "Content-Type": "application/json;charset=utf-8" } ).respond() @sut.trigger 'flow-uuid', 'trigger-id', 'device-uuid', 'device-token' @httpBackend.flush() describe '->getTriggers', -> it 'should exist', -> expect(@sut.getTriggers).to.exist describe 'when getTriggers is called with a uuid and token', -> beforeEach -> @sut.getTriggers 'device-uuid', 'device-token', 'owner-uuid' return null it 'should query meshblu using those credentials', -> @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid', (headers)=> expect(headers.meshblu_auth_uuid).to.equal 'device-uuid' expect(headers.meshblu_auth_token).to.equal 'device-token' ).respond() @httpBackend.flush() describe 'when meshblu returns some flows', -> beforeEach -> flow = { flow: [ { type: 'trigger', name: 'Women Trigger', id: 1234 } { type: 'bacon', id: 4321 } { type: 'not-something-important', id: 2341 } ], uuid: 6789 } @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid').respond devices: [ flow ] it 'should return a list containing one trigger', -> @sut.getTriggers(null, null, 'owner-uuid').then (triggers) => expect(triggers.length).to.equal 1 @httpBackend.flush() it 'should return a correctly formatted trigger', -> @sut.getTriggers(null, null, 'owner-uuid').then (triggers) => expect(triggers).to.deep.equal [{flow: 6789, name: 'Women Trigger', id: 1234 }] @httpBackend.flush() describe 'when meshblu returns a different flow', -> beforeEach -> flow = { flow: [ { type: 'bacon', id: 12345 } { type: 'trigger', name: 'Monster Trigger', id: 128937 } { type: 'not-something-important', id: 90123 } ], uuid: 1589 } @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid').respond devices: [ flow ] it 'should return a correctly formatted trigger', -> @sut.getTriggers(@uuid, @token, 'owner-uuid').then (triggers) => expect(triggers).to.deep.equal [{flow: 1589, name: 'Monster Trigger', id: 128937 }] @httpBackend.flush() describe 'when getTriggers is called with a different uuid and token present', -> beforeEach -> @sut.getTriggers 'bludgeoned-with-trophy', 'treachery', 'owner-uuid' return null it 'should query meshblu using those credentials', -> @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid', (headers)=> expect(headers.meshblu_auth_uuid).to.equal 'bludgeoned-with-trophy' expect(headers.meshblu_auth_token).to.equal '<PASSWORD>' ).respond() @httpBackend.flush()
true
describe 'TriggerService', => beforeEach -> module 'blu', => inject (_$httpBackend_, TriggerService) => @httpBackend = _$httpBackend_ @sut = TriggerService it 'should exist', -> expect(@sut).to.exist describe '->trigger', -> it 'should exist', -> expect(@sut.trigger).to.exist describe 'when it is called with a uuid and token present', -> it 'should message meshblu using those credentials and data', -> @httpBackend.expectPOST('https://meshblu.octoblu.com/messages', { devices: ['flow-uuid'] topic: 'button' payload: from: 'trigger-id' },{ meshblu_auth_uuid: 'device-uuid' meshblu_auth_token: 'device-token' Accept: "application/json, text/plain, */*" "Content-Type": "application/json;charset=utf-8" } ).respond() @sut.trigger 'flow-uuid', 'trigger-id', 'device-uuid', 'device-token' @httpBackend.flush() describe '->getTriggers', -> it 'should exist', -> expect(@sut.getTriggers).to.exist describe 'when getTriggers is called with a uuid and token', -> beforeEach -> @sut.getTriggers 'device-uuid', 'device-token', 'owner-uuid' return null it 'should query meshblu using those credentials', -> @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid', (headers)=> expect(headers.meshblu_auth_uuid).to.equal 'device-uuid' expect(headers.meshblu_auth_token).to.equal 'device-token' ).respond() @httpBackend.flush() describe 'when meshblu returns some flows', -> beforeEach -> flow = { flow: [ { type: 'trigger', name: 'Women Trigger', id: 1234 } { type: 'bacon', id: 4321 } { type: 'not-something-important', id: 2341 } ], uuid: 6789 } @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid').respond devices: [ flow ] it 'should return a list containing one trigger', -> @sut.getTriggers(null, null, 'owner-uuid').then (triggers) => expect(triggers.length).to.equal 1 @httpBackend.flush() it 'should return a correctly formatted trigger', -> @sut.getTriggers(null, null, 'owner-uuid').then (triggers) => expect(triggers).to.deep.equal [{flow: 6789, name: 'Women Trigger', id: 1234 }] @httpBackend.flush() describe 'when meshblu returns a different flow', -> beforeEach -> flow = { flow: [ { type: 'bacon', id: 12345 } { type: 'trigger', name: 'Monster Trigger', id: 128937 } { type: 'not-something-important', id: 90123 } ], uuid: 1589 } @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid').respond devices: [ flow ] it 'should return a correctly formatted trigger', -> @sut.getTriggers(@uuid, @token, 'owner-uuid').then (triggers) => expect(triggers).to.deep.equal [{flow: 1589, name: 'Monster Trigger', id: 128937 }] @httpBackend.flush() describe 'when getTriggers is called with a different uuid and token present', -> beforeEach -> @sut.getTriggers 'bludgeoned-with-trophy', 'treachery', 'owner-uuid' return null it 'should query meshblu using those credentials', -> @httpBackend.expectGET('https://meshblu.octoblu.com/devices?type=octoblu:flow&owner=owner-uuid', (headers)=> expect(headers.meshblu_auth_uuid).to.equal 'bludgeoned-with-trophy' expect(headers.meshblu_auth_token).to.equal 'PI:PASSWORD:<PASSWORD>END_PI' ).respond() @httpBackend.flush()
[ { "context": "***************************\n ** Copyright (c) 2019 Sujaykumar.Hublikar <hello@sujaykumarh.com> **\n ** ", "end": 138, "score": 0.9998968839645386, "start": 119, "tag": "NAME", "value": "Sujaykumar.Hublikar" }, { "context": "*****\n ** Copyright (c) 20...
docs/assets/js/default.coffee
sujaykumarh/sujaykumarh.github.io
3
--- --- ### ********************************************************************************* ** Copyright (c) 2019 Sujaykumar.Hublikar <hello@sujaykumarh.com> ** ** ** ** Licensed under the Apache License, Version 2.0 (the "License") ** ** you may not use this file except in compliance with the License. ** ** You may obtain a copy of the License at ** ** ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** ** ** Unless required by applicable law or agreed to in writing, software ** ** distributed under the License is distributed on an "AS IS" BASIS, ** ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** ** See the License for the specific language governing permissions and ** ** limitations under the License. ** ** ** ** ** ** Fork it on GitHub ==> https://github.com/Sujaykumarh ** ** ** ********************************************************************************* ### # https://coffeescript.org/#introduction $(document).ready -> ## Defaults $('.disabled').click -> false # Page Control staticURL = ["/contact" , "/privacy", "/terms"] if staticURL.indexOf(window.location.pathname) > -1 $('.navbar').removeClass('sticky-top') ## For Posts page $('#post-page img').addClass('img-fluid') # Portfolio link hover $('.portfolio-links a .card').on 'mouseover', -> #$('.portfolio-links .card').not(this).stop().animate({opacity: .5}, 100) #$(this).stop().animate({opacity: .5}, 100) $(this).parent().parent().parent().find('.card').not(this).stop().animate({ opacity: .65 }, 100) $(this).stop().animate({opacity: 1}, 100) $('.portfolio-links a').on 'mouseout', -> $('.portfolio-links .card').stop().animate({opacity: 1}, 100) # add margin to top of height equal to navbar #$('#main-content').css('margin-top', $('nav').height() + 20 + "px" ) # Enable tooltips $('[data-toggle="tooltip"]').tooltip() # change navbar on scroll $(window).scroll -> if staticURL.indexOf(window.location.pathname) > -1 return if document.body.scrollTop > 30 || document.documentElement.scrollTop > 30 # background $('nav').addClass('navBg') $('nav').removeClass('navNoBg') else #no background $('nav').addClass('navNoBg') $('nav').removeClass('navBg') #### Contact Form ## Form Reset $('#btnContactReset').click -> $('#inputName, #inputEmail, #inputMobile, #inputMessage').val('') $('#contactMenu').val('default') $('#inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeClass('error is-valid is-invalid') $('#form-status-message').hide() $('#form-status-spinner').hide() $('#form-status-success').hide() $('#form-status-error').hide() false # return false to prevent default ## Monitor input change $('.form-control').on 'input change keyup paste propertychange', -> $(this).removeClass('error is-valid is-invalid') ## Form Submit $('#btnContactSubmit').click -> # REGEX emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ nameReg = /^\S(?!.*\s{2}).*?\S$/ contactReg = /^(\+\d{1,3}[- ]?)?\d{10}$/ # --- Validation valid = true name = $("#inputName").val() email = $("#inputEmail").val().toLowerCase() message = $("#inputMessage").val() mobileNumber = $("#inputMobile").val() contactMenu = $("#contactMenu").val() # --- Contact Name if name == "" valid = false $("#inputName").addClass('error is-invalid') else if nameReg.test(name) $("#inputName").removeClass('error is-invalid') $("#inputName").addClass('is-valid') else valid = false $("#inputName").addClass('error is-invalid') # --- Contact Email if email == "" valid = false $("#inputEmail").addClass('error is-invalid') else if emailReg.test(email) $("#inputEmail").removeClass('error is-invalid') $("#inputEmail").addClass('is-valid') else valid = false $("#inputEmail").addClass('error is-invalid') # --- Contact Message if message == "" valid = false $("#inputMessage").addClass('error is-invalid') else $("#inputMessage").removeClass('error is-invalid') $("#inputMessage").addClass('is-valid') # --- Contact Menu Option if contactMenu == "default" valid = false $("#contactMenu").addClass('error is-invalid') else $("#contactMenu").removeClass('error is-invalid') $("#contactMenu").addClass('is-valid') # --- Contact number if mobileNumber == "" valid = false $("#inputMobile").addClass('error is-invalid') else mobileNumber = mobileNumber.trim() if contactReg.test(mobileNumber) $("#inputMobile").removeClass('error is-invalid') $("#inputMobile").addClass('is-valid') else valid = false $("#inputMobile").addClass('error is-invalid') # --- Check Valid form #if !valid # console.log("Invalid Form") if valid $('#form-status-message').hide() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').attr('disabled', '') $('#form-status-spinner').show() $('#form-status-success').hide() $('#form-status-error').hide() # +++ SUBMIT FORM postURL = "https://formspree.io/f/xeqnqjzg"; postData = { name : name, email : email, contactNumber : mobileNumber, topic : contactMenu, message : message } $.ajax url : postURL method : "POST" data : postData, dataType : "json" success : -> $('#form-status-spinner').hide() $('#form-status-success').show() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeAttr('disabled') console.log "SUCCESS" error : (e) -> $('#form-status-spinner').hide() $('#form-status-error').show() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeAttr('disabled') console.log "ERROR" console.log e false # return false to prevent default
184933
--- --- ### ********************************************************************************* ** Copyright (c) 2019 <NAME> <<EMAIL>> ** ** ** ** Licensed under the Apache License, Version 2.0 (the "License") ** ** you may not use this file except in compliance with the License. ** ** You may obtain a copy of the License at ** ** ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** ** ** Unless required by applicable law or agreed to in writing, software ** ** distributed under the License is distributed on an "AS IS" BASIS, ** ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** ** See the License for the specific language governing permissions and ** ** limitations under the License. ** ** ** ** ** ** Fork it on GitHub ==> https://github.com/Sujaykumarh ** ** ** ********************************************************************************* ### # https://coffeescript.org/#introduction $(document).ready -> ## Defaults $('.disabled').click -> false # Page Control staticURL = ["/contact" , "/privacy", "/terms"] if staticURL.indexOf(window.location.pathname) > -1 $('.navbar').removeClass('sticky-top') ## For Posts page $('#post-page img').addClass('img-fluid') # Portfolio link hover $('.portfolio-links a .card').on 'mouseover', -> #$('.portfolio-links .card').not(this).stop().animate({opacity: .5}, 100) #$(this).stop().animate({opacity: .5}, 100) $(this).parent().parent().parent().find('.card').not(this).stop().animate({ opacity: .65 }, 100) $(this).stop().animate({opacity: 1}, 100) $('.portfolio-links a').on 'mouseout', -> $('.portfolio-links .card').stop().animate({opacity: 1}, 100) # add margin to top of height equal to navbar #$('#main-content').css('margin-top', $('nav').height() + 20 + "px" ) # Enable tooltips $('[data-toggle="tooltip"]').tooltip() # change navbar on scroll $(window).scroll -> if staticURL.indexOf(window.location.pathname) > -1 return if document.body.scrollTop > 30 || document.documentElement.scrollTop > 30 # background $('nav').addClass('navBg') $('nav').removeClass('navNoBg') else #no background $('nav').addClass('navNoBg') $('nav').removeClass('navBg') #### Contact Form ## Form Reset $('#btnContactReset').click -> $('#inputName, #inputEmail, #inputMobile, #inputMessage').val('') $('#contactMenu').val('default') $('#inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeClass('error is-valid is-invalid') $('#form-status-message').hide() $('#form-status-spinner').hide() $('#form-status-success').hide() $('#form-status-error').hide() false # return false to prevent default ## Monitor input change $('.form-control').on 'input change keyup paste propertychange', -> $(this).removeClass('error is-valid is-invalid') ## Form Submit $('#btnContactSubmit').click -> # REGEX emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ nameReg = /^\S(?!.*\s{2}).*?\S$/ contactReg = /^(\+\d{1,3}[- ]?)?\d{10}$/ # --- Validation valid = true name = $("#inputName").val() email = $("#inputEmail").val().toLowerCase() message = $("#inputMessage").val() mobileNumber = $("#inputMobile").val() contactMenu = $("#contactMenu").val() # --- Contact Name if name == "" valid = false $("#inputName").addClass('error is-invalid') else if nameReg.test(name) $("#inputName").removeClass('error is-invalid') $("#inputName").addClass('is-valid') else valid = false $("#inputName").addClass('error is-invalid') # --- Contact Email if email == "" valid = false $("#inputEmail").addClass('error is-invalid') else if emailReg.test(email) $("#inputEmail").removeClass('error is-invalid') $("#inputEmail").addClass('is-valid') else valid = false $("#inputEmail").addClass('error is-invalid') # --- Contact Message if message == "" valid = false $("#inputMessage").addClass('error is-invalid') else $("#inputMessage").removeClass('error is-invalid') $("#inputMessage").addClass('is-valid') # --- Contact Menu Option if contactMenu == "default" valid = false $("#contactMenu").addClass('error is-invalid') else $("#contactMenu").removeClass('error is-invalid') $("#contactMenu").addClass('is-valid') # --- Contact number if mobileNumber == "" valid = false $("#inputMobile").addClass('error is-invalid') else mobileNumber = mobileNumber.trim() if contactReg.test(mobileNumber) $("#inputMobile").removeClass('error is-invalid') $("#inputMobile").addClass('is-valid') else valid = false $("#inputMobile").addClass('error is-invalid') # --- Check Valid form #if !valid # console.log("Invalid Form") if valid $('#form-status-message').hide() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').attr('disabled', '') $('#form-status-spinner').show() $('#form-status-success').hide() $('#form-status-error').hide() # +++ SUBMIT FORM postURL = "https://formspree.io/f/xeqnqjzg"; postData = { name : <NAME>, email : email, contactNumber : mobileNumber, topic : contactMenu, message : message } $.ajax url : postURL method : "POST" data : postData, dataType : "json" success : -> $('#form-status-spinner').hide() $('#form-status-success').show() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeAttr('disabled') console.log "SUCCESS" error : (e) -> $('#form-status-spinner').hide() $('#form-status-error').show() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeAttr('disabled') console.log "ERROR" console.log e false # return false to prevent default
true
--- --- ### ********************************************************************************* ** Copyright (c) 2019 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ** ** ** ** Licensed under the Apache License, Version 2.0 (the "License") ** ** you may not use this file except in compliance with the License. ** ** You may obtain a copy of the License at ** ** ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** ** ** Unless required by applicable law or agreed to in writing, software ** ** distributed under the License is distributed on an "AS IS" BASIS, ** ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** ** See the License for the specific language governing permissions and ** ** limitations under the License. ** ** ** ** ** ** Fork it on GitHub ==> https://github.com/Sujaykumarh ** ** ** ********************************************************************************* ### # https://coffeescript.org/#introduction $(document).ready -> ## Defaults $('.disabled').click -> false # Page Control staticURL = ["/contact" , "/privacy", "/terms"] if staticURL.indexOf(window.location.pathname) > -1 $('.navbar').removeClass('sticky-top') ## For Posts page $('#post-page img').addClass('img-fluid') # Portfolio link hover $('.portfolio-links a .card').on 'mouseover', -> #$('.portfolio-links .card').not(this).stop().animate({opacity: .5}, 100) #$(this).stop().animate({opacity: .5}, 100) $(this).parent().parent().parent().find('.card').not(this).stop().animate({ opacity: .65 }, 100) $(this).stop().animate({opacity: 1}, 100) $('.portfolio-links a').on 'mouseout', -> $('.portfolio-links .card').stop().animate({opacity: 1}, 100) # add margin to top of height equal to navbar #$('#main-content').css('margin-top', $('nav').height() + 20 + "px" ) # Enable tooltips $('[data-toggle="tooltip"]').tooltip() # change navbar on scroll $(window).scroll -> if staticURL.indexOf(window.location.pathname) > -1 return if document.body.scrollTop > 30 || document.documentElement.scrollTop > 30 # background $('nav').addClass('navBg') $('nav').removeClass('navNoBg') else #no background $('nav').addClass('navNoBg') $('nav').removeClass('navBg') #### Contact Form ## Form Reset $('#btnContactReset').click -> $('#inputName, #inputEmail, #inputMobile, #inputMessage').val('') $('#contactMenu').val('default') $('#inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeClass('error is-valid is-invalid') $('#form-status-message').hide() $('#form-status-spinner').hide() $('#form-status-success').hide() $('#form-status-error').hide() false # return false to prevent default ## Monitor input change $('.form-control').on 'input change keyup paste propertychange', -> $(this).removeClass('error is-valid is-invalid') ## Form Submit $('#btnContactSubmit').click -> # REGEX emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ nameReg = /^\S(?!.*\s{2}).*?\S$/ contactReg = /^(\+\d{1,3}[- ]?)?\d{10}$/ # --- Validation valid = true name = $("#inputName").val() email = $("#inputEmail").val().toLowerCase() message = $("#inputMessage").val() mobileNumber = $("#inputMobile").val() contactMenu = $("#contactMenu").val() # --- Contact Name if name == "" valid = false $("#inputName").addClass('error is-invalid') else if nameReg.test(name) $("#inputName").removeClass('error is-invalid') $("#inputName").addClass('is-valid') else valid = false $("#inputName").addClass('error is-invalid') # --- Contact Email if email == "" valid = false $("#inputEmail").addClass('error is-invalid') else if emailReg.test(email) $("#inputEmail").removeClass('error is-invalid') $("#inputEmail").addClass('is-valid') else valid = false $("#inputEmail").addClass('error is-invalid') # --- Contact Message if message == "" valid = false $("#inputMessage").addClass('error is-invalid') else $("#inputMessage").removeClass('error is-invalid') $("#inputMessage").addClass('is-valid') # --- Contact Menu Option if contactMenu == "default" valid = false $("#contactMenu").addClass('error is-invalid') else $("#contactMenu").removeClass('error is-invalid') $("#contactMenu").addClass('is-valid') # --- Contact number if mobileNumber == "" valid = false $("#inputMobile").addClass('error is-invalid') else mobileNumber = mobileNumber.trim() if contactReg.test(mobileNumber) $("#inputMobile").removeClass('error is-invalid') $("#inputMobile").addClass('is-valid') else valid = false $("#inputMobile").addClass('error is-invalid') # --- Check Valid form #if !valid # console.log("Invalid Form") if valid $('#form-status-message').hide() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').attr('disabled', '') $('#form-status-spinner').show() $('#form-status-success').hide() $('#form-status-error').hide() # +++ SUBMIT FORM postURL = "https://formspree.io/f/xeqnqjzg"; postData = { name : PI:NAME:<NAME>END_PI, email : email, contactNumber : mobileNumber, topic : contactMenu, message : message } $.ajax url : postURL method : "POST" data : postData, dataType : "json" success : -> $('#form-status-spinner').hide() $('#form-status-success').show() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeAttr('disabled') console.log "SUCCESS" error : (e) -> $('#form-status-spinner').hide() $('#form-status-error').show() $('#btnContactSubmit, #btnContactReset, #inputName, #inputEmail, #inputMobile, #inputMessage, #contactMenu').removeAttr('disabled') console.log "ERROR" console.log e false # return false to prevent default
[ { "context": "d in room.beds\n key = night.id + '|' + bed.id\n if key of ", "end": 4180, "score": 0.8140323162078857, "start": 4178, "tag": "KEY", "value": "id" }, { "context": "room.beds\n key = night.id + '|' + be...
static/main.coffee
cassiamartin/hrsfanssummerparty
0
# Utility functions and classes # A mixin for formatting (positive and negative) dollar values _.mixin dollars: (x, precision = 2, blank_zero = false) -> if not x? or (blank_zero and Math.abs(x) < 0.005) return '' val = '$' + Math.abs(x).toFixed(precision) if x < 0 val = '(' + val + ')' val # Mixins for standard date formats _.mixin short_date: (t) -> moment(t * 1000).format("MMM D") _.mixin long_date: (t) -> moment(t * 1000).format("YYYY-MM-DD HH:mm") # Choose among the options by the sign of the value; accepts a range around zero to handle rounding choose_by_sign = (val, pos, neg, zero) => if val > 0.005 return pos if val < -0.005 return neg return zero # Due to throttling, certain one-time status-dependent code has to be given a delay dodge_throttle = (f) -> setTimeout(f, 75) # Compare x and y, coercing null and undefined to the empty string. eq = (x, y) -> (x ? '') == (y ? '') # Compare x and y, coercing null and undefined to null. eq_strict = (x, y) -> if not x? return not y? if not y? return false x == y # Is this a valid (possibly signed) floating-point number? Used to validate money entries. valid_float = (x) -> /^[0-9]+(\.[0-9]+)?$/.test(x ? '') valid_signed_float = (x) -> /^-?[0-9]+(\.[0-9]+)?$/.test(x ? '') # The main object backing the page class PageModel # Constructor constructor: -> # Initialize data req = new XMLHttpRequest() req.open('GET', 'call/init', false) req.send() { @is_admin, @logout_url, @party_data, @server_data, @username } = JSON.parse req.response # Variables backing the group selector @all_groups = ko.observable [] @selected_group = ko.observable('').extend(notify: 'always') @selected_group.subscribe @selected_group_sub # Variables of convenience: a number of sections need only one of these observables @regs_by_name = ko.observable [] @group_regs_by_name = ko.observable [] @nights = @party_data.days[...-1] @reservations_open = @party_data.reservations_enabled or @is_admin # Set up sections @visible_section = ko.observable null @sections = [ @register = new Register this @reservations = new Reservations this @confirmation = new Confirmation this @payment = new Payment this @guest_list = new GuestList this ] @admin_sections = [] if @is_admin @admin_sections = [ @payments = new Payments this @expenses = new Expenses this @credits = new Credits this @registrations = new Registrations this @financials = new Financials this @dietary_info = new DietaryInfo this @other_info = new OtherInfo this @email_list = new EmailList this @phone_list = new PhoneList this ] # Reset sections @reset() # Post method; pass the endpoint and the message to post post_json: (url, message) => message.group = @selected_group() req = new XMLHttpRequest() req.open('POST', url, false) req.send JSON.stringify message { @server_data, error } = JSON.parse req.response @reset() if error window.alert(error + ' (If you think this is a bug, please let us know.)') # Postprocess data after retrieval from the server and reset the sections reset: => # Tag each registration with its name for name, reg of @server_data.registrations reg.name = name # Tag each registration with the nights it's staying and add room, nightly, and meal charges for name, reg of @server_data.registrations reg.credits = [] reg.nights = {} reg._room_charge = 0 for night in @nights for id, group of @party_data.rooms for room in group for bed in room.beds key = night.id + '|' + bed.id if key of @server_data.reservations name = @server_data.reservations[key] @server_data.registrations[name]._room_charge += bed.costs[night.id] @server_data.registrations[name].nights[night.id] = true for name, reg of @server_data.registrations reg.num_nights = 0 for id, is_reserved of reg.nights if is_reserved reg.num_nights += 1 if reg._room_charge reg.credits.push { amount: -reg._room_charge, category: 'Rooms', date: null } delete reg._room_charge if reg.num_nights reg.credits.push amount: -@party_data.nightly_fee * reg.num_nights category: 'Snacks / Supplies / Space' date: null if not reg.meal_opt_out reg.credits.push amount: -@party_data.meals_fee * reg.num_nights category: 'Meals' date: null # Aid and subsidy charges for name, reg of @server_data.registrations if reg.consolidated reg.credits.push amount: -reg.consolidated, category: 'Consolidated Aid Contribution' date: null if reg.aid reg.credits.push amount: -reg.aid category: 'Financial Assistance' date: null if reg.subsidy reg.credits.push amount: -reg.subsidy category: 'Transport Subsidy' date: null # Credit groups: set up a list of associated credits and a field for the unallocated amount for id, cg of @server_data.credit_groups cg.unallocated = cg.amount cg.id = parseInt id cg.credits = [] # Credits for id, credit of @server_data.credits credit.id = parseInt id @server_data.registrations[credit.name].credits.push credit if credit.credit_group cg = @server_data.credit_groups[credit.credit_group] cg.credits.push credit cg.unallocated -= credit.amount # Sort a few things; sum up the amount due for name, reg of @server_data.registrations reg.due = 0 for credit in reg.credits reg.due -= credit.amount reg.credits = _.sortBy(reg.credits, 'date') for id, cg of @server_data.credit_groups cg.credits = _.sortBy(cg.credits, (x) -> x.name.toLowerCase()) # Set up a particularly useful sorted table @regs_by_name _.sortBy(_.values(@server_data.registrations), (x) -> x.name.toLowerCase()) # Determine the group names and reset the selected group groups = (reg.group for reg in @regs_by_name() when reg.group?) groups.push @server_data.group @all_groups _.sortBy(_.uniq(groups), (x) -> x.toLowerCase()) @selected_group @server_data.group # Refresh handler for things depending on the selected group selected_group_sub: (group) => @group_regs_by_name _.filter(@regs_by_name(), (reg) => reg.group == @selected_group()) # Reset the sections for section in @sections section.reset() for section in @admin_sections section.reset() # Select the earliest non-good non-admin section (but only if we're not on an admin section) dodge_throttle => if @visible_section() not in @admin_sections for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null # Base class for sections class Section # Constructor: pass the parent constructor: (@parent) -> @message = ko.observable '' @status = ko.computed(@get_status).extend(throttle: 25) @status_for_selector = ko.computed @get_status_for_selector # Attempt to make this section visible try_set_visible: => if @status() != 'disabled' @parent.visible_section this true # This allows click events to pass through, e.g. to checkboxes # Get the section status (for coloring and other purposes); often overridden get_status: => 'header' # Get the status for the selector, which considers whether the section is selected or selectable get_status_for_selector: => result = @status() if @parent.visible_section() == this result += ' section_selected' else if @status() != 'disabled' result += ' pointer' result # Reset; often overridden reset: => # Section: registering class Register extends Section label: '1. Register' # Overridden methods constructor: (parent) -> @visible_section = ko.observable null @sections = ko.observableArray [] @add_registration = new AddRegistration(parent, this) super parent reset: => @visible_section null @sections [] for reg in @parent.group_regs_by_name() @sections.push new EditRegistration(@parent, this, reg) @add_registration.reset() # Set a default email, but only on initial load if @parent.group_regs_by_name().length == 0 @add_registration.email @parent.server_data.group # Select the earliest non-good section dodge_throttle => @add_registration.try_set_visible() for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null get_status: => for status in ['changed', 'error'] for section in @sections() if section.status() == status return status if @add_registration.status() == status return status if not @sections().length return 'error' 'good' # A pair of observables for a textbox gated by a checkbox class OptionalEntry # Constructor constructor: -> @checkbox = ko.observable false @text = ko.observable '' # Reset to a given value reset: (value) => @checkbox value.length > 0 @text value # Extract the value value: => if @checkbox() return @text() '' # Subsection: edit registration class EditRegistration extends Section # Overridden methods constructor: (@page, parent, @server_reg) -> # A ton of observables backing the various sections of the registration form @full_name = ko.observable() @phone = ko.observable() @emergency = ko.observable() @meal_opt_out = ko.observable(false) @dietary = new OptionalEntry() @medical = new OptionalEntry() @children = new OptionalEntry() @guest = new OptionalEntry() @reset() super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) @allow_del = true reset: => @full_name @server_reg?.full_name @phone @server_reg?.phone @emergency @server_reg?.emergency @meal_opt_out @server_reg?.meal_opt_out @dietary.reset @server_reg?.dietary @medical.reset @server_reg?.medical @children.reset @server_reg?.children @guest.reset @server_reg?.guest get_status: => if not eq(@full_name(), @server_reg?.full_name) return 'changed' if not eq(@phone(), @server_reg?.phone) return 'changed' if not eq(@emergency(), @server_reg?.emergency) return 'changed' if not eq(@meal_opt_out(), @server_reg?.meal_opt_out) return 'changed' if not eq(@dietary.value(), @server_reg?.dietary) return 'changed' if not eq(@medical.value(), @server_reg?.medical) return 'changed' if not eq(@children.value(), @server_reg?.children) return 'changed' if not eq(@guest.value(), @server_reg?.guest) return 'changed' if not @server_reg.full_name return 'error' @message '' 'good' # Submission methods submit: => message = name: @server_reg.name full_name: @full_name() phone: @phone() emergency: @emergency() meal_opt_out: @meal_opt_out() dietary: @dietary.value() medical: @medical.value() children: @children.value() guest: @guest.value() @page.post_json('call/update_registration', message) # Note that not all fields are required; keep this in sync with the server-side validation code! get_allow_submit: => if not @full_name()?.length @message 'Please enter a full name.' return false if not @phone()?.length @message 'Please enter a phone number.' return false else if not @emergency()?.length @message 'Please provide emergency contact information.' return false @message '' true del: => if window.confirm 'Delete the registration for ' + @server_reg.name + '?' @page.post_json('call/delete_registration', { name: @server_reg.name }) # Subsection: add registration class AddRegistration extends Section # Overridden methods constructor: (@page, parent) -> @name = ko.observable '' @email = ko.observable '' super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => @name '' @email '' get_status: => if @email() or @name() return 'changed' 'good' # Submission methods submit: => @page.post_json('call/create_registration', { name: @name(), email: @email() }) get_allow_submit: => @message '' if @name().length return true if @email() @message 'Please enter a name.' false # Section: reservations class Reservations extends Section label: '2. Reserve Rooms' # Overridden methods constructor: (parent) -> # A map from <night>|<room> ids to ClickableCells (or FixedCells) @cells = {} for night in parent.nights for id, group of parent.party_data.rooms for room in group for bed in room.beds key = night.id + '|' + bed.id @cells[key] = ko.observable new FixedCell('Loading...', 'bg_xdarkgray') # Status monitoring variables @has_active_reg = ko.observable false @has_unreserved = ko.observable false super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Regenerate the cells values = [null] for reg in @parent.group_regs_by_name() values.push(reg.name) for night in @parent.nights for id, group of @parent.party_data.rooms for room in group for bed in room.beds key = night.id + '|' + bed.id existing = @parent.server_data.reservations[key] or null # ClickableCells for rooms we can reserve. This happens if: if @parent.reservations_open and # We can reserve things values.length > 1 and # We are attending the party at all night.id of bed.costs and # The room is available existing in values # Nobody else has reserved the room styles = [] for value in values if eq(value, existing) if value style = 'bg_green pointer' else style = 'bg_slate pointer' else style = 'bg_yellow pointer' styles.push style @cells[key] new ClickableCell(values, styles, existing) # FixedCells for rooms we can't reserve. else if existing style = 'bg_purple' else style = 'bg_xdarkgray' @cells[key] new FixedCell(existing, style) # Set monitoring variables has_active_reg = false has_unreserved = false for reg in @parent.group_regs_by_name() has_active_reg = has_active_reg or reg.full_name has_unreserved = has_unreserved or not reg.num_nights @has_active_reg has_active_reg @has_unreserved has_unreserved get_status: => if not @parent.reservations_open @message 'Room reservations are not yet open.' return 'error' if not @has_active_reg() @message 'You have not entered any registrations.' return 'error' for key, cell of @cells if cell().changed?() @message '' return 'changed' if @has_unreserved() @message 'Warning: you have not reserved rooms for one or more people.' return 'error' @message '' 'good' # Submission methods submit: => message = {} for key, cell of @cells if cell().changed?() message[key] = cell().value() @parent.post_json('call/update_reservations', message) get_allow_submit: => @status() == 'changed' # Storage for a table cell which toggles its value when clicked, and can cycle through styles class ClickableCell # Internally this stores state as an index into the various arrays constructor: (@values, @styles, initial) -> @initial = Math.max(@values.indexOf(initial), 0) @selected = ko.observable @initial @value = ko.computed => @values[@selected()] @style = ko.computed => @styles[@selected()] @changed = ko.computed => @selected() != @initial toggle: => @selected((@selected() + 1) % @values.length) # This is a dummy version of ClickableCell which allows the HTML to ignore the fact that some # cells in the reservation table are in fact unclickable class FixedCell constructor: (@value, @style) -> toggle: => # Section: confirmation class Confirmation extends Section label: '3. Confirm' # Overridden methods constructor: (parent) -> @visible_section = ko.observable null @sections = ko.observableArray [] super parent reset: => @visible_section null @sections [] for reg in @parent.group_regs_by_name() if reg.num_nights @sections.push new ConfirmRegistration(@parent, this, reg) # Select the earliest non-good section dodge_throttle => for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null get_status: => if not @parent.reservations_open or not @sections().length return 'disabled' for status in ['changed', 'error'] for section in @sections() if section.status() == status return status if not @sections().length return 'error' 'good' # Subsection: confirm registration class ConfirmRegistration extends Section # Overridden methods constructor: (@page, parent, @server_reg) -> @consolidated = ko.observable() @subsidy_choice = ko.observable() @subsidy_value = ko.observable() @aid_choice = ko.observable() @aid_value = ko.observable() @aid_pledge = ko.observable() @confirmed = ko.observable() @reset() super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => [subsidy_choice, subsidy_value] = @parse_amt @server_reg.subsidy [aid_choice, aid_value] = @parse_amt @server_reg.aid @consolidated @server_reg.consolidated @subsidy_choice subsidy_choice @subsidy_value subsidy_value @aid_choice aid_choice @aid_value aid_value @aid_pledge @server_reg.aid_pledge @confirmed @server_reg.confirmed get_status: => if not eq(@consolidated(), @server_reg.consolidated) return 'changed' if not eq_strict(@subsidy(), @server_reg.subsidy) return 'changed' if not eq_strict(@aid(), @server_reg.aid) return 'changed' if not eq(@aid_pledge(), @server_reg.aid_pledge) return 'changed' if @confirmed() != @server_reg.confirmed return 'changed' if not @server_reg.confirmed return 'error' 'good' # Submission methods submit: => message = name: @server_reg.name consolidated: parseFloat @consolidated() subsidy: @subsidy() aid: @aid() aid_pledge: if @aid() == 0 then 0 else parseFloat @aid_pledge() confirmed: @confirmed() @page.post_json('call/update_registration', message) get_allow_submit: => if not @consolidated()? or not valid_float(@consolidated()) @message 'Please indicate whether you are contributing to the consolidated aid fund.' return false if not @subsidy()? @message 'Please select a valid transportation subsidy option.' return false if not @aid()? or (@aid_choice() == 'contributing' and not valid_float(@aid_pledge())) @message 'Please select a valid financial assistance option.' return false if not @confirmed() @message 'Please confirm this registration.' return false @message '' true # Utility methods; these impedance-match between server-side floats and our radio-and-blanks parse_amt: (amt) => if amt == 0 return ['none', 0] if amt > 0 return ['contributing', amt] ['requesting', -amt] get_amt: (choice, value) => if choice == 'none' return 0 if not valid_float(value) return null result = parseFloat(value) if choice == 'requesting' result = -result result aid: => @get_amt(@aid_choice(), @aid_value()) subsidy: => @get_amt(@subsidy_choice(), @subsidy_value()) # Section: payment class Payment extends Section label: '4. Payment' # Overridden methods constructor: (parent) -> @due = ko.observable 0 @display_section = ko.computed @get_display_section super parent reset: => due = 0 for reg in @parent.group_regs_by_name() if reg.confirmed due += reg.due @due due get_status: => if not _.any(@parent.group_regs_by_name(), (reg) -> reg.confirmed) return 'disabled' @status_for_due @due() # Helpers for formatting get_display_section: => choose_by_sign(@due(), 'due', 'excess', 'zero') status_for_due: (due) => choose_by_sign(due, 'error', 'error', 'good') total_label: (due) => choose_by_sign(due, 'Amount Due', 'Excess Paid', '') total_style: (due) => choose_by_sign(due, 'bg_yellow', 'bg_purple', 'bg_green') # Section: guest list class GuestList extends Section label: 'Guest List' # Overridden methods constructor: (parent) -> @counts = ko.observable {} super parent reset: => counts = {} for day in @parent.party_data.days count = 0 for reg in @parent.regs_by_name() if reg.nights[day.id] count += 1 counts[day.id] = count @counts counts # Compute the CSS class for a (column, guest name) cell # We have data for nights, but want to display days; hence we care about index - 1 (last night) # and index (tonight). class_for_cell: (index, name) => reg_nights = @parent.server_data.registrations[name].nights last_cell = false if index > 0 last_cell = reg_nights[@parent.party_data.days[index - 1].id] this_cell = reg_nights[@parent.party_data.days[index].id] if last_cell if this_cell return 'bg_green' return 'bg_green_purple' if this_cell return 'bg_purple_green' 'bg_purple' # Shared base class for payments and expenses class CreditGroupBase extends Section # Overridden methods constructor: (parent) -> # Display observables @data = ko.observable [] # Editing observables @selected = ko.observable null @edit_amount = ko.observable '' @edit_credits = ko.observableArray [] @allow_del = @selected super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Pull out the relevant credit groups data = [] for id, cg of @parent.server_data.credit_groups if cg.kind == @cg_kind data.push cg @data _.sortBy(data, 'date').reverse() # Reset the editing section @selected null @edit_amount '' @edit_credits [] @add_edit_credit() get_status: => if @selected()? or @edit_amount() return 'changed' for cg in @data() if Math.abs(cg.unallocated) > 0.005 return 'error' 'good' # Submission methods submit: => credits = [] for credit in @edit_credits() if credit.amount() credits.push amount: parseFloat credit.amount() name: credit.name() category: @credit_category(credit) message = id: @selected()?.id amount: parseFloat @edit_amount() credits: credits kind: @cg_kind details: @cg_details() @parent.post_json('call/admin/record_credit_group', message) get_allow_submit: => if not @edit_amount() @message '' return false if not valid_signed_float @edit_amount() @message 'Cannot parse amount received.' return false net = parseFloat @edit_amount() for credit in @edit_credits() if credit.amount() if not valid_signed_float credit.amount() @message 'Cannot parse amount credited.' return false if not credit.name() @message 'No registration selected.' return false if not @extra_credit_checks_ok(credit) return false net -= parseFloat credit.amount() if Math.abs(net) > 0.005 @message 'Warning: amount not fully allocated.' else if @extra_cg_checks_ok() @message '' true del: => @parent.post_json('call/admin/delete_credit_group', { id: @selected().id }) # Formatting and interaction helpers cg_class: (cg) => if @selected() == cg return 'bg_yellow' if Math.abs(cg.unallocated) > 0.005 return 'bg_red' 'bg_gray' cg_select: (cg) => @selected cg @edit_amount cg.amount @edit_credits [] for credit in cg.credits @add_edit_credit credit if not @edit_credits().length @add_edit_credit() # Admin section: payments class Payments extends CreditGroupBase label: 'Payments' # This is used for sorting the credit groups cg_kind: 'payment' # Overridden methods constructor: (parent) -> @regs = [] @total = ko.observable 0 @edit_from = ko.observable '' @edit_via = ko.observable '' super parent reset: => # Refresh the options list @regs = _.sortBy(@parent.regs_by_name(), (x) -> Math.abs(x.due) < 0.005) @edit_from '' @edit_via '' super() total = 0 for cg in @data() total += cg.amount @total total cg_select: (cg) => super cg @edit_from cg.details.from @edit_via cg.details.via # Dispatch methods cg_details: => { from: @edit_from(), via: @edit_via() } credit_category: (credit) => 'Payment / Refund' extra_credit_checks_ok: (credit) => true extra_cg_checks_ok: => if not @edit_from() @message 'Warning: no entry for whom the payment is from.' return false else if not @edit_via() @message 'Warning: no entry for how the payment was received.' return false true # Required methods add_edit_credit: (credit = null) => @edit_credits.push amount: ko.observable(credit?.amount ? '') name: ko.observable(credit?.name ? '') # Formatter for the dropdown format_reg: (reg) => result = reg.name if Math.abs(reg.due) > 0.005 result += ' - ' + _.dollars(reg.due) + ' due' result # Admin section: expenses class Expenses extends CreditGroupBase label: 'Expenses' # This is used for sorting the credit groups cg_kind: 'expense' # Overridden methods constructor: (parent) -> @edit_description = ko.observable '' super parent reset: => @edit_description '' super() cg_select: (cg) => super cg @edit_description cg.details.description # Dispatch methods cg_details: => { description: @edit_description() } credit_category: (credit) => credit.category() extra_credit_checks_ok: (credit) => if not credit.category() @message 'No category selected.' return false true extra_cg_checks_ok: => if not @edit_description() @message 'Warning: no description of the expense.' return false true # Required methods add_edit_credit: (credit = null) => @edit_credits.push amount: ko.observable(credit?.amount ? '') name: ko.observable(credit?.name ? '') category: ko.observable(credit?.category ? '') # Admin section: credits class Credits extends Section label: 'Misc Credits' # Overridden methods constructor: (parent) -> # Display observables @data = ko.observable [] # Editing observables @selected = ko.observable null @edit_amount = ko.observable '' @edit_name = ko.observable '' @edit_category = ko.observable '' @allow_del = @selected super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Pull out the relevant credit groups data = [] for id, credit of @parent.server_data.credits if not credit.credit_group data.push credit @data _.sortBy(data, 'date').reverse() # Refresh the options @selected null @edit_amount '' @edit_name '' @edit_category '' get_status: => if @selected()? or @edit_amount() return 'changed' 'good' # Submission methods submit: => message = id: @selected()?.id amount: parseFloat @edit_amount() name: @edit_name() category: @edit_category() @parent.post_json('call/admin/record_credit', message) get_allow_submit: => if not @edit_amount() @message '' return false if not valid_signed_float @edit_amount() @message 'Cannot parse amount received.' return false if not @edit_name() @message 'No registration selected.' return false if not @edit_category() @message 'No category selected.' return false true del: => @parent.post_json('call/admin/delete_credit', { id: @selected().id }) # Formatting and interaction helpers select: (credit) => @selected credit @edit_amount credit.amount @edit_name credit.name @edit_category credit.category credit_class: (credit) => if @selected() == credit return 'bg_yellow' 'bg_gray' # Admin section: registrations table class Registrations extends Section label: 'Registrations' # Prefixes to total by total_by: [ 'General' 'Consolidated' 'Financial' 'Transport' 'Payment / Refund' 'Expense' 'Other' ] # Overridden methods constructor: (parent) -> @counts = ko.observable {} @data = ko.observable [] super parent reset: => # The "General" prefix is not actually a prefix, so we hack around this general_categories = ['Rooms', 'Snacks / Supplies / Space', 'Meals'] # Generate the counts counts = no_nights: 0 unconfirmed: 0 unpaid: 0 complete: 0 for reg in @parent.regs_by_name() if not reg.num_nights counts.no_nights += 1 else if not reg.confirmed counts.unconfirmed += 1 else if Math.abs(reg.due) > 0.005 counts.unpaid += 1 else counts.complete += 1 @counts counts # Generate the data for the table data = [] sortkey = (x) -> [x.num_nights > 0, x.confirmed, Math.abs(x.due) < 0.005] for reg in _.sortBy(@parent.regs_by_name(), sortkey) totals = {} for category in @total_by totals[category] = 0 for credit in reg.credits prefix = 'Other' if credit.category in general_categories prefix = "General" else for p in @total_by if credit.category[...p.length] == p prefix = p break totals[prefix] -= credit.amount data.push { reg, totals } @data data # Interaction helpers select: ({ reg, totals }) => @parent.selected_group reg.group # Admin section: financial summary class Financials extends Section label: 'Financials' # A table of the credit categories for each section; sections starting with * are hidden surplus_categories: [ ['General Fund', [ 'Rooms' 'Snacks / Supplies / Space' 'Meals' 'Donations' 'Expense: Houses / Hotels' 'Expense: Meals / Snacks / Supplies' 'Expense: Other' 'Adjustment: Rooms' 'Adjustment: Meals' 'Adjustment: Other' ]] ['Aid Funds', [ 'Consolidated Aid Contribution' 'Financial Assistance' 'Transport Subsidy' ]] ['*Net Payments', ['Payment / Refund']] ['Other', ['Expense: Deposits']] ] signed_categories: ['Financial Assistance', 'Transport Subsidy'] # Overridden methods constructor: (parent) -> @data = ko.observable [] @grand_total = ko.observable 0 super parent reset: => # Collect the surpluses surpluses_normal = {} surpluses_signed = {} for category in @signed_categories surpluses_signed[category] = { pos: 0, num_pos: 0, neg: 0, num_neg: 0 } grand_total = 0 for reg in @parent.regs_by_name() for credit in reg.credits if credit.category of surpluses_signed entry = surpluses_signed[credit.category] if credit.amount > 0 entry.neg -= credit.amount entry.num_neg += 1 else if credit.amount < 0 entry.pos -= credit.amount entry.num_pos += 1 else if credit.category not of surpluses_normal surpluses_normal[credit.category] = 0 surpluses_normal[credit.category] -= credit.amount grand_total -= credit.amount @grand_total grand_total # Assemble data for display data = [] for [group, categories] in @surplus_categories values = [] total = 0 for category in categories if category of surpluses_signed entry = surpluses_signed[category] values.push category: category + ': contributions (' + entry.num_pos + ')' amount: entry.pos values.push category: category + ': requests (' + entry.num_neg + ')' amount: entry.neg total += entry.pos + entry.neg else amount = surpluses_normal[category] ? 0 delete surpluses_normal[category] values.push { category, amount } total += amount if not /^\*/.test group data.push { group, values, total } # File any unprocessed categories in the last group. We assume all signed categories are # properly in a group (since that can be verified by simple inspection) for category, amount of surpluses_normal _.last(data).values.push { category, amount } _.last(data).total += amount @data data # Helpers for formatting total_style: (due) => choose_by_sign(due, 'bg_green', 'bg_red', 'bg_gray') # Admin section: dietary information list class DietaryInfo extends Section label: 'Dietary' # Admin section: other information list class OtherInfo extends Section label: 'Other Info' # Admin section: phone list class PhoneList extends Section label: 'Phone List' # Overridden methods constructor: (parent) -> @data = ko.observable [] super parent reset: => by_name = (_.pick(r, 'name', 'phone') for r in @parent.regs_by_name() when r.phone?.length) by_phone = _.sortBy(by_name, (x) -> x.phone.replace(/[^0-9]/g, '')) data = [] for i in [0...by_name.length] data.push [by_name[i].name, by_name[i].phone, by_phone[i].phone, by_phone[i].name] @data data # Admin section: email list class EmailList extends Section label: 'Email List' # Bind the model bind = => ko.applyBindings new PageModel() if document.readyState != 'loading' bind() else document.addEventListener('DOMContentLoaded', bind)
31047
# Utility functions and classes # A mixin for formatting (positive and negative) dollar values _.mixin dollars: (x, precision = 2, blank_zero = false) -> if not x? or (blank_zero and Math.abs(x) < 0.005) return '' val = '$' + Math.abs(x).toFixed(precision) if x < 0 val = '(' + val + ')' val # Mixins for standard date formats _.mixin short_date: (t) -> moment(t * 1000).format("MMM D") _.mixin long_date: (t) -> moment(t * 1000).format("YYYY-MM-DD HH:mm") # Choose among the options by the sign of the value; accepts a range around zero to handle rounding choose_by_sign = (val, pos, neg, zero) => if val > 0.005 return pos if val < -0.005 return neg return zero # Due to throttling, certain one-time status-dependent code has to be given a delay dodge_throttle = (f) -> setTimeout(f, 75) # Compare x and y, coercing null and undefined to the empty string. eq = (x, y) -> (x ? '') == (y ? '') # Compare x and y, coercing null and undefined to null. eq_strict = (x, y) -> if not x? return not y? if not y? return false x == y # Is this a valid (possibly signed) floating-point number? Used to validate money entries. valid_float = (x) -> /^[0-9]+(\.[0-9]+)?$/.test(x ? '') valid_signed_float = (x) -> /^-?[0-9]+(\.[0-9]+)?$/.test(x ? '') # The main object backing the page class PageModel # Constructor constructor: -> # Initialize data req = new XMLHttpRequest() req.open('GET', 'call/init', false) req.send() { @is_admin, @logout_url, @party_data, @server_data, @username } = JSON.parse req.response # Variables backing the group selector @all_groups = ko.observable [] @selected_group = ko.observable('').extend(notify: 'always') @selected_group.subscribe @selected_group_sub # Variables of convenience: a number of sections need only one of these observables @regs_by_name = ko.observable [] @group_regs_by_name = ko.observable [] @nights = @party_data.days[...-1] @reservations_open = @party_data.reservations_enabled or @is_admin # Set up sections @visible_section = ko.observable null @sections = [ @register = new Register this @reservations = new Reservations this @confirmation = new Confirmation this @payment = new Payment this @guest_list = new GuestList this ] @admin_sections = [] if @is_admin @admin_sections = [ @payments = new Payments this @expenses = new Expenses this @credits = new Credits this @registrations = new Registrations this @financials = new Financials this @dietary_info = new DietaryInfo this @other_info = new OtherInfo this @email_list = new EmailList this @phone_list = new PhoneList this ] # Reset sections @reset() # Post method; pass the endpoint and the message to post post_json: (url, message) => message.group = @selected_group() req = new XMLHttpRequest() req.open('POST', url, false) req.send JSON.stringify message { @server_data, error } = JSON.parse req.response @reset() if error window.alert(error + ' (If you think this is a bug, please let us know.)') # Postprocess data after retrieval from the server and reset the sections reset: => # Tag each registration with its name for name, reg of @server_data.registrations reg.name = name # Tag each registration with the nights it's staying and add room, nightly, and meal charges for name, reg of @server_data.registrations reg.credits = [] reg.nights = {} reg._room_charge = 0 for night in @nights for id, group of @party_data.rooms for room in group for bed in room.beds key = night.<KEY> + <KEY> + bed.<KEY> if key of @server_data.reservations name = @server_data.reservations[key] @server_data.registrations[name]._room_charge += bed.costs[night.id] @server_data.registrations[name].nights[night.id] = true for name, reg of @server_data.registrations reg.num_nights = 0 for id, is_reserved of reg.nights if is_reserved reg.num_nights += 1 if reg._room_charge reg.credits.push { amount: -reg._room_charge, category: 'Rooms', date: null } delete reg._room_charge if reg.num_nights reg.credits.push amount: -@party_data.nightly_fee * reg.num_nights category: 'Snacks / Supplies / Space' date: null if not reg.meal_opt_out reg.credits.push amount: -@party_data.meals_fee * reg.num_nights category: 'Meals' date: null # Aid and subsidy charges for name, reg of @server_data.registrations if reg.consolidated reg.credits.push amount: -reg.consolidated, category: 'Consolidated Aid Contribution' date: null if reg.aid reg.credits.push amount: -reg.aid category: 'Financial Assistance' date: null if reg.subsidy reg.credits.push amount: -reg.subsidy category: 'Transport Subsidy' date: null # Credit groups: set up a list of associated credits and a field for the unallocated amount for id, cg of @server_data.credit_groups cg.unallocated = cg.amount cg.id = parseInt id cg.credits = [] # Credits for id, credit of @server_data.credits credit.id = parseInt id @server_data.registrations[credit.name].credits.push credit if credit.credit_group cg = @server_data.credit_groups[credit.credit_group] cg.credits.push credit cg.unallocated -= credit.amount # Sort a few things; sum up the amount due for name, reg of @server_data.registrations reg.due = 0 for credit in reg.credits reg.due -= credit.amount reg.credits = _.sortBy(reg.credits, 'date') for id, cg of @server_data.credit_groups cg.credits = _.sortBy(cg.credits, (x) -> x.name.toLowerCase()) # Set up a particularly useful sorted table @regs_by_name _.sortBy(_.values(@server_data.registrations), (x) -> x.name.toLowerCase()) # Determine the group names and reset the selected group groups = (reg.group for reg in @regs_by_name() when reg.group?) groups.push @server_data.group @all_groups _.sortBy(_.uniq(groups), (x) -> x.toLowerCase()) @selected_group @server_data.group # Refresh handler for things depending on the selected group selected_group_sub: (group) => @group_regs_by_name _.filter(@regs_by_name(), (reg) => reg.group == @selected_group()) # Reset the sections for section in @sections section.reset() for section in @admin_sections section.reset() # Select the earliest non-good non-admin section (but only if we're not on an admin section) dodge_throttle => if @visible_section() not in @admin_sections for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null # Base class for sections class Section # Constructor: pass the parent constructor: (@parent) -> @message = ko.observable '' @status = ko.computed(@get_status).extend(throttle: 25) @status_for_selector = ko.computed @get_status_for_selector # Attempt to make this section visible try_set_visible: => if @status() != 'disabled' @parent.visible_section this true # This allows click events to pass through, e.g. to checkboxes # Get the section status (for coloring and other purposes); often overridden get_status: => 'header' # Get the status for the selector, which considers whether the section is selected or selectable get_status_for_selector: => result = @status() if @parent.visible_section() == this result += ' section_selected' else if @status() != 'disabled' result += ' pointer' result # Reset; often overridden reset: => # Section: registering class Register extends Section label: '1. Register' # Overridden methods constructor: (parent) -> @visible_section = ko.observable null @sections = ko.observableArray [] @add_registration = new AddRegistration(parent, this) super parent reset: => @visible_section null @sections [] for reg in @parent.group_regs_by_name() @sections.push new EditRegistration(@parent, this, reg) @add_registration.reset() # Set a default email, but only on initial load if @parent.group_regs_by_name().length == 0 @add_registration.email @parent.server_data.group # Select the earliest non-good section dodge_throttle => @add_registration.try_set_visible() for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null get_status: => for status in ['changed', 'error'] for section in @sections() if section.status() == status return status if @add_registration.status() == status return status if not @sections().length return 'error' 'good' # A pair of observables for a textbox gated by a checkbox class OptionalEntry # Constructor constructor: -> @checkbox = ko.observable false @text = ko.observable '' # Reset to a given value reset: (value) => @checkbox value.length > 0 @text value # Extract the value value: => if @checkbox() return @text() '' # Subsection: edit registration class EditRegistration extends Section # Overridden methods constructor: (@page, parent, @server_reg) -> # A ton of observables backing the various sections of the registration form @full_name = ko.observable() @phone = ko.observable() @emergency = ko.observable() @meal_opt_out = ko.observable(false) @dietary = new OptionalEntry() @medical = new OptionalEntry() @children = new OptionalEntry() @guest = new OptionalEntry() @reset() super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) @allow_del = true reset: => @full_name @server_reg?.full_name @phone @server_reg?.phone @emergency @server_reg?.emergency @meal_opt_out @server_reg?.meal_opt_out @dietary.reset @server_reg?.dietary @medical.reset @server_reg?.medical @children.reset @server_reg?.children @guest.reset @server_reg?.guest get_status: => if not eq(@full_name(), @server_reg?.full_name) return 'changed' if not eq(@phone(), @server_reg?.phone) return 'changed' if not eq(@emergency(), @server_reg?.emergency) return 'changed' if not eq(@meal_opt_out(), @server_reg?.meal_opt_out) return 'changed' if not eq(@dietary.value(), @server_reg?.dietary) return 'changed' if not eq(@medical.value(), @server_reg?.medical) return 'changed' if not eq(@children.value(), @server_reg?.children) return 'changed' if not eq(@guest.value(), @server_reg?.guest) return 'changed' if not @server_reg.full_name return 'error' @message '' 'good' # Submission methods submit: => message = name: @server_reg.name full_name: @full_name() phone: @phone() emergency: @emergency() meal_opt_out: @meal_opt_out() dietary: @dietary.value() medical: @medical.value() children: @children.value() guest: @guest.value() @page.post_json('call/update_registration', message) # Note that not all fields are required; keep this in sync with the server-side validation code! get_allow_submit: => if not @full_name()?.length @message 'Please enter a full name.' return false if not @phone()?.length @message 'Please enter a phone number.' return false else if not @emergency()?.length @message 'Please provide emergency contact information.' return false @message '' true del: => if window.confirm 'Delete the registration for ' + @server_reg.name + '?' @page.post_json('call/delete_registration', { name: @server_reg.name }) # Subsection: add registration class AddRegistration extends Section # Overridden methods constructor: (@page, parent) -> @name = ko.observable '' @email = ko.observable '' super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => @name '' @email '' get_status: => if @email() or @name() return 'changed' 'good' # Submission methods submit: => @page.post_json('call/create_registration', { name: @name(), email: @email() }) get_allow_submit: => @message '' if @name().length return true if @email() @message 'Please enter a name.' false # Section: reservations class Reservations extends Section label: '2. Reserve Rooms' # Overridden methods constructor: (parent) -> # A map from <night>|<room> ids to ClickableCells (or FixedCells) @cells = {} for night in parent.nights for id, group of parent.party_data.rooms for room in group for bed in room.beds key = <KEY> @cells[key] = ko.observable new FixedCell('Loading...', 'bg_xdarkgray') # Status monitoring variables @has_active_reg = ko.observable false @has_unreserved = ko.observable false super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Regenerate the cells values = [null] for reg in @parent.group_regs_by_name() values.push(reg.name) for night in @parent.nights for id, group of @parent.party_data.rooms for room in group for bed in room.beds key = <KEY> existing = @parent.server_data.reservations[key] or null # ClickableCells for rooms we can reserve. This happens if: if @parent.reservations_open and # We can reserve things values.length > 1 and # We are attending the party at all night.id of bed.costs and # The room is available existing in values # Nobody else has reserved the room styles = [] for value in values if eq(value, existing) if value style = 'bg_green pointer' else style = 'bg_slate pointer' else style = 'bg_yellow pointer' styles.push style @cells[key] new ClickableCell(values, styles, existing) # FixedCells for rooms we can't reserve. else if existing style = 'bg_purple' else style = 'bg_xdarkgray' @cells[key] new FixedCell(existing, style) # Set monitoring variables has_active_reg = false has_unreserved = false for reg in @parent.group_regs_by_name() has_active_reg = has_active_reg or reg.full_name has_unreserved = has_unreserved or not reg.num_nights @has_active_reg has_active_reg @has_unreserved has_unreserved get_status: => if not @parent.reservations_open @message 'Room reservations are not yet open.' return 'error' if not @has_active_reg() @message 'You have not entered any registrations.' return 'error' for key, cell of @cells if cell().changed?() @message '' return 'changed' if @has_unreserved() @message 'Warning: you have not reserved rooms for one or more people.' return 'error' @message '' 'good' # Submission methods submit: => message = {} for key, cell of @cells if cell().changed?() message[key] = cell().value() @parent.post_json('call/update_reservations', message) get_allow_submit: => @status() == 'changed' # Storage for a table cell which toggles its value when clicked, and can cycle through styles class ClickableCell # Internally this stores state as an index into the various arrays constructor: (@values, @styles, initial) -> @initial = Math.max(@values.indexOf(initial), 0) @selected = ko.observable @initial @value = ko.computed => @values[@selected()] @style = ko.computed => @styles[@selected()] @changed = ko.computed => @selected() != @initial toggle: => @selected((@selected() + 1) % @values.length) # This is a dummy version of ClickableCell which allows the HTML to ignore the fact that some # cells in the reservation table are in fact unclickable class FixedCell constructor: (@value, @style) -> toggle: => # Section: confirmation class Confirmation extends Section label: '3. Confirm' # Overridden methods constructor: (parent) -> @visible_section = ko.observable null @sections = ko.observableArray [] super parent reset: => @visible_section null @sections [] for reg in @parent.group_regs_by_name() if reg.num_nights @sections.push new ConfirmRegistration(@parent, this, reg) # Select the earliest non-good section dodge_throttle => for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null get_status: => if not @parent.reservations_open or not @sections().length return 'disabled' for status in ['changed', 'error'] for section in @sections() if section.status() == status return status if not @sections().length return 'error' 'good' # Subsection: confirm registration class ConfirmRegistration extends Section # Overridden methods constructor: (@page, parent, @server_reg) -> @consolidated = ko.observable() @subsidy_choice = ko.observable() @subsidy_value = ko.observable() @aid_choice = ko.observable() @aid_value = ko.observable() @aid_pledge = ko.observable() @confirmed = ko.observable() @reset() super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => [subsidy_choice, subsidy_value] = @parse_amt @server_reg.subsidy [aid_choice, aid_value] = @parse_amt @server_reg.aid @consolidated @server_reg.consolidated @subsidy_choice subsidy_choice @subsidy_value subsidy_value @aid_choice aid_choice @aid_value aid_value @aid_pledge @server_reg.aid_pledge @confirmed @server_reg.confirmed get_status: => if not eq(@consolidated(), @server_reg.consolidated) return 'changed' if not eq_strict(@subsidy(), @server_reg.subsidy) return 'changed' if not eq_strict(@aid(), @server_reg.aid) return 'changed' if not eq(@aid_pledge(), @server_reg.aid_pledge) return 'changed' if @confirmed() != @server_reg.confirmed return 'changed' if not @server_reg.confirmed return 'error' 'good' # Submission methods submit: => message = name: @server_reg.name consolidated: parseFloat @consolidated() subsidy: @subsidy() aid: @aid() aid_pledge: if @aid() == 0 then 0 else parseFloat @aid_pledge() confirmed: @confirmed() @page.post_json('call/update_registration', message) get_allow_submit: => if not @consolidated()? or not valid_float(@consolidated()) @message 'Please indicate whether you are contributing to the consolidated aid fund.' return false if not @subsidy()? @message 'Please select a valid transportation subsidy option.' return false if not @aid()? or (@aid_choice() == 'contributing' and not valid_float(@aid_pledge())) @message 'Please select a valid financial assistance option.' return false if not @confirmed() @message 'Please confirm this registration.' return false @message '' true # Utility methods; these impedance-match between server-side floats and our radio-and-blanks parse_amt: (amt) => if amt == 0 return ['none', 0] if amt > 0 return ['contributing', amt] ['requesting', -amt] get_amt: (choice, value) => if choice == 'none' return 0 if not valid_float(value) return null result = parseFloat(value) if choice == 'requesting' result = -result result aid: => @get_amt(@aid_choice(), @aid_value()) subsidy: => @get_amt(@subsidy_choice(), @subsidy_value()) # Section: payment class Payment extends Section label: '4. Payment' # Overridden methods constructor: (parent) -> @due = ko.observable 0 @display_section = ko.computed @get_display_section super parent reset: => due = 0 for reg in @parent.group_regs_by_name() if reg.confirmed due += reg.due @due due get_status: => if not _.any(@parent.group_regs_by_name(), (reg) -> reg.confirmed) return 'disabled' @status_for_due @due() # Helpers for formatting get_display_section: => choose_by_sign(@due(), 'due', 'excess', 'zero') status_for_due: (due) => choose_by_sign(due, 'error', 'error', 'good') total_label: (due) => choose_by_sign(due, 'Amount Due', 'Excess Paid', '') total_style: (due) => choose_by_sign(due, 'bg_yellow', 'bg_purple', 'bg_green') # Section: guest list class GuestList extends Section label: 'Guest List' # Overridden methods constructor: (parent) -> @counts = ko.observable {} super parent reset: => counts = {} for day in @parent.party_data.days count = 0 for reg in @parent.regs_by_name() if reg.nights[day.id] count += 1 counts[day.id] = count @counts counts # Compute the CSS class for a (column, guest name) cell # We have data for nights, but want to display days; hence we care about index - 1 (last night) # and index (tonight). class_for_cell: (index, name) => reg_nights = @parent.server_data.registrations[name].nights last_cell = false if index > 0 last_cell = reg_nights[@parent.party_data.days[index - 1].id] this_cell = reg_nights[@parent.party_data.days[index].id] if last_cell if this_cell return 'bg_green' return 'bg_green_purple' if this_cell return 'bg_purple_green' 'bg_purple' # Shared base class for payments and expenses class CreditGroupBase extends Section # Overridden methods constructor: (parent) -> # Display observables @data = ko.observable [] # Editing observables @selected = ko.observable null @edit_amount = ko.observable '' @edit_credits = ko.observableArray [] @allow_del = @selected super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Pull out the relevant credit groups data = [] for id, cg of @parent.server_data.credit_groups if cg.kind == @cg_kind data.push cg @data _.sortBy(data, 'date').reverse() # Reset the editing section @selected null @edit_amount '' @edit_credits [] @add_edit_credit() get_status: => if @selected()? or @edit_amount() return 'changed' for cg in @data() if Math.abs(cg.unallocated) > 0.005 return 'error' 'good' # Submission methods submit: => credits = [] for credit in @edit_credits() if credit.amount() credits.push amount: parseFloat credit.amount() name: credit.name() category: @credit_category(credit) message = id: @selected()?.id amount: parseFloat @edit_amount() credits: credits kind: @cg_kind details: @cg_details() @parent.post_json('call/admin/record_credit_group', message) get_allow_submit: => if not @edit_amount() @message '' return false if not valid_signed_float @edit_amount() @message 'Cannot parse amount received.' return false net = parseFloat @edit_amount() for credit in @edit_credits() if credit.amount() if not valid_signed_float credit.amount() @message 'Cannot parse amount credited.' return false if not credit.name() @message 'No registration selected.' return false if not @extra_credit_checks_ok(credit) return false net -= parseFloat credit.amount() if Math.abs(net) > 0.005 @message 'Warning: amount not fully allocated.' else if @extra_cg_checks_ok() @message '' true del: => @parent.post_json('call/admin/delete_credit_group', { id: @selected().id }) # Formatting and interaction helpers cg_class: (cg) => if @selected() == cg return 'bg_yellow' if Math.abs(cg.unallocated) > 0.005 return 'bg_red' 'bg_gray' cg_select: (cg) => @selected cg @edit_amount cg.amount @edit_credits [] for credit in cg.credits @add_edit_credit credit if not @edit_credits().length @add_edit_credit() # Admin section: payments class Payments extends CreditGroupBase label: 'Payments' # This is used for sorting the credit groups cg_kind: 'payment' # Overridden methods constructor: (parent) -> @regs = [] @total = ko.observable 0 @edit_from = ko.observable '' @edit_via = ko.observable '' super parent reset: => # Refresh the options list @regs = _.sortBy(@parent.regs_by_name(), (x) -> Math.abs(x.due) < 0.005) @edit_from '' @edit_via '' super() total = 0 for cg in @data() total += cg.amount @total total cg_select: (cg) => super cg @edit_from cg.details.from @edit_via cg.details.via # Dispatch methods cg_details: => { from: @edit_from(), via: @edit_via() } credit_category: (credit) => 'Payment / Refund' extra_credit_checks_ok: (credit) => true extra_cg_checks_ok: => if not @edit_from() @message 'Warning: no entry for whom the payment is from.' return false else if not @edit_via() @message 'Warning: no entry for how the payment was received.' return false true # Required methods add_edit_credit: (credit = null) => @edit_credits.push amount: ko.observable(credit?.amount ? '') name: ko.observable(credit?.name ? '') # Formatter for the dropdown format_reg: (reg) => result = reg.name if Math.abs(reg.due) > 0.005 result += ' - ' + _.dollars(reg.due) + ' due' result # Admin section: expenses class Expenses extends CreditGroupBase label: 'Expenses' # This is used for sorting the credit groups cg_kind: 'expense' # Overridden methods constructor: (parent) -> @edit_description = ko.observable '' super parent reset: => @edit_description '' super() cg_select: (cg) => super cg @edit_description cg.details.description # Dispatch methods cg_details: => { description: @edit_description() } credit_category: (credit) => credit.category() extra_credit_checks_ok: (credit) => if not credit.category() @message 'No category selected.' return false true extra_cg_checks_ok: => if not @edit_description() @message 'Warning: no description of the expense.' return false true # Required methods add_edit_credit: (credit = null) => @edit_credits.push amount: ko.observable(credit?.amount ? '') name: ko.observable(credit?.name ? '') category: ko.observable(credit?.category ? '') # Admin section: credits class Credits extends Section label: 'Misc Credits' # Overridden methods constructor: (parent) -> # Display observables @data = ko.observable [] # Editing observables @selected = ko.observable null @edit_amount = ko.observable '' @edit_name = ko.observable '' @edit_category = ko.observable '' @allow_del = @selected super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Pull out the relevant credit groups data = [] for id, credit of @parent.server_data.credits if not credit.credit_group data.push credit @data _.sortBy(data, 'date').reverse() # Refresh the options @selected null @edit_amount '' @edit_name '' @edit_category '' get_status: => if @selected()? or @edit_amount() return 'changed' 'good' # Submission methods submit: => message = id: @selected()?.id amount: parseFloat @edit_amount() name: @edit_name() category: @edit_category() @parent.post_json('call/admin/record_credit', message) get_allow_submit: => if not @edit_amount() @message '' return false if not valid_signed_float @edit_amount() @message 'Cannot parse amount received.' return false if not @edit_name() @message 'No registration selected.' return false if not @edit_category() @message 'No category selected.' return false true del: => @parent.post_json('call/admin/delete_credit', { id: @selected().id }) # Formatting and interaction helpers select: (credit) => @selected credit @edit_amount credit.amount @edit_name credit.name @edit_category credit.category credit_class: (credit) => if @selected() == credit return 'bg_yellow' 'bg_gray' # Admin section: registrations table class Registrations extends Section label: 'Registrations' # Prefixes to total by total_by: [ 'General' 'Consolidated' 'Financial' 'Transport' 'Payment / Refund' 'Expense' 'Other' ] # Overridden methods constructor: (parent) -> @counts = ko.observable {} @data = ko.observable [] super parent reset: => # The "General" prefix is not actually a prefix, so we hack around this general_categories = ['Rooms', 'Snacks / Supplies / Space', 'Meals'] # Generate the counts counts = no_nights: 0 unconfirmed: 0 unpaid: 0 complete: 0 for reg in @parent.regs_by_name() if not reg.num_nights counts.no_nights += 1 else if not reg.confirmed counts.unconfirmed += 1 else if Math.abs(reg.due) > 0.005 counts.unpaid += 1 else counts.complete += 1 @counts counts # Generate the data for the table data = [] sortkey = (x) -> [x.num_nights > 0, x.confirmed, Math.abs(x.due) < 0.005] for reg in _.sortBy(@parent.regs_by_name(), sortkey) totals = {} for category in @total_by totals[category] = 0 for credit in reg.credits prefix = 'Other' if credit.category in general_categories prefix = "General" else for p in @total_by if credit.category[...p.length] == p prefix = p break totals[prefix] -= credit.amount data.push { reg, totals } @data data # Interaction helpers select: ({ reg, totals }) => @parent.selected_group reg.group # Admin section: financial summary class Financials extends Section label: 'Financials' # A table of the credit categories for each section; sections starting with * are hidden surplus_categories: [ ['General Fund', [ 'Rooms' 'Snacks / Supplies / Space' 'Meals' 'Donations' 'Expense: Houses / Hotels' 'Expense: Meals / Snacks / Supplies' 'Expense: Other' 'Adjustment: Rooms' 'Adjustment: Meals' 'Adjustment: Other' ]] ['Aid Funds', [ 'Consolidated Aid Contribution' 'Financial Assistance' 'Transport Subsidy' ]] ['*Net Payments', ['Payment / Refund']] ['Other', ['Expense: Deposits']] ] signed_categories: ['Financial Assistance', 'Transport Subsidy'] # Overridden methods constructor: (parent) -> @data = ko.observable [] @grand_total = ko.observable 0 super parent reset: => # Collect the surpluses surpluses_normal = {} surpluses_signed = {} for category in @signed_categories surpluses_signed[category] = { pos: 0, num_pos: 0, neg: 0, num_neg: 0 } grand_total = 0 for reg in @parent.regs_by_name() for credit in reg.credits if credit.category of surpluses_signed entry = surpluses_signed[credit.category] if credit.amount > 0 entry.neg -= credit.amount entry.num_neg += 1 else if credit.amount < 0 entry.pos -= credit.amount entry.num_pos += 1 else if credit.category not of surpluses_normal surpluses_normal[credit.category] = 0 surpluses_normal[credit.category] -= credit.amount grand_total -= credit.amount @grand_total grand_total # Assemble data for display data = [] for [group, categories] in @surplus_categories values = [] total = 0 for category in categories if category of surpluses_signed entry = surpluses_signed[category] values.push category: category + ': contributions (' + entry.num_pos + ')' amount: entry.pos values.push category: category + ': requests (' + entry.num_neg + ')' amount: entry.neg total += entry.pos + entry.neg else amount = surpluses_normal[category] ? 0 delete surpluses_normal[category] values.push { category, amount } total += amount if not /^\*/.test group data.push { group, values, total } # File any unprocessed categories in the last group. We assume all signed categories are # properly in a group (since that can be verified by simple inspection) for category, amount of surpluses_normal _.last(data).values.push { category, amount } _.last(data).total += amount @data data # Helpers for formatting total_style: (due) => choose_by_sign(due, 'bg_green', 'bg_red', 'bg_gray') # Admin section: dietary information list class DietaryInfo extends Section label: 'Dietary' # Admin section: other information list class OtherInfo extends Section label: 'Other Info' # Admin section: phone list class PhoneList extends Section label: 'Phone List' # Overridden methods constructor: (parent) -> @data = ko.observable [] super parent reset: => by_name = (_.pick(r, 'name', 'phone') for r in @parent.regs_by_name() when r.phone?.length) by_phone = _.sortBy(by_name, (x) -> x.phone.replace(/[^0-9]/g, '')) data = [] for i in [0...by_name.length] data.push [by_name[i].name, by_name[i].phone, by_phone[i].phone, by_phone[i].name] @data data # Admin section: email list class EmailList extends Section label: 'Email List' # Bind the model bind = => ko.applyBindings new PageModel() if document.readyState != 'loading' bind() else document.addEventListener('DOMContentLoaded', bind)
true
# Utility functions and classes # A mixin for formatting (positive and negative) dollar values _.mixin dollars: (x, precision = 2, blank_zero = false) -> if not x? or (blank_zero and Math.abs(x) < 0.005) return '' val = '$' + Math.abs(x).toFixed(precision) if x < 0 val = '(' + val + ')' val # Mixins for standard date formats _.mixin short_date: (t) -> moment(t * 1000).format("MMM D") _.mixin long_date: (t) -> moment(t * 1000).format("YYYY-MM-DD HH:mm") # Choose among the options by the sign of the value; accepts a range around zero to handle rounding choose_by_sign = (val, pos, neg, zero) => if val > 0.005 return pos if val < -0.005 return neg return zero # Due to throttling, certain one-time status-dependent code has to be given a delay dodge_throttle = (f) -> setTimeout(f, 75) # Compare x and y, coercing null and undefined to the empty string. eq = (x, y) -> (x ? '') == (y ? '') # Compare x and y, coercing null and undefined to null. eq_strict = (x, y) -> if not x? return not y? if not y? return false x == y # Is this a valid (possibly signed) floating-point number? Used to validate money entries. valid_float = (x) -> /^[0-9]+(\.[0-9]+)?$/.test(x ? '') valid_signed_float = (x) -> /^-?[0-9]+(\.[0-9]+)?$/.test(x ? '') # The main object backing the page class PageModel # Constructor constructor: -> # Initialize data req = new XMLHttpRequest() req.open('GET', 'call/init', false) req.send() { @is_admin, @logout_url, @party_data, @server_data, @username } = JSON.parse req.response # Variables backing the group selector @all_groups = ko.observable [] @selected_group = ko.observable('').extend(notify: 'always') @selected_group.subscribe @selected_group_sub # Variables of convenience: a number of sections need only one of these observables @regs_by_name = ko.observable [] @group_regs_by_name = ko.observable [] @nights = @party_data.days[...-1] @reservations_open = @party_data.reservations_enabled or @is_admin # Set up sections @visible_section = ko.observable null @sections = [ @register = new Register this @reservations = new Reservations this @confirmation = new Confirmation this @payment = new Payment this @guest_list = new GuestList this ] @admin_sections = [] if @is_admin @admin_sections = [ @payments = new Payments this @expenses = new Expenses this @credits = new Credits this @registrations = new Registrations this @financials = new Financials this @dietary_info = new DietaryInfo this @other_info = new OtherInfo this @email_list = new EmailList this @phone_list = new PhoneList this ] # Reset sections @reset() # Post method; pass the endpoint and the message to post post_json: (url, message) => message.group = @selected_group() req = new XMLHttpRequest() req.open('POST', url, false) req.send JSON.stringify message { @server_data, error } = JSON.parse req.response @reset() if error window.alert(error + ' (If you think this is a bug, please let us know.)') # Postprocess data after retrieval from the server and reset the sections reset: => # Tag each registration with its name for name, reg of @server_data.registrations reg.name = name # Tag each registration with the nights it's staying and add room, nightly, and meal charges for name, reg of @server_data.registrations reg.credits = [] reg.nights = {} reg._room_charge = 0 for night in @nights for id, group of @party_data.rooms for room in group for bed in room.beds key = night.PI:KEY:<KEY>END_PI + PI:KEY:<KEY>END_PI + bed.PI:KEY:<KEY>END_PI if key of @server_data.reservations name = @server_data.reservations[key] @server_data.registrations[name]._room_charge += bed.costs[night.id] @server_data.registrations[name].nights[night.id] = true for name, reg of @server_data.registrations reg.num_nights = 0 for id, is_reserved of reg.nights if is_reserved reg.num_nights += 1 if reg._room_charge reg.credits.push { amount: -reg._room_charge, category: 'Rooms', date: null } delete reg._room_charge if reg.num_nights reg.credits.push amount: -@party_data.nightly_fee * reg.num_nights category: 'Snacks / Supplies / Space' date: null if not reg.meal_opt_out reg.credits.push amount: -@party_data.meals_fee * reg.num_nights category: 'Meals' date: null # Aid and subsidy charges for name, reg of @server_data.registrations if reg.consolidated reg.credits.push amount: -reg.consolidated, category: 'Consolidated Aid Contribution' date: null if reg.aid reg.credits.push amount: -reg.aid category: 'Financial Assistance' date: null if reg.subsidy reg.credits.push amount: -reg.subsidy category: 'Transport Subsidy' date: null # Credit groups: set up a list of associated credits and a field for the unallocated amount for id, cg of @server_data.credit_groups cg.unallocated = cg.amount cg.id = parseInt id cg.credits = [] # Credits for id, credit of @server_data.credits credit.id = parseInt id @server_data.registrations[credit.name].credits.push credit if credit.credit_group cg = @server_data.credit_groups[credit.credit_group] cg.credits.push credit cg.unallocated -= credit.amount # Sort a few things; sum up the amount due for name, reg of @server_data.registrations reg.due = 0 for credit in reg.credits reg.due -= credit.amount reg.credits = _.sortBy(reg.credits, 'date') for id, cg of @server_data.credit_groups cg.credits = _.sortBy(cg.credits, (x) -> x.name.toLowerCase()) # Set up a particularly useful sorted table @regs_by_name _.sortBy(_.values(@server_data.registrations), (x) -> x.name.toLowerCase()) # Determine the group names and reset the selected group groups = (reg.group for reg in @regs_by_name() when reg.group?) groups.push @server_data.group @all_groups _.sortBy(_.uniq(groups), (x) -> x.toLowerCase()) @selected_group @server_data.group # Refresh handler for things depending on the selected group selected_group_sub: (group) => @group_regs_by_name _.filter(@regs_by_name(), (reg) => reg.group == @selected_group()) # Reset the sections for section in @sections section.reset() for section in @admin_sections section.reset() # Select the earliest non-good non-admin section (but only if we're not on an admin section) dodge_throttle => if @visible_section() not in @admin_sections for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null # Base class for sections class Section # Constructor: pass the parent constructor: (@parent) -> @message = ko.observable '' @status = ko.computed(@get_status).extend(throttle: 25) @status_for_selector = ko.computed @get_status_for_selector # Attempt to make this section visible try_set_visible: => if @status() != 'disabled' @parent.visible_section this true # This allows click events to pass through, e.g. to checkboxes # Get the section status (for coloring and other purposes); often overridden get_status: => 'header' # Get the status for the selector, which considers whether the section is selected or selectable get_status_for_selector: => result = @status() if @parent.visible_section() == this result += ' section_selected' else if @status() != 'disabled' result += ' pointer' result # Reset; often overridden reset: => # Section: registering class Register extends Section label: '1. Register' # Overridden methods constructor: (parent) -> @visible_section = ko.observable null @sections = ko.observableArray [] @add_registration = new AddRegistration(parent, this) super parent reset: => @visible_section null @sections [] for reg in @parent.group_regs_by_name() @sections.push new EditRegistration(@parent, this, reg) @add_registration.reset() # Set a default email, but only on initial load if @parent.group_regs_by_name().length == 0 @add_registration.email @parent.server_data.group # Select the earliest non-good section dodge_throttle => @add_registration.try_set_visible() for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null get_status: => for status in ['changed', 'error'] for section in @sections() if section.status() == status return status if @add_registration.status() == status return status if not @sections().length return 'error' 'good' # A pair of observables for a textbox gated by a checkbox class OptionalEntry # Constructor constructor: -> @checkbox = ko.observable false @text = ko.observable '' # Reset to a given value reset: (value) => @checkbox value.length > 0 @text value # Extract the value value: => if @checkbox() return @text() '' # Subsection: edit registration class EditRegistration extends Section # Overridden methods constructor: (@page, parent, @server_reg) -> # A ton of observables backing the various sections of the registration form @full_name = ko.observable() @phone = ko.observable() @emergency = ko.observable() @meal_opt_out = ko.observable(false) @dietary = new OptionalEntry() @medical = new OptionalEntry() @children = new OptionalEntry() @guest = new OptionalEntry() @reset() super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) @allow_del = true reset: => @full_name @server_reg?.full_name @phone @server_reg?.phone @emergency @server_reg?.emergency @meal_opt_out @server_reg?.meal_opt_out @dietary.reset @server_reg?.dietary @medical.reset @server_reg?.medical @children.reset @server_reg?.children @guest.reset @server_reg?.guest get_status: => if not eq(@full_name(), @server_reg?.full_name) return 'changed' if not eq(@phone(), @server_reg?.phone) return 'changed' if not eq(@emergency(), @server_reg?.emergency) return 'changed' if not eq(@meal_opt_out(), @server_reg?.meal_opt_out) return 'changed' if not eq(@dietary.value(), @server_reg?.dietary) return 'changed' if not eq(@medical.value(), @server_reg?.medical) return 'changed' if not eq(@children.value(), @server_reg?.children) return 'changed' if not eq(@guest.value(), @server_reg?.guest) return 'changed' if not @server_reg.full_name return 'error' @message '' 'good' # Submission methods submit: => message = name: @server_reg.name full_name: @full_name() phone: @phone() emergency: @emergency() meal_opt_out: @meal_opt_out() dietary: @dietary.value() medical: @medical.value() children: @children.value() guest: @guest.value() @page.post_json('call/update_registration', message) # Note that not all fields are required; keep this in sync with the server-side validation code! get_allow_submit: => if not @full_name()?.length @message 'Please enter a full name.' return false if not @phone()?.length @message 'Please enter a phone number.' return false else if not @emergency()?.length @message 'Please provide emergency contact information.' return false @message '' true del: => if window.confirm 'Delete the registration for ' + @server_reg.name + '?' @page.post_json('call/delete_registration', { name: @server_reg.name }) # Subsection: add registration class AddRegistration extends Section # Overridden methods constructor: (@page, parent) -> @name = ko.observable '' @email = ko.observable '' super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => @name '' @email '' get_status: => if @email() or @name() return 'changed' 'good' # Submission methods submit: => @page.post_json('call/create_registration', { name: @name(), email: @email() }) get_allow_submit: => @message '' if @name().length return true if @email() @message 'Please enter a name.' false # Section: reservations class Reservations extends Section label: '2. Reserve Rooms' # Overridden methods constructor: (parent) -> # A map from <night>|<room> ids to ClickableCells (or FixedCells) @cells = {} for night in parent.nights for id, group of parent.party_data.rooms for room in group for bed in room.beds key = PI:KEY:<KEY>END_PI @cells[key] = ko.observable new FixedCell('Loading...', 'bg_xdarkgray') # Status monitoring variables @has_active_reg = ko.observable false @has_unreserved = ko.observable false super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Regenerate the cells values = [null] for reg in @parent.group_regs_by_name() values.push(reg.name) for night in @parent.nights for id, group of @parent.party_data.rooms for room in group for bed in room.beds key = PI:KEY:<KEY>END_PI existing = @parent.server_data.reservations[key] or null # ClickableCells for rooms we can reserve. This happens if: if @parent.reservations_open and # We can reserve things values.length > 1 and # We are attending the party at all night.id of bed.costs and # The room is available existing in values # Nobody else has reserved the room styles = [] for value in values if eq(value, existing) if value style = 'bg_green pointer' else style = 'bg_slate pointer' else style = 'bg_yellow pointer' styles.push style @cells[key] new ClickableCell(values, styles, existing) # FixedCells for rooms we can't reserve. else if existing style = 'bg_purple' else style = 'bg_xdarkgray' @cells[key] new FixedCell(existing, style) # Set monitoring variables has_active_reg = false has_unreserved = false for reg in @parent.group_regs_by_name() has_active_reg = has_active_reg or reg.full_name has_unreserved = has_unreserved or not reg.num_nights @has_active_reg has_active_reg @has_unreserved has_unreserved get_status: => if not @parent.reservations_open @message 'Room reservations are not yet open.' return 'error' if not @has_active_reg() @message 'You have not entered any registrations.' return 'error' for key, cell of @cells if cell().changed?() @message '' return 'changed' if @has_unreserved() @message 'Warning: you have not reserved rooms for one or more people.' return 'error' @message '' 'good' # Submission methods submit: => message = {} for key, cell of @cells if cell().changed?() message[key] = cell().value() @parent.post_json('call/update_reservations', message) get_allow_submit: => @status() == 'changed' # Storage for a table cell which toggles its value when clicked, and can cycle through styles class ClickableCell # Internally this stores state as an index into the various arrays constructor: (@values, @styles, initial) -> @initial = Math.max(@values.indexOf(initial), 0) @selected = ko.observable @initial @value = ko.computed => @values[@selected()] @style = ko.computed => @styles[@selected()] @changed = ko.computed => @selected() != @initial toggle: => @selected((@selected() + 1) % @values.length) # This is a dummy version of ClickableCell which allows the HTML to ignore the fact that some # cells in the reservation table are in fact unclickable class FixedCell constructor: (@value, @style) -> toggle: => # Section: confirmation class Confirmation extends Section label: '3. Confirm' # Overridden methods constructor: (parent) -> @visible_section = ko.observable null @sections = ko.observableArray [] super parent reset: => @visible_section null @sections [] for reg in @parent.group_regs_by_name() if reg.num_nights @sections.push new ConfirmRegistration(@parent, this, reg) # Select the earliest non-good section dodge_throttle => for section in @sections.slice().reverse() if section.status() != 'good' section.try_set_visible() null get_status: => if not @parent.reservations_open or not @sections().length return 'disabled' for status in ['changed', 'error'] for section in @sections() if section.status() == status return status if not @sections().length return 'error' 'good' # Subsection: confirm registration class ConfirmRegistration extends Section # Overridden methods constructor: (@page, parent, @server_reg) -> @consolidated = ko.observable() @subsidy_choice = ko.observable() @subsidy_value = ko.observable() @aid_choice = ko.observable() @aid_value = ko.observable() @aid_pledge = ko.observable() @confirmed = ko.observable() @reset() super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => [subsidy_choice, subsidy_value] = @parse_amt @server_reg.subsidy [aid_choice, aid_value] = @parse_amt @server_reg.aid @consolidated @server_reg.consolidated @subsidy_choice subsidy_choice @subsidy_value subsidy_value @aid_choice aid_choice @aid_value aid_value @aid_pledge @server_reg.aid_pledge @confirmed @server_reg.confirmed get_status: => if not eq(@consolidated(), @server_reg.consolidated) return 'changed' if not eq_strict(@subsidy(), @server_reg.subsidy) return 'changed' if not eq_strict(@aid(), @server_reg.aid) return 'changed' if not eq(@aid_pledge(), @server_reg.aid_pledge) return 'changed' if @confirmed() != @server_reg.confirmed return 'changed' if not @server_reg.confirmed return 'error' 'good' # Submission methods submit: => message = name: @server_reg.name consolidated: parseFloat @consolidated() subsidy: @subsidy() aid: @aid() aid_pledge: if @aid() == 0 then 0 else parseFloat @aid_pledge() confirmed: @confirmed() @page.post_json('call/update_registration', message) get_allow_submit: => if not @consolidated()? or not valid_float(@consolidated()) @message 'Please indicate whether you are contributing to the consolidated aid fund.' return false if not @subsidy()? @message 'Please select a valid transportation subsidy option.' return false if not @aid()? or (@aid_choice() == 'contributing' and not valid_float(@aid_pledge())) @message 'Please select a valid financial assistance option.' return false if not @confirmed() @message 'Please confirm this registration.' return false @message '' true # Utility methods; these impedance-match between server-side floats and our radio-and-blanks parse_amt: (amt) => if amt == 0 return ['none', 0] if amt > 0 return ['contributing', amt] ['requesting', -amt] get_amt: (choice, value) => if choice == 'none' return 0 if not valid_float(value) return null result = parseFloat(value) if choice == 'requesting' result = -result result aid: => @get_amt(@aid_choice(), @aid_value()) subsidy: => @get_amt(@subsidy_choice(), @subsidy_value()) # Section: payment class Payment extends Section label: '4. Payment' # Overridden methods constructor: (parent) -> @due = ko.observable 0 @display_section = ko.computed @get_display_section super parent reset: => due = 0 for reg in @parent.group_regs_by_name() if reg.confirmed due += reg.due @due due get_status: => if not _.any(@parent.group_regs_by_name(), (reg) -> reg.confirmed) return 'disabled' @status_for_due @due() # Helpers for formatting get_display_section: => choose_by_sign(@due(), 'due', 'excess', 'zero') status_for_due: (due) => choose_by_sign(due, 'error', 'error', 'good') total_label: (due) => choose_by_sign(due, 'Amount Due', 'Excess Paid', '') total_style: (due) => choose_by_sign(due, 'bg_yellow', 'bg_purple', 'bg_green') # Section: guest list class GuestList extends Section label: 'Guest List' # Overridden methods constructor: (parent) -> @counts = ko.observable {} super parent reset: => counts = {} for day in @parent.party_data.days count = 0 for reg in @parent.regs_by_name() if reg.nights[day.id] count += 1 counts[day.id] = count @counts counts # Compute the CSS class for a (column, guest name) cell # We have data for nights, but want to display days; hence we care about index - 1 (last night) # and index (tonight). class_for_cell: (index, name) => reg_nights = @parent.server_data.registrations[name].nights last_cell = false if index > 0 last_cell = reg_nights[@parent.party_data.days[index - 1].id] this_cell = reg_nights[@parent.party_data.days[index].id] if last_cell if this_cell return 'bg_green' return 'bg_green_purple' if this_cell return 'bg_purple_green' 'bg_purple' # Shared base class for payments and expenses class CreditGroupBase extends Section # Overridden methods constructor: (parent) -> # Display observables @data = ko.observable [] # Editing observables @selected = ko.observable null @edit_amount = ko.observable '' @edit_credits = ko.observableArray [] @allow_del = @selected super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Pull out the relevant credit groups data = [] for id, cg of @parent.server_data.credit_groups if cg.kind == @cg_kind data.push cg @data _.sortBy(data, 'date').reverse() # Reset the editing section @selected null @edit_amount '' @edit_credits [] @add_edit_credit() get_status: => if @selected()? or @edit_amount() return 'changed' for cg in @data() if Math.abs(cg.unallocated) > 0.005 return 'error' 'good' # Submission methods submit: => credits = [] for credit in @edit_credits() if credit.amount() credits.push amount: parseFloat credit.amount() name: credit.name() category: @credit_category(credit) message = id: @selected()?.id amount: parseFloat @edit_amount() credits: credits kind: @cg_kind details: @cg_details() @parent.post_json('call/admin/record_credit_group', message) get_allow_submit: => if not @edit_amount() @message '' return false if not valid_signed_float @edit_amount() @message 'Cannot parse amount received.' return false net = parseFloat @edit_amount() for credit in @edit_credits() if credit.amount() if not valid_signed_float credit.amount() @message 'Cannot parse amount credited.' return false if not credit.name() @message 'No registration selected.' return false if not @extra_credit_checks_ok(credit) return false net -= parseFloat credit.amount() if Math.abs(net) > 0.005 @message 'Warning: amount not fully allocated.' else if @extra_cg_checks_ok() @message '' true del: => @parent.post_json('call/admin/delete_credit_group', { id: @selected().id }) # Formatting and interaction helpers cg_class: (cg) => if @selected() == cg return 'bg_yellow' if Math.abs(cg.unallocated) > 0.005 return 'bg_red' 'bg_gray' cg_select: (cg) => @selected cg @edit_amount cg.amount @edit_credits [] for credit in cg.credits @add_edit_credit credit if not @edit_credits().length @add_edit_credit() # Admin section: payments class Payments extends CreditGroupBase label: 'Payments' # This is used for sorting the credit groups cg_kind: 'payment' # Overridden methods constructor: (parent) -> @regs = [] @total = ko.observable 0 @edit_from = ko.observable '' @edit_via = ko.observable '' super parent reset: => # Refresh the options list @regs = _.sortBy(@parent.regs_by_name(), (x) -> Math.abs(x.due) < 0.005) @edit_from '' @edit_via '' super() total = 0 for cg in @data() total += cg.amount @total total cg_select: (cg) => super cg @edit_from cg.details.from @edit_via cg.details.via # Dispatch methods cg_details: => { from: @edit_from(), via: @edit_via() } credit_category: (credit) => 'Payment / Refund' extra_credit_checks_ok: (credit) => true extra_cg_checks_ok: => if not @edit_from() @message 'Warning: no entry for whom the payment is from.' return false else if not @edit_via() @message 'Warning: no entry for how the payment was received.' return false true # Required methods add_edit_credit: (credit = null) => @edit_credits.push amount: ko.observable(credit?.amount ? '') name: ko.observable(credit?.name ? '') # Formatter for the dropdown format_reg: (reg) => result = reg.name if Math.abs(reg.due) > 0.005 result += ' - ' + _.dollars(reg.due) + ' due' result # Admin section: expenses class Expenses extends CreditGroupBase label: 'Expenses' # This is used for sorting the credit groups cg_kind: 'expense' # Overridden methods constructor: (parent) -> @edit_description = ko.observable '' super parent reset: => @edit_description '' super() cg_select: (cg) => super cg @edit_description cg.details.description # Dispatch methods cg_details: => { description: @edit_description() } credit_category: (credit) => credit.category() extra_credit_checks_ok: (credit) => if not credit.category() @message 'No category selected.' return false true extra_cg_checks_ok: => if not @edit_description() @message 'Warning: no description of the expense.' return false true # Required methods add_edit_credit: (credit = null) => @edit_credits.push amount: ko.observable(credit?.amount ? '') name: ko.observable(credit?.name ? '') category: ko.observable(credit?.category ? '') # Admin section: credits class Credits extends Section label: 'Misc Credits' # Overridden methods constructor: (parent) -> # Display observables @data = ko.observable [] # Editing observables @selected = ko.observable null @edit_amount = ko.observable '' @edit_name = ko.observable '' @edit_category = ko.observable '' @allow_del = @selected super parent @allow_submit = ko.computed(@get_allow_submit).extend(throttle: 25) reset: => # Pull out the relevant credit groups data = [] for id, credit of @parent.server_data.credits if not credit.credit_group data.push credit @data _.sortBy(data, 'date').reverse() # Refresh the options @selected null @edit_amount '' @edit_name '' @edit_category '' get_status: => if @selected()? or @edit_amount() return 'changed' 'good' # Submission methods submit: => message = id: @selected()?.id amount: parseFloat @edit_amount() name: @edit_name() category: @edit_category() @parent.post_json('call/admin/record_credit', message) get_allow_submit: => if not @edit_amount() @message '' return false if not valid_signed_float @edit_amount() @message 'Cannot parse amount received.' return false if not @edit_name() @message 'No registration selected.' return false if not @edit_category() @message 'No category selected.' return false true del: => @parent.post_json('call/admin/delete_credit', { id: @selected().id }) # Formatting and interaction helpers select: (credit) => @selected credit @edit_amount credit.amount @edit_name credit.name @edit_category credit.category credit_class: (credit) => if @selected() == credit return 'bg_yellow' 'bg_gray' # Admin section: registrations table class Registrations extends Section label: 'Registrations' # Prefixes to total by total_by: [ 'General' 'Consolidated' 'Financial' 'Transport' 'Payment / Refund' 'Expense' 'Other' ] # Overridden methods constructor: (parent) -> @counts = ko.observable {} @data = ko.observable [] super parent reset: => # The "General" prefix is not actually a prefix, so we hack around this general_categories = ['Rooms', 'Snacks / Supplies / Space', 'Meals'] # Generate the counts counts = no_nights: 0 unconfirmed: 0 unpaid: 0 complete: 0 for reg in @parent.regs_by_name() if not reg.num_nights counts.no_nights += 1 else if not reg.confirmed counts.unconfirmed += 1 else if Math.abs(reg.due) > 0.005 counts.unpaid += 1 else counts.complete += 1 @counts counts # Generate the data for the table data = [] sortkey = (x) -> [x.num_nights > 0, x.confirmed, Math.abs(x.due) < 0.005] for reg in _.sortBy(@parent.regs_by_name(), sortkey) totals = {} for category in @total_by totals[category] = 0 for credit in reg.credits prefix = 'Other' if credit.category in general_categories prefix = "General" else for p in @total_by if credit.category[...p.length] == p prefix = p break totals[prefix] -= credit.amount data.push { reg, totals } @data data # Interaction helpers select: ({ reg, totals }) => @parent.selected_group reg.group # Admin section: financial summary class Financials extends Section label: 'Financials' # A table of the credit categories for each section; sections starting with * are hidden surplus_categories: [ ['General Fund', [ 'Rooms' 'Snacks / Supplies / Space' 'Meals' 'Donations' 'Expense: Houses / Hotels' 'Expense: Meals / Snacks / Supplies' 'Expense: Other' 'Adjustment: Rooms' 'Adjustment: Meals' 'Adjustment: Other' ]] ['Aid Funds', [ 'Consolidated Aid Contribution' 'Financial Assistance' 'Transport Subsidy' ]] ['*Net Payments', ['Payment / Refund']] ['Other', ['Expense: Deposits']] ] signed_categories: ['Financial Assistance', 'Transport Subsidy'] # Overridden methods constructor: (parent) -> @data = ko.observable [] @grand_total = ko.observable 0 super parent reset: => # Collect the surpluses surpluses_normal = {} surpluses_signed = {} for category in @signed_categories surpluses_signed[category] = { pos: 0, num_pos: 0, neg: 0, num_neg: 0 } grand_total = 0 for reg in @parent.regs_by_name() for credit in reg.credits if credit.category of surpluses_signed entry = surpluses_signed[credit.category] if credit.amount > 0 entry.neg -= credit.amount entry.num_neg += 1 else if credit.amount < 0 entry.pos -= credit.amount entry.num_pos += 1 else if credit.category not of surpluses_normal surpluses_normal[credit.category] = 0 surpluses_normal[credit.category] -= credit.amount grand_total -= credit.amount @grand_total grand_total # Assemble data for display data = [] for [group, categories] in @surplus_categories values = [] total = 0 for category in categories if category of surpluses_signed entry = surpluses_signed[category] values.push category: category + ': contributions (' + entry.num_pos + ')' amount: entry.pos values.push category: category + ': requests (' + entry.num_neg + ')' amount: entry.neg total += entry.pos + entry.neg else amount = surpluses_normal[category] ? 0 delete surpluses_normal[category] values.push { category, amount } total += amount if not /^\*/.test group data.push { group, values, total } # File any unprocessed categories in the last group. We assume all signed categories are # properly in a group (since that can be verified by simple inspection) for category, amount of surpluses_normal _.last(data).values.push { category, amount } _.last(data).total += amount @data data # Helpers for formatting total_style: (due) => choose_by_sign(due, 'bg_green', 'bg_red', 'bg_gray') # Admin section: dietary information list class DietaryInfo extends Section label: 'Dietary' # Admin section: other information list class OtherInfo extends Section label: 'Other Info' # Admin section: phone list class PhoneList extends Section label: 'Phone List' # Overridden methods constructor: (parent) -> @data = ko.observable [] super parent reset: => by_name = (_.pick(r, 'name', 'phone') for r in @parent.regs_by_name() when r.phone?.length) by_phone = _.sortBy(by_name, (x) -> x.phone.replace(/[^0-9]/g, '')) data = [] for i in [0...by_name.length] data.push [by_name[i].name, by_name[i].phone, by_phone[i].phone, by_phone[i].name] @data data # Admin section: email list class EmailList extends Section label: 'Email List' # Bind the model bind = => ko.applyBindings new PageModel() if document.readyState != 'loading' bind() else document.addEventListener('DOMContentLoaded', bind)
[ { "context": "or k,v of params}\"\n\n rest = (config) ->\n key = createKey(config)\n if config.join and (not config.method", "end": 466, "score": 0.6327545642852783, "start": 457, "tag": "KEY", "value": "createKey" } ]
ModelCatalogueCorePluginTestApp/grails-app/assets/javascripts/modelcatalogue/util/rest.fct.coffee
passionfruit18/ModelCataloguePlugin
0
angular.module('mc.util.rest', ['mc.util.messages', 'mc.util.objectVisitor']).factory 'rest', ($q, $log, $http, $rootScope, $timeout, objectVisitor) -> staleTolerance = 100 # do not request again within this period (ms) pendingRequests = {} createKey = (config) -> method = config.method ? 'GET' url = config.url params = config.params ? {} return "#{method}:#{url}?#{"#{k}=#{v}" for k,v of params}" rest = (config) -> key = createKey(config) if config.join and (not config.method or config.method is 'GET') and pendingRequests.hasOwnProperty(key) return pendingRequests[key] deferred = $q.defer() if config.data config.data = objectVisitor.visit config.data, (value, name) -> unless value? or name in ['__enhancedBy', 'defaultExcludes', 'updatableProperties', 'original', 'availableReports'] return undefined if value and name in ['ext'] return value if angular.isDate(value) or angular.isFunction(value) return value if value and name in ['dataModel', 'classification', 'dataClass', 'measurementUnit', 'dataElement', 'dataType'] and angular.isObject(value) and value.hasOwnProperty('id') return {id: value.id, elementType: value.elementType} return value # for debugging circular references place a breakpoint into the angular.toJson() # seen = []; # seenPlaces = [] # # objectVisitor.visit config.data, (value, name) -> # if value and angular.isObject(value) # return value if angular.isArray(value) and value.length == 0 # if value and name in ['__enhancedBy', 'defaultExcludes', 'updatableProperties', 'original', 'availableReports'] # return value # if angular.isDate(value) or angular.isFunction(value) # return value # idx = seen.indexOf(value) # if idx >= 0 # $log.warn(value, " (", name, ") has been already seen as ", seenPlaces[0]) # seen.push(value) # seenPlaces.push(name) # return value $http(config).then( (response) -> config.statusListener(response.status) if config.statusListener? if !response.data and response.status >=200 and response.status < 300 deferred.resolve response.status else if !response.data.errors? deferred.resolve response.data else deferred.reject response , (response) -> config.statusListener(response.status) if config.statusListener? if response.status is 0 $rootScope.$broadcast 'applicationOffline', response deferred.reject response return if response.status is 404 if config.noRetry404 or config.method isnt 'GET' deferred.reject response return retryNotFound = -> newConfig = angular.copy(config) newConfig.noRetry404 = true rest(newConfig).then (newResult) -> deferred.resolve newResult , (newResponse) -> deferred.reject newResponse $timeout retryNotFound, (if config.retryAfter then config.retryAfter else 1000) return deferred.reject response , (update) -> deferred.update update ).finally -> $timeout((-> delete pendingRequests[key]), staleTolerance) pendingRequests[key] = deferred.promise rest.cleanCache = -> pendingRequests = {} rest.setStaleTolerance = (tolerance) -> staleTolerance = tolerance rest
198652
angular.module('mc.util.rest', ['mc.util.messages', 'mc.util.objectVisitor']).factory 'rest', ($q, $log, $http, $rootScope, $timeout, objectVisitor) -> staleTolerance = 100 # do not request again within this period (ms) pendingRequests = {} createKey = (config) -> method = config.method ? 'GET' url = config.url params = config.params ? {} return "#{method}:#{url}?#{"#{k}=#{v}" for k,v of params}" rest = (config) -> key = <KEY>(config) if config.join and (not config.method or config.method is 'GET') and pendingRequests.hasOwnProperty(key) return pendingRequests[key] deferred = $q.defer() if config.data config.data = objectVisitor.visit config.data, (value, name) -> unless value? or name in ['__enhancedBy', 'defaultExcludes', 'updatableProperties', 'original', 'availableReports'] return undefined if value and name in ['ext'] return value if angular.isDate(value) or angular.isFunction(value) return value if value and name in ['dataModel', 'classification', 'dataClass', 'measurementUnit', 'dataElement', 'dataType'] and angular.isObject(value) and value.hasOwnProperty('id') return {id: value.id, elementType: value.elementType} return value # for debugging circular references place a breakpoint into the angular.toJson() # seen = []; # seenPlaces = [] # # objectVisitor.visit config.data, (value, name) -> # if value and angular.isObject(value) # return value if angular.isArray(value) and value.length == 0 # if value and name in ['__enhancedBy', 'defaultExcludes', 'updatableProperties', 'original', 'availableReports'] # return value # if angular.isDate(value) or angular.isFunction(value) # return value # idx = seen.indexOf(value) # if idx >= 0 # $log.warn(value, " (", name, ") has been already seen as ", seenPlaces[0]) # seen.push(value) # seenPlaces.push(name) # return value $http(config).then( (response) -> config.statusListener(response.status) if config.statusListener? if !response.data and response.status >=200 and response.status < 300 deferred.resolve response.status else if !response.data.errors? deferred.resolve response.data else deferred.reject response , (response) -> config.statusListener(response.status) if config.statusListener? if response.status is 0 $rootScope.$broadcast 'applicationOffline', response deferred.reject response return if response.status is 404 if config.noRetry404 or config.method isnt 'GET' deferred.reject response return retryNotFound = -> newConfig = angular.copy(config) newConfig.noRetry404 = true rest(newConfig).then (newResult) -> deferred.resolve newResult , (newResponse) -> deferred.reject newResponse $timeout retryNotFound, (if config.retryAfter then config.retryAfter else 1000) return deferred.reject response , (update) -> deferred.update update ).finally -> $timeout((-> delete pendingRequests[key]), staleTolerance) pendingRequests[key] = deferred.promise rest.cleanCache = -> pendingRequests = {} rest.setStaleTolerance = (tolerance) -> staleTolerance = tolerance rest
true
angular.module('mc.util.rest', ['mc.util.messages', 'mc.util.objectVisitor']).factory 'rest', ($q, $log, $http, $rootScope, $timeout, objectVisitor) -> staleTolerance = 100 # do not request again within this period (ms) pendingRequests = {} createKey = (config) -> method = config.method ? 'GET' url = config.url params = config.params ? {} return "#{method}:#{url}?#{"#{k}=#{v}" for k,v of params}" rest = (config) -> key = PI:KEY:<KEY>END_PI(config) if config.join and (not config.method or config.method is 'GET') and pendingRequests.hasOwnProperty(key) return pendingRequests[key] deferred = $q.defer() if config.data config.data = objectVisitor.visit config.data, (value, name) -> unless value? or name in ['__enhancedBy', 'defaultExcludes', 'updatableProperties', 'original', 'availableReports'] return undefined if value and name in ['ext'] return value if angular.isDate(value) or angular.isFunction(value) return value if value and name in ['dataModel', 'classification', 'dataClass', 'measurementUnit', 'dataElement', 'dataType'] and angular.isObject(value) and value.hasOwnProperty('id') return {id: value.id, elementType: value.elementType} return value # for debugging circular references place a breakpoint into the angular.toJson() # seen = []; # seenPlaces = [] # # objectVisitor.visit config.data, (value, name) -> # if value and angular.isObject(value) # return value if angular.isArray(value) and value.length == 0 # if value and name in ['__enhancedBy', 'defaultExcludes', 'updatableProperties', 'original', 'availableReports'] # return value # if angular.isDate(value) or angular.isFunction(value) # return value # idx = seen.indexOf(value) # if idx >= 0 # $log.warn(value, " (", name, ") has been already seen as ", seenPlaces[0]) # seen.push(value) # seenPlaces.push(name) # return value $http(config).then( (response) -> config.statusListener(response.status) if config.statusListener? if !response.data and response.status >=200 and response.status < 300 deferred.resolve response.status else if !response.data.errors? deferred.resolve response.data else deferred.reject response , (response) -> config.statusListener(response.status) if config.statusListener? if response.status is 0 $rootScope.$broadcast 'applicationOffline', response deferred.reject response return if response.status is 404 if config.noRetry404 or config.method isnt 'GET' deferred.reject response return retryNotFound = -> newConfig = angular.copy(config) newConfig.noRetry404 = true rest(newConfig).then (newResult) -> deferred.resolve newResult , (newResponse) -> deferred.reject newResponse $timeout retryNotFound, (if config.retryAfter then config.retryAfter else 1000) return deferred.reject response , (update) -> deferred.update update ).finally -> $timeout((-> delete pendingRequests[key]), staleTolerance) pendingRequests[key] = deferred.promise rest.cleanCache = -> pendingRequests = {} rest.setStaleTolerance = (tolerance) -> staleTolerance = tolerance rest
[ { "context": "er [ \n {id:1, age: 12, gender: 0, author: 'John', labels: [1,4,6]},\n {id:2, age: 20, gende", "end": 868, "score": 0.9988235831260681, "start": 864, "tag": "NAME", "value": "John" }, { "context": ",6]},\n {id:2, age: 20, gender: 1, author: 'Bob', l...
test/components/list/filterable_list_test.coffee
pieces-js/pieces-list
0
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List.Filterable", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="filterable" data-pid="test" style="position:relative"> <ul class="list"> <script class="pi-renderer" type="text/html"> <div class='item'>{{ name }} <span class='author'>{{ author }}</span> </div> </script> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') list.data_provider [ {id:1, age: 12, gender: 0, author: 'John', labels: [1,4,6]}, {id:2, age: 20, gender: 1, author: 'Bob', labels: [1,2]}, {id:3, age: 18, gender: 1, author: 'John', labels: [1,3,4]} {id:3, age: 25, gender: 0, author: 'Michael', labels: [1,3,4]} ] afterEach -> test_div.remove() it "filter with one-key object", -> list.filter gender: 0 expect(list.size).to.equal 2 list.filter author: 'John' expect(list.size).to.equal 2 it "filter with continuation", -> list.filter gender: 0 expect(list.size).to.equal 2 list.filter author: 'John', gender: 0 expect(list.size).to.equal 1 it "filter with more/less operands", -> list.filter "age>": 20 expect(list.size).to.equal 2 list.filter "age<": 20, gender: 0 expect(list.size).to.equal 1 list.filter "age<": 20 expect(list.size).to.equal 3 it "filter with any operand", -> list.filter "author?": ['Bob','John'] expect(list.size).to.equal 3 list.filter "author?": ['Bob','John'], gender: 1 expect(list.size).to.equal 2 list.filter "gender?": [0,1] expect(list.size).to.equal 4 it "filter with contains operand", -> list.filter "labels?&": [1,4] expect(list.size).to.equal 3 list.filter "labels?&": [2,3] expect(list.size).to.equal 0 list.filter "labels?&": [3,4] expect(list.size).to.equal 2 it "return all not-removed items on filter stop", -> list.filter gender: 0 expect(list.size).to.equal 2 list.remove_item_at 0 expect(list.size).to.equal 1 list.filter() expect(list.size).to.equal 3 it "refilter after new item added", (done) -> list.filter gender: 0 expect(list.size).to.equal 2 list.on 'update', (e) => return unless e.data.type is 'item_added' expect(list.size).to.equal 3 list.filter() expect(list.size).to.equal 5 done() list.add_item {id:5, age: 12, gender: 0, author: 'Jack'} it "refilter after item updated", (done) -> list.filter gender: 0 expect(list.size).to.equal 2 list.on 'update', (e) => return unless e.data.type is 'item_updated' expect(list.size).to.equal 1 expect(list.all('.item').length).to.equal 1 list.filter() expect(list.size).to.equal 4 done() list.update_item list.items[0], {id:1, age: 20, gender: 1, author: 'Bob'}
110401
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List.Filterable", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="filterable" data-pid="test" style="position:relative"> <ul class="list"> <script class="pi-renderer" type="text/html"> <div class='item'>{{ name }} <span class='author'>{{ author }}</span> </div> </script> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') list.data_provider [ {id:1, age: 12, gender: 0, author: '<NAME>', labels: [1,4,6]}, {id:2, age: 20, gender: 1, author: '<NAME>', labels: [1,2]}, {id:3, age: 18, gender: 1, author: '<NAME>', labels: [1,3,4]} {id:3, age: 25, gender: 0, author: '<NAME>', labels: [1,3,4]} ] afterEach -> test_div.remove() it "filter with one-key object", -> list.filter gender: 0 expect(list.size).to.equal 2 list.filter author: '<NAME>' expect(list.size).to.equal 2 it "filter with continuation", -> list.filter gender: 0 expect(list.size).to.equal 2 list.filter author: '<NAME>', gender: 0 expect(list.size).to.equal 1 it "filter with more/less operands", -> list.filter "age>": 20 expect(list.size).to.equal 2 list.filter "age<": 20, gender: 0 expect(list.size).to.equal 1 list.filter "age<": 20 expect(list.size).to.equal 3 it "filter with any operand", -> list.filter "author?": ['<NAME>','<NAME>'] expect(list.size).to.equal 3 list.filter "author?": ['<NAME>','<NAME>'], gender: 1 expect(list.size).to.equal 2 list.filter "gender?": [0,1] expect(list.size).to.equal 4 it "filter with contains operand", -> list.filter "labels?&": [1,4] expect(list.size).to.equal 3 list.filter "labels?&": [2,3] expect(list.size).to.equal 0 list.filter "labels?&": [3,4] expect(list.size).to.equal 2 it "return all not-removed items on filter stop", -> list.filter gender: 0 expect(list.size).to.equal 2 list.remove_item_at 0 expect(list.size).to.equal 1 list.filter() expect(list.size).to.equal 3 it "refilter after new item added", (done) -> list.filter gender: 0 expect(list.size).to.equal 2 list.on 'update', (e) => return unless e.data.type is 'item_added' expect(list.size).to.equal 3 list.filter() expect(list.size).to.equal 5 done() list.add_item {id:5, age: 12, gender: 0, author: '<NAME>'} it "refilter after item updated", (done) -> list.filter gender: 0 expect(list.size).to.equal 2 list.on 'update', (e) => return unless e.data.type is 'item_updated' expect(list.size).to.equal 1 expect(list.all('.item').length).to.equal 1 list.filter() expect(list.size).to.equal 4 done() list.update_item list.items[0], {id:1, age: 20, gender: 1, author: '<NAME>'}
true
'use strict' h = require 'pieces-list/test/helpers' utils = pi.utils Nod = pi.Nod describe "List.Filterable", -> root = h.test_cont(pi.Nod.body) after -> root.remove() test_div = list = null beforeEach -> test_div = Nod.create('div') test_div.style position:'relative' root.append test_div test_div.append """ <div class="pi test" data-component="list" data-plugins="filterable" data-pid="test" style="position:relative"> <ul class="list"> <script class="pi-renderer" type="text/html"> <div class='item'>{{ name }} <span class='author'>{{ author }}</span> </div> </script> </ul> </div> """ pi.app.view.piecify() list = test_div.find('.test') list.data_provider [ {id:1, age: 12, gender: 0, author: 'PI:NAME:<NAME>END_PI', labels: [1,4,6]}, {id:2, age: 20, gender: 1, author: 'PI:NAME:<NAME>END_PI', labels: [1,2]}, {id:3, age: 18, gender: 1, author: 'PI:NAME:<NAME>END_PI', labels: [1,3,4]} {id:3, age: 25, gender: 0, author: 'PI:NAME:<NAME>END_PI', labels: [1,3,4]} ] afterEach -> test_div.remove() it "filter with one-key object", -> list.filter gender: 0 expect(list.size).to.equal 2 list.filter author: 'PI:NAME:<NAME>END_PI' expect(list.size).to.equal 2 it "filter with continuation", -> list.filter gender: 0 expect(list.size).to.equal 2 list.filter author: 'PI:NAME:<NAME>END_PI', gender: 0 expect(list.size).to.equal 1 it "filter with more/less operands", -> list.filter "age>": 20 expect(list.size).to.equal 2 list.filter "age<": 20, gender: 0 expect(list.size).to.equal 1 list.filter "age<": 20 expect(list.size).to.equal 3 it "filter with any operand", -> list.filter "author?": ['PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI'] expect(list.size).to.equal 3 list.filter "author?": ['PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI'], gender: 1 expect(list.size).to.equal 2 list.filter "gender?": [0,1] expect(list.size).to.equal 4 it "filter with contains operand", -> list.filter "labels?&": [1,4] expect(list.size).to.equal 3 list.filter "labels?&": [2,3] expect(list.size).to.equal 0 list.filter "labels?&": [3,4] expect(list.size).to.equal 2 it "return all not-removed items on filter stop", -> list.filter gender: 0 expect(list.size).to.equal 2 list.remove_item_at 0 expect(list.size).to.equal 1 list.filter() expect(list.size).to.equal 3 it "refilter after new item added", (done) -> list.filter gender: 0 expect(list.size).to.equal 2 list.on 'update', (e) => return unless e.data.type is 'item_added' expect(list.size).to.equal 3 list.filter() expect(list.size).to.equal 5 done() list.add_item {id:5, age: 12, gender: 0, author: 'PI:NAME:<NAME>END_PI'} it "refilter after item updated", (done) -> list.filter gender: 0 expect(list.size).to.equal 2 list.on 'update', (e) => return unless e.data.type is 'item_updated' expect(list.size).to.equal 1 expect(list.all('.item').length).to.equal 1 list.filter() expect(list.size).to.equal 4 done() list.update_item list.items[0], {id:1, age: 20, gender: 1, author: 'PI:NAME:<NAME>END_PI'}
[ { "context": "###\nLayer filter effect\n\n@auther threeword (dev@threeword.com)\n@since 2016.07.08\n###\nMateria", "end": 42, "score": 0.9977370500564575, "start": 33, "tag": "USERNAME", "value": "threeword" }, { "context": "###\nLayer filter effect\n\n@auther threeword (dev@threewor...
framer/backups/backup-2016-07-10 22.42.26.coffee
framer-modules/layer-filter.framer
1
### Layer filter effect @auther threeword (dev@threeword.com) @since 2016.07.08 ### MaterialColor = require "MaterialColor" COLOR = Red: { DEFAULT: "#F44336" } # Constant DEFINED = COLORS: { DEFAULT: "rgba(85,85,85,1.0)", ACCENT: "rgba(51,176,247,1.0)" } STATES: { SHOW: "show", DISMISS: "dismiss", DEFAULT: "default"} FONT: Utils.deviceFont() # See the filter value as possible in the Layers filtersRefer = new Layer visible: false # Filters Filters = Brightness: { default: filtersRefer.brightness, min:0 ,max: 1000 } , Saturate: { default: filtersRefer.saturate, min:0 ,max: 100 } , HueRotate: { default: filtersRefer.hueRotate, min:0 ,max: 360 } , Contrast: { default: filtersRefer.contrast, min:0 ,max: 100 } , Invert: { default: filtersRefer.invert, min:0 ,max: 100 } , Grayscale: { default: filtersRefer.grayscale, min:0 ,max: 100 } , Sepia: { default: filtersRefer.sepia, min:0 ,max: 100 } # Background new BackgroundLayer color: 'white' # Flexable body canvasWidth = 750; canvasHeight = 1334; ratio= Screen.width / canvasWidth ratioWidth = canvasWidth; ratioHeight = canvasHeight - (Math.abs((canvasHeight * ratio) - Screen.height))/ratio body = new Layer width: ratioWidth, height: ratioHeight, scale: ratio, originX: 0, originY: 0, backgroundColor: '' # Image Area box box = new Layer name: 'box', parent: body , x: Align.center , width: body.width, height: body.height-700 # Image image = new Layer name: 'image', parent: box , x: Align.center, y: Align.center , width: 192, height: 192 , image: "images/icon-192.png" , backgroundColor: '', color: 'white' # Button : Set default value defaultBtn = new Layer name: 'defaultBtn', parent: body , x: Align.left(20), y: Align.top(20) , width: 200, height: 80 , borderRadius: 20 , backgroundColor: DEFINED.COLORS.ACCENT , html: "Set default", style: { color:"#fff", textAlign:"center", font: "bolder 30px/80px #{DEFINED.FONT}", letterSpacing:"-1px"} defaultBtn.onClick -> slider.animateToValue Filters[slider.name.split("_")[1]].default, curve: "spring(500,50,0)" for slider in sliders # Bubble : Animation : End bubbleAnimationEnd = (animation, layer) -> layer.animate properties: { rotation: 0 }, curve: "spring(100,10,10)" count = 0; sliders = [] for key, value of Filters labelNslider = new Layer name: 'labelNslider', parent: body , y: Align.bottom(100 * (count++) - (100 * 6)) , width: body.width, height: 100 , backgroundColor: '' # Label new Layer name: "label_#{key}", parent: labelNslider , x: Align.right(-540), y: Align.center , width: 210, height: 50 , backgroundColor: '' , html: "#{key}", style: { color: DEFINED.COLORS.DEFAULT, textAlign:"right", font: "500 32px/50px #{DEFINED.FONT}", letterSpacing:"-1px"} # Slider slider = new SliderComponent name: "slider_#{key}", parent: labelNslider , x: Align.right(-50), y: Align.center , width: 430, height: 6 , knobSize: 60 , backgroundColor: "rgba(0,0,0,0.1)" , min: value.min, max: value.max, value: 0 sliders.push(slider) slider.animateToValue value.default, curve: "spring(500,50,0)" # Slider : Knob slider.knob.props = scale: .8, borderRadius: "100%" , borderColor: DEFINED.COLORS.DEFAULT , borderWidth: 5 , boxShadow: "0 2px 0 rgba(0,0,0,0.1), 0 2px 5px rgba(0,0,0,0.3)" , backgroundColor: 'white' slider.knob.draggable.momentum = false # Slider : Fill slider.fill.props = { backgroundColor: DEFINED.COLORS.DEFAULT } slider.fill.states.add "#{DEFINED.STATES.SHOW}": { backgroundColor: DEFINED.COLORS.ACCENT }, "#{DEFINED.STATES.DISMISS}": { backgroundColor: DEFINED.COLORS.DEFAULT } # Value bubble bubble = new Layer name: 'bubble' , x: Align.center, maxY: slider.knob.y + 25 , width: 100, height: 120 , parent: slider.knob , image: "images/bubble.png" , scale: 0, originX:.5, originY: 1 , style: { color: "#fff", textAlign: "center", font: "bold 38px/100px #{DEFINED.FONT}", letterSpacing:"-2px"} , rotation: 0 # Value bubble : States bubble.states.add "#{DEFINED.STATES.SHOW}": { scale: 1 }, "#{DEFINED.STATES.DISMISS}": { scale: 0 } # Slider : Event : Drag knob slider.knob.onDragStart -> this.animate properties: { scale: 1, borderColor: DEFINED.COLORS.ACCENT, borderWidth: 8 }, curve: "spring(400,30,0)" this.children[0].states.switch DEFINED.STATES.SHOW, curve: "spring(100,10,10)" this.parent.fill.states.switchInstant DEFINED.STATES.SHOW this.parent.parent.children[0].color = DEFINED.COLORS.ACCENT slider.knob.onMove -> this.children[0].animate properties: { rotation: Utils.modulate(this.draggable.velocity.x, [-2.0, 2.0], [60, -60], true) } , curve: "ease", time: .1 this.children[0].off Events.AnimationEnd, bubbleAnimationEnd this.children[0].on Events.AnimationEnd, bubbleAnimationEnd slider.knob.onDragEnd -> this.animate properties: { scale: .8, borderColor: DEFINED.COLORS.DEFAULT, borderWidth: 5}, curve: "spring(400,30,0)" this.children[0].states.switch DEFINED.STATES.DISMISS, curve: "spring(500,50,0)" this.parent.fill.states.switchInstant DEFINED.STATES.DISMISS this.parent.parent.children[0].color = DEFINED.COLORS.DEFAULT # Silder : Event : Change value slider.onValueChange -> filter = this.name.split("_")[1].toLowerCase() image[filter] = this.value this.knob.children[0].html = parseInt(this.value)
39687
### Layer filter effect @auther threeword (<EMAIL>) @since 2016.07.08 ### MaterialColor = require "MaterialColor" COLOR = Red: { DEFAULT: "#F44336" } # Constant DEFINED = COLORS: { DEFAULT: "rgba(85,85,85,1.0)", ACCENT: "rgba(51,176,247,1.0)" } STATES: { SHOW: "show", DISMISS: "dismiss", DEFAULT: "default"} FONT: Utils.deviceFont() # See the filter value as possible in the Layers filtersRefer = new Layer visible: false # Filters Filters = Brightness: { default: filtersRefer.brightness, min:0 ,max: 1000 } , Saturate: { default: filtersRefer.saturate, min:0 ,max: 100 } , HueRotate: { default: filtersRefer.hueRotate, min:0 ,max: 360 } , Contrast: { default: filtersRefer.contrast, min:0 ,max: 100 } , Invert: { default: filtersRefer.invert, min:0 ,max: 100 } , Grayscale: { default: filtersRefer.grayscale, min:0 ,max: 100 } , Sepia: { default: filtersRefer.sepia, min:0 ,max: 100 } # Background new BackgroundLayer color: 'white' # Flexable body canvasWidth = 750; canvasHeight = 1334; ratio= Screen.width / canvasWidth ratioWidth = canvasWidth; ratioHeight = canvasHeight - (Math.abs((canvasHeight * ratio) - Screen.height))/ratio body = new Layer width: ratioWidth, height: ratioHeight, scale: ratio, originX: 0, originY: 0, backgroundColor: '' # Image Area box box = new Layer name: 'box', parent: body , x: Align.center , width: body.width, height: body.height-700 # Image image = new Layer name: 'image', parent: box , x: Align.center, y: Align.center , width: 192, height: 192 , image: "images/icon-192.png" , backgroundColor: '', color: 'white' # Button : Set default value defaultBtn = new Layer name: 'defaultBtn', parent: body , x: Align.left(20), y: Align.top(20) , width: 200, height: 80 , borderRadius: 20 , backgroundColor: DEFINED.COLORS.ACCENT , html: "Set default", style: { color:"#fff", textAlign:"center", font: "bolder 30px/80px #{DEFINED.FONT}", letterSpacing:"-1px"} defaultBtn.onClick -> slider.animateToValue Filters[slider.name.split("_")[1]].default, curve: "spring(500,50,0)" for slider in sliders # Bubble : Animation : End bubbleAnimationEnd = (animation, layer) -> layer.animate properties: { rotation: 0 }, curve: "spring(100,10,10)" count = 0; sliders = [] for key, value of Filters labelNslider = new Layer name: 'labelNslider', parent: body , y: Align.bottom(100 * (count++) - (100 * 6)) , width: body.width, height: 100 , backgroundColor: '' # Label new Layer name: "label_#{key}", parent: labelNslider , x: Align.right(-540), y: Align.center , width: 210, height: 50 , backgroundColor: '' , html: "#{key}", style: { color: DEFINED.COLORS.DEFAULT, textAlign:"right", font: "500 32px/50px #{DEFINED.FONT}", letterSpacing:"-1px"} # Slider slider = new SliderComponent name: "slider_#{key}", parent: labelNslider , x: Align.right(-50), y: Align.center , width: 430, height: 6 , knobSize: 60 , backgroundColor: "rgba(0,0,0,0.1)" , min: value.min, max: value.max, value: 0 sliders.push(slider) slider.animateToValue value.default, curve: "spring(500,50,0)" # Slider : Knob slider.knob.props = scale: .8, borderRadius: "100%" , borderColor: DEFINED.COLORS.DEFAULT , borderWidth: 5 , boxShadow: "0 2px 0 rgba(0,0,0,0.1), 0 2px 5px rgba(0,0,0,0.3)" , backgroundColor: 'white' slider.knob.draggable.momentum = false # Slider : Fill slider.fill.props = { backgroundColor: DEFINED.COLORS.DEFAULT } slider.fill.states.add "#{DEFINED.STATES.SHOW}": { backgroundColor: DEFINED.COLORS.ACCENT }, "#{DEFINED.STATES.DISMISS}": { backgroundColor: DEFINED.COLORS.DEFAULT } # Value bubble bubble = new Layer name: 'bubble' , x: Align.center, maxY: slider.knob.y + 25 , width: 100, height: 120 , parent: slider.knob , image: "images/bubble.png" , scale: 0, originX:.5, originY: 1 , style: { color: "#fff", textAlign: "center", font: "bold 38px/100px #{DEFINED.FONT}", letterSpacing:"-2px"} , rotation: 0 # Value bubble : States bubble.states.add "#{DEFINED.STATES.SHOW}": { scale: 1 }, "#{DEFINED.STATES.DISMISS}": { scale: 0 } # Slider : Event : Drag knob slider.knob.onDragStart -> this.animate properties: { scale: 1, borderColor: DEFINED.COLORS.ACCENT, borderWidth: 8 }, curve: "spring(400,30,0)" this.children[0].states.switch DEFINED.STATES.SHOW, curve: "spring(100,10,10)" this.parent.fill.states.switchInstant DEFINED.STATES.SHOW this.parent.parent.children[0].color = DEFINED.COLORS.ACCENT slider.knob.onMove -> this.children[0].animate properties: { rotation: Utils.modulate(this.draggable.velocity.x, [-2.0, 2.0], [60, -60], true) } , curve: "ease", time: .1 this.children[0].off Events.AnimationEnd, bubbleAnimationEnd this.children[0].on Events.AnimationEnd, bubbleAnimationEnd slider.knob.onDragEnd -> this.animate properties: { scale: .8, borderColor: DEFINED.COLORS.DEFAULT, borderWidth: 5}, curve: "spring(400,30,0)" this.children[0].states.switch DEFINED.STATES.DISMISS, curve: "spring(500,50,0)" this.parent.fill.states.switchInstant DEFINED.STATES.DISMISS this.parent.parent.children[0].color = DEFINED.COLORS.DEFAULT # Silder : Event : Change value slider.onValueChange -> filter = this.name.split("_")[1].toLowerCase() image[filter] = this.value this.knob.children[0].html = parseInt(this.value)
true
### Layer filter effect @auther threeword (PI:EMAIL:<EMAIL>END_PI) @since 2016.07.08 ### MaterialColor = require "MaterialColor" COLOR = Red: { DEFAULT: "#F44336" } # Constant DEFINED = COLORS: { DEFAULT: "rgba(85,85,85,1.0)", ACCENT: "rgba(51,176,247,1.0)" } STATES: { SHOW: "show", DISMISS: "dismiss", DEFAULT: "default"} FONT: Utils.deviceFont() # See the filter value as possible in the Layers filtersRefer = new Layer visible: false # Filters Filters = Brightness: { default: filtersRefer.brightness, min:0 ,max: 1000 } , Saturate: { default: filtersRefer.saturate, min:0 ,max: 100 } , HueRotate: { default: filtersRefer.hueRotate, min:0 ,max: 360 } , Contrast: { default: filtersRefer.contrast, min:0 ,max: 100 } , Invert: { default: filtersRefer.invert, min:0 ,max: 100 } , Grayscale: { default: filtersRefer.grayscale, min:0 ,max: 100 } , Sepia: { default: filtersRefer.sepia, min:0 ,max: 100 } # Background new BackgroundLayer color: 'white' # Flexable body canvasWidth = 750; canvasHeight = 1334; ratio= Screen.width / canvasWidth ratioWidth = canvasWidth; ratioHeight = canvasHeight - (Math.abs((canvasHeight * ratio) - Screen.height))/ratio body = new Layer width: ratioWidth, height: ratioHeight, scale: ratio, originX: 0, originY: 0, backgroundColor: '' # Image Area box box = new Layer name: 'box', parent: body , x: Align.center , width: body.width, height: body.height-700 # Image image = new Layer name: 'image', parent: box , x: Align.center, y: Align.center , width: 192, height: 192 , image: "images/icon-192.png" , backgroundColor: '', color: 'white' # Button : Set default value defaultBtn = new Layer name: 'defaultBtn', parent: body , x: Align.left(20), y: Align.top(20) , width: 200, height: 80 , borderRadius: 20 , backgroundColor: DEFINED.COLORS.ACCENT , html: "Set default", style: { color:"#fff", textAlign:"center", font: "bolder 30px/80px #{DEFINED.FONT}", letterSpacing:"-1px"} defaultBtn.onClick -> slider.animateToValue Filters[slider.name.split("_")[1]].default, curve: "spring(500,50,0)" for slider in sliders # Bubble : Animation : End bubbleAnimationEnd = (animation, layer) -> layer.animate properties: { rotation: 0 }, curve: "spring(100,10,10)" count = 0; sliders = [] for key, value of Filters labelNslider = new Layer name: 'labelNslider', parent: body , y: Align.bottom(100 * (count++) - (100 * 6)) , width: body.width, height: 100 , backgroundColor: '' # Label new Layer name: "label_#{key}", parent: labelNslider , x: Align.right(-540), y: Align.center , width: 210, height: 50 , backgroundColor: '' , html: "#{key}", style: { color: DEFINED.COLORS.DEFAULT, textAlign:"right", font: "500 32px/50px #{DEFINED.FONT}", letterSpacing:"-1px"} # Slider slider = new SliderComponent name: "slider_#{key}", parent: labelNslider , x: Align.right(-50), y: Align.center , width: 430, height: 6 , knobSize: 60 , backgroundColor: "rgba(0,0,0,0.1)" , min: value.min, max: value.max, value: 0 sliders.push(slider) slider.animateToValue value.default, curve: "spring(500,50,0)" # Slider : Knob slider.knob.props = scale: .8, borderRadius: "100%" , borderColor: DEFINED.COLORS.DEFAULT , borderWidth: 5 , boxShadow: "0 2px 0 rgba(0,0,0,0.1), 0 2px 5px rgba(0,0,0,0.3)" , backgroundColor: 'white' slider.knob.draggable.momentum = false # Slider : Fill slider.fill.props = { backgroundColor: DEFINED.COLORS.DEFAULT } slider.fill.states.add "#{DEFINED.STATES.SHOW}": { backgroundColor: DEFINED.COLORS.ACCENT }, "#{DEFINED.STATES.DISMISS}": { backgroundColor: DEFINED.COLORS.DEFAULT } # Value bubble bubble = new Layer name: 'bubble' , x: Align.center, maxY: slider.knob.y + 25 , width: 100, height: 120 , parent: slider.knob , image: "images/bubble.png" , scale: 0, originX:.5, originY: 1 , style: { color: "#fff", textAlign: "center", font: "bold 38px/100px #{DEFINED.FONT}", letterSpacing:"-2px"} , rotation: 0 # Value bubble : States bubble.states.add "#{DEFINED.STATES.SHOW}": { scale: 1 }, "#{DEFINED.STATES.DISMISS}": { scale: 0 } # Slider : Event : Drag knob slider.knob.onDragStart -> this.animate properties: { scale: 1, borderColor: DEFINED.COLORS.ACCENT, borderWidth: 8 }, curve: "spring(400,30,0)" this.children[0].states.switch DEFINED.STATES.SHOW, curve: "spring(100,10,10)" this.parent.fill.states.switchInstant DEFINED.STATES.SHOW this.parent.parent.children[0].color = DEFINED.COLORS.ACCENT slider.knob.onMove -> this.children[0].animate properties: { rotation: Utils.modulate(this.draggable.velocity.x, [-2.0, 2.0], [60, -60], true) } , curve: "ease", time: .1 this.children[0].off Events.AnimationEnd, bubbleAnimationEnd this.children[0].on Events.AnimationEnd, bubbleAnimationEnd slider.knob.onDragEnd -> this.animate properties: { scale: .8, borderColor: DEFINED.COLORS.DEFAULT, borderWidth: 5}, curve: "spring(400,30,0)" this.children[0].states.switch DEFINED.STATES.DISMISS, curve: "spring(500,50,0)" this.parent.fill.states.switchInstant DEFINED.STATES.DISMISS this.parent.parent.children[0].color = DEFINED.COLORS.DEFAULT # Silder : Event : Change value slider.onValueChange -> filter = this.name.split("_")[1].toLowerCase() image[filter] = this.value this.knob.children[0].html = parseInt(this.value)
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.999912440776825, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/_components/big-button.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 { a, button, span, i } from 'react-dom-factories' import { Spinner } from 'spinner' el = React.createElement export BigButton = ({modifiers = [], text, icon, props = {}, extraClasses = [], isBusy = false}) -> props.className = osu.classWithModifiers('btn-osu-big', modifiers) props.className += " #{klass}" for klass in extraClasses blockElement = if props.href? if props.disabled span else a else button blockElement props, span className: "btn-osu-big__content #{if !text? || !icon? then 'btn-osu-big__content--center' else ''}", if text? span className: 'btn-osu-big__left', span className: 'btn-osu-big__text-top', text.top ? text if text.bottom? span className: 'btn-osu-big__text-bottom', text.bottom if icon? span className: 'btn-osu-big__icon', # ensure no random width change when changing icon span className: 'fa-fw', if isBusy el Spinner else i className: icon
24828
# 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 { a, button, span, i } from 'react-dom-factories' import { Spinner } from 'spinner' el = React.createElement export BigButton = ({modifiers = [], text, icon, props = {}, extraClasses = [], isBusy = false}) -> props.className = osu.classWithModifiers('btn-osu-big', modifiers) props.className += " #{klass}" for klass in extraClasses blockElement = if props.href? if props.disabled span else a else button blockElement props, span className: "btn-osu-big__content #{if !text? || !icon? then 'btn-osu-big__content--center' else ''}", if text? span className: 'btn-osu-big__left', span className: 'btn-osu-big__text-top', text.top ? text if text.bottom? span className: 'btn-osu-big__text-bottom', text.bottom if icon? span className: 'btn-osu-big__icon', # ensure no random width change when changing icon span className: 'fa-fw', if isBusy el Spinner else i className: icon
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 { a, button, span, i } from 'react-dom-factories' import { Spinner } from 'spinner' el = React.createElement export BigButton = ({modifiers = [], text, icon, props = {}, extraClasses = [], isBusy = false}) -> props.className = osu.classWithModifiers('btn-osu-big', modifiers) props.className += " #{klass}" for klass in extraClasses blockElement = if props.href? if props.disabled span else a else button blockElement props, span className: "btn-osu-big__content #{if !text? || !icon? then 'btn-osu-big__content--center' else ''}", if text? span className: 'btn-osu-big__left', span className: 'btn-osu-big__text-top', text.top ? text if text.bottom? span className: 'btn-osu-big__text-bottom', text.bottom if icon? span className: 'btn-osu-big__icon', # ensure no random width change when changing icon span className: 'fa-fw', if isBusy el Spinner else i className: icon
[ { "context": "v.HUBOT_FLOWDOCK_LOGIN_EMAIL\n login_password: process.env.HUBOT_FLOWDOCK_LOGIN_PASSWORD\n\n bot = new flowdock.Session(options.login_ema", "end": 494, "score": 0.8669915199279785, "start": 453, "tag": "PASSWORD", "value": "process.env.HUBOT_FLOWDOCK_LOGIN_PASSWORD" }...
src/adapters/flowdock.coffee
ivey/hubot
1
Robot = require "../robot" flowdock = require "flowdock" class Flowdock extends Robot.Adapter send: (user, strings...) -> strings.forEach (str) => @bot.chatMessage(user.flow.subdomain, user.flow.name, str) reply: (user, strings...) -> strings.forEach (str) => @send user, "#{user.name}: #{str}" run: -> self = @ options = login_email: process.env.HUBOT_FLOWDOCK_LOGIN_EMAIL login_password: process.env.HUBOT_FLOWDOCK_LOGIN_PASSWORD bot = new flowdock.Session(options.login_email, options.login_password) bot.fetchFlows((flows) => flows.forEach (flow) => bot.fetchUsers(flow.organization.subdomain, flow.slug, (users) => users.forEach (flow_user) => return if flow_user.user.disabled == true user = id: flow_user.user.id name: flow_user.user.nick @userForId(user.id, user) ) bot.subscribe(flow.organization.subdomain, flow.slug) ) bot.on "message", (message) => return unless message.event == 'message' flow = bot.flows.filter((flow) -> return flow.name == message.flow)[0] author = @userForId(message.user) return if @name == author.name author.flow = flow self.receive new Robot.TextMessage(author, message.content) @bot = bot module.exports = Flowdock
144632
Robot = require "../robot" flowdock = require "flowdock" class Flowdock extends Robot.Adapter send: (user, strings...) -> strings.forEach (str) => @bot.chatMessage(user.flow.subdomain, user.flow.name, str) reply: (user, strings...) -> strings.forEach (str) => @send user, "#{user.name}: #{str}" run: -> self = @ options = login_email: process.env.HUBOT_FLOWDOCK_LOGIN_EMAIL login_password: <PASSWORD> bot = new flowdock.Session(options.login_email, options.login_password) bot.fetchFlows((flows) => flows.forEach (flow) => bot.fetchUsers(flow.organization.subdomain, flow.slug, (users) => users.forEach (flow_user) => return if flow_user.user.disabled == true user = id: flow_user.user.id name: flow_user.user.nick @userForId(user.id, user) ) bot.subscribe(flow.organization.subdomain, flow.slug) ) bot.on "message", (message) => return unless message.event == 'message' flow = bot.flows.filter((flow) -> return flow.name == message.flow)[0] author = @userForId(message.user) return if @name == author.name author.flow = flow self.receive new Robot.TextMessage(author, message.content) @bot = bot module.exports = Flowdock
true
Robot = require "../robot" flowdock = require "flowdock" class Flowdock extends Robot.Adapter send: (user, strings...) -> strings.forEach (str) => @bot.chatMessage(user.flow.subdomain, user.flow.name, str) reply: (user, strings...) -> strings.forEach (str) => @send user, "#{user.name}: #{str}" run: -> self = @ options = login_email: process.env.HUBOT_FLOWDOCK_LOGIN_EMAIL login_password: PI:PASSWORD:<PASSWORD>END_PI bot = new flowdock.Session(options.login_email, options.login_password) bot.fetchFlows((flows) => flows.forEach (flow) => bot.fetchUsers(flow.organization.subdomain, flow.slug, (users) => users.forEach (flow_user) => return if flow_user.user.disabled == true user = id: flow_user.user.id name: flow_user.user.nick @userForId(user.id, user) ) bot.subscribe(flow.organization.subdomain, flow.slug) ) bot.on "message", (message) => return unless message.event == 'message' flow = bot.flows.filter((flow) -> return flow.name == message.flow)[0] author = @userForId(message.user) return if @name == author.name author.flow = flow self.receive new Robot.TextMessage(author, message.content) @bot = bot module.exports = Flowdock
[ { "context": "'\n 'Maltese'\n 'Manatee'\n 'Mandrill'\n 'Markhor'\n 'Mastiff'\n 'Mayfly'\n 'Meerkat'\n 'Mi", "end": 2286, "score": 0.5920019149780273, "start": 2279, "tag": "NAME", "value": "Markhor" }, { "context": "alrus'\n 'Warthog'\n 'Wasp'\n 'Weas...
coffeescript/public/js/services/animals.coffee
purple-circle/chat
0
app = angular.module('app') app.service 'animals', -> animals = [ 'Abyssinian' 'Affenpinscher' 'Akbash' 'Akita' 'Albatross' 'Alligator' 'Angelfish' 'Ant' 'Anteater' 'Antelope' 'Armadillo' 'Avocet' 'Axolotl' 'Baboon' 'Badger' 'Balinese' 'Bandicoot' 'Barb' 'Barnacle' 'Barracuda' 'Bat' 'Beagle' 'Bear' 'Beaver' 'Beetle' 'Binturong' 'Bird' 'Birman' 'Bison' 'Bloodhound' 'Bobcat' 'Bombay' 'Bongo' 'Bonobo' 'Booby' 'Budgerigar' 'Buffalo' 'Bulldog' 'Bullfrog' 'Burmese' 'Butterfly' 'Caiman' 'Camel' 'Capybara' 'Caracal' 'Cassowary' 'Cat' 'Caterpillar' 'Catfish' 'Centipede' 'Chameleon' 'Chamois' 'Cheetah' 'Chicken' 'Chihuahua' 'Chimpanzee' 'Chinchilla' 'Chinook' 'Chipmunk' 'Cichlid' 'Coati' 'Cockroach' 'Collie' 'Coral' 'Cougar' 'Cow' 'Coyote' 'Crab' 'Crane' 'Crocodile' 'Cuscus' 'Cuttlefish' 'Dachshund' 'Dalmatian' 'Deer' 'Dhole' 'Dingo' 'Discus' 'Dodo' 'Dog' 'Dolphin' 'Donkey' 'Dormouse' 'Dragonfly' 'Drever' 'Duck' 'Dugong' 'Dunker' 'Eagle' 'Earwig' 'Echidna' 'Elephant' 'Emu' 'Falcon' 'Ferret' 'Fish' 'Flamingo' 'Flounder' 'Fly' 'Fossa' 'Fox' 'Frigatebird' 'Frog' 'Gar' 'Gecko' 'Gerbil' 'Gharial' 'Gibbon' 'Giraffe' 'Goat' 'Goose' 'Gopher' 'Gorilla' 'Grasshopper' 'Eater' 'Greyhound' 'Grouse' 'Guppy' 'Hamster' 'Hare' 'Harrier' 'Havanese' 'Hedgehog' 'Heron' 'Himalayan' 'Hippopotamus' 'Horse' 'Human' 'Hummingbird' 'Hyena' 'Ibis' 'Iguana' 'Impala' 'Indri' 'Insect' 'Jackal' 'Jaguar' 'Javanese' 'Jellyfish' 'Kakapo' 'Kangaroo' 'Kingfisher' 'Kiwi' 'Koala' 'Kudu' 'Labradoodle' 'Ladybird' 'Lemming' 'Lemur' 'Leopard' 'Liger' 'Lion' 'Lionfish' 'Lizard' 'Llama' 'Lobster' 'Lynx' 'Macaw' 'Magpie' 'Maltese' 'Manatee' 'Mandrill' 'Markhor' 'Mastiff' 'Mayfly' 'Meerkat' 'Millipede' 'Mole' 'Molly' 'Mongoose' 'Mongrel' 'Monkey' 'Moorhen' 'Moose' 'Moth' 'Mouse' 'Mule' 'Neanderthal' 'Newfoundland' 'Newt' 'Nightingale' 'Numbat' 'Ocelot' 'Octopus' 'Okapi' 'Olm' 'Opossum' 'utan' 'Ostrich' 'Otter' 'Oyster' 'Pademelon' 'Panther' 'Parrot' 'Peacock' 'Pekingese' 'Pelican' 'Penguin' 'Persian' 'Pheasant' 'Pig' 'Pika' 'Pike' 'Piranha' 'Platypus' 'Pointer' 'Poodle' 'Porcupine' 'Possum' 'Prawn' 'Puffin' 'Pug' 'Puma' 'Quail' 'Quetzal' 'Quokka' 'Quoll' 'Rabbit' 'Raccoon' 'Ragdoll' 'Rat' 'Rattlesnake' 'Reindeer' 'Rhinoceros' 'Robin' 'Rottweiler' 'Salamander' 'Saola' 'Scorpion' 'Seahorse' 'Seal' 'Serval' 'Sheep' 'Shrimp' 'Skunk' 'Sloth' 'Snail' 'Snake' 'Snowshoe' 'Sparrow' 'Sponge' 'Squid' 'Squirrel' 'Starfish' 'Stingray' 'Stoat' 'Swan' 'Tang' 'Tapir' 'Tarsier' 'Termite' 'Tetra' 'Tiffany' 'Tiger' 'Tortoise' 'Toucan' 'Tropicbird' 'Tuatara' 'Turkey' 'Uakari' 'Uguisu' 'Umbrellabird' 'Vulture' 'Wallaby' 'Walrus' 'Warthog' 'Wasp' 'Weasel' 'Whippet' 'Wildebeest' 'Wolf' 'Wolverine' 'Wombat' 'Woodlouse' 'Woodpecker' 'Wrasse' 'Yak' 'Zebra' 'Zebu' 'Zonkey' 'Zorse' ] getRandom: -> animals[Math.floor(Math.random() * animals.length)]
34763
app = angular.module('app') app.service 'animals', -> animals = [ 'Abyssinian' 'Affenpinscher' 'Akbash' 'Akita' 'Albatross' 'Alligator' 'Angelfish' 'Ant' 'Anteater' 'Antelope' 'Armadillo' 'Avocet' 'Axolotl' 'Baboon' 'Badger' 'Balinese' 'Bandicoot' 'Barb' 'Barnacle' 'Barracuda' 'Bat' 'Beagle' 'Bear' 'Beaver' 'Beetle' 'Binturong' 'Bird' 'Birman' 'Bison' 'Bloodhound' 'Bobcat' 'Bombay' 'Bongo' 'Bonobo' 'Booby' 'Budgerigar' 'Buffalo' 'Bulldog' 'Bullfrog' 'Burmese' 'Butterfly' 'Caiman' 'Camel' 'Capybara' 'Caracal' 'Cassowary' 'Cat' 'Caterpillar' 'Catfish' 'Centipede' 'Chameleon' 'Chamois' 'Cheetah' 'Chicken' 'Chihuahua' 'Chimpanzee' 'Chinchilla' 'Chinook' 'Chipmunk' 'Cichlid' 'Coati' 'Cockroach' 'Collie' 'Coral' 'Cougar' 'Cow' 'Coyote' 'Crab' 'Crane' 'Crocodile' 'Cuscus' 'Cuttlefish' 'Dachshund' 'Dalmatian' 'Deer' 'Dhole' 'Dingo' 'Discus' 'Dodo' 'Dog' 'Dolphin' 'Donkey' 'Dormouse' 'Dragonfly' 'Drever' 'Duck' 'Dugong' 'Dunker' 'Eagle' 'Earwig' 'Echidna' 'Elephant' 'Emu' 'Falcon' 'Ferret' 'Fish' 'Flamingo' 'Flounder' 'Fly' 'Fossa' 'Fox' 'Frigatebird' 'Frog' 'Gar' 'Gecko' 'Gerbil' 'Gharial' 'Gibbon' 'Giraffe' 'Goat' 'Goose' 'Gopher' 'Gorilla' 'Grasshopper' 'Eater' 'Greyhound' 'Grouse' 'Guppy' 'Hamster' 'Hare' 'Harrier' 'Havanese' 'Hedgehog' 'Heron' 'Himalayan' 'Hippopotamus' 'Horse' 'Human' 'Hummingbird' 'Hyena' 'Ibis' 'Iguana' 'Impala' 'Indri' 'Insect' 'Jackal' 'Jaguar' 'Javanese' 'Jellyfish' 'Kakapo' 'Kangaroo' 'Kingfisher' 'Kiwi' 'Koala' 'Kudu' 'Labradoodle' 'Ladybird' 'Lemming' 'Lemur' 'Leopard' 'Liger' 'Lion' 'Lionfish' 'Lizard' 'Llama' 'Lobster' 'Lynx' 'Macaw' 'Magpie' 'Maltese' 'Manatee' 'Mandrill' '<NAME>' 'Mastiff' 'Mayfly' 'Meerkat' 'Millipede' 'Mole' 'Molly' 'Mongoose' 'Mongrel' 'Monkey' 'Moorhen' 'Moose' 'Moth' 'Mouse' 'Mule' 'Neanderthal' 'Newfoundland' 'Newt' 'Nightingale' 'Numbat' 'Ocelot' 'Octopus' 'Okapi' 'Olm' 'Opossum' 'utan' 'Ostrich' 'Otter' 'Oyster' 'Pademelon' 'Panther' 'Parrot' 'Peacock' 'Pekingese' 'Pelican' 'Penguin' 'Persian' 'Pheasant' 'Pig' 'Pika' 'Pike' 'Piranha' 'Platypus' 'Pointer' 'Poodle' 'Porcupine' 'Possum' 'Prawn' 'Puffin' 'Pug' 'Puma' 'Quail' 'Quetzal' 'Quokka' 'Quoll' 'Rabbit' 'Raccoon' 'Ragdoll' 'Rat' 'Rattlesnake' 'Reindeer' 'Rhinoceros' 'Robin' 'Rottweiler' 'Salamander' 'Saola' 'Scorpion' 'Seahorse' 'Seal' 'Serval' 'Sheep' 'Shrimp' 'Skunk' 'Sloth' 'Snail' 'Snake' 'Snowshoe' 'Sparrow' 'Sponge' 'Squid' 'Squirrel' 'Starfish' 'Stingray' 'Stoat' 'Swan' 'Tang' 'Tapir' 'Tarsier' 'Termite' 'Tetra' 'Tiffany' 'Tiger' 'Tortoise' 'Toucan' 'Tropicbird' 'Tuatara' 'Turkey' 'Uakari' 'Uguisu' 'Umbrellabird' 'Vulture' 'Wallaby' 'Walrus' 'Warthog' 'Wasp' 'Weasel' '<NAME>' '<NAME>' '<NAME>' 'W<NAME>ine' 'W<NAME>bat' '<NAME>' '<NAME>' '<NAME>' 'Yak' 'Zebra' 'Zebu' 'Zonkey' 'Zorse' ] getRandom: -> animals[Math.floor(Math.random() * animals.length)]
true
app = angular.module('app') app.service 'animals', -> animals = [ 'Abyssinian' 'Affenpinscher' 'Akbash' 'Akita' 'Albatross' 'Alligator' 'Angelfish' 'Ant' 'Anteater' 'Antelope' 'Armadillo' 'Avocet' 'Axolotl' 'Baboon' 'Badger' 'Balinese' 'Bandicoot' 'Barb' 'Barnacle' 'Barracuda' 'Bat' 'Beagle' 'Bear' 'Beaver' 'Beetle' 'Binturong' 'Bird' 'Birman' 'Bison' 'Bloodhound' 'Bobcat' 'Bombay' 'Bongo' 'Bonobo' 'Booby' 'Budgerigar' 'Buffalo' 'Bulldog' 'Bullfrog' 'Burmese' 'Butterfly' 'Caiman' 'Camel' 'Capybara' 'Caracal' 'Cassowary' 'Cat' 'Caterpillar' 'Catfish' 'Centipede' 'Chameleon' 'Chamois' 'Cheetah' 'Chicken' 'Chihuahua' 'Chimpanzee' 'Chinchilla' 'Chinook' 'Chipmunk' 'Cichlid' 'Coati' 'Cockroach' 'Collie' 'Coral' 'Cougar' 'Cow' 'Coyote' 'Crab' 'Crane' 'Crocodile' 'Cuscus' 'Cuttlefish' 'Dachshund' 'Dalmatian' 'Deer' 'Dhole' 'Dingo' 'Discus' 'Dodo' 'Dog' 'Dolphin' 'Donkey' 'Dormouse' 'Dragonfly' 'Drever' 'Duck' 'Dugong' 'Dunker' 'Eagle' 'Earwig' 'Echidna' 'Elephant' 'Emu' 'Falcon' 'Ferret' 'Fish' 'Flamingo' 'Flounder' 'Fly' 'Fossa' 'Fox' 'Frigatebird' 'Frog' 'Gar' 'Gecko' 'Gerbil' 'Gharial' 'Gibbon' 'Giraffe' 'Goat' 'Goose' 'Gopher' 'Gorilla' 'Grasshopper' 'Eater' 'Greyhound' 'Grouse' 'Guppy' 'Hamster' 'Hare' 'Harrier' 'Havanese' 'Hedgehog' 'Heron' 'Himalayan' 'Hippopotamus' 'Horse' 'Human' 'Hummingbird' 'Hyena' 'Ibis' 'Iguana' 'Impala' 'Indri' 'Insect' 'Jackal' 'Jaguar' 'Javanese' 'Jellyfish' 'Kakapo' 'Kangaroo' 'Kingfisher' 'Kiwi' 'Koala' 'Kudu' 'Labradoodle' 'Ladybird' 'Lemming' 'Lemur' 'Leopard' 'Liger' 'Lion' 'Lionfish' 'Lizard' 'Llama' 'Lobster' 'Lynx' 'Macaw' 'Magpie' 'Maltese' 'Manatee' 'Mandrill' 'PI:NAME:<NAME>END_PI' 'Mastiff' 'Mayfly' 'Meerkat' 'Millipede' 'Mole' 'Molly' 'Mongoose' 'Mongrel' 'Monkey' 'Moorhen' 'Moose' 'Moth' 'Mouse' 'Mule' 'Neanderthal' 'Newfoundland' 'Newt' 'Nightingale' 'Numbat' 'Ocelot' 'Octopus' 'Okapi' 'Olm' 'Opossum' 'utan' 'Ostrich' 'Otter' 'Oyster' 'Pademelon' 'Panther' 'Parrot' 'Peacock' 'Pekingese' 'Pelican' 'Penguin' 'Persian' 'Pheasant' 'Pig' 'Pika' 'Pike' 'Piranha' 'Platypus' 'Pointer' 'Poodle' 'Porcupine' 'Possum' 'Prawn' 'Puffin' 'Pug' 'Puma' 'Quail' 'Quetzal' 'Quokka' 'Quoll' 'Rabbit' 'Raccoon' 'Ragdoll' 'Rat' 'Rattlesnake' 'Reindeer' 'Rhinoceros' 'Robin' 'Rottweiler' 'Salamander' 'Saola' 'Scorpion' 'Seahorse' 'Seal' 'Serval' 'Sheep' 'Shrimp' 'Skunk' 'Sloth' 'Snail' 'Snake' 'Snowshoe' 'Sparrow' 'Sponge' 'Squid' 'Squirrel' 'Starfish' 'Stingray' 'Stoat' 'Swan' 'Tang' 'Tapir' 'Tarsier' 'Termite' 'Tetra' 'Tiffany' 'Tiger' 'Tortoise' 'Toucan' 'Tropicbird' 'Tuatara' 'Turkey' 'Uakari' 'Uguisu' 'Umbrellabird' 'Vulture' 'Wallaby' 'Walrus' 'Warthog' 'Wasp' 'Weasel' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'WPI:NAME:<NAME>END_PIine' 'WPI:NAME:<NAME>END_PIbat' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'Yak' 'Zebra' 'Zebu' 'Zonkey' 'Zorse' ] getRandom: -> animals[Math.floor(Math.random() * animals.length)]
[ { "context": " ikey\n\t\t\t\t\t\t\t\"data\": [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"key\": \"Raw\"\n\t\t\t\t\t\t\t\t\t\"values\": $scope.stride(values)\n\t\t\t\t\t\t\t", "end": 2863, "score": 0.5628635883331299, "start": 2860, "tag": "KEY", "value": "Raw" }, { "context": "ikey)\n\...
ers_frontend/app/scripts/video/video_feature.coffee
dumoulinj/erf
0
frame2seconds = (frameNb, fps) -> frameNb * 1 / fps seconds2frame = (seconds, fps) -> seconds * fps angular .module 'app.video' .controller 'FeaturesCtrl', ($scope, video, $timeout, Restangular, $dragon, featureTypes, featureFunctionTypes) -> # Initialize tooltips on buttons $timeout(() -> $('[data-toggle="tooltip"]').tooltip() , 500) $scope.getSize = (collection) -> _.size(collection) $scope.video = video $scope.$parent.displayVideo = true $scope.featureTypes = featureTypes $scope.availableFeatures = [] $scope.allFeatures = [] $scope.showFeatures = {} $scope.checkAllFeatures = (featuresType) -> _.map($scope.showFeatures[featuresType], (val, i, arr) -> arr[i] = true ) $scope.uncheckAllFeatures = (featuresType) -> _.map($scope.showFeatures[featuresType], (val, i, arr) -> arr[i] = false ) $scope.hasFeatures = () -> _.size($scope.availableFeatures) > 0 $('[data-toggle="tooltip"]').tooltip() $scope.$watch "video.available_features", -> try availableFeatures = $.parseJSON($scope.video.available_features) $scope.availableFeatures = _.filter(featureTypes, (feature_type) -> feature_type.value in availableFeatures ) catch $scope.showAddFeatureButton = () -> $scope.addFeature.feature != undefined && _.find($scope.allFeatures, {'type': $scope.addFeature.feature}) == undefined $scope.getFeatureLabel = (value) -> _.result(_.find(featureTypes, { 'value': value }), 'label') $scope.getFeatureFunctionLabel = (value) -> _.result(_.find(featureFunctionTypes, {'value':value}), 'label') $scope.removeFeature = (featureType) -> removed = _.remove($scope.allFeatures, (features) -> features["type"] == featureType ) delete $scope.hoverLines[featureType] $scope.maxValues = 400 $scope.stride = (values) -> result = [] size = _.size(values) if size > $scope.maxValues n = Math.floor(size / $scope.maxValues) _.forEach(values, (v, i) -> if i % n == 0 result.push(v) ) result else values $scope.addFeature = () -> $dragon.callRouter('get_feature', 'video', {video_id: $scope.video.id, feature_type: $scope.addFeature.feature}).then((response) -> features = response.data $scope.showFeatures[features.type] = {} values values_normalized values_processed all_feature_functions = {} value = {} if _.size(features.values) > 0 values = features.values if _.size(features.values_normalized) > 0 values_normalized = features.values_normalized if _.size(features.values_processed) > 0 values_processed = features.values_processed functionTypes = [] _.forEach(values, (values, key) -> ikey = parseInt(key) if ikey == 0 value = { "type": ikey "data": [ { "key": "Raw" "values": $scope.stride(values) } ] } else functionTypes.push(ikey) $scope.showFeatures[features.type][ikey] = true all_feature_functions[ikey] = { "type": ikey "title": $scope.getFeatureFunctionLabel(ikey) "data": [ { "key": "Raw" "values": $scope.stride(values) } ] } ) _.forEach(values_normalized, (values, key) -> ikey = parseInt(key) value["data"].push({ "key": "Normalized" "values": $scope.stride(values) }) ) _.forEach(values_processed, (values, key) -> ikey = parseInt(key) value["data"].push({ "key": "Processed" "values": $scope.stride(values) }) ) $scope.allFeatures.push({ "type": features.type "title": $scope.getFeatureLabel(features.type) "value": value "functionFeatures": all_feature_functions }) # Initialize tooltips on buttons $timeout(() -> $('[data-toggle="tooltip"]').tooltip() , 500) $timeout(() -> $scope.drawHoverLine(features.type, 0) _.forEach(functionTypes, (functionType) -> $scope.drawHoverLine(features.type, functionType) ) ,3000) ) $scope.yAxisTickFormatFunction = () -> (d) -> d3.round(d, 2) $scope.xAxisTickFormatFunction = () -> (d) -> d3.round(frame2seconds(d, $scope.video.video_part.fps), 0) $scope.hoverLines = {} updateTimeline = (posX) -> _.forEach($scope.hoverLines, (functions) -> _.forEach(functions, (hoverLine) -> hoverLine.attr("x1", posX).attr("x2", posX) ) ) $scope.onVideoPlayerReady = (API) -> $scope.videoAPI = API $scope.arousalChart = d3.select('#arousalCurveId svg g g g.nv-linesWrap') $scope.$parent.onUpdateTime = (currentTime, totalTime) -> frameNb = seconds2frame(currentTime, $scope.video.video_part.fps) pos = getXPosFromValue(frameNb) updateTimeline(pos) $scope.$parent.crtTime = currentTime $scope.$on('elementClick.directive', (angularEvent, event) -> seek = frame2seconds(event.point[0], $scope.video.video_part.fps) $scope.videoAPI.seekTime(seek) pos = getXPosFromValue(event.point[0], $scope.video.video_part.fps) updateTimeline(pos) ) graphWidth = 0 graphHeight = 0 maxXValue = 0 getXPosFromValue = (value) -> graphWidth * value / maxXValue getYPosFromValue = (value) -> graphHeight * value / 1 $scope.drawHoverLine = (featuresType, functionType) -> id = '#features_' + featuresType + '_' + functionType chart = d3.select(id + ' .nv-linesWrap') # arousalCurveChart = d3.select(id + ' .nv-series-0') rect = d3.select(id + ' .nv-lineChart g rect') # Chart hover lines graphWidth = rect.attr("width") graphHeight = rect.attr("height") if functionType == 0 featuresData = _.result(_.find($scope.allFeatures, {'type': featuresType}), 'value') functionData = featuresData['data'][0]['values'] else featuresData = _.result(_.find($scope.allFeatures, {'type': featuresType}), 'functionFeatures') functionData = featuresData[functionType]['data'][0]['values'] maxXValue = _.last(functionData)[0] # Playing line$ frameNb = seconds2frame($scope.$parent.crtTime, $scope.video.video_part.fps) pos = getXPosFromValue(frameNb) hoverLine = chart.append("line") .attr("x1", pos).attr("x2", pos) .attr("y1", 0).attr("y2", graphHeight) .attr("stroke-width", 1) .style("opacity", 0.9) .attr("stroke", "grey") if $scope.hoverLines[featuresType] == undefined $scope.hoverLines[featuresType] = {} $scope.hoverLines[featuresType][functionType] = hoverLine
33503
frame2seconds = (frameNb, fps) -> frameNb * 1 / fps seconds2frame = (seconds, fps) -> seconds * fps angular .module 'app.video' .controller 'FeaturesCtrl', ($scope, video, $timeout, Restangular, $dragon, featureTypes, featureFunctionTypes) -> # Initialize tooltips on buttons $timeout(() -> $('[data-toggle="tooltip"]').tooltip() , 500) $scope.getSize = (collection) -> _.size(collection) $scope.video = video $scope.$parent.displayVideo = true $scope.featureTypes = featureTypes $scope.availableFeatures = [] $scope.allFeatures = [] $scope.showFeatures = {} $scope.checkAllFeatures = (featuresType) -> _.map($scope.showFeatures[featuresType], (val, i, arr) -> arr[i] = true ) $scope.uncheckAllFeatures = (featuresType) -> _.map($scope.showFeatures[featuresType], (val, i, arr) -> arr[i] = false ) $scope.hasFeatures = () -> _.size($scope.availableFeatures) > 0 $('[data-toggle="tooltip"]').tooltip() $scope.$watch "video.available_features", -> try availableFeatures = $.parseJSON($scope.video.available_features) $scope.availableFeatures = _.filter(featureTypes, (feature_type) -> feature_type.value in availableFeatures ) catch $scope.showAddFeatureButton = () -> $scope.addFeature.feature != undefined && _.find($scope.allFeatures, {'type': $scope.addFeature.feature}) == undefined $scope.getFeatureLabel = (value) -> _.result(_.find(featureTypes, { 'value': value }), 'label') $scope.getFeatureFunctionLabel = (value) -> _.result(_.find(featureFunctionTypes, {'value':value}), 'label') $scope.removeFeature = (featureType) -> removed = _.remove($scope.allFeatures, (features) -> features["type"] == featureType ) delete $scope.hoverLines[featureType] $scope.maxValues = 400 $scope.stride = (values) -> result = [] size = _.size(values) if size > $scope.maxValues n = Math.floor(size / $scope.maxValues) _.forEach(values, (v, i) -> if i % n == 0 result.push(v) ) result else values $scope.addFeature = () -> $dragon.callRouter('get_feature', 'video', {video_id: $scope.video.id, feature_type: $scope.addFeature.feature}).then((response) -> features = response.data $scope.showFeatures[features.type] = {} values values_normalized values_processed all_feature_functions = {} value = {} if _.size(features.values) > 0 values = features.values if _.size(features.values_normalized) > 0 values_normalized = features.values_normalized if _.size(features.values_processed) > 0 values_processed = features.values_processed functionTypes = [] _.forEach(values, (values, key) -> ikey = parseInt(key) if ikey == 0 value = { "type": ikey "data": [ { "key": "<KEY>" "values": $scope.stride(values) } ] } else functionTypes.push(ikey) $scope.showFeatures[features.type][ikey] = true all_feature_functions[ikey] = { "type": ikey "title": $scope.getFeatureFunctionLabel(ikey) "data": [ { "key": "<KEY>" "values": $scope.stride(values) } ] } ) _.forEach(values_normalized, (values, key) -> ikey = parseInt(key) value["data"].push({ "key": "Normalized" "values": $scope.stride(values) }) ) _.forEach(values_processed, (values, key) -> ikey = parseInt(key) value["data"].push({ "key": "Processed" "values": $scope.stride(values) }) ) $scope.allFeatures.push({ "type": features.type "title": $scope.getFeatureLabel(features.type) "value": value "functionFeatures": all_feature_functions }) # Initialize tooltips on buttons $timeout(() -> $('[data-toggle="tooltip"]').tooltip() , 500) $timeout(() -> $scope.drawHoverLine(features.type, 0) _.forEach(functionTypes, (functionType) -> $scope.drawHoverLine(features.type, functionType) ) ,3000) ) $scope.yAxisTickFormatFunction = () -> (d) -> d3.round(d, 2) $scope.xAxisTickFormatFunction = () -> (d) -> d3.round(frame2seconds(d, $scope.video.video_part.fps), 0) $scope.hoverLines = {} updateTimeline = (posX) -> _.forEach($scope.hoverLines, (functions) -> _.forEach(functions, (hoverLine) -> hoverLine.attr("x1", posX).attr("x2", posX) ) ) $scope.onVideoPlayerReady = (API) -> $scope.videoAPI = API $scope.arousalChart = d3.select('#arousalCurveId svg g g g.nv-linesWrap') $scope.$parent.onUpdateTime = (currentTime, totalTime) -> frameNb = seconds2frame(currentTime, $scope.video.video_part.fps) pos = getXPosFromValue(frameNb) updateTimeline(pos) $scope.$parent.crtTime = currentTime $scope.$on('elementClick.directive', (angularEvent, event) -> seek = frame2seconds(event.point[0], $scope.video.video_part.fps) $scope.videoAPI.seekTime(seek) pos = getXPosFromValue(event.point[0], $scope.video.video_part.fps) updateTimeline(pos) ) graphWidth = 0 graphHeight = 0 maxXValue = 0 getXPosFromValue = (value) -> graphWidth * value / maxXValue getYPosFromValue = (value) -> graphHeight * value / 1 $scope.drawHoverLine = (featuresType, functionType) -> id = '#features_' + featuresType + '_' + functionType chart = d3.select(id + ' .nv-linesWrap') # arousalCurveChart = d3.select(id + ' .nv-series-0') rect = d3.select(id + ' .nv-lineChart g rect') # Chart hover lines graphWidth = rect.attr("width") graphHeight = rect.attr("height") if functionType == 0 featuresData = _.result(_.find($scope.allFeatures, {'type': featuresType}), 'value') functionData = featuresData['data'][0]['values'] else featuresData = _.result(_.find($scope.allFeatures, {'type': featuresType}), 'functionFeatures') functionData = featuresData[functionType]['data'][0]['values'] maxXValue = _.last(functionData)[0] # Playing line$ frameNb = seconds2frame($scope.$parent.crtTime, $scope.video.video_part.fps) pos = getXPosFromValue(frameNb) hoverLine = chart.append("line") .attr("x1", pos).attr("x2", pos) .attr("y1", 0).attr("y2", graphHeight) .attr("stroke-width", 1) .style("opacity", 0.9) .attr("stroke", "grey") if $scope.hoverLines[featuresType] == undefined $scope.hoverLines[featuresType] = {} $scope.hoverLines[featuresType][functionType] = hoverLine
true
frame2seconds = (frameNb, fps) -> frameNb * 1 / fps seconds2frame = (seconds, fps) -> seconds * fps angular .module 'app.video' .controller 'FeaturesCtrl', ($scope, video, $timeout, Restangular, $dragon, featureTypes, featureFunctionTypes) -> # Initialize tooltips on buttons $timeout(() -> $('[data-toggle="tooltip"]').tooltip() , 500) $scope.getSize = (collection) -> _.size(collection) $scope.video = video $scope.$parent.displayVideo = true $scope.featureTypes = featureTypes $scope.availableFeatures = [] $scope.allFeatures = [] $scope.showFeatures = {} $scope.checkAllFeatures = (featuresType) -> _.map($scope.showFeatures[featuresType], (val, i, arr) -> arr[i] = true ) $scope.uncheckAllFeatures = (featuresType) -> _.map($scope.showFeatures[featuresType], (val, i, arr) -> arr[i] = false ) $scope.hasFeatures = () -> _.size($scope.availableFeatures) > 0 $('[data-toggle="tooltip"]').tooltip() $scope.$watch "video.available_features", -> try availableFeatures = $.parseJSON($scope.video.available_features) $scope.availableFeatures = _.filter(featureTypes, (feature_type) -> feature_type.value in availableFeatures ) catch $scope.showAddFeatureButton = () -> $scope.addFeature.feature != undefined && _.find($scope.allFeatures, {'type': $scope.addFeature.feature}) == undefined $scope.getFeatureLabel = (value) -> _.result(_.find(featureTypes, { 'value': value }), 'label') $scope.getFeatureFunctionLabel = (value) -> _.result(_.find(featureFunctionTypes, {'value':value}), 'label') $scope.removeFeature = (featureType) -> removed = _.remove($scope.allFeatures, (features) -> features["type"] == featureType ) delete $scope.hoverLines[featureType] $scope.maxValues = 400 $scope.stride = (values) -> result = [] size = _.size(values) if size > $scope.maxValues n = Math.floor(size / $scope.maxValues) _.forEach(values, (v, i) -> if i % n == 0 result.push(v) ) result else values $scope.addFeature = () -> $dragon.callRouter('get_feature', 'video', {video_id: $scope.video.id, feature_type: $scope.addFeature.feature}).then((response) -> features = response.data $scope.showFeatures[features.type] = {} values values_normalized values_processed all_feature_functions = {} value = {} if _.size(features.values) > 0 values = features.values if _.size(features.values_normalized) > 0 values_normalized = features.values_normalized if _.size(features.values_processed) > 0 values_processed = features.values_processed functionTypes = [] _.forEach(values, (values, key) -> ikey = parseInt(key) if ikey == 0 value = { "type": ikey "data": [ { "key": "PI:KEY:<KEY>END_PI" "values": $scope.stride(values) } ] } else functionTypes.push(ikey) $scope.showFeatures[features.type][ikey] = true all_feature_functions[ikey] = { "type": ikey "title": $scope.getFeatureFunctionLabel(ikey) "data": [ { "key": "PI:KEY:<KEY>END_PI" "values": $scope.stride(values) } ] } ) _.forEach(values_normalized, (values, key) -> ikey = parseInt(key) value["data"].push({ "key": "Normalized" "values": $scope.stride(values) }) ) _.forEach(values_processed, (values, key) -> ikey = parseInt(key) value["data"].push({ "key": "Processed" "values": $scope.stride(values) }) ) $scope.allFeatures.push({ "type": features.type "title": $scope.getFeatureLabel(features.type) "value": value "functionFeatures": all_feature_functions }) # Initialize tooltips on buttons $timeout(() -> $('[data-toggle="tooltip"]').tooltip() , 500) $timeout(() -> $scope.drawHoverLine(features.type, 0) _.forEach(functionTypes, (functionType) -> $scope.drawHoverLine(features.type, functionType) ) ,3000) ) $scope.yAxisTickFormatFunction = () -> (d) -> d3.round(d, 2) $scope.xAxisTickFormatFunction = () -> (d) -> d3.round(frame2seconds(d, $scope.video.video_part.fps), 0) $scope.hoverLines = {} updateTimeline = (posX) -> _.forEach($scope.hoverLines, (functions) -> _.forEach(functions, (hoverLine) -> hoverLine.attr("x1", posX).attr("x2", posX) ) ) $scope.onVideoPlayerReady = (API) -> $scope.videoAPI = API $scope.arousalChart = d3.select('#arousalCurveId svg g g g.nv-linesWrap') $scope.$parent.onUpdateTime = (currentTime, totalTime) -> frameNb = seconds2frame(currentTime, $scope.video.video_part.fps) pos = getXPosFromValue(frameNb) updateTimeline(pos) $scope.$parent.crtTime = currentTime $scope.$on('elementClick.directive', (angularEvent, event) -> seek = frame2seconds(event.point[0], $scope.video.video_part.fps) $scope.videoAPI.seekTime(seek) pos = getXPosFromValue(event.point[0], $scope.video.video_part.fps) updateTimeline(pos) ) graphWidth = 0 graphHeight = 0 maxXValue = 0 getXPosFromValue = (value) -> graphWidth * value / maxXValue getYPosFromValue = (value) -> graphHeight * value / 1 $scope.drawHoverLine = (featuresType, functionType) -> id = '#features_' + featuresType + '_' + functionType chart = d3.select(id + ' .nv-linesWrap') # arousalCurveChart = d3.select(id + ' .nv-series-0') rect = d3.select(id + ' .nv-lineChart g rect') # Chart hover lines graphWidth = rect.attr("width") graphHeight = rect.attr("height") if functionType == 0 featuresData = _.result(_.find($scope.allFeatures, {'type': featuresType}), 'value') functionData = featuresData['data'][0]['values'] else featuresData = _.result(_.find($scope.allFeatures, {'type': featuresType}), 'functionFeatures') functionData = featuresData[functionType]['data'][0]['values'] maxXValue = _.last(functionData)[0] # Playing line$ frameNb = seconds2frame($scope.$parent.crtTime, $scope.video.video_part.fps) pos = getXPosFromValue(frameNb) hoverLine = chart.append("line") .attr("x1", pos).attr("x2", pos) .attr("y1", 0).attr("y2", graphHeight) .attr("stroke-width", 1) .style("opacity", 0.9) .attr("stroke", "grey") if $scope.hoverLines[featuresType] == undefined $scope.hoverLines[featuresType] = {} $scope.hoverLines[featuresType][functionType] = hoverLine
[ { "context": "l] [?email ?height]]',\n args: \"\"\"[\n [\"Doe\" \"John\" \"jdoe@example.com\"]\n [\"jdoe@exampl", "end": 2503, "score": 0.9997677206993103, "start": 2500, "tag": "NAME", "value": "Doe" }, { "context": "mail ?height]]',\n args: \"\"\"[\n ...
test/datomic.coffee
limadelic/datomicjs
37
{ Datomic } = require src + 'datomic' parse = require '../lib/parse' schema = require './schema' describe 'Datomic', -> datomic = new Datomic 'localhost', 8888, 'db', 'test' it 'should fetch available storage aliases', (done) -> datomic.storages (err, storages) -> parse.json(storages).should.include 'db' done() it 'should fetch a list of databases for a storage alias', (done) -> datomic.databases 'db', (err, databases) -> parse.json(databases).should.include 'test' done() it 'should create a DB', (done) -> datomic.createDatabase (err, created) -> datomic.db (err, db) -> parse.json(db)['db/alias'].should.equal 'db/test' done() it 'should make transactions', (done) -> datomic.transact schema.movies, (err, future) -> future.should.include ':db-after' done() it 'should get datoms', (done) -> datomic.datoms 'eavt', (err, datoms) -> datoms.should.not.be.empty done() it 'should get datoms with options', (done) -> datomic.datoms 'avet', {limit:1}, (err, datoms) -> parse.json(datoms).length.should.equal 1 done() it 'should get a range of index data', (done) -> datomic.indexRange 'db/ident', (err, datoms) -> datoms.should.not.be.empty done() it 'should get an entity', (done) -> datomic.entity 1, (err, entity) -> parse.json(entity)['db/id'].should.equal 1 done() it 'should get an entity with options', (done) -> datomic.entity {e:1, since:0}, (err, entity) -> parse.json(entity)['db/id'].should.equal 1 done() it 'should allow to query', (done) -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "trainspotting"]]', -> datomic.q '[:find ?m :where [?m :movie/title "trainspotting"]]', (err, movies) -> parse.json(movies)[0][0].should.be.above 1 done() it 'should allow to query with opt', (done) -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "the matrix"]]', -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "the matrix reloaded"]]', -> datomic.q '[:find ?m :where [?m :movie/title]]', {limit:1, offset:2}, (err, movies) -> parse.json(movies)[0][0].should.be.above 1 done() it 'should allow passing arguments to query', (done) -> datomic.q '[:find ?first ?height :in [?last ?first ?email] [?email ?height]]', args: """[ ["Doe" "John" "jdoe@example.com"] ["jdoe@example.com" 71] ]""" (err, result) -> data = parse.json result data[0][0].should.equal 'John' data[0][1].should.equal 71 done() it 'should register to events', (done) -> client = datomic.events() client.onmessage = (event) -> event.data.should.include ':db-after' client.close() done() datomic.transact schema.movies, ->
146437
{ Datomic } = require src + 'datomic' parse = require '../lib/parse' schema = require './schema' describe 'Datomic', -> datomic = new Datomic 'localhost', 8888, 'db', 'test' it 'should fetch available storage aliases', (done) -> datomic.storages (err, storages) -> parse.json(storages).should.include 'db' done() it 'should fetch a list of databases for a storage alias', (done) -> datomic.databases 'db', (err, databases) -> parse.json(databases).should.include 'test' done() it 'should create a DB', (done) -> datomic.createDatabase (err, created) -> datomic.db (err, db) -> parse.json(db)['db/alias'].should.equal 'db/test' done() it 'should make transactions', (done) -> datomic.transact schema.movies, (err, future) -> future.should.include ':db-after' done() it 'should get datoms', (done) -> datomic.datoms 'eavt', (err, datoms) -> datoms.should.not.be.empty done() it 'should get datoms with options', (done) -> datomic.datoms 'avet', {limit:1}, (err, datoms) -> parse.json(datoms).length.should.equal 1 done() it 'should get a range of index data', (done) -> datomic.indexRange 'db/ident', (err, datoms) -> datoms.should.not.be.empty done() it 'should get an entity', (done) -> datomic.entity 1, (err, entity) -> parse.json(entity)['db/id'].should.equal 1 done() it 'should get an entity with options', (done) -> datomic.entity {e:1, since:0}, (err, entity) -> parse.json(entity)['db/id'].should.equal 1 done() it 'should allow to query', (done) -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "trainspotting"]]', -> datomic.q '[:find ?m :where [?m :movie/title "trainspotting"]]', (err, movies) -> parse.json(movies)[0][0].should.be.above 1 done() it 'should allow to query with opt', (done) -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "the matrix"]]', -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "the matrix reloaded"]]', -> datomic.q '[:find ?m :where [?m :movie/title]]', {limit:1, offset:2}, (err, movies) -> parse.json(movies)[0][0].should.be.above 1 done() it 'should allow passing arguments to query', (done) -> datomic.q '[:find ?first ?height :in [?last ?first ?email] [?email ?height]]', args: """[ ["<NAME>" "<NAME>" "<EMAIL>"] ["<EMAIL>" 71] ]""" (err, result) -> data = parse.json result data[0][0].should.equal '<NAME>' data[0][1].should.equal 71 done() it 'should register to events', (done) -> client = datomic.events() client.onmessage = (event) -> event.data.should.include ':db-after' client.close() done() datomic.transact schema.movies, ->
true
{ Datomic } = require src + 'datomic' parse = require '../lib/parse' schema = require './schema' describe 'Datomic', -> datomic = new Datomic 'localhost', 8888, 'db', 'test' it 'should fetch available storage aliases', (done) -> datomic.storages (err, storages) -> parse.json(storages).should.include 'db' done() it 'should fetch a list of databases for a storage alias', (done) -> datomic.databases 'db', (err, databases) -> parse.json(databases).should.include 'test' done() it 'should create a DB', (done) -> datomic.createDatabase (err, created) -> datomic.db (err, db) -> parse.json(db)['db/alias'].should.equal 'db/test' done() it 'should make transactions', (done) -> datomic.transact schema.movies, (err, future) -> future.should.include ':db-after' done() it 'should get datoms', (done) -> datomic.datoms 'eavt', (err, datoms) -> datoms.should.not.be.empty done() it 'should get datoms with options', (done) -> datomic.datoms 'avet', {limit:1}, (err, datoms) -> parse.json(datoms).length.should.equal 1 done() it 'should get a range of index data', (done) -> datomic.indexRange 'db/ident', (err, datoms) -> datoms.should.not.be.empty done() it 'should get an entity', (done) -> datomic.entity 1, (err, entity) -> parse.json(entity)['db/id'].should.equal 1 done() it 'should get an entity with options', (done) -> datomic.entity {e:1, since:0}, (err, entity) -> parse.json(entity)['db/id'].should.equal 1 done() it 'should allow to query', (done) -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "trainspotting"]]', -> datomic.q '[:find ?m :where [?m :movie/title "trainspotting"]]', (err, movies) -> parse.json(movies)[0][0].should.be.above 1 done() it 'should allow to query with opt', (done) -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "the matrix"]]', -> datomic.transact '[[:db/add #db/id [:db.part/user] :movie/title "the matrix reloaded"]]', -> datomic.q '[:find ?m :where [?m :movie/title]]', {limit:1, offset:2}, (err, movies) -> parse.json(movies)[0][0].should.be.above 1 done() it 'should allow passing arguments to query', (done) -> datomic.q '[:find ?first ?height :in [?last ?first ?email] [?email ?height]]', args: """[ ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI"] ["PI:EMAIL:<EMAIL>END_PI" 71] ]""" (err, result) -> data = parse.json result data[0][0].should.equal 'PI:NAME:<NAME>END_PI' data[0][1].should.equal 71 done() it 'should register to events', (done) -> client = datomic.events() client.onmessage = (event) -> event.data.should.include ':db-after' client.close() done() datomic.transact schema.movies, ->
[ { "context": "try = new Sentry()\n assert.equal _sentry.key, 'c28500314a0f4cf28b6d658c3dd37ddb'\n assert.equal _sentry.secret, 'a5d3fcd72b7049", "end": 774, "score": 0.9997715353965759, "start": 742, "tag": "KEY", "value": "c28500314a0f4cf28b6d658c3dd37ddb" }, { "context": "6d6...
socketio/node_modules/sentry-node/test/sentry.coffee
motephyr/realtime_demo
0
_ = require 'underscore' assert = require 'assert' os = require 'os' nock = require 'nock' Sentry = require("#{__dirname}/../lib/sentry") sentry_settings = require("#{__dirname}/credentials").sentry describe 'sentry-node', -> before -> @sentry = new Sentry sentry_settings # because only in production env sentry api would make http request process.env.NODE_ENV = 'production' it 'setup sentry client from SENTRY_DSN correctly', (done) -> # mock sentry dsn with random uuid as public_key and secret_key dsn = 'https://c28500314a0f4cf28b6d658c3dd37ddb:a5d3fcd72b70494b877a1c2deba6ad74@app.getsentry.com/16088' process.env.SENTRY_DSN = dsn _sentry = new Sentry() assert.equal _sentry.key, 'c28500314a0f4cf28b6d658c3dd37ddb' assert.equal _sentry.secret, 'a5d3fcd72b70494b877a1c2deba6ad74' assert.equal _sentry.project_id, '16088' assert.equal os.hostname(), _sentry.hostname assert.deepEqual ['production'], _sentry.enable_env assert.equal _sentry.enabled, true delete process.env.SENTRY_DSN _sentry = new Sentry dsn assert.equal _sentry.key, 'c28500314a0f4cf28b6d658c3dd37ddb' assert.equal _sentry.secret, 'a5d3fcd72b70494b877a1c2deba6ad74' assert.equal _sentry.project_id, '16088' assert.equal os.hostname(), _sentry.hostname assert.deepEqual ['production'], _sentry.enable_env assert.equal _sentry.enabled, true done() it 'setup sentry client from credentials correctly', (done) -> assert.equal sentry_settings.key, @sentry.key assert.equal sentry_settings.secret, @sentry.secret assert.equal sentry_settings.project_id, @sentry.project_id assert.equal os.hostname(), @sentry.hostname assert.deepEqual ['production'], @sentry.enable_env assert.equal @sentry.enabled, true done() it 'setup sentry client settings from settings passed in correctly', (done) -> _sentry = new Sentry { enable_env: ['production', 'staging'] } assert.deepEqual _sentry.enable_env, ['production', 'staging'] done() it 'empty or missing DSN should disable the client', (done) -> _sentry = new Sentry "" assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "You SENTRY_DSN is missing or empty. Sentry client is disabled." _sentry = new Sentry() assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "You SENTRY_DSN is missing or empty. Sentry client is disabled." done() it 'invalid DSN should disable the client', (done) -> _sentry = new Sentry "https://app.getsentry.com/16088" assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "Your SENTRY_DSN is invalid. Use correct DSN to enable your sentry client." done() it 'passed in settings should update credentials of sentry client', (done) -> dsn = 'https://c28500314a0f4cf28b6d658c3dd37ddb:a5d3fcd72b70494b877a1c2deba6ad74@app.getsentry.com/16088' process.env.SENTRY_DSN = dsn _sentry = new Sentry(sentry_settings) assert.equal sentry_settings.key, _sentry.key assert.equal sentry_settings.secret, _sentry.secret assert.equal sentry_settings.project_id, _sentry.project_id done() it 'fails if passed an error that isnt an instance of Error', -> assert.throws (=> @sentry.error 'not an Error'), /error must be an instance of Error/ it 'send error correctly', (done) -> scope = nock('https://app.getsentry.com') .matchHeader('X-Sentry-Auth' , "Sentry sentry_version=4, sentry_key=#{sentry_settings.key}, sentry_secret=#{sentry_settings.secret}, sentry_client=sentry-node/0.1.3") .filteringRequestBody (path) -> params = JSON.parse path if _.every(['culprit','message','logger','server_name','platform','level'], (prop) -> _.has(params, prop)) if params.extra?.stacktrace? return 'error' throw Error 'Body of Sentry error request is incorrect.' .post("/api/#{sentry_settings.project_id}/store/", 'error') .reply(200, {"id": "534f9b1b491241b28ee8d6b571e1999d"}) # mock sentry response with a random uuid assert.doesNotThrow => err = @sentry.error new Error('Error message'), 'message', '/path/to/logger' scope.done() done() it 'send message correctly', (done) -> scope = nock('https://app.getsentry.com') .matchHeader('X-Sentry-Auth' , "Sentry sentry_version=4, sentry_key=#{sentry_settings.key}, sentry_secret=#{sentry_settings.secret}, sentry_client=sentry-node/0.1.3") .filteringRequestBody (path) -> params = JSON.parse path if _.every(['message','logger','level'], (prop) -> _.has(params, prop)) unless _.some(['culprit','server_name','platform','extra'], (prop) -> _.has(params, prop)) return 'message' throw Error 'Body of Sentry message request is incorrect.' .post("/api/#{sentry_settings.project_id}/store/", 'message') .reply(200, {"id": "c3115249083246efa839cfac2abbdefb"}) # mock sentry response with a random uuid assert.doesNotThrow => @sentry.message 'message', '/path/to/logger' scope.done() done() it 'emit logged event when successfully made an api call', (done) -> scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(200, 'OK') @sentry.on 'logged', -> scope.done() done() @sentry.error new Error('wtf?'), "Unknown Error", "/" it 'emit error event when the api call returned an error', (done) -> scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(500, 'Oops!', {'x-sentry-error': 'Oops!'}) @sentry.on 'error', -> scope.done() done() @sentry.message "hey!", "/" it 'one time listener should work correctly', (done) -> _sentry = new Sentry(sentry_settings) scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(500, 'Oops!', {'x-sentry-error': 'Oops!'}) _sentry.once 'error', -> scope.done() done() _sentry.message "hey!", "/"
11320
_ = require 'underscore' assert = require 'assert' os = require 'os' nock = require 'nock' Sentry = require("#{__dirname}/../lib/sentry") sentry_settings = require("#{__dirname}/credentials").sentry describe 'sentry-node', -> before -> @sentry = new Sentry sentry_settings # because only in production env sentry api would make http request process.env.NODE_ENV = 'production' it 'setup sentry client from SENTRY_DSN correctly', (done) -> # mock sentry dsn with random uuid as public_key and secret_key dsn = 'https://c28500314a0f4cf28b6d658c3dd37ddb:a5d3fcd72b70494b877a1c2deba6ad74@app.getsentry.com/16088' process.env.SENTRY_DSN = dsn _sentry = new Sentry() assert.equal _sentry.key, '<KEY>' assert.equal _sentry.secret, '<KEY>' assert.equal _sentry.project_id, '16088' assert.equal os.hostname(), _sentry.hostname assert.deepEqual ['production'], _sentry.enable_env assert.equal _sentry.enabled, true delete process.env.SENTRY_DSN _sentry = new Sentry dsn assert.equal _sentry.key, '<KEY>' assert.equal _sentry.secret, '<KEY>' assert.equal _sentry.project_id, '16088' assert.equal os.hostname(), _sentry.hostname assert.deepEqual ['production'], _sentry.enable_env assert.equal _sentry.enabled, true done() it 'setup sentry client from credentials correctly', (done) -> assert.equal sentry_settings.key, @sentry.key assert.equal sentry_settings.secret, @sentry.secret assert.equal sentry_settings.project_id, @sentry.project_id assert.equal os.hostname(), @sentry.hostname assert.deepEqual ['production'], @sentry.enable_env assert.equal @sentry.enabled, true done() it 'setup sentry client settings from settings passed in correctly', (done) -> _sentry = new Sentry { enable_env: ['production', 'staging'] } assert.deepEqual _sentry.enable_env, ['production', 'staging'] done() it 'empty or missing DSN should disable the client', (done) -> _sentry = new Sentry "" assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "You SENTRY_DSN is missing or empty. Sentry client is disabled." _sentry = new Sentry() assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "You SENTRY_DSN is missing or empty. Sentry client is disabled." done() it 'invalid DSN should disable the client', (done) -> _sentry = new Sentry "https://app.getsentry.com/16088" assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "Your SENTRY_DSN is invalid. Use correct DSN to enable your sentry client." done() it 'passed in settings should update credentials of sentry client', (done) -> dsn = 'https://c28500314a0f4cf28b6d658c3dd37ddb:a5d3fcd72b70494b877a1c2deba6ad74@app.getsentry.com/16088' process.env.SENTRY_DSN = dsn _sentry = new Sentry(sentry_settings) assert.equal sentry_settings.key, _sentry.key assert.equal sentry_settings.secret, _sentry.secret assert.equal sentry_settings.project_id, _sentry.project_id done() it 'fails if passed an error that isnt an instance of Error', -> assert.throws (=> @sentry.error 'not an Error'), /error must be an instance of Error/ it 'send error correctly', (done) -> scope = nock('https://app.getsentry.com') .matchHeader('X-Sentry-Auth' , "Sentry sentry_version=4, sentry_key=#{sentry_settings.key}, sentry_secret=#{sentry_settings.secret}, sentry_client=sentry-node/0.1.3") .filteringRequestBody (path) -> params = JSON.parse path if _.every(['culprit','message','logger','server_name','platform','level'], (prop) -> _.has(params, prop)) if params.extra?.stacktrace? return 'error' throw Error 'Body of Sentry error request is incorrect.' .post("/api/#{sentry_settings.project_id}/store/", 'error') .reply(200, {"id": "534f9b1b491241b28ee8d6b571e1999d"}) # mock sentry response with a random uuid assert.doesNotThrow => err = @sentry.error new Error('Error message'), 'message', '/path/to/logger' scope.done() done() it 'send message correctly', (done) -> scope = nock('https://app.getsentry.com') .matchHeader('X-Sentry-Auth' , "Sentry sentry_version=4, sentry_key=#{sentry_settings.key}, sentry_secret=#{sentry_settings.secret}, sentry_client=sentry-node/0.1.3") .filteringRequestBody (path) -> params = JSON.parse path if _.every(['message','logger','level'], (prop) -> _.has(params, prop)) unless _.some(['culprit','server_name','platform','extra'], (prop) -> _.has(params, prop)) return 'message' throw Error 'Body of Sentry message request is incorrect.' .post("/api/#{sentry_settings.project_id}/store/", 'message') .reply(200, {"id": "c3115249083246efa839cfac2abbdefb"}) # mock sentry response with a random uuid assert.doesNotThrow => @sentry.message 'message', '/path/to/logger' scope.done() done() it 'emit logged event when successfully made an api call', (done) -> scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(200, 'OK') @sentry.on 'logged', -> scope.done() done() @sentry.error new Error('wtf?'), "Unknown Error", "/" it 'emit error event when the api call returned an error', (done) -> scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(500, 'Oops!', {'x-sentry-error': 'Oops!'}) @sentry.on 'error', -> scope.done() done() @sentry.message "hey!", "/" it 'one time listener should work correctly', (done) -> _sentry = new Sentry(sentry_settings) scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(500, 'Oops!', {'x-sentry-error': 'Oops!'}) _sentry.once 'error', -> scope.done() done() _sentry.message "hey!", "/"
true
_ = require 'underscore' assert = require 'assert' os = require 'os' nock = require 'nock' Sentry = require("#{__dirname}/../lib/sentry") sentry_settings = require("#{__dirname}/credentials").sentry describe 'sentry-node', -> before -> @sentry = new Sentry sentry_settings # because only in production env sentry api would make http request process.env.NODE_ENV = 'production' it 'setup sentry client from SENTRY_DSN correctly', (done) -> # mock sentry dsn with random uuid as public_key and secret_key dsn = 'https://c28500314a0f4cf28b6d658c3dd37ddb:a5d3fcd72b70494b877a1c2deba6ad74@app.getsentry.com/16088' process.env.SENTRY_DSN = dsn _sentry = new Sentry() assert.equal _sentry.key, 'PI:KEY:<KEY>END_PI' assert.equal _sentry.secret, 'PI:KEY:<KEY>END_PI' assert.equal _sentry.project_id, '16088' assert.equal os.hostname(), _sentry.hostname assert.deepEqual ['production'], _sentry.enable_env assert.equal _sentry.enabled, true delete process.env.SENTRY_DSN _sentry = new Sentry dsn assert.equal _sentry.key, 'PI:KEY:<KEY>END_PI' assert.equal _sentry.secret, 'PI:KEY:<KEY>END_PI' assert.equal _sentry.project_id, '16088' assert.equal os.hostname(), _sentry.hostname assert.deepEqual ['production'], _sentry.enable_env assert.equal _sentry.enabled, true done() it 'setup sentry client from credentials correctly', (done) -> assert.equal sentry_settings.key, @sentry.key assert.equal sentry_settings.secret, @sentry.secret assert.equal sentry_settings.project_id, @sentry.project_id assert.equal os.hostname(), @sentry.hostname assert.deepEqual ['production'], @sentry.enable_env assert.equal @sentry.enabled, true done() it 'setup sentry client settings from settings passed in correctly', (done) -> _sentry = new Sentry { enable_env: ['production', 'staging'] } assert.deepEqual _sentry.enable_env, ['production', 'staging'] done() it 'empty or missing DSN should disable the client', (done) -> _sentry = new Sentry "" assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "You SENTRY_DSN is missing or empty. Sentry client is disabled." _sentry = new Sentry() assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "You SENTRY_DSN is missing or empty. Sentry client is disabled." done() it 'invalid DSN should disable the client', (done) -> _sentry = new Sentry "https://app.getsentry.com/16088" assert.equal _sentry.enabled, false assert.equal _sentry.disable_message, "Your SENTRY_DSN is invalid. Use correct DSN to enable your sentry client." done() it 'passed in settings should update credentials of sentry client', (done) -> dsn = 'https://c28500314a0f4cf28b6d658c3dd37ddb:a5d3fcd72b70494b877a1c2deba6ad74@app.getsentry.com/16088' process.env.SENTRY_DSN = dsn _sentry = new Sentry(sentry_settings) assert.equal sentry_settings.key, _sentry.key assert.equal sentry_settings.secret, _sentry.secret assert.equal sentry_settings.project_id, _sentry.project_id done() it 'fails if passed an error that isnt an instance of Error', -> assert.throws (=> @sentry.error 'not an Error'), /error must be an instance of Error/ it 'send error correctly', (done) -> scope = nock('https://app.getsentry.com') .matchHeader('X-Sentry-Auth' , "Sentry sentry_version=4, sentry_key=#{sentry_settings.key}, sentry_secret=#{sentry_settings.secret}, sentry_client=sentry-node/0.1.3") .filteringRequestBody (path) -> params = JSON.parse path if _.every(['culprit','message','logger','server_name','platform','level'], (prop) -> _.has(params, prop)) if params.extra?.stacktrace? return 'error' throw Error 'Body of Sentry error request is incorrect.' .post("/api/#{sentry_settings.project_id}/store/", 'error') .reply(200, {"id": "534f9b1b491241b28ee8d6b571e1999d"}) # mock sentry response with a random uuid assert.doesNotThrow => err = @sentry.error new Error('Error message'), 'message', '/path/to/logger' scope.done() done() it 'send message correctly', (done) -> scope = nock('https://app.getsentry.com') .matchHeader('X-Sentry-Auth' , "Sentry sentry_version=4, sentry_key=#{sentry_settings.key}, sentry_secret=#{sentry_settings.secret}, sentry_client=sentry-node/0.1.3") .filteringRequestBody (path) -> params = JSON.parse path if _.every(['message','logger','level'], (prop) -> _.has(params, prop)) unless _.some(['culprit','server_name','platform','extra'], (prop) -> _.has(params, prop)) return 'message' throw Error 'Body of Sentry message request is incorrect.' .post("/api/#{sentry_settings.project_id}/store/", 'message') .reply(200, {"id": "c3115249083246efa839cfac2abbdefb"}) # mock sentry response with a random uuid assert.doesNotThrow => @sentry.message 'message', '/path/to/logger' scope.done() done() it 'emit logged event when successfully made an api call', (done) -> scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(200, 'OK') @sentry.on 'logged', -> scope.done() done() @sentry.error new Error('wtf?'), "Unknown Error", "/" it 'emit error event when the api call returned an error', (done) -> scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(500, 'Oops!', {'x-sentry-error': 'Oops!'}) @sentry.on 'error', -> scope.done() done() @sentry.message "hey!", "/" it 'one time listener should work correctly', (done) -> _sentry = new Sentry(sentry_settings) scope = nock('https://app.getsentry.com') .filteringRequestBody(/.*/, '*') .post("/api/#{sentry_settings.project_id}/store/", '*') .reply(500, 'Oops!', {'x-sentry-error': 'Oops!'}) _sentry.once 'error', -> scope.done() done() _sentry.message "hey!", "/"
[ { "context": " likely to get into monster battles.\n *\n * @name Warmonger\n * @prerequisite Enter 10 battles\n * @category ", "end": 156, "score": 0.9960800409317017, "start": 147, "tag": "NAME", "value": "Warmonger" } ]
src/character/personalities/Warmonger.coffee
sadbear-/IdleLands
3
Personality = require "../base/Personality" `/** * This personality makes it so you are more likely to get into monster battles. * * @name Warmonger * @prerequisite Enter 10 battles * @category Personalities * @package Player */` class Warmonger extends Personality constructor: -> eventModifier: (player, event) -> if event.type is "battle" then 150 @canUse = (player) -> player.statistics["combat battle start"] >= 10 @desc = "Enter 10 battles" module.exports = exports = Warmonger
159914
Personality = require "../base/Personality" `/** * This personality makes it so you are more likely to get into monster battles. * * @name <NAME> * @prerequisite Enter 10 battles * @category Personalities * @package Player */` class Warmonger extends Personality constructor: -> eventModifier: (player, event) -> if event.type is "battle" then 150 @canUse = (player) -> player.statistics["combat battle start"] >= 10 @desc = "Enter 10 battles" module.exports = exports = Warmonger
true
Personality = require "../base/Personality" `/** * This personality makes it so you are more likely to get into monster battles. * * @name PI:NAME:<NAME>END_PI * @prerequisite Enter 10 battles * @category Personalities * @package Player */` class Warmonger extends Personality constructor: -> eventModifier: (player, event) -> if event.type is "battle" then 150 @canUse = (player) -> player.statistics["combat battle start"] >= 10 @desc = "Enter 10 battles" module.exports = exports = Warmonger
[ { "context": "present a collection of graphic object\n*\n* @author David Jegat <david.jegat@gmail.com>\n###\nclass GraphicCollecti", "end": 71, "score": 0.9998871088027954, "start": 60, "tag": "NAME", "value": "David Jegat" }, { "context": "ection of graphic object\n*\n* @author Davi...
src/Collection/GraphicCollection.coffee
Djeg/MicroRacing
1
###* * Represent a collection of graphic object * * @author David Jegat <david.jegat@gmail.com> ### class GraphicCollection extends Collection ###* * REdefined the add to handle Graphic object only support * * @param {BaseGraphic} graphic * @throws String, if the graphic is not a BaseGraphic * @return {GraphicCollection} ### add: (graphic) -> if not graphic instanceof BaseGraphic throw "Invalid graphic" super graphic @
152572
###* * Represent a collection of graphic object * * @author <NAME> <<EMAIL>> ### class GraphicCollection extends Collection ###* * REdefined the add to handle Graphic object only support * * @param {BaseGraphic} graphic * @throws String, if the graphic is not a BaseGraphic * @return {GraphicCollection} ### add: (graphic) -> if not graphic instanceof BaseGraphic throw "Invalid graphic" super graphic @
true
###* * Represent a collection of graphic object * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### class GraphicCollection extends Collection ###* * REdefined the add to handle Graphic object only support * * @param {BaseGraphic} graphic * @throws String, if the graphic is not a BaseGraphic * @return {GraphicCollection} ### add: (graphic) -> if not graphic instanceof BaseGraphic throw "Invalid graphic" super graphic @
[ { "context": " \"hostname\": \"localhost\"\n \"user\": username\n \"password\": password\n \"dat", "end": 693, "score": 0.9976575970649719, "start": 685, "tag": "USERNAME", "value": "username" }, { "context": " \"user\": username\n ...
server/magnet_server.coffee
elfsternberg/fridgemagnets
0
express = require 'express' mysql = require('db-mysql') OAuth = require('oauth').OAuth util = require('util') config = require('./config') fs = require('fs') wordlist = JSON.parse(fs.readFileSync('./wordlist.js', 'utf-8')) wordstream = (i.w for i in wordlist).join(' ') body_to_haiku = (lines) -> ret = (for words in lines line = words[0].w for word in words[1...words.length] line += if word.s == 1 then word.w else ' ' + word.w line).join(" / ") console.log(ret) ret class AddressTracker constructor: (database, username, password) -> @db = new mysql.Database({ "hostname": "localhost" "user": username "password": password "database": database}) @db.on('ready', () -> @connection = this) @db.on('error', () -> console.log(arguments)) connect: (cb) -> atrack = @ @db.connect () -> atrack.connection = this cb.apply(this, arguments) validate: (ip_address, message, cb) -> yesterday = new Date((new Date()).valueOf() - 1000 * 86400) connection = @connection connection.query(). select('*'). from('tweets'). where('address = ? and entered > ?', [ip_address, yesterday]). execute (err, rows, cols) -> return cb(err, null) if (err) return cb("You've used up your allotted number of tweets today", null) if rows.length > 10 connection.query(). select('*'). from('tweets'). where('tweet = ?', [body_to_haiku(message.message)]). execute (err, rows, cols) -> return cb(err, null) if (err) return cb("You've already sent that poem!", null) if rows.length > 0 connection.query(). insert('tweets', ['address', 'tweet', 'entered'], [ip_address, body_to_haiku(message.message), (new Date())]). execute (err, result) -> return cb(err, null) if err cb(null, result) class TwitterPoster constructor: -> @oauth = new OAuth( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", config.twitter.consumer_key, config.twitter.consumer_private_key, "1.0", null, "HMAC-SHA1" ) post: (message, callback) -> @oauth.post( "http://api.twitter.com/1/statuses/update.json", config.twitter.access_token_key, config.twitter.access_token_secret, {"status": body_to_haiku(message.message) }, "application/json", (error, data, response2) -> if error console.log(error) if error callback(error, null) return callback(null, data) ) app = module.exports = express.createServer() # Configuration app.configure -> app.use express.bodyParser() app.use express.methodOverride() app.use express.logger() app.use app.router app.configure 'development', -> app.use express.errorHandler dumpExceptions: true showStack: true app.configure 'production', -> app.use express.errorHandler() all_good_words = (lines) -> for words in lines for word in words if not (new RegExp('\\b' + word + '\\b')).test(wordstream) return false return true address_tracker = new AddressTracker(config.tracker.database, config.tracker.username, config.tracker.password) twitter_poster = new TwitterPoster() # Our single route app.post '/poems/', (req, res) -> if not req.body? or not req.body.message? res.send({error: true, code: -1, message: "We did not receive a poem."}) return if not all_good_words(req.body.message) res.send({error: true, code: -1, message: "ERROR -5: HACKSTOP."}) return address_tracker.validate req.headers['x-forwarded-for'], req.body, (err, result) -> if err != null console.log(err) res.send({error: true, code: 1, message: err}) return twitter_poster.post req.body, (err, result) -> if err != null console.log(err) res.send({error: true, code: 2, message: err}) return res.send({error: false, message: result}) address_tracker.connect () -> app.listen 8012 console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
135951
express = require 'express' mysql = require('db-mysql') OAuth = require('oauth').OAuth util = require('util') config = require('./config') fs = require('fs') wordlist = JSON.parse(fs.readFileSync('./wordlist.js', 'utf-8')) wordstream = (i.w for i in wordlist).join(' ') body_to_haiku = (lines) -> ret = (for words in lines line = words[0].w for word in words[1...words.length] line += if word.s == 1 then word.w else ' ' + word.w line).join(" / ") console.log(ret) ret class AddressTracker constructor: (database, username, password) -> @db = new mysql.Database({ "hostname": "localhost" "user": username "password": <PASSWORD> "database": database}) @db.on('ready', () -> @connection = this) @db.on('error', () -> console.log(arguments)) connect: (cb) -> atrack = @ @db.connect () -> atrack.connection = this cb.apply(this, arguments) validate: (ip_address, message, cb) -> yesterday = new Date((new Date()).valueOf() - 1000 * 86400) connection = @connection connection.query(). select('*'). from('tweets'). where('address = ? and entered > ?', [ip_address, yesterday]). execute (err, rows, cols) -> return cb(err, null) if (err) return cb("You've used up your allotted number of tweets today", null) if rows.length > 10 connection.query(). select('*'). from('tweets'). where('tweet = ?', [body_to_haiku(message.message)]). execute (err, rows, cols) -> return cb(err, null) if (err) return cb("You've already sent that poem!", null) if rows.length > 0 connection.query(). insert('tweets', ['address', 'tweet', 'entered'], [ip_address, body_to_haiku(message.message), (new Date())]). execute (err, result) -> return cb(err, null) if err cb(null, result) class TwitterPoster constructor: -> @oauth = new OAuth( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", config.twitter.consumer_key, config.twitter.consumer_private_key, "1.0", null, "HMAC-SHA1" ) post: (message, callback) -> @oauth.post( "http://api.twitter.com/1/statuses/update.json", config.twitter.access_token_key, config.twitter.access_token_secret, {"status": body_to_haiku(message.message) }, "application/json", (error, data, response2) -> if error console.log(error) if error callback(error, null) return callback(null, data) ) app = module.exports = express.createServer() # Configuration app.configure -> app.use express.bodyParser() app.use express.methodOverride() app.use express.logger() app.use app.router app.configure 'development', -> app.use express.errorHandler dumpExceptions: true showStack: true app.configure 'production', -> app.use express.errorHandler() all_good_words = (lines) -> for words in lines for word in words if not (new RegExp('\\b' + word + '\\b')).test(wordstream) return false return true address_tracker = new AddressTracker(config.tracker.database, config.tracker.username, config.tracker.password) twitter_poster = new TwitterPoster() # Our single route app.post '/poems/', (req, res) -> if not req.body? or not req.body.message? res.send({error: true, code: -1, message: "We did not receive a poem."}) return if not all_good_words(req.body.message) res.send({error: true, code: -1, message: "ERROR -5: HACKSTOP."}) return address_tracker.validate req.headers['x-forwarded-for'], req.body, (err, result) -> if err != null console.log(err) res.send({error: true, code: 1, message: err}) return twitter_poster.post req.body, (err, result) -> if err != null console.log(err) res.send({error: true, code: 2, message: err}) return res.send({error: false, message: result}) address_tracker.connect () -> app.listen 8012 console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
true
express = require 'express' mysql = require('db-mysql') OAuth = require('oauth').OAuth util = require('util') config = require('./config') fs = require('fs') wordlist = JSON.parse(fs.readFileSync('./wordlist.js', 'utf-8')) wordstream = (i.w for i in wordlist).join(' ') body_to_haiku = (lines) -> ret = (for words in lines line = words[0].w for word in words[1...words.length] line += if word.s == 1 then word.w else ' ' + word.w line).join(" / ") console.log(ret) ret class AddressTracker constructor: (database, username, password) -> @db = new mysql.Database({ "hostname": "localhost" "user": username "password": PI:PASSWORD:<PASSWORD>END_PI "database": database}) @db.on('ready', () -> @connection = this) @db.on('error', () -> console.log(arguments)) connect: (cb) -> atrack = @ @db.connect () -> atrack.connection = this cb.apply(this, arguments) validate: (ip_address, message, cb) -> yesterday = new Date((new Date()).valueOf() - 1000 * 86400) connection = @connection connection.query(). select('*'). from('tweets'). where('address = ? and entered > ?', [ip_address, yesterday]). execute (err, rows, cols) -> return cb(err, null) if (err) return cb("You've used up your allotted number of tweets today", null) if rows.length > 10 connection.query(). select('*'). from('tweets'). where('tweet = ?', [body_to_haiku(message.message)]). execute (err, rows, cols) -> return cb(err, null) if (err) return cb("You've already sent that poem!", null) if rows.length > 0 connection.query(). insert('tweets', ['address', 'tweet', 'entered'], [ip_address, body_to_haiku(message.message), (new Date())]). execute (err, result) -> return cb(err, null) if err cb(null, result) class TwitterPoster constructor: -> @oauth = new OAuth( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", config.twitter.consumer_key, config.twitter.consumer_private_key, "1.0", null, "HMAC-SHA1" ) post: (message, callback) -> @oauth.post( "http://api.twitter.com/1/statuses/update.json", config.twitter.access_token_key, config.twitter.access_token_secret, {"status": body_to_haiku(message.message) }, "application/json", (error, data, response2) -> if error console.log(error) if error callback(error, null) return callback(null, data) ) app = module.exports = express.createServer() # Configuration app.configure -> app.use express.bodyParser() app.use express.methodOverride() app.use express.logger() app.use app.router app.configure 'development', -> app.use express.errorHandler dumpExceptions: true showStack: true app.configure 'production', -> app.use express.errorHandler() all_good_words = (lines) -> for words in lines for word in words if not (new RegExp('\\b' + word + '\\b')).test(wordstream) return false return true address_tracker = new AddressTracker(config.tracker.database, config.tracker.username, config.tracker.password) twitter_poster = new TwitterPoster() # Our single route app.post '/poems/', (req, res) -> if not req.body? or not req.body.message? res.send({error: true, code: -1, message: "We did not receive a poem."}) return if not all_good_words(req.body.message) res.send({error: true, code: -1, message: "ERROR -5: HACKSTOP."}) return address_tracker.validate req.headers['x-forwarded-for'], req.body, (err, result) -> if err != null console.log(err) res.send({error: true, code: 1, message: err}) return twitter_poster.post req.body, (err, result) -> if err != null console.log(err) res.send({error: true, code: 2, message: err}) return res.send({error: false, message: result}) address_tracker.connect () -> app.listen 8012 console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
[ { "context": "CompanyIds();\n\t# params[\"X-Auth-Token\"] = Accounts._storedLoginToken();\n\tsdk = require(\"@steedos/builder-com", "end": 9512, "score": 0.5480586886405945, "start": 9506, "tag": "KEY", "value": "stored" } ]
creator/packages/steedos-creator/core.coffee
baozhoutao/steedos-platform
0
# Creator.initApps() # Creator.initApps = ()-> # if Meteor.isServer # _.each Creator.Apps, (app, app_id)-> # db_app = db.apps.findOne(app_id) # if !db_app # app._id = app_id # db.apps.insert(app) # else # app._id = app_id # db.apps.update({_id: app_id}, app) Creator.getSchema = (object_name)-> return Creator.getObject(object_name)?.schema Creator.getObjectHomeComponent = (object_name)-> if Meteor.isClient return ReactSteedos.pluginComponentSelector(ReactSteedos.store.getState(), "ObjectHome", object_name) Creator.getObjectUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id) else if object_name is "meeting" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else if Creator.getObjectHomeComponent(object_name) return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name) else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getObjectAbsoluteUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id, true) else if object_name is "meeting" return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/calendar/", true) else return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id, true) Creator.getObjectRouterUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return "/app/" + app_id + "/" + object_name + "/view/" + record_id else if object_name is "meeting" return "/app/" + app_id + "/" + object_name + "/calendar/" else return "/app/" + app_id + "/" + object_name + "/grid/" + list_view_id Creator.getListViewUrl = (object_name, app_id, list_view_id) -> url = Creator.getListViewRelativeUrl(object_name, app_id, list_view_id) return Creator.getRelativeUrl(url) Creator.getListViewRelativeUrl = (object_name, app_id, list_view_id) -> if list_view_id is "calendar" return "/app/" + app_id + "/" + object_name + "/calendar/" else return "/app/" + app_id + "/" + object_name + "/grid/" + list_view_id Creator.getSwitchListUrl = (object_name, app_id, list_view_id) -> if list_view_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + list_view_id + "/list") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/list/switch") Creator.getRelatedObjectUrl = (object_name, app_id, record_id, related_object_name, related_field_name) -> if related_field_name return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid?related_field_name=" + related_field_name) else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid") Creator.getObjectLookupFieldOptions = (object_name, is_deep, is_skip_hide, is_related)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields icon = _object?.icon _.forEach fields, (f, k)-> if is_skip_hide and f.hidden return if f.type == "select" _options.push {label: "#{f.label || k}", value: "#{k}", icon: icon} else _options.push {label: f.label || k, value: k, icon: icon} if is_deep _.forEach fields, (f, k)-> if is_skip_hide and f.hidden return if (f.type == "lookup" || f.type == "master_detail") && f.reference_to && _.isString(f.reference_to) # 不支持f.reference_to为function的情况,有需求再说 r_object = Creator.getObject(f.reference_to) if r_object _.forEach r_object.fields, (f2, k2)-> _options.push {label: "#{f.label || k}=>#{f2.label || k2}", value: "#{k}.#{k2}", icon: r_object?.icon} if is_related relatedObjects = Creator.getRelatedObjects(object_name) _.each relatedObjects, (_relatedObject)=> relatedOptions = Creator.getObjectLookupFieldOptions(_relatedObject.object_name, false, false, false) relatedObject = Creator.getObject(_relatedObject.object_name) _.each relatedOptions, (relatedOption)-> if _relatedObject.foreign_key != relatedOption.value _options.push {label: "#{relatedObject.label || relatedObject.name}=>#{relatedOption.label}", value: "#{relatedObject.name}.#{relatedOption.value}", icon: relatedObject?.icon} return _options # 统一为对象object_name提供可用于过虑器过虑字段 Creator.getObjectFilterFieldOptions = (object_name)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields permission_fields = Creator.getFields(object_name) icon = _object?.icon _.forEach fields, (f, k)-> # hidden,grid等类型的字段,不需要过滤 if !_.include(["grid","object", "[Object]", "[object]", "Object", "avatar", "image", "markdown", "html"], f.type) and !f.hidden # filters.$.field及flow.current等子字段也不需要过滤 if !/\w+\./.test(k) and _.indexOf(permission_fields, k) > -1 _options.push {label: f.label || k, value: k, icon: icon} return _options Creator.getObjectFieldOptions = (object_name)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields permission_fields = Creator.getFields(object_name) icon = _object?.icon _.forEach fields, (f, k)-> if !_.include(["grid","object", "[Object]", "[object]", "Object", "markdown", "html"], f.type) if !/\w+\./.test(k) and _.indexOf(permission_fields, k) > -1 _options.push {label: f.label || k, value: k, icon: icon} return _options ### filters: 要转换的filters fields: 对象字段 filter_fields: 默认过滤字段,支持字符串数组和对象数组两种格式,如:['filed_name1','filed_name2'],[{field:'filed_name1',required:true}] 处理逻辑: 把filters中存在于filter_fields的过滤条件增加每项的is_default、is_required属性,不存在于filter_fields的过滤条件对应的移除每项的相关属性 返回结果: 处理后的filters ### Creator.getFiltersWithFilterFields = (filters, fields, filter_fields)-> unless filters filters = [] unless filter_fields filter_fields = [] if filter_fields?.length filter_fields.forEach (n)-> if _.isString(n) n = field: n, required: false if fields[n.field] and !_.findWhere(filters,{field:n.field}) filters.push field: n.field, is_default: true, is_required: n.required filters.forEach (filterItem)-> matchField = filter_fields.find (n)-> return n == filterItem.field or n.field == filterItem.field if _.isString(matchField) matchField = field: matchField, required: false if matchField filterItem.is_default = true filterItem.is_required = matchField.required else delete filterItem.is_default delete filterItem.is_required return filters Creator.getObjectRecord = (object_name, record_id, select_fields, expand)-> if !object_name object_name = Session.get("object_name") if !record_id record_id = Session.get("record_id") if Meteor.isClient if object_name == Session.get("object_name") && record_id == Session.get("record_id") if Template.instance()?.record return Template.instance()?.record?.get() else return Creator.odata.get(object_name, record_id, select_fields, expand) collection = Creator.getCollection(object_name) if collection record = collection.findOne(record_id) return record Creator.getObjectRecordName = (record, object_name)-> unless record record = Creator.getObjectRecord() if record # 显示组织列表时,特殊处理name_field_key为name字段 name_field_key = if object_name == "organizations" then "name" else Creator.getObject(object_name)?.NAME_FIELD_KEY if record and name_field_key return record.label || record[name_field_key] Creator.getApp = (app_id)-> if !app_id app_id = Session.get("app_id") app = Creator.Apps[app_id] Creator.deps?.app?.depend() return app Creator.getAppDashboard = (app_id)-> app = Creator.getApp(app_id) if !app return dashboard = null _.each Creator.Dashboards, (v, k)-> if v.apps?.indexOf(app._id) > -1 dashboard = v; return dashboard; Creator.getAppDashboardComponent = (app_id)-> app = Creator.getApp(app_id) if !app return return ReactSteedos.pluginComponentSelector(ReactSteedos.store.getState(), "Dashboard", app._id); Creator.getAppObjectNames = (app_id)-> app = Creator.getApp(app_id) if !app return isMobile = Steedos.isMobile() appObjects = if isMobile then app.mobile_objects else app.objects objects = [] if app _.each appObjects, (v)-> obj = Creator.getObject(v) if obj?.permissions.get().allowRead objects.push v return objects Creator.getAppMenu = (app_id, menu_id)-> menus = Creator.getAppMenus(app_id) return menus && menus.find (menu)-> return menu.id == menu_id Creator.getAppMenuUrlForInternet = (menu)-> # 当tabs类型为url时,按外部链接处理,支持配置表达式并加上统一的url参数 params = {}; params["X-Space-Id"] = Steedos.spaceId() params["X-User-Id"] = Steedos.userId(); params["X-Company-Ids"] = Steedos.getUserCompanyIds(); # params["X-Auth-Token"] = Accounts._storedLoginToken(); sdk = require("@steedos/builder-community/dist/builder-community.react.js") url = menu.path if sdk and sdk.Utils and sdk.Utils.isExpression(url) url = sdk.Utils.parseSingleExpression(url, menu, "#", Creator.USER_CONTEXT) linkStr = if url.indexOf("?") < 0 then "?" else "&" return "#{url}#{linkStr}#{$.param(params)}" Creator.getAppMenuUrl = (menu)-> url = menu.path if menu.type == "url" if menu.target return Creator.getAppMenuUrlForInternet(menu) else # 在iframe中显示url界面 return "/app/-/tab_iframe/#{menu.id}" else return menu.path Creator.getAppMenus = (app_id)-> app = Creator.getApp(app_id) if !app return [] appMenus = Session.get("app_menus"); unless appMenus return [] curentAppMenus = appMenus.find (menuItem) -> return menuItem.id == app._id if curentAppMenus return curentAppMenus.children Creator.loadAppsMenus = ()-> isMobile = Steedos.isMobile() data = { } if isMobile data.mobile = isMobile options = { type: 'get', data: data, success: (data)-> Session.set("app_menus", data); } Steedos.authRequest "/service/api/apps/menus", options Creator.getVisibleApps = (includeAdmin)-> changeApp = Creator._subApp.get(); ReactSteedos.store.getState().entities.apps = Object.assign({}, ReactSteedos.store.getState().entities.apps, {apps: changeApp}); return ReactSteedos.visibleAppsSelector(ReactSteedos.store.getState(), includeAdmin) Creator.getVisibleAppsObjects = ()-> apps = Creator.getVisibleApps() visibleObjectNames = _.flatten(_.pluck(apps,'objects')) objects = _.filter Creator.Objects, (obj)-> if visibleObjectNames.indexOf(obj.name) < 0 return false else return true objects = objects.sort(Creator.sortingMethod.bind({key:"label"})) objects = _.pluck(objects,'name') return _.uniq objects Creator.getAppsObjects = ()-> objects = [] tempObjects = [] _.forEach Creator.Apps, (app)-> tempObjects = _.filter app.objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) return _.uniq objects Creator.validateFilters = (filters, logic)-> filter_items = _.map filters, (obj) -> if _.isEmpty(obj) return false else return obj filter_items = _.compact(filter_items) errorMsg = "" filter_length = filter_items.length if logic # 格式化filter logic = logic.replace(/\n/g, "").replace(/\s+/g, " ") # 判断特殊字符 if /[._\-!+]+/ig.test(logic) errorMsg = "含有特殊字符。" if !errorMsg index = logic.match(/\d+/ig) if !index errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" else index.forEach (i)-> if i < 1 or i > filter_length errorMsg = "您的筛选条件引用了未定义的筛选器:#{i}。" flag = 1 while flag <= filter_length if !index.includes("#{flag}") errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" flag++; if !errorMsg # 判断是否有非法英文字符 word = logic.match(/[a-zA-Z]+/ig) if word word.forEach (w)-> if !/^(and|or)$/ig.test(w) errorMsg = "检查您的高级筛选条件中的拼写。" if !errorMsg # 判断格式是否正确 try Creator.eval(logic.replace(/and/ig, "&&").replace(/or/ig, "||")) catch e errorMsg = "您的筛选器中含有特殊字符" if /(AND)[^()]+(OR)/ig.test(logic) || /(OR)[^()]+(AND)/ig.test(logic) errorMsg = "您的筛选器必须在连续性的 AND 和 OR 表达式前后使用括号。" if errorMsg console.log "error", errorMsg if Meteor.isClient toastr.error(errorMsg) return false else return true # "=", "<>", ">", ">=", "<", "<=", "startswith", "contains", "notcontains". ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToMongo = (filters, options)-> unless filters?.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = {} sub_selector[field] = {} if option == "=" sub_selector[field]["$eq"] = value else if option == "<>" sub_selector[field]["$ne"] = value else if option == ">" sub_selector[field]["$gt"] = value else if option == ">=" sub_selector[field]["$gte"] = value else if option == "<" sub_selector[field]["$lt"] = value else if option == "<=" sub_selector[field]["$lte"] = value else if option == "startswith" reg = new RegExp("^" + value, "i") sub_selector[field]["$regex"] = reg else if option == "contains" reg = new RegExp(value, "i") sub_selector[field]["$regex"] = reg else if option == "notcontains" reg = new RegExp("^((?!" + value + ").)*$", "i") sub_selector[field]["$regex"] = reg selector.push sub_selector return selector Creator.isBetweenFilterOperation = (operation)-> return operation == "between" or !!Creator.getBetweenTimeBuiltinValues(true)?[operation] ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToDev = (filters, object_name, options)-> steedosFilters = require("@steedos/filters"); unless filters.length return if options?.is_logic_or # 如果is_logic_or为true,为filters第一层元素增加or间隔 logicTempFilters = [] filters.forEach (n)-> logicTempFilters.push(n) logicTempFilters.push("or") logicTempFilters.pop() filters = logicTempFilters selector = steedosFilters.formatFiltersToDev(filters, Creator.USER_CONTEXT) return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatLogicFiltersToDev = (filters, filter_logic, options)-> format_logic = filter_logic.replace(/\(\s+/ig, "(").replace(/\s+\)/ig, ")").replace(/\(/g, "[").replace(/\)/g, "]").replace(/\s+/g, ",").replace(/(and|or)/ig, "'$1'") format_logic = format_logic.replace(/(\d)+/ig, (x)-> _f = filters[x-1] field = _f.field option = _f.operation if Meteor.isClient value = Creator.evaluateFormula(_f.value) else value = Creator.evaluateFormula(_f.value, null, options) sub_selector = [] if _.isArray(value) == true if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() else sub_selector = [field, option, value] console.log "sub_selector", sub_selector return JSON.stringify(sub_selector) ) format_logic = "[#{format_logic}]" return Creator.eval(format_logic) Creator.getRelatedObjects = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() related_object_names = [] _object = Creator.getObject(object_name) if !_object return related_object_names # related_object_names = _.pluck(_object.related_objects,"object_name") related_objects = Creator.getObjectRelateds(_object._collection_name) related_object_names = _.pluck(related_objects,"object_name") if related_object_names?.length == 0 return related_object_names permissions = Creator.getPermissions(object_name, spaceId, userId) unrelated_objects = permissions.unrelated_objects related_object_names = _.difference related_object_names, unrelated_objects return _.filter related_objects, (related_object)-> related_object_name = related_object.object_name isActive = related_object_names.indexOf(related_object_name) > -1 # related_object_name = if related_object_name == "cfs_files_filerecord" then "cfs.files.filerecord" else related_object_name allowRead = Creator.getPermissions(related_object_name, spaceId, userId)?.allowRead if related_object_name == "cms_files" allowRead = allowRead && permissions.allowReadFiles return isActive and allowRead Creator.getRelatedObjectNames = (object_name, spaceId, userId)-> related_objects = Creator.getRelatedObjects(object_name, spaceId, userId) return _.pluck(related_objects,"object_name") Creator.getActions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() obj = Creator.getObject(object_name) if !obj return permissions = Creator.getPermissions(object_name, spaceId, userId) disabled_actions = permissions.disabled_actions actions = _.sortBy(_.values(obj.actions) , 'sort'); if _.has(obj, 'allow_customActions') actions = _.filter actions, (action)-> return _.include(obj.allow_customActions, action.name) || _.include(_.keys(Creator.getObject('base').actions) || {}, action.name) if _.has(obj, 'exclude_actions') actions = _.filter actions, (action)-> return !_.include(obj.exclude_actions, action.name) _.each actions, (action)-> # 手机上只显示编辑按钮,其他的放到折叠下拉菜单中 if Steedos.isMobile() && ["record", "record_only"].indexOf(action.on) > -1 && action.name != 'standard_edit' if action.on == "record_only" action.on = 'record_only_more' else action.on = 'record_more' if Steedos.isMobile() && ["cms_files", "cfs.files.filerecord"].indexOf(object_name) > -1 # 附件特殊处理,下载按钮放在主菜单,编辑按钮放到底下折叠下拉菜单中 actions.find((n)-> return n.name == "standard_edit")?.on = "record_more" actions.find((n)-> return n.name == "download")?.on = "record" actions = _.filter actions, (action)-> return _.indexOf(disabled_actions, action.name) < 0 return actions /// 返回当前用户有权限访问的所有list_view,包括分享的,用户自定义非分享的(除非owner变了),以及默认的其他视图 注意Creator.getPermissions函数中是不会有用户自定义非分享的视图的,所以Creator.getPermissions函数中拿到的结果不全,并不是当前用户能看到所有视图 /// Creator.getListViews = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() unless object_name return object = Creator.getObject(object_name) if !object return disabled_list_views = Creator.getPermissions(object_name, spaceId, userId)?.disabled_list_views || [] list_views = [] isMobile = Steedos.isMobile() _.each object.list_views, (item, item_name)-> item.name = item_name listViews = _.sortBy(_.values(object.list_views) , 'sort_no'); _.each listViews, (item)-> if isMobile and item.type == "calendar" # 手机上先不显示日历视图 return if item.name != "default" isDisabled = _.indexOf(disabled_list_views, item.name) > -1 || (item._id && _.indexOf(disabled_list_views, item._id) > -1) if !isDisabled || item.owner == userId list_views.push item return list_views # 前台理论上不应该调用该函数,因为字段的权限都在Creator.getObject(object_name).fields的相关属性中有标识了 Creator.getFields = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() fieldsName = Creator.getObjectFieldsName(object_name) unreadable_fields = Creator.getPermissions(object_name, spaceId, userId)?.unreadable_fields return _.difference(fieldsName, unreadable_fields) Creator.isloading = ()-> return !Creator.bootstrapLoaded.get() Creator.convertSpecialCharacter = (str)-> return str.replace(/([\^\$\(\)\*\+\?\.\\\|\[\]\{\}])/g, "\\$1") # 计算fields相关函数 # START Creator.getDisabledFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.disabled and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getHiddenFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.type == "hidden" and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithNoGroup = (schema)-> fields = _.map(schema, (field, fieldName) -> return (!field.autoform or !field.autoform.group or field.autoform.group == "-") and (!field.autoform or field.autoform.type != "hidden") and fieldName ) fields = _.compact(fields) return fields Creator.getSortedFieldGroupNames = (schema)-> names = _.map(schema, (field) -> return field.autoform and field.autoform.group != "-" and field.autoform.group ) names = _.compact(names) names = _.unique(names) return names Creator.getFieldsForGroup = (schema, groupName) -> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.group == groupName and field.autoform.type != "hidden" and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithoutOmit = (schema, keys) -> keys = _.map(keys, (key) -> field = _.pick(schema, key) if field[key].autoform?.omit return false else return key ) keys = _.compact(keys) return keys Creator.getFieldsInFirstLevel = (firstLevelKeys, keys) -> keys = _.map(keys, (key) -> if _.indexOf(firstLevelKeys, key) > -1 return key else return false ) keys = _.compact(keys) return keys Creator.getFieldsForReorder = (schema, keys, isSingle) -> fields = [] i = 0 _keys = _.filter(keys, (key)-> return !key.endsWith('_endLine') ); while i < _keys.length sc_1 = _.pick(schema, _keys[i]) sc_2 = _.pick(schema, _keys[i+1]) is_wide_1 = false is_wide_2 = false # is_range_1 = false # is_range_2 = false _.each sc_1, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_1 = true # if value.autoform?.is_range # is_range_1 = true _.each sc_2, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_2 = true # if value.autoform?.is_range # is_range_2 = true if Steedos.isMobile() is_wide_1 = true is_wide_2 = true if isSingle fields.push _keys.slice(i, i+1) i += 1 else # if !is_range_1 && is_range_2 # childKeys = _keys.slice(i, i+1) # childKeys.push undefined # fields.push childKeys # i += 1 # else if is_wide_1 fields.push _keys.slice(i, i+1) i += 1 else if !is_wide_1 and is_wide_2 childKeys = _keys.slice(i, i+1) childKeys.push undefined fields.push childKeys i += 1 else if !is_wide_1 and !is_wide_2 childKeys = _keys.slice(i, i+1) if _keys[i+1] childKeys.push _keys[i+1] else childKeys.push undefined fields.push childKeys i += 2 return fields Creator.isFilterValueEmpty = (v) -> return typeof v == "undefined" || v == null || Number.isNaN(v) || v.length == 0 Creator.getFieldDataType = (objectFields, key)-> if objectFields and key result = objectFields[key]?.type if ["formula", "summary"].indexOf(result) > -1 result = objectFields[key].data_type return result else return "text" # END if Meteor.isServer Creator.getAllRelatedObjects = (object_name)-> related_object_names = [] _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name related_object_names.push related_object_name if Creator.getObject(object_name).enable_files related_object_names.push "cms_files" return related_object_names if Meteor.isServer Steedos.formatIndex = (array) -> object = { background: true }; isdocumentDB = Meteor.settings?.datasources?.default?.documentDB || false; if isdocumentDB if array.length > 0 indexName = array.join("."); object.name = indexName; if (indexName.length > 52) object.name = indexName.substring(0,52); return object;
217421
# Creator.initApps() # Creator.initApps = ()-> # if Meteor.isServer # _.each Creator.Apps, (app, app_id)-> # db_app = db.apps.findOne(app_id) # if !db_app # app._id = app_id # db.apps.insert(app) # else # app._id = app_id # db.apps.update({_id: app_id}, app) Creator.getSchema = (object_name)-> return Creator.getObject(object_name)?.schema Creator.getObjectHomeComponent = (object_name)-> if Meteor.isClient return ReactSteedos.pluginComponentSelector(ReactSteedos.store.getState(), "ObjectHome", object_name) Creator.getObjectUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id) else if object_name is "meeting" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else if Creator.getObjectHomeComponent(object_name) return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name) else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getObjectAbsoluteUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id, true) else if object_name is "meeting" return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/calendar/", true) else return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id, true) Creator.getObjectRouterUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return "/app/" + app_id + "/" + object_name + "/view/" + record_id else if object_name is "meeting" return "/app/" + app_id + "/" + object_name + "/calendar/" else return "/app/" + app_id + "/" + object_name + "/grid/" + list_view_id Creator.getListViewUrl = (object_name, app_id, list_view_id) -> url = Creator.getListViewRelativeUrl(object_name, app_id, list_view_id) return Creator.getRelativeUrl(url) Creator.getListViewRelativeUrl = (object_name, app_id, list_view_id) -> if list_view_id is "calendar" return "/app/" + app_id + "/" + object_name + "/calendar/" else return "/app/" + app_id + "/" + object_name + "/grid/" + list_view_id Creator.getSwitchListUrl = (object_name, app_id, list_view_id) -> if list_view_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + list_view_id + "/list") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/list/switch") Creator.getRelatedObjectUrl = (object_name, app_id, record_id, related_object_name, related_field_name) -> if related_field_name return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid?related_field_name=" + related_field_name) else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid") Creator.getObjectLookupFieldOptions = (object_name, is_deep, is_skip_hide, is_related)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields icon = _object?.icon _.forEach fields, (f, k)-> if is_skip_hide and f.hidden return if f.type == "select" _options.push {label: "#{f.label || k}", value: "#{k}", icon: icon} else _options.push {label: f.label || k, value: k, icon: icon} if is_deep _.forEach fields, (f, k)-> if is_skip_hide and f.hidden return if (f.type == "lookup" || f.type == "master_detail") && f.reference_to && _.isString(f.reference_to) # 不支持f.reference_to为function的情况,有需求再说 r_object = Creator.getObject(f.reference_to) if r_object _.forEach r_object.fields, (f2, k2)-> _options.push {label: "#{f.label || k}=>#{f2.label || k2}", value: "#{k}.#{k2}", icon: r_object?.icon} if is_related relatedObjects = Creator.getRelatedObjects(object_name) _.each relatedObjects, (_relatedObject)=> relatedOptions = Creator.getObjectLookupFieldOptions(_relatedObject.object_name, false, false, false) relatedObject = Creator.getObject(_relatedObject.object_name) _.each relatedOptions, (relatedOption)-> if _relatedObject.foreign_key != relatedOption.value _options.push {label: "#{relatedObject.label || relatedObject.name}=>#{relatedOption.label}", value: "#{relatedObject.name}.#{relatedOption.value}", icon: relatedObject?.icon} return _options # 统一为对象object_name提供可用于过虑器过虑字段 Creator.getObjectFilterFieldOptions = (object_name)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields permission_fields = Creator.getFields(object_name) icon = _object?.icon _.forEach fields, (f, k)-> # hidden,grid等类型的字段,不需要过滤 if !_.include(["grid","object", "[Object]", "[object]", "Object", "avatar", "image", "markdown", "html"], f.type) and !f.hidden # filters.$.field及flow.current等子字段也不需要过滤 if !/\w+\./.test(k) and _.indexOf(permission_fields, k) > -1 _options.push {label: f.label || k, value: k, icon: icon} return _options Creator.getObjectFieldOptions = (object_name)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields permission_fields = Creator.getFields(object_name) icon = _object?.icon _.forEach fields, (f, k)-> if !_.include(["grid","object", "[Object]", "[object]", "Object", "markdown", "html"], f.type) if !/\w+\./.test(k) and _.indexOf(permission_fields, k) > -1 _options.push {label: f.label || k, value: k, icon: icon} return _options ### filters: 要转换的filters fields: 对象字段 filter_fields: 默认过滤字段,支持字符串数组和对象数组两种格式,如:['filed_name1','filed_name2'],[{field:'filed_name1',required:true}] 处理逻辑: 把filters中存在于filter_fields的过滤条件增加每项的is_default、is_required属性,不存在于filter_fields的过滤条件对应的移除每项的相关属性 返回结果: 处理后的filters ### Creator.getFiltersWithFilterFields = (filters, fields, filter_fields)-> unless filters filters = [] unless filter_fields filter_fields = [] if filter_fields?.length filter_fields.forEach (n)-> if _.isString(n) n = field: n, required: false if fields[n.field] and !_.findWhere(filters,{field:n.field}) filters.push field: n.field, is_default: true, is_required: n.required filters.forEach (filterItem)-> matchField = filter_fields.find (n)-> return n == filterItem.field or n.field == filterItem.field if _.isString(matchField) matchField = field: matchField, required: false if matchField filterItem.is_default = true filterItem.is_required = matchField.required else delete filterItem.is_default delete filterItem.is_required return filters Creator.getObjectRecord = (object_name, record_id, select_fields, expand)-> if !object_name object_name = Session.get("object_name") if !record_id record_id = Session.get("record_id") if Meteor.isClient if object_name == Session.get("object_name") && record_id == Session.get("record_id") if Template.instance()?.record return Template.instance()?.record?.get() else return Creator.odata.get(object_name, record_id, select_fields, expand) collection = Creator.getCollection(object_name) if collection record = collection.findOne(record_id) return record Creator.getObjectRecordName = (record, object_name)-> unless record record = Creator.getObjectRecord() if record # 显示组织列表时,特殊处理name_field_key为name字段 name_field_key = if object_name == "organizations" then "name" else Creator.getObject(object_name)?.NAME_FIELD_KEY if record and name_field_key return record.label || record[name_field_key] Creator.getApp = (app_id)-> if !app_id app_id = Session.get("app_id") app = Creator.Apps[app_id] Creator.deps?.app?.depend() return app Creator.getAppDashboard = (app_id)-> app = Creator.getApp(app_id) if !app return dashboard = null _.each Creator.Dashboards, (v, k)-> if v.apps?.indexOf(app._id) > -1 dashboard = v; return dashboard; Creator.getAppDashboardComponent = (app_id)-> app = Creator.getApp(app_id) if !app return return ReactSteedos.pluginComponentSelector(ReactSteedos.store.getState(), "Dashboard", app._id); Creator.getAppObjectNames = (app_id)-> app = Creator.getApp(app_id) if !app return isMobile = Steedos.isMobile() appObjects = if isMobile then app.mobile_objects else app.objects objects = [] if app _.each appObjects, (v)-> obj = Creator.getObject(v) if obj?.permissions.get().allowRead objects.push v return objects Creator.getAppMenu = (app_id, menu_id)-> menus = Creator.getAppMenus(app_id) return menus && menus.find (menu)-> return menu.id == menu_id Creator.getAppMenuUrlForInternet = (menu)-> # 当tabs类型为url时,按外部链接处理,支持配置表达式并加上统一的url参数 params = {}; params["X-Space-Id"] = Steedos.spaceId() params["X-User-Id"] = Steedos.userId(); params["X-Company-Ids"] = Steedos.getUserCompanyIds(); # params["X-Auth-Token"] = Accounts._<KEY>LoginToken(); sdk = require("@steedos/builder-community/dist/builder-community.react.js") url = menu.path if sdk and sdk.Utils and sdk.Utils.isExpression(url) url = sdk.Utils.parseSingleExpression(url, menu, "#", Creator.USER_CONTEXT) linkStr = if url.indexOf("?") < 0 then "?" else "&" return "#{url}#{linkStr}#{$.param(params)}" Creator.getAppMenuUrl = (menu)-> url = menu.path if menu.type == "url" if menu.target return Creator.getAppMenuUrlForInternet(menu) else # 在iframe中显示url界面 return "/app/-/tab_iframe/#{menu.id}" else return menu.path Creator.getAppMenus = (app_id)-> app = Creator.getApp(app_id) if !app return [] appMenus = Session.get("app_menus"); unless appMenus return [] curentAppMenus = appMenus.find (menuItem) -> return menuItem.id == app._id if curentAppMenus return curentAppMenus.children Creator.loadAppsMenus = ()-> isMobile = Steedos.isMobile() data = { } if isMobile data.mobile = isMobile options = { type: 'get', data: data, success: (data)-> Session.set("app_menus", data); } Steedos.authRequest "/service/api/apps/menus", options Creator.getVisibleApps = (includeAdmin)-> changeApp = Creator._subApp.get(); ReactSteedos.store.getState().entities.apps = Object.assign({}, ReactSteedos.store.getState().entities.apps, {apps: changeApp}); return ReactSteedos.visibleAppsSelector(ReactSteedos.store.getState(), includeAdmin) Creator.getVisibleAppsObjects = ()-> apps = Creator.getVisibleApps() visibleObjectNames = _.flatten(_.pluck(apps,'objects')) objects = _.filter Creator.Objects, (obj)-> if visibleObjectNames.indexOf(obj.name) < 0 return false else return true objects = objects.sort(Creator.sortingMethod.bind({key:"label"})) objects = _.pluck(objects,'name') return _.uniq objects Creator.getAppsObjects = ()-> objects = [] tempObjects = [] _.forEach Creator.Apps, (app)-> tempObjects = _.filter app.objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) return _.uniq objects Creator.validateFilters = (filters, logic)-> filter_items = _.map filters, (obj) -> if _.isEmpty(obj) return false else return obj filter_items = _.compact(filter_items) errorMsg = "" filter_length = filter_items.length if logic # 格式化filter logic = logic.replace(/\n/g, "").replace(/\s+/g, " ") # 判断特殊字符 if /[._\-!+]+/ig.test(logic) errorMsg = "含有特殊字符。" if !errorMsg index = logic.match(/\d+/ig) if !index errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" else index.forEach (i)-> if i < 1 or i > filter_length errorMsg = "您的筛选条件引用了未定义的筛选器:#{i}。" flag = 1 while flag <= filter_length if !index.includes("#{flag}") errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" flag++; if !errorMsg # 判断是否有非法英文字符 word = logic.match(/[a-zA-Z]+/ig) if word word.forEach (w)-> if !/^(and|or)$/ig.test(w) errorMsg = "检查您的高级筛选条件中的拼写。" if !errorMsg # 判断格式是否正确 try Creator.eval(logic.replace(/and/ig, "&&").replace(/or/ig, "||")) catch e errorMsg = "您的筛选器中含有特殊字符" if /(AND)[^()]+(OR)/ig.test(logic) || /(OR)[^()]+(AND)/ig.test(logic) errorMsg = "您的筛选器必须在连续性的 AND 和 OR 表达式前后使用括号。" if errorMsg console.log "error", errorMsg if Meteor.isClient toastr.error(errorMsg) return false else return true # "=", "<>", ">", ">=", "<", "<=", "startswith", "contains", "notcontains". ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToMongo = (filters, options)-> unless filters?.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = {} sub_selector[field] = {} if option == "=" sub_selector[field]["$eq"] = value else if option == "<>" sub_selector[field]["$ne"] = value else if option == ">" sub_selector[field]["$gt"] = value else if option == ">=" sub_selector[field]["$gte"] = value else if option == "<" sub_selector[field]["$lt"] = value else if option == "<=" sub_selector[field]["$lte"] = value else if option == "startswith" reg = new RegExp("^" + value, "i") sub_selector[field]["$regex"] = reg else if option == "contains" reg = new RegExp(value, "i") sub_selector[field]["$regex"] = reg else if option == "notcontains" reg = new RegExp("^((?!" + value + ").)*$", "i") sub_selector[field]["$regex"] = reg selector.push sub_selector return selector Creator.isBetweenFilterOperation = (operation)-> return operation == "between" or !!Creator.getBetweenTimeBuiltinValues(true)?[operation] ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToDev = (filters, object_name, options)-> steedosFilters = require("@steedos/filters"); unless filters.length return if options?.is_logic_or # 如果is_logic_or为true,为filters第一层元素增加or间隔 logicTempFilters = [] filters.forEach (n)-> logicTempFilters.push(n) logicTempFilters.push("or") logicTempFilters.pop() filters = logicTempFilters selector = steedosFilters.formatFiltersToDev(filters, Creator.USER_CONTEXT) return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatLogicFiltersToDev = (filters, filter_logic, options)-> format_logic = filter_logic.replace(/\(\s+/ig, "(").replace(/\s+\)/ig, ")").replace(/\(/g, "[").replace(/\)/g, "]").replace(/\s+/g, ",").replace(/(and|or)/ig, "'$1'") format_logic = format_logic.replace(/(\d)+/ig, (x)-> _f = filters[x-1] field = _f.field option = _f.operation if Meteor.isClient value = Creator.evaluateFormula(_f.value) else value = Creator.evaluateFormula(_f.value, null, options) sub_selector = [] if _.isArray(value) == true if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() else sub_selector = [field, option, value] console.log "sub_selector", sub_selector return JSON.stringify(sub_selector) ) format_logic = "[#{format_logic}]" return Creator.eval(format_logic) Creator.getRelatedObjects = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() related_object_names = [] _object = Creator.getObject(object_name) if !_object return related_object_names # related_object_names = _.pluck(_object.related_objects,"object_name") related_objects = Creator.getObjectRelateds(_object._collection_name) related_object_names = _.pluck(related_objects,"object_name") if related_object_names?.length == 0 return related_object_names permissions = Creator.getPermissions(object_name, spaceId, userId) unrelated_objects = permissions.unrelated_objects related_object_names = _.difference related_object_names, unrelated_objects return _.filter related_objects, (related_object)-> related_object_name = related_object.object_name isActive = related_object_names.indexOf(related_object_name) > -1 # related_object_name = if related_object_name == "cfs_files_filerecord" then "cfs.files.filerecord" else related_object_name allowRead = Creator.getPermissions(related_object_name, spaceId, userId)?.allowRead if related_object_name == "cms_files" allowRead = allowRead && permissions.allowReadFiles return isActive and allowRead Creator.getRelatedObjectNames = (object_name, spaceId, userId)-> related_objects = Creator.getRelatedObjects(object_name, spaceId, userId) return _.pluck(related_objects,"object_name") Creator.getActions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() obj = Creator.getObject(object_name) if !obj return permissions = Creator.getPermissions(object_name, spaceId, userId) disabled_actions = permissions.disabled_actions actions = _.sortBy(_.values(obj.actions) , 'sort'); if _.has(obj, 'allow_customActions') actions = _.filter actions, (action)-> return _.include(obj.allow_customActions, action.name) || _.include(_.keys(Creator.getObject('base').actions) || {}, action.name) if _.has(obj, 'exclude_actions') actions = _.filter actions, (action)-> return !_.include(obj.exclude_actions, action.name) _.each actions, (action)-> # 手机上只显示编辑按钮,其他的放到折叠下拉菜单中 if Steedos.isMobile() && ["record", "record_only"].indexOf(action.on) > -1 && action.name != 'standard_edit' if action.on == "record_only" action.on = 'record_only_more' else action.on = 'record_more' if Steedos.isMobile() && ["cms_files", "cfs.files.filerecord"].indexOf(object_name) > -1 # 附件特殊处理,下载按钮放在主菜单,编辑按钮放到底下折叠下拉菜单中 actions.find((n)-> return n.name == "standard_edit")?.on = "record_more" actions.find((n)-> return n.name == "download")?.on = "record" actions = _.filter actions, (action)-> return _.indexOf(disabled_actions, action.name) < 0 return actions /// 返回当前用户有权限访问的所有list_view,包括分享的,用户自定义非分享的(除非owner变了),以及默认的其他视图 注意Creator.getPermissions函数中是不会有用户自定义非分享的视图的,所以Creator.getPermissions函数中拿到的结果不全,并不是当前用户能看到所有视图 /// Creator.getListViews = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() unless object_name return object = Creator.getObject(object_name) if !object return disabled_list_views = Creator.getPermissions(object_name, spaceId, userId)?.disabled_list_views || [] list_views = [] isMobile = Steedos.isMobile() _.each object.list_views, (item, item_name)-> item.name = item_name listViews = _.sortBy(_.values(object.list_views) , 'sort_no'); _.each listViews, (item)-> if isMobile and item.type == "calendar" # 手机上先不显示日历视图 return if item.name != "default" isDisabled = _.indexOf(disabled_list_views, item.name) > -1 || (item._id && _.indexOf(disabled_list_views, item._id) > -1) if !isDisabled || item.owner == userId list_views.push item return list_views # 前台理论上不应该调用该函数,因为字段的权限都在Creator.getObject(object_name).fields的相关属性中有标识了 Creator.getFields = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() fieldsName = Creator.getObjectFieldsName(object_name) unreadable_fields = Creator.getPermissions(object_name, spaceId, userId)?.unreadable_fields return _.difference(fieldsName, unreadable_fields) Creator.isloading = ()-> return !Creator.bootstrapLoaded.get() Creator.convertSpecialCharacter = (str)-> return str.replace(/([\^\$\(\)\*\+\?\.\\\|\[\]\{\}])/g, "\\$1") # 计算fields相关函数 # START Creator.getDisabledFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.disabled and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getHiddenFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.type == "hidden" and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithNoGroup = (schema)-> fields = _.map(schema, (field, fieldName) -> return (!field.autoform or !field.autoform.group or field.autoform.group == "-") and (!field.autoform or field.autoform.type != "hidden") and fieldName ) fields = _.compact(fields) return fields Creator.getSortedFieldGroupNames = (schema)-> names = _.map(schema, (field) -> return field.autoform and field.autoform.group != "-" and field.autoform.group ) names = _.compact(names) names = _.unique(names) return names Creator.getFieldsForGroup = (schema, groupName) -> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.group == groupName and field.autoform.type != "hidden" and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithoutOmit = (schema, keys) -> keys = _.map(keys, (key) -> field = _.pick(schema, key) if field[key].autoform?.omit return false else return key ) keys = _.compact(keys) return keys Creator.getFieldsInFirstLevel = (firstLevelKeys, keys) -> keys = _.map(keys, (key) -> if _.indexOf(firstLevelKeys, key) > -1 return key else return false ) keys = _.compact(keys) return keys Creator.getFieldsForReorder = (schema, keys, isSingle) -> fields = [] i = 0 _keys = _.filter(keys, (key)-> return !key.endsWith('_endLine') ); while i < _keys.length sc_1 = _.pick(schema, _keys[i]) sc_2 = _.pick(schema, _keys[i+1]) is_wide_1 = false is_wide_2 = false # is_range_1 = false # is_range_2 = false _.each sc_1, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_1 = true # if value.autoform?.is_range # is_range_1 = true _.each sc_2, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_2 = true # if value.autoform?.is_range # is_range_2 = true if Steedos.isMobile() is_wide_1 = true is_wide_2 = true if isSingle fields.push _keys.slice(i, i+1) i += 1 else # if !is_range_1 && is_range_2 # childKeys = _keys.slice(i, i+1) # childKeys.push undefined # fields.push childKeys # i += 1 # else if is_wide_1 fields.push _keys.slice(i, i+1) i += 1 else if !is_wide_1 and is_wide_2 childKeys = _keys.slice(i, i+1) childKeys.push undefined fields.push childKeys i += 1 else if !is_wide_1 and !is_wide_2 childKeys = _keys.slice(i, i+1) if _keys[i+1] childKeys.push _keys[i+1] else childKeys.push undefined fields.push childKeys i += 2 return fields Creator.isFilterValueEmpty = (v) -> return typeof v == "undefined" || v == null || Number.isNaN(v) || v.length == 0 Creator.getFieldDataType = (objectFields, key)-> if objectFields and key result = objectFields[key]?.type if ["formula", "summary"].indexOf(result) > -1 result = objectFields[key].data_type return result else return "text" # END if Meteor.isServer Creator.getAllRelatedObjects = (object_name)-> related_object_names = [] _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name related_object_names.push related_object_name if Creator.getObject(object_name).enable_files related_object_names.push "cms_files" return related_object_names if Meteor.isServer Steedos.formatIndex = (array) -> object = { background: true }; isdocumentDB = Meteor.settings?.datasources?.default?.documentDB || false; if isdocumentDB if array.length > 0 indexName = array.join("."); object.name = indexName; if (indexName.length > 52) object.name = indexName.substring(0,52); return object;
true
# Creator.initApps() # Creator.initApps = ()-> # if Meteor.isServer # _.each Creator.Apps, (app, app_id)-> # db_app = db.apps.findOne(app_id) # if !db_app # app._id = app_id # db.apps.insert(app) # else # app._id = app_id # db.apps.update({_id: app_id}, app) Creator.getSchema = (object_name)-> return Creator.getObject(object_name)?.schema Creator.getObjectHomeComponent = (object_name)-> if Meteor.isClient return ReactSteedos.pluginComponentSelector(ReactSteedos.store.getState(), "ObjectHome", object_name) Creator.getObjectUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id) else if object_name is "meeting" return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/calendar/") else if Creator.getObjectHomeComponent(object_name) return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name) else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id) Creator.getObjectAbsoluteUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/view/" + record_id, true) else if object_name is "meeting" return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/calendar/", true) else return Steedos.absoluteUrl("/app/" + app_id + "/" + object_name + "/grid/" + list_view_id, true) Creator.getObjectRouterUrl = (object_name, record_id, app_id) -> if !app_id app_id = Session.get("app_id") if !object_name object_name = Session.get("object_name") list_view = Creator.getListView(object_name, null) list_view_id = list_view?._id if record_id return "/app/" + app_id + "/" + object_name + "/view/" + record_id else if object_name is "meeting" return "/app/" + app_id + "/" + object_name + "/calendar/" else return "/app/" + app_id + "/" + object_name + "/grid/" + list_view_id Creator.getListViewUrl = (object_name, app_id, list_view_id) -> url = Creator.getListViewRelativeUrl(object_name, app_id, list_view_id) return Creator.getRelativeUrl(url) Creator.getListViewRelativeUrl = (object_name, app_id, list_view_id) -> if list_view_id is "calendar" return "/app/" + app_id + "/" + object_name + "/calendar/" else return "/app/" + app_id + "/" + object_name + "/grid/" + list_view_id Creator.getSwitchListUrl = (object_name, app_id, list_view_id) -> if list_view_id return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + list_view_id + "/list") else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/list/switch") Creator.getRelatedObjectUrl = (object_name, app_id, record_id, related_object_name, related_field_name) -> if related_field_name return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid?related_field_name=" + related_field_name) else return Creator.getRelativeUrl("/app/" + app_id + "/" + object_name + "/" + record_id + "/" + related_object_name + "/grid") Creator.getObjectLookupFieldOptions = (object_name, is_deep, is_skip_hide, is_related)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields icon = _object?.icon _.forEach fields, (f, k)-> if is_skip_hide and f.hidden return if f.type == "select" _options.push {label: "#{f.label || k}", value: "#{k}", icon: icon} else _options.push {label: f.label || k, value: k, icon: icon} if is_deep _.forEach fields, (f, k)-> if is_skip_hide and f.hidden return if (f.type == "lookup" || f.type == "master_detail") && f.reference_to && _.isString(f.reference_to) # 不支持f.reference_to为function的情况,有需求再说 r_object = Creator.getObject(f.reference_to) if r_object _.forEach r_object.fields, (f2, k2)-> _options.push {label: "#{f.label || k}=>#{f2.label || k2}", value: "#{k}.#{k2}", icon: r_object?.icon} if is_related relatedObjects = Creator.getRelatedObjects(object_name) _.each relatedObjects, (_relatedObject)=> relatedOptions = Creator.getObjectLookupFieldOptions(_relatedObject.object_name, false, false, false) relatedObject = Creator.getObject(_relatedObject.object_name) _.each relatedOptions, (relatedOption)-> if _relatedObject.foreign_key != relatedOption.value _options.push {label: "#{relatedObject.label || relatedObject.name}=>#{relatedOption.label}", value: "#{relatedObject.name}.#{relatedOption.value}", icon: relatedObject?.icon} return _options # 统一为对象object_name提供可用于过虑器过虑字段 Creator.getObjectFilterFieldOptions = (object_name)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields permission_fields = Creator.getFields(object_name) icon = _object?.icon _.forEach fields, (f, k)-> # hidden,grid等类型的字段,不需要过滤 if !_.include(["grid","object", "[Object]", "[object]", "Object", "avatar", "image", "markdown", "html"], f.type) and !f.hidden # filters.$.field及flow.current等子字段也不需要过滤 if !/\w+\./.test(k) and _.indexOf(permission_fields, k) > -1 _options.push {label: f.label || k, value: k, icon: icon} return _options Creator.getObjectFieldOptions = (object_name)-> _options = [] unless object_name return _options _object = Creator.getObject(object_name) fields = _object?.fields permission_fields = Creator.getFields(object_name) icon = _object?.icon _.forEach fields, (f, k)-> if !_.include(["grid","object", "[Object]", "[object]", "Object", "markdown", "html"], f.type) if !/\w+\./.test(k) and _.indexOf(permission_fields, k) > -1 _options.push {label: f.label || k, value: k, icon: icon} return _options ### filters: 要转换的filters fields: 对象字段 filter_fields: 默认过滤字段,支持字符串数组和对象数组两种格式,如:['filed_name1','filed_name2'],[{field:'filed_name1',required:true}] 处理逻辑: 把filters中存在于filter_fields的过滤条件增加每项的is_default、is_required属性,不存在于filter_fields的过滤条件对应的移除每项的相关属性 返回结果: 处理后的filters ### Creator.getFiltersWithFilterFields = (filters, fields, filter_fields)-> unless filters filters = [] unless filter_fields filter_fields = [] if filter_fields?.length filter_fields.forEach (n)-> if _.isString(n) n = field: n, required: false if fields[n.field] and !_.findWhere(filters,{field:n.field}) filters.push field: n.field, is_default: true, is_required: n.required filters.forEach (filterItem)-> matchField = filter_fields.find (n)-> return n == filterItem.field or n.field == filterItem.field if _.isString(matchField) matchField = field: matchField, required: false if matchField filterItem.is_default = true filterItem.is_required = matchField.required else delete filterItem.is_default delete filterItem.is_required return filters Creator.getObjectRecord = (object_name, record_id, select_fields, expand)-> if !object_name object_name = Session.get("object_name") if !record_id record_id = Session.get("record_id") if Meteor.isClient if object_name == Session.get("object_name") && record_id == Session.get("record_id") if Template.instance()?.record return Template.instance()?.record?.get() else return Creator.odata.get(object_name, record_id, select_fields, expand) collection = Creator.getCollection(object_name) if collection record = collection.findOne(record_id) return record Creator.getObjectRecordName = (record, object_name)-> unless record record = Creator.getObjectRecord() if record # 显示组织列表时,特殊处理name_field_key为name字段 name_field_key = if object_name == "organizations" then "name" else Creator.getObject(object_name)?.NAME_FIELD_KEY if record and name_field_key return record.label || record[name_field_key] Creator.getApp = (app_id)-> if !app_id app_id = Session.get("app_id") app = Creator.Apps[app_id] Creator.deps?.app?.depend() return app Creator.getAppDashboard = (app_id)-> app = Creator.getApp(app_id) if !app return dashboard = null _.each Creator.Dashboards, (v, k)-> if v.apps?.indexOf(app._id) > -1 dashboard = v; return dashboard; Creator.getAppDashboardComponent = (app_id)-> app = Creator.getApp(app_id) if !app return return ReactSteedos.pluginComponentSelector(ReactSteedos.store.getState(), "Dashboard", app._id); Creator.getAppObjectNames = (app_id)-> app = Creator.getApp(app_id) if !app return isMobile = Steedos.isMobile() appObjects = if isMobile then app.mobile_objects else app.objects objects = [] if app _.each appObjects, (v)-> obj = Creator.getObject(v) if obj?.permissions.get().allowRead objects.push v return objects Creator.getAppMenu = (app_id, menu_id)-> menus = Creator.getAppMenus(app_id) return menus && menus.find (menu)-> return menu.id == menu_id Creator.getAppMenuUrlForInternet = (menu)-> # 当tabs类型为url时,按外部链接处理,支持配置表达式并加上统一的url参数 params = {}; params["X-Space-Id"] = Steedos.spaceId() params["X-User-Id"] = Steedos.userId(); params["X-Company-Ids"] = Steedos.getUserCompanyIds(); # params["X-Auth-Token"] = Accounts._PI:KEY:<KEY>END_PILoginToken(); sdk = require("@steedos/builder-community/dist/builder-community.react.js") url = menu.path if sdk and sdk.Utils and sdk.Utils.isExpression(url) url = sdk.Utils.parseSingleExpression(url, menu, "#", Creator.USER_CONTEXT) linkStr = if url.indexOf("?") < 0 then "?" else "&" return "#{url}#{linkStr}#{$.param(params)}" Creator.getAppMenuUrl = (menu)-> url = menu.path if menu.type == "url" if menu.target return Creator.getAppMenuUrlForInternet(menu) else # 在iframe中显示url界面 return "/app/-/tab_iframe/#{menu.id}" else return menu.path Creator.getAppMenus = (app_id)-> app = Creator.getApp(app_id) if !app return [] appMenus = Session.get("app_menus"); unless appMenus return [] curentAppMenus = appMenus.find (menuItem) -> return menuItem.id == app._id if curentAppMenus return curentAppMenus.children Creator.loadAppsMenus = ()-> isMobile = Steedos.isMobile() data = { } if isMobile data.mobile = isMobile options = { type: 'get', data: data, success: (data)-> Session.set("app_menus", data); } Steedos.authRequest "/service/api/apps/menus", options Creator.getVisibleApps = (includeAdmin)-> changeApp = Creator._subApp.get(); ReactSteedos.store.getState().entities.apps = Object.assign({}, ReactSteedos.store.getState().entities.apps, {apps: changeApp}); return ReactSteedos.visibleAppsSelector(ReactSteedos.store.getState(), includeAdmin) Creator.getVisibleAppsObjects = ()-> apps = Creator.getVisibleApps() visibleObjectNames = _.flatten(_.pluck(apps,'objects')) objects = _.filter Creator.Objects, (obj)-> if visibleObjectNames.indexOf(obj.name) < 0 return false else return true objects = objects.sort(Creator.sortingMethod.bind({key:"label"})) objects = _.pluck(objects,'name') return _.uniq objects Creator.getAppsObjects = ()-> objects = [] tempObjects = [] _.forEach Creator.Apps, (app)-> tempObjects = _.filter app.objects, (obj)-> return !obj.hidden objects = objects.concat(tempObjects) return _.uniq objects Creator.validateFilters = (filters, logic)-> filter_items = _.map filters, (obj) -> if _.isEmpty(obj) return false else return obj filter_items = _.compact(filter_items) errorMsg = "" filter_length = filter_items.length if logic # 格式化filter logic = logic.replace(/\n/g, "").replace(/\s+/g, " ") # 判断特殊字符 if /[._\-!+]+/ig.test(logic) errorMsg = "含有特殊字符。" if !errorMsg index = logic.match(/\d+/ig) if !index errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" else index.forEach (i)-> if i < 1 or i > filter_length errorMsg = "您的筛选条件引用了未定义的筛选器:#{i}。" flag = 1 while flag <= filter_length if !index.includes("#{flag}") errorMsg = "有些筛选条件进行了定义,但未在高级筛选条件中被引用。" flag++; if !errorMsg # 判断是否有非法英文字符 word = logic.match(/[a-zA-Z]+/ig) if word word.forEach (w)-> if !/^(and|or)$/ig.test(w) errorMsg = "检查您的高级筛选条件中的拼写。" if !errorMsg # 判断格式是否正确 try Creator.eval(logic.replace(/and/ig, "&&").replace(/or/ig, "||")) catch e errorMsg = "您的筛选器中含有特殊字符" if /(AND)[^()]+(OR)/ig.test(logic) || /(OR)[^()]+(AND)/ig.test(logic) errorMsg = "您的筛选器必须在连续性的 AND 和 OR 表达式前后使用括号。" if errorMsg console.log "error", errorMsg if Meteor.isClient toastr.error(errorMsg) return false else return true # "=", "<>", ">", ">=", "<", "<=", "startswith", "contains", "notcontains". ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToMongo = (filters, options)-> unless filters?.length return # 当filters不是[Array]类型而是[Object]类型时,进行格式转换 unless filters[0] instanceof Array filters = _.map filters, (obj)-> return [obj.field, obj.operation, obj.value] selector = [] _.each filters, (filter)-> field = filter[0] option = filter[1] if Meteor.isClient value = Creator.evaluateFormula(filter[2]) else value = Creator.evaluateFormula(filter[2], null, options) sub_selector = {} sub_selector[field] = {} if option == "=" sub_selector[field]["$eq"] = value else if option == "<>" sub_selector[field]["$ne"] = value else if option == ">" sub_selector[field]["$gt"] = value else if option == ">=" sub_selector[field]["$gte"] = value else if option == "<" sub_selector[field]["$lt"] = value else if option == "<=" sub_selector[field]["$lte"] = value else if option == "startswith" reg = new RegExp("^" + value, "i") sub_selector[field]["$regex"] = reg else if option == "contains" reg = new RegExp(value, "i") sub_selector[field]["$regex"] = reg else if option == "notcontains" reg = new RegExp("^((?!" + value + ").)*$", "i") sub_selector[field]["$regex"] = reg selector.push sub_selector return selector Creator.isBetweenFilterOperation = (operation)-> return operation == "between" or !!Creator.getBetweenTimeBuiltinValues(true)?[operation] ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatFiltersToDev = (filters, object_name, options)-> steedosFilters = require("@steedos/filters"); unless filters.length return if options?.is_logic_or # 如果is_logic_or为true,为filters第一层元素增加or间隔 logicTempFilters = [] filters.forEach (n)-> logicTempFilters.push(n) logicTempFilters.push("or") logicTempFilters.pop() filters = logicTempFilters selector = steedosFilters.formatFiltersToDev(filters, Creator.USER_CONTEXT) return selector ### options参数: extend-- 是否需要把当前用户基本信息加入公式,即让公式支持Creator.USER_CONTEXT中的值,默认为true userId-- 当前登录用户 spaceId-- 当前所在工作区 extend为true时,后端需要额外传入userId及spaceId用于抓取Creator.USER_CONTEXT对应的值 ### Creator.formatLogicFiltersToDev = (filters, filter_logic, options)-> format_logic = filter_logic.replace(/\(\s+/ig, "(").replace(/\s+\)/ig, ")").replace(/\(/g, "[").replace(/\)/g, "]").replace(/\s+/g, ",").replace(/(and|or)/ig, "'$1'") format_logic = format_logic.replace(/(\d)+/ig, (x)-> _f = filters[x-1] field = _f.field option = _f.operation if Meteor.isClient value = Creator.evaluateFormula(_f.value) else value = Creator.evaluateFormula(_f.value, null, options) sub_selector = [] if _.isArray(value) == true if option == "=" _.each value, (v)-> sub_selector.push [field, option, v], "or" else if option == "<>" _.each value, (v)-> sub_selector.push [field, option, v], "and" else _.each value, (v)-> sub_selector.push [field, option, v], "or" if sub_selector[sub_selector.length - 1] == "and" || sub_selector[sub_selector.length - 1] == "or" sub_selector.pop() else sub_selector = [field, option, value] console.log "sub_selector", sub_selector return JSON.stringify(sub_selector) ) format_logic = "[#{format_logic}]" return Creator.eval(format_logic) Creator.getRelatedObjects = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() related_object_names = [] _object = Creator.getObject(object_name) if !_object return related_object_names # related_object_names = _.pluck(_object.related_objects,"object_name") related_objects = Creator.getObjectRelateds(_object._collection_name) related_object_names = _.pluck(related_objects,"object_name") if related_object_names?.length == 0 return related_object_names permissions = Creator.getPermissions(object_name, spaceId, userId) unrelated_objects = permissions.unrelated_objects related_object_names = _.difference related_object_names, unrelated_objects return _.filter related_objects, (related_object)-> related_object_name = related_object.object_name isActive = related_object_names.indexOf(related_object_name) > -1 # related_object_name = if related_object_name == "cfs_files_filerecord" then "cfs.files.filerecord" else related_object_name allowRead = Creator.getPermissions(related_object_name, spaceId, userId)?.allowRead if related_object_name == "cms_files" allowRead = allowRead && permissions.allowReadFiles return isActive and allowRead Creator.getRelatedObjectNames = (object_name, spaceId, userId)-> related_objects = Creator.getRelatedObjects(object_name, spaceId, userId) return _.pluck(related_objects,"object_name") Creator.getActions = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() obj = Creator.getObject(object_name) if !obj return permissions = Creator.getPermissions(object_name, spaceId, userId) disabled_actions = permissions.disabled_actions actions = _.sortBy(_.values(obj.actions) , 'sort'); if _.has(obj, 'allow_customActions') actions = _.filter actions, (action)-> return _.include(obj.allow_customActions, action.name) || _.include(_.keys(Creator.getObject('base').actions) || {}, action.name) if _.has(obj, 'exclude_actions') actions = _.filter actions, (action)-> return !_.include(obj.exclude_actions, action.name) _.each actions, (action)-> # 手机上只显示编辑按钮,其他的放到折叠下拉菜单中 if Steedos.isMobile() && ["record", "record_only"].indexOf(action.on) > -1 && action.name != 'standard_edit' if action.on == "record_only" action.on = 'record_only_more' else action.on = 'record_more' if Steedos.isMobile() && ["cms_files", "cfs.files.filerecord"].indexOf(object_name) > -1 # 附件特殊处理,下载按钮放在主菜单,编辑按钮放到底下折叠下拉菜单中 actions.find((n)-> return n.name == "standard_edit")?.on = "record_more" actions.find((n)-> return n.name == "download")?.on = "record" actions = _.filter actions, (action)-> return _.indexOf(disabled_actions, action.name) < 0 return actions /// 返回当前用户有权限访问的所有list_view,包括分享的,用户自定义非分享的(除非owner变了),以及默认的其他视图 注意Creator.getPermissions函数中是不会有用户自定义非分享的视图的,所以Creator.getPermissions函数中拿到的结果不全,并不是当前用户能看到所有视图 /// Creator.getListViews = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() unless object_name return object = Creator.getObject(object_name) if !object return disabled_list_views = Creator.getPermissions(object_name, spaceId, userId)?.disabled_list_views || [] list_views = [] isMobile = Steedos.isMobile() _.each object.list_views, (item, item_name)-> item.name = item_name listViews = _.sortBy(_.values(object.list_views) , 'sort_no'); _.each listViews, (item)-> if isMobile and item.type == "calendar" # 手机上先不显示日历视图 return if item.name != "default" isDisabled = _.indexOf(disabled_list_views, item.name) > -1 || (item._id && _.indexOf(disabled_list_views, item._id) > -1) if !isDisabled || item.owner == userId list_views.push item return list_views # 前台理论上不应该调用该函数,因为字段的权限都在Creator.getObject(object_name).fields的相关属性中有标识了 Creator.getFields = (object_name, spaceId, userId)-> if Meteor.isClient if !object_name object_name = Session.get("object_name") if !spaceId spaceId = Session.get("spaceId") if !userId userId = Meteor.userId() fieldsName = Creator.getObjectFieldsName(object_name) unreadable_fields = Creator.getPermissions(object_name, spaceId, userId)?.unreadable_fields return _.difference(fieldsName, unreadable_fields) Creator.isloading = ()-> return !Creator.bootstrapLoaded.get() Creator.convertSpecialCharacter = (str)-> return str.replace(/([\^\$\(\)\*\+\?\.\\\|\[\]\{\}])/g, "\\$1") # 计算fields相关函数 # START Creator.getDisabledFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.disabled and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getHiddenFields = (schema)-> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.type == "hidden" and !field.autoform.omit and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithNoGroup = (schema)-> fields = _.map(schema, (field, fieldName) -> return (!field.autoform or !field.autoform.group or field.autoform.group == "-") and (!field.autoform or field.autoform.type != "hidden") and fieldName ) fields = _.compact(fields) return fields Creator.getSortedFieldGroupNames = (schema)-> names = _.map(schema, (field) -> return field.autoform and field.autoform.group != "-" and field.autoform.group ) names = _.compact(names) names = _.unique(names) return names Creator.getFieldsForGroup = (schema, groupName) -> fields = _.map(schema, (field, fieldName) -> return field.autoform and field.autoform.group == groupName and field.autoform.type != "hidden" and fieldName ) fields = _.compact(fields) return fields Creator.getFieldsWithoutOmit = (schema, keys) -> keys = _.map(keys, (key) -> field = _.pick(schema, key) if field[key].autoform?.omit return false else return key ) keys = _.compact(keys) return keys Creator.getFieldsInFirstLevel = (firstLevelKeys, keys) -> keys = _.map(keys, (key) -> if _.indexOf(firstLevelKeys, key) > -1 return key else return false ) keys = _.compact(keys) return keys Creator.getFieldsForReorder = (schema, keys, isSingle) -> fields = [] i = 0 _keys = _.filter(keys, (key)-> return !key.endsWith('_endLine') ); while i < _keys.length sc_1 = _.pick(schema, _keys[i]) sc_2 = _.pick(schema, _keys[i+1]) is_wide_1 = false is_wide_2 = false # is_range_1 = false # is_range_2 = false _.each sc_1, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_1 = true # if value.autoform?.is_range # is_range_1 = true _.each sc_2, (value) -> if value.autoform?.is_wide || value.autoform?.type == "table" is_wide_2 = true # if value.autoform?.is_range # is_range_2 = true if Steedos.isMobile() is_wide_1 = true is_wide_2 = true if isSingle fields.push _keys.slice(i, i+1) i += 1 else # if !is_range_1 && is_range_2 # childKeys = _keys.slice(i, i+1) # childKeys.push undefined # fields.push childKeys # i += 1 # else if is_wide_1 fields.push _keys.slice(i, i+1) i += 1 else if !is_wide_1 and is_wide_2 childKeys = _keys.slice(i, i+1) childKeys.push undefined fields.push childKeys i += 1 else if !is_wide_1 and !is_wide_2 childKeys = _keys.slice(i, i+1) if _keys[i+1] childKeys.push _keys[i+1] else childKeys.push undefined fields.push childKeys i += 2 return fields Creator.isFilterValueEmpty = (v) -> return typeof v == "undefined" || v == null || Number.isNaN(v) || v.length == 0 Creator.getFieldDataType = (objectFields, key)-> if objectFields and key result = objectFields[key]?.type if ["formula", "summary"].indexOf(result) > -1 result = objectFields[key].data_type return result else return "text" # END if Meteor.isServer Creator.getAllRelatedObjects = (object_name)-> related_object_names = [] _.each Creator.Objects, (related_object, related_object_name)-> _.each related_object.fields, (related_field, related_field_name)-> if related_field.type == "master_detail" and related_field.reference_to and related_field.reference_to == object_name related_object_names.push related_object_name if Creator.getObject(object_name).enable_files related_object_names.push "cms_files" return related_object_names if Meteor.isServer Steedos.formatIndex = (array) -> object = { background: true }; isdocumentDB = Meteor.settings?.datasources?.default?.documentDB || false; if isdocumentDB if array.length > 0 indexName = array.join("."); object.name = indexName; if (indexName.length > 52) object.name = indexName.substring(0,52); return object;
[ { "context": "t \"checks the arguments\", ->\n obj = { name: 'A'}\n vm = new ViewModel obj\n assert.isTru", "end": 256, "score": 0.8980189561843872, "start": 255, "tag": "NAME", "value": "A" }, { "context": "operties in load object\", ->\n obj = { name: \"A\" }\n ...
tests/viewmodel-instance.coffee
ManuelDeLeon/viewmodel
215
describe "ViewModel instance", -> beforeEach -> @checkStub = sinon.stub ViewModel, "check" @viewmodel = new ViewModel() afterEach -> sinon.restoreAll() describe "constructor", -> it "checks the arguments", -> obj = { name: 'A'} vm = new ViewModel obj assert.isTrue @checkStub.calledWith '#constructor', obj it "adds property as function", -> vm = new ViewModel({ name: 'A'}) assert.isFunction vm.name assert.equal 'A', vm.name() vm.name('B') assert.equal 'B', vm.name() it "adds properties in load object", -> obj = { name: "A" } vm = new ViewModel load: obj assert.equal 'A', vm.name() it "adds properties in load array", -> arr = [ { name: "A" }, { age: 1 } ] vm = new ViewModel load: arr assert.equal 'A', vm.name() assert.equal 1, vm.age() it "doesn't convert functions", -> f = -> vm = new ViewModel fun: f assert.equal f, vm.fun describe "loading hooks direct", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin hooksMixin: onCreated: -> 'onCreatedMixin' onRendered: -> 'onRenderedMixin' onDestroyed: -> 'onDestroyedMixin' autorun: -> 'autorunMixin' ViewModel.shared = {} ViewModel.share hooksShare: onCreated: -> 'onCreatedShare' onRendered: -> 'onRenderedShare' onDestroyed: -> 'onDestroyedShare' autorun: -> 'autorunShare' @viewmodel = new ViewModel share: 'hooksShare' mixin: 'hooksMixin' load: onCreated: -> 'onCreatedLoad' onRendered: -> 'onRenderedLoad' onDestroyed: -> 'onDestroyedLoad' autorun: -> 'autorunLoad' onCreated: -> 'onCreatedBase' onRendered: -> 'onRenderedBase' onDestroyed: -> 'onDestroyedBase' autorun: -> 'autorunBase' return it "adds hooks to onCreated", -> assert.equal @viewmodel.vmOnCreated.length, 4 assert.equal @viewmodel.vmOnCreated[0](), 'onCreatedShare' assert.equal @viewmodel.vmOnCreated[1](), 'onCreatedMixin' assert.equal @viewmodel.vmOnCreated[2](), 'onCreatedLoad' assert.equal @viewmodel.vmOnCreated[3](), 'onCreatedBase' it "adds hooks to onRendered", -> assert.equal @viewmodel.vmOnRendered.length, 4 assert.equal @viewmodel.vmOnRendered[0](), 'onRenderedShare' assert.equal @viewmodel.vmOnRendered[1](), 'onRenderedMixin' assert.equal @viewmodel.vmOnRendered[2](), 'onRenderedLoad' assert.equal @viewmodel.vmOnRendered[3](), 'onRenderedBase' it "adds hooks to onDestroyed", -> assert.equal @viewmodel.vmOnDestroyed.length, 4 assert.equal @viewmodel.vmOnDestroyed[0](), 'onDestroyedShare' assert.equal @viewmodel.vmOnDestroyed[1](), 'onDestroyedMixin' assert.equal @viewmodel.vmOnDestroyed[2](), 'onDestroyedLoad' assert.equal @viewmodel.vmOnDestroyed[3](), 'onDestroyedBase' it "adds hooks to autorun", -> assert.equal @viewmodel.vmAutorun.length, 4 assert.equal @viewmodel.vmAutorun[0](), 'autorunShare' assert.equal @viewmodel.vmAutorun[1](), 'autorunMixin' assert.equal @viewmodel.vmAutorun[2](), 'autorunLoad' assert.equal @viewmodel.vmAutorun[3](), 'autorunBase' describe "loading hooks from array", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin hooksMixin: onCreated: [ (-> 'onCreatedMixin')] onRendered: [ (-> 'onRenderedMixin')] onDestroyed: [ (-> 'onDestroyedMixin')] autorun: [ (-> 'autorunMixin')] ViewModel.shared = {} ViewModel.share hooksShare: onCreated: [ (-> 'onCreatedShare')] onRendered: [ (-> 'onRenderedShare')] onDestroyed: [ (-> 'onDestroyedShare')] autorun: [ (-> 'autorunShare')] @viewmodel = new ViewModel share: 'hooksShare' mixin: 'hooksMixin' load: onCreated: [ (-> 'onCreatedLoad')] onRendered: [ (-> 'onRenderedLoad')] onDestroyed: [ (-> 'onDestroyedLoad')] autorun: [ (-> 'autorunLoad')] onCreated: [ (-> 'onCreatedBase')] onRendered: [ (-> 'onRenderedBase')] onDestroyed: [ (-> 'onDestroyedBase')] autorun: [ (-> 'autorunBase')] return it "adds hooks to onCreated", -> assert.equal @viewmodel.vmOnCreated.length, 4 assert.equal @viewmodel.vmOnCreated[0](), 'onCreatedShare' assert.equal @viewmodel.vmOnCreated[1](), 'onCreatedMixin' assert.equal @viewmodel.vmOnCreated[2](), 'onCreatedLoad' assert.equal @viewmodel.vmOnCreated[3](), 'onCreatedBase' it "adds hooks to onRendered", -> assert.equal @viewmodel.vmOnRendered.length, 4 assert.equal @viewmodel.vmOnRendered[0](), 'onRenderedShare' assert.equal @viewmodel.vmOnRendered[1](), 'onRenderedMixin' assert.equal @viewmodel.vmOnRendered[2](), 'onRenderedLoad' assert.equal @viewmodel.vmOnRendered[3](), 'onRenderedBase' it "adds hooks to onDestroyed", -> assert.equal @viewmodel.vmOnDestroyed.length, 4 assert.equal @viewmodel.vmOnDestroyed[0](), 'onDestroyedShare' assert.equal @viewmodel.vmOnDestroyed[1](), 'onDestroyedMixin' assert.equal @viewmodel.vmOnDestroyed[2](), 'onDestroyedLoad' assert.equal @viewmodel.vmOnDestroyed[3](), 'onDestroyedBase' it "adds hooks to autorun", -> assert.equal @viewmodel.vmAutorun.length, 4 assert.equal @viewmodel.vmAutorun[0](), 'autorunShare' assert.equal @viewmodel.vmAutorun[1](), 'autorunMixin' assert.equal @viewmodel.vmAutorun[2](), 'autorunLoad' assert.equal @viewmodel.vmAutorun[3](), 'autorunBase' describe "load order", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin name: name: 'mixin' ViewModel.shared = {} ViewModel.share name: name: 'share' ViewModel.signals = {} ViewModel.signal name: name: target: document event: 'keydown' it "loads base name last", -> vm = new ViewModel({ name: 'base', load: { name: 'load' }, mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "base" it "loads from load 2nd to last", -> vm = new ViewModel({ load: { name: 'load' }, mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "load" it "loads from mixin 3rd to last", -> vm = new ViewModel({ mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "mixin" it "loads from share 4th to last", -> vm = new ViewModel({ share: 'name', signal: 'name' }) assert.equal vm.name(), "share" it "loads from signal first", -> vm = new ViewModel({ signal: 'name' }) assert.equal _.keys(vm.name()).length, 0 describe "#bind", -> beforeEach -> @bindSingleStub = sinon.stub ViewModel, 'bindSingle' it "calls bindSingle for each entry in bindObject", -> bindObject = a: 1 b: 2 vm = {} bindings = a: 1 b: 2 @viewmodel.bind.call vm, bindObject, 'templateInstance', 'element', bindings assert.isTrue @bindSingleStub.calledTwice assert.isTrue @bindSingleStub.calledWith 'templateInstance', 'element', 'a', 1, bindObject, vm, bindings assert.isTrue @bindSingleStub.calledWith 'templateInstance', 'element', 'b', 2, bindObject, vm, bindings it "returns undefined", -> bindObject = {} ret = @viewmodel.bind bindObject, 'templateInstance', 'element', 'bindings' assert.isUndefined ret describe "validation", -> it "vm is valid with an undefined", -> @viewmodel.load({ name: undefined }) assert.equal true, @viewmodel.valid() return describe "#load", -> it "adds a property to the view model", -> @viewmodel.load({ name: 'Alan' }) assert.equal 'Alan', @viewmodel.name() it "adds onRendered from an array", -> f = -> @viewmodel.load([ onRendered: f ]) assert.equal f, @viewmodel.vmOnRendered[0] it "adds a properties from an array", -> @viewmodel.load([{ name: 'Alan' },{ two: 'Brito' }]) assert.equal 'Alan', @viewmodel.name() assert.equal 'Brito', @viewmodel.two() it "adds function to the view model", -> f = -> @viewmodel.load({ fun: f }) assert.equal f, @viewmodel.fun it "doesn't create a new property when extending the same name", -> @viewmodel.load({ name: 'Alan' }) old = @viewmodel.name @viewmodel.load({ name: 'Brito' }) assert.equal 'Brito', @viewmodel.name() assert.equal old, @viewmodel.name it "overwrite existing functions", -> @viewmodel.load({ name: -> 'Alan' }) old = @viewmodel.name @viewmodel.load({ name: 'Brito' }) theNew = @viewmodel.name assert.equal 'Brito', @viewmodel.name() assert.equal theNew, @viewmodel.name assert.notEqual old, theNew it "doesn't add events", -> @viewmodel.load({ events: { 'click one' : -> } }) assert.equal 0, @viewmodel.vmEvents.length it "adds events", -> @viewmodel.load({ events: { 'click one' : -> } }, true) assert.equal 1, @viewmodel.vmEvents.length it "doesn't do anything with null and undefined", -> @viewmodel.load(undefined ) @viewmodel.load(null) describe "#parent", -> beforeEach -> @viewmodel.templateInstance = view: parentView: name: 'Template.A' templateInstance: -> viewmodel: "X" it "returns the view model of the parent template", -> parent = @viewmodel.parent() assert.equal "X", parent it "returns the first view model up the chain", -> @viewmodel.templateInstance = view: parentView: name: 'Template.something' templateInstance: -> view: parentView: name: 'Template.A' templateInstance: -> viewmodel: "Y" parent = @viewmodel.parent() assert.equal "Y", parent it "checks the arguments", -> @viewmodel.parent('X') assert.isTrue @checkStub.calledWith '#parent', 'X' describe "#children", -> beforeEach -> @viewmodel.children().push age: -> 1 name: -> "AA" templateInstance: view: name: 'Template.A' @viewmodel.children().push age: -> 2 name: -> "BB" templateInstance: view: name: 'Template.B' @viewmodel.children().push age: -> 1 templateInstance: view: name: 'Template.A' it "returns all without arguments", -> assert.equal 3, @viewmodel.children().length @viewmodel.children().push("X") assert.equal 4, @viewmodel.children().length assert.equal "X", @viewmodel.children()[3] it "returns by template when passed a string", -> arr = @viewmodel.children('A') assert.equal 2, arr.length assert.equal 1, arr[0].age() assert.equal 1, arr[1].age() it "returns array from a predicate", -> arr = @viewmodel.children((vm) -> vm.age() is 2) assert.equal 1, arr.length assert.equal "BB", arr[0].name() it "calls .depend", -> array = @viewmodel.children() spy = sinon.spy array, 'depend' @viewmodel.children() assert.isTrue spy.called it "doesn't check without arguments", -> @viewmodel.children() assert.isFalse @checkStub.calledWith '#children' it "checks with arguments", -> @viewmodel.children('X') assert.isTrue @checkStub.calledWith '#children', 'X' describe "#reset", -> beforeEach -> @viewmodel.templateInstance = view: name: 'body' @viewmodel.load name: 'A' arr: ['A'] it "resets a string", -> @viewmodel.name('B') @viewmodel.reset() assert.equal "A", @viewmodel.name() it "resets an array", -> @viewmodel.arr().push('B') @viewmodel.reset() assert.equal 1, @viewmodel.arr().length assert.equal 'A', @viewmodel.arr()[0] describe "#data", -> beforeEach -> @viewmodel.load name: 'A' arr: ['B'] it "creates js object", -> obj = @viewmodel.data() assert.equal 'A', obj.name assert.equal 'B', obj.arr[0] return it "only loads fields specified", -> obj = @viewmodel.data(['name']) assert.equal 'A', obj.name assert.isUndefined obj.arr return describe "#load", -> beforeEach -> @viewmodel.load name: 'A' age: 2 f: -> 'X' it "loads js object", -> @viewmodel.load name: 'B' f: -> 'Y' assert.equal 'B', @viewmodel.name() assert.equal 2, @viewmodel.age() assert.equal 'Y', @viewmodel.f() return describe "mixin", -> beforeEach -> ViewModel.mixin house: address: 'A' person: name: 'X' glob: mixin: 'person' prom: mixin: scoped: 'glob' bland: mixin: [ { subGlob: 'glob'}, 'house'] it "sub-mixin adds property to vm", -> vm = new ViewModel mixin: 'glob' assert.equal 'X', vm.name() it "sub-mixin adds sub-property to vm", -> vm = new ViewModel mixin: scoped: 'glob' assert.equal 'X', vm.scoped.name() it "sub-mixin adds sub-property to vm prom", -> vm = new ViewModel mixin: 'prom' assert.equal 'X', vm.scoped.name() it "sub-mixin adds sub-property to vm bland", -> vm = new ViewModel mixin: 'bland' assert.equal 'A', vm.address() assert.equal 'X', vm.subGlob.name() it "sub-mixin adds sub-property to vm bland scoped", -> vm = new ViewModel mixin: scoped: 'bland' assert.equal 'A', vm.scoped.address() assert.equal 'X', vm.scoped.subGlob.name() it "adds property to vm", -> vm = new ViewModel mixin: 'house' assert.equal 'A', vm.address() it "adds property to vm from array", -> vm = new ViewModel mixin: ['house'] assert.equal 'A', vm.address() it "doesn't share the property", -> vm1 = new ViewModel mixin: 'house' vm2 = new ViewModel mixin: 'house' vm2.address 'B' assert.equal 'A', vm1.address() assert.equal 'B', vm2.address() it "adds object to vm", -> vm = new ViewModel mixin: location: 'house' assert.equal 'A', vm.location.address() it "adds array to vm", -> vm = new ViewModel mixin: location: ['house', 'person'] assert.equal 'A', vm.location.address() assert.equal 'X', vm.location.name() it "adds mix to vm", -> vm = new ViewModel mixin: [ { location: 'house' }, 'person' ] assert.equal 'A', vm.location.address() assert.equal 'X', vm.name() describe "share", -> beforeEach -> ViewModel.share house: address: 'A' person: name: 'X' it "adds property to vm", -> vm = new ViewModel share: 'house' assert.equal 'A', vm.address() it "adds property to vm from array", -> vm = new ViewModel share: ['house'] assert.equal 'A', vm.address() it "adds object to vm", -> vm = new ViewModel share: location: 'house' assert.equal 'A', vm.location.address() it "shares the property", -> vm1 = new ViewModel share: 'house' vm2 = new ViewModel share: 'house' vm2.address 'B' assert.equal 'B', vm1.address() assert.equal 'B', vm2.address() assert.equal vm1.address, vm1.address it "adds array to vm", -> vm = new ViewModel share: location: ['house', 'person'] assert.equal 'A', vm.location.address() assert.equal 'X', vm.location.name() it "adds mix to vm", -> vm = new ViewModel share: [ { location: 'house' }, 'person' ] assert.equal 'A', vm.location.address() assert.equal 'X', vm.name()
38474
describe "ViewModel instance", -> beforeEach -> @checkStub = sinon.stub ViewModel, "check" @viewmodel = new ViewModel() afterEach -> sinon.restoreAll() describe "constructor", -> it "checks the arguments", -> obj = { name: '<NAME>'} vm = new ViewModel obj assert.isTrue @checkStub.calledWith '#constructor', obj it "adds property as function", -> vm = new ViewModel({ name: 'A'}) assert.isFunction vm.name assert.equal 'A', vm.name() vm.name('B') assert.equal 'B', vm.name() it "adds properties in load object", -> obj = { name: "<NAME>" } vm = new ViewModel load: obj assert.equal 'A', vm.name() it "adds properties in load array", -> arr = [ { name: "<NAME>" }, { age: 1 } ] vm = new ViewModel load: arr assert.equal 'A', vm.name() assert.equal 1, vm.age() it "doesn't convert functions", -> f = -> vm = new ViewModel fun: f assert.equal f, vm.fun describe "loading hooks direct", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin hooksMixin: onCreated: -> 'onCreatedMixin' onRendered: -> 'onRenderedMixin' onDestroyed: -> 'onDestroyedMixin' autorun: -> 'autorunMixin' ViewModel.shared = {} ViewModel.share hooksShare: onCreated: -> 'onCreatedShare' onRendered: -> 'onRenderedShare' onDestroyed: -> 'onDestroyedShare' autorun: -> 'autorunShare' @viewmodel = new ViewModel share: 'hooksShare' mixin: 'hooksMixin' load: onCreated: -> 'onCreatedLoad' onRendered: -> 'onRenderedLoad' onDestroyed: -> 'onDestroyedLoad' autorun: -> 'autorunLoad' onCreated: -> 'onCreatedBase' onRendered: -> 'onRenderedBase' onDestroyed: -> 'onDestroyedBase' autorun: -> 'autorunBase' return it "adds hooks to onCreated", -> assert.equal @viewmodel.vmOnCreated.length, 4 assert.equal @viewmodel.vmOnCreated[0](), 'onCreatedShare' assert.equal @viewmodel.vmOnCreated[1](), 'onCreatedMixin' assert.equal @viewmodel.vmOnCreated[2](), 'onCreatedLoad' assert.equal @viewmodel.vmOnCreated[3](), 'onCreatedBase' it "adds hooks to onRendered", -> assert.equal @viewmodel.vmOnRendered.length, 4 assert.equal @viewmodel.vmOnRendered[0](), 'onRenderedShare' assert.equal @viewmodel.vmOnRendered[1](), 'onRenderedMixin' assert.equal @viewmodel.vmOnRendered[2](), 'onRenderedLoad' assert.equal @viewmodel.vmOnRendered[3](), 'onRenderedBase' it "adds hooks to onDestroyed", -> assert.equal @viewmodel.vmOnDestroyed.length, 4 assert.equal @viewmodel.vmOnDestroyed[0](), 'onDestroyedShare' assert.equal @viewmodel.vmOnDestroyed[1](), 'onDestroyedMixin' assert.equal @viewmodel.vmOnDestroyed[2](), 'onDestroyedLoad' assert.equal @viewmodel.vmOnDestroyed[3](), 'onDestroyedBase' it "adds hooks to autorun", -> assert.equal @viewmodel.vmAutorun.length, 4 assert.equal @viewmodel.vmAutorun[0](), 'autorunShare' assert.equal @viewmodel.vmAutorun[1](), 'autorunMixin' assert.equal @viewmodel.vmAutorun[2](), 'autorunLoad' assert.equal @viewmodel.vmAutorun[3](), 'autorunBase' describe "loading hooks from array", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin hooksMixin: onCreated: [ (-> 'onCreatedMixin')] onRendered: [ (-> 'onRenderedMixin')] onDestroyed: [ (-> 'onDestroyedMixin')] autorun: [ (-> 'autorunMixin')] ViewModel.shared = {} ViewModel.share hooksShare: onCreated: [ (-> 'onCreatedShare')] onRendered: [ (-> 'onRenderedShare')] onDestroyed: [ (-> 'onDestroyedShare')] autorun: [ (-> 'autorunShare')] @viewmodel = new ViewModel share: 'hooksShare' mixin: 'hooksMixin' load: onCreated: [ (-> 'onCreatedLoad')] onRendered: [ (-> 'onRenderedLoad')] onDestroyed: [ (-> 'onDestroyedLoad')] autorun: [ (-> 'autorunLoad')] onCreated: [ (-> 'onCreatedBase')] onRendered: [ (-> 'onRenderedBase')] onDestroyed: [ (-> 'onDestroyedBase')] autorun: [ (-> 'autorunBase')] return it "adds hooks to onCreated", -> assert.equal @viewmodel.vmOnCreated.length, 4 assert.equal @viewmodel.vmOnCreated[0](), 'onCreatedShare' assert.equal @viewmodel.vmOnCreated[1](), 'onCreatedMixin' assert.equal @viewmodel.vmOnCreated[2](), 'onCreatedLoad' assert.equal @viewmodel.vmOnCreated[3](), 'onCreatedBase' it "adds hooks to onRendered", -> assert.equal @viewmodel.vmOnRendered.length, 4 assert.equal @viewmodel.vmOnRendered[0](), 'onRenderedShare' assert.equal @viewmodel.vmOnRendered[1](), 'onRenderedMixin' assert.equal @viewmodel.vmOnRendered[2](), 'onRenderedLoad' assert.equal @viewmodel.vmOnRendered[3](), 'onRenderedBase' it "adds hooks to onDestroyed", -> assert.equal @viewmodel.vmOnDestroyed.length, 4 assert.equal @viewmodel.vmOnDestroyed[0](), 'onDestroyedShare' assert.equal @viewmodel.vmOnDestroyed[1](), 'onDestroyedMixin' assert.equal @viewmodel.vmOnDestroyed[2](), 'onDestroyedLoad' assert.equal @viewmodel.vmOnDestroyed[3](), 'onDestroyedBase' it "adds hooks to autorun", -> assert.equal @viewmodel.vmAutorun.length, 4 assert.equal @viewmodel.vmAutorun[0](), 'autorunShare' assert.equal @viewmodel.vmAutorun[1](), 'autorunMixin' assert.equal @viewmodel.vmAutorun[2](), 'autorunLoad' assert.equal @viewmodel.vmAutorun[3](), 'autorunBase' describe "load order", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin name: name: 'mixin' ViewModel.shared = {} ViewModel.share name: name: 'share' ViewModel.signals = {} ViewModel.signal name: name: target: document event: 'keydown' it "loads base name last", -> vm = new ViewModel({ name: 'base', load: { name: 'load' }, mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "base" it "loads from load 2nd to last", -> vm = new ViewModel({ load: { name: 'load' }, mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "load" it "loads from mixin 3rd to last", -> vm = new ViewModel({ mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "mixin" it "loads from share 4th to last", -> vm = new ViewModel({ share: 'name', signal: 'name' }) assert.equal vm.name(), "share" it "loads from signal first", -> vm = new ViewModel({ signal: 'name' }) assert.equal _.keys(vm.name()).length, 0 describe "#bind", -> beforeEach -> @bindSingleStub = sinon.stub ViewModel, 'bindSingle' it "calls bindSingle for each entry in bindObject", -> bindObject = a: 1 b: 2 vm = {} bindings = a: 1 b: 2 @viewmodel.bind.call vm, bindObject, 'templateInstance', 'element', bindings assert.isTrue @bindSingleStub.calledTwice assert.isTrue @bindSingleStub.calledWith 'templateInstance', 'element', 'a', 1, bindObject, vm, bindings assert.isTrue @bindSingleStub.calledWith 'templateInstance', 'element', 'b', 2, bindObject, vm, bindings it "returns undefined", -> bindObject = {} ret = @viewmodel.bind bindObject, 'templateInstance', 'element', 'bindings' assert.isUndefined ret describe "validation", -> it "vm is valid with an undefined", -> @viewmodel.load({ name: undefined }) assert.equal true, @viewmodel.valid() return describe "#load", -> it "adds a property to the view model", -> @viewmodel.load({ name: '<NAME>' }) assert.equal '<NAME>', @viewmodel.name() it "adds onRendered from an array", -> f = -> @viewmodel.load([ onRendered: f ]) assert.equal f, @viewmodel.vmOnRendered[0] it "adds a properties from an array", -> @viewmodel.load([{ name: '<NAME>' },{ two: '<NAME>' }]) assert.equal '<NAME>', @viewmodel.name() assert.equal '<NAME>', @viewmodel.two() it "adds function to the view model", -> f = -> @viewmodel.load({ fun: f }) assert.equal f, @viewmodel.fun it "doesn't create a new property when extending the same name", -> @viewmodel.load({ name: '<NAME>' }) old = @viewmodel.name @viewmodel.load({ name: '<NAME>' }) assert.equal '<NAME>', @viewmodel.name() assert.equal old, @viewmodel.name it "overwrite existing functions", -> @viewmodel.load({ name: -> '<NAME>' }) old = @viewmodel.name @viewmodel.load({ name: '<NAME>' }) theNew = @viewmodel.name assert.equal '<NAME>', @viewmodel.name() assert.equal theNew, @viewmodel.name assert.notEqual old, theNew it "doesn't add events", -> @viewmodel.load({ events: { 'click one' : -> } }) assert.equal 0, @viewmodel.vmEvents.length it "adds events", -> @viewmodel.load({ events: { 'click one' : -> } }, true) assert.equal 1, @viewmodel.vmEvents.length it "doesn't do anything with null and undefined", -> @viewmodel.load(undefined ) @viewmodel.load(null) describe "#parent", -> beforeEach -> @viewmodel.templateInstance = view: parentView: name: 'Template.A' templateInstance: -> viewmodel: "X" it "returns the view model of the parent template", -> parent = @viewmodel.parent() assert.equal "X", parent it "returns the first view model up the chain", -> @viewmodel.templateInstance = view: parentView: name: 'Template.something' templateInstance: -> view: parentView: name: 'Template.A' templateInstance: -> viewmodel: "Y" parent = @viewmodel.parent() assert.equal "Y", parent it "checks the arguments", -> @viewmodel.parent('X') assert.isTrue @checkStub.calledWith '#parent', 'X' describe "#children", -> beforeEach -> @viewmodel.children().push age: -> 1 name: -> "<NAME>" templateInstance: view: name: 'Template.A' @viewmodel.children().push age: -> 2 name: -> "<NAME>" templateInstance: view: name: 'Template.B' @viewmodel.children().push age: -> 1 templateInstance: view: name: 'Template.A' it "returns all without arguments", -> assert.equal 3, @viewmodel.children().length @viewmodel.children().push("X") assert.equal 4, @viewmodel.children().length assert.equal "X", @viewmodel.children()[3] it "returns by template when passed a string", -> arr = @viewmodel.children('A') assert.equal 2, arr.length assert.equal 1, arr[0].age() assert.equal 1, arr[1].age() it "returns array from a predicate", -> arr = @viewmodel.children((vm) -> vm.age() is 2) assert.equal 1, arr.length assert.equal "BB", arr[0].name() it "calls .depend", -> array = @viewmodel.children() spy = sinon.spy array, 'depend' @viewmodel.children() assert.isTrue spy.called it "doesn't check without arguments", -> @viewmodel.children() assert.isFalse @checkStub.calledWith '#children' it "checks with arguments", -> @viewmodel.children('X') assert.isTrue @checkStub.calledWith '#children', 'X' describe "#reset", -> beforeEach -> @viewmodel.templateInstance = view: name: 'body' @viewmodel.load name: 'A' arr: ['A'] it "resets a string", -> @viewmodel.name('B') @viewmodel.reset() assert.equal "A", @viewmodel.name() it "resets an array", -> @viewmodel.arr().push('B') @viewmodel.reset() assert.equal 1, @viewmodel.arr().length assert.equal 'A', @viewmodel.arr()[0] describe "#data", -> beforeEach -> @viewmodel.load name: 'A' arr: ['B'] it "creates js object", -> obj = @viewmodel.data() assert.equal 'A', obj.name assert.equal 'B', obj.arr[0] return it "only loads fields specified", -> obj = @viewmodel.data(['name']) assert.equal 'A', obj.name assert.isUndefined obj.arr return describe "#load", -> beforeEach -> @viewmodel.load name: 'A' age: 2 f: -> 'X' it "loads js object", -> @viewmodel.load name: 'B' f: -> 'Y' assert.equal 'B', @viewmodel.name() assert.equal 2, @viewmodel.age() assert.equal 'Y', @viewmodel.f() return describe "mixin", -> beforeEach -> ViewModel.mixin house: address: 'A' person: name: 'X' glob: mixin: 'person' prom: mixin: scoped: 'glob' bland: mixin: [ { subGlob: 'glob'}, 'house'] it "sub-mixin adds property to vm", -> vm = new ViewModel mixin: 'glob' assert.equal 'X', vm.name() it "sub-mixin adds sub-property to vm", -> vm = new ViewModel mixin: scoped: 'glob' assert.equal 'X', vm.scoped.name() it "sub-mixin adds sub-property to vm prom", -> vm = new ViewModel mixin: 'prom' assert.equal 'X', vm.scoped.name() it "sub-mixin adds sub-property to vm bland", -> vm = new ViewModel mixin: 'bland' assert.equal 'A', vm.address() assert.equal 'X', vm.subGlob.name() it "sub-mixin adds sub-property to vm bland scoped", -> vm = new ViewModel mixin: scoped: 'bland' assert.equal 'A', vm.scoped.address() assert.equal 'X', vm.scoped.subGlob.name() it "adds property to vm", -> vm = new ViewModel mixin: 'house' assert.equal 'A', vm.address() it "adds property to vm from array", -> vm = new ViewModel mixin: ['house'] assert.equal 'A', vm.address() it "doesn't share the property", -> vm1 = new ViewModel mixin: 'house' vm2 = new ViewModel mixin: 'house' vm2.address 'B' assert.equal 'A', vm1.address() assert.equal 'B', vm2.address() it "adds object to vm", -> vm = new ViewModel mixin: location: 'house' assert.equal 'A', vm.location.address() it "adds array to vm", -> vm = new ViewModel mixin: location: ['house', 'person'] assert.equal 'A', vm.location.address() assert.equal 'X', vm.location.name() it "adds mix to vm", -> vm = new ViewModel mixin: [ { location: 'house' }, '<NAME>' ] assert.equal 'A', vm.location.address() assert.equal 'X', vm.name() describe "share", -> beforeEach -> ViewModel.share house: address: 'A' person: name: '<NAME>' it "adds property to vm", -> vm = new ViewModel share: 'house' assert.equal 'A', vm.address() it "adds property to vm from array", -> vm = new ViewModel share: ['house'] assert.equal 'A', vm.address() it "adds object to vm", -> vm = new ViewModel share: location: 'house' assert.equal 'A', vm.location.address() it "shares the property", -> vm1 = new ViewModel share: 'house' vm2 = new ViewModel share: 'house' vm2.address 'B' assert.equal 'B', vm1.address() assert.equal 'B', vm2.address() assert.equal vm1.address, vm1.address it "adds array to vm", -> vm = new ViewModel share: location: ['house', 'person'] assert.equal 'A', vm.location.address() assert.equal 'X', vm.location.name() it "adds mix to vm", -> vm = new ViewModel share: [ { location: 'house' }, 'person' ] assert.equal 'A', vm.location.address() assert.equal 'X', vm.name()
true
describe "ViewModel instance", -> beforeEach -> @checkStub = sinon.stub ViewModel, "check" @viewmodel = new ViewModel() afterEach -> sinon.restoreAll() describe "constructor", -> it "checks the arguments", -> obj = { name: 'PI:NAME:<NAME>END_PI'} vm = new ViewModel obj assert.isTrue @checkStub.calledWith '#constructor', obj it "adds property as function", -> vm = new ViewModel({ name: 'A'}) assert.isFunction vm.name assert.equal 'A', vm.name() vm.name('B') assert.equal 'B', vm.name() it "adds properties in load object", -> obj = { name: "PI:NAME:<NAME>END_PI" } vm = new ViewModel load: obj assert.equal 'A', vm.name() it "adds properties in load array", -> arr = [ { name: "PI:NAME:<NAME>END_PI" }, { age: 1 } ] vm = new ViewModel load: arr assert.equal 'A', vm.name() assert.equal 1, vm.age() it "doesn't convert functions", -> f = -> vm = new ViewModel fun: f assert.equal f, vm.fun describe "loading hooks direct", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin hooksMixin: onCreated: -> 'onCreatedMixin' onRendered: -> 'onRenderedMixin' onDestroyed: -> 'onDestroyedMixin' autorun: -> 'autorunMixin' ViewModel.shared = {} ViewModel.share hooksShare: onCreated: -> 'onCreatedShare' onRendered: -> 'onRenderedShare' onDestroyed: -> 'onDestroyedShare' autorun: -> 'autorunShare' @viewmodel = new ViewModel share: 'hooksShare' mixin: 'hooksMixin' load: onCreated: -> 'onCreatedLoad' onRendered: -> 'onRenderedLoad' onDestroyed: -> 'onDestroyedLoad' autorun: -> 'autorunLoad' onCreated: -> 'onCreatedBase' onRendered: -> 'onRenderedBase' onDestroyed: -> 'onDestroyedBase' autorun: -> 'autorunBase' return it "adds hooks to onCreated", -> assert.equal @viewmodel.vmOnCreated.length, 4 assert.equal @viewmodel.vmOnCreated[0](), 'onCreatedShare' assert.equal @viewmodel.vmOnCreated[1](), 'onCreatedMixin' assert.equal @viewmodel.vmOnCreated[2](), 'onCreatedLoad' assert.equal @viewmodel.vmOnCreated[3](), 'onCreatedBase' it "adds hooks to onRendered", -> assert.equal @viewmodel.vmOnRendered.length, 4 assert.equal @viewmodel.vmOnRendered[0](), 'onRenderedShare' assert.equal @viewmodel.vmOnRendered[1](), 'onRenderedMixin' assert.equal @viewmodel.vmOnRendered[2](), 'onRenderedLoad' assert.equal @viewmodel.vmOnRendered[3](), 'onRenderedBase' it "adds hooks to onDestroyed", -> assert.equal @viewmodel.vmOnDestroyed.length, 4 assert.equal @viewmodel.vmOnDestroyed[0](), 'onDestroyedShare' assert.equal @viewmodel.vmOnDestroyed[1](), 'onDestroyedMixin' assert.equal @viewmodel.vmOnDestroyed[2](), 'onDestroyedLoad' assert.equal @viewmodel.vmOnDestroyed[3](), 'onDestroyedBase' it "adds hooks to autorun", -> assert.equal @viewmodel.vmAutorun.length, 4 assert.equal @viewmodel.vmAutorun[0](), 'autorunShare' assert.equal @viewmodel.vmAutorun[1](), 'autorunMixin' assert.equal @viewmodel.vmAutorun[2](), 'autorunLoad' assert.equal @viewmodel.vmAutorun[3](), 'autorunBase' describe "loading hooks from array", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin hooksMixin: onCreated: [ (-> 'onCreatedMixin')] onRendered: [ (-> 'onRenderedMixin')] onDestroyed: [ (-> 'onDestroyedMixin')] autorun: [ (-> 'autorunMixin')] ViewModel.shared = {} ViewModel.share hooksShare: onCreated: [ (-> 'onCreatedShare')] onRendered: [ (-> 'onRenderedShare')] onDestroyed: [ (-> 'onDestroyedShare')] autorun: [ (-> 'autorunShare')] @viewmodel = new ViewModel share: 'hooksShare' mixin: 'hooksMixin' load: onCreated: [ (-> 'onCreatedLoad')] onRendered: [ (-> 'onRenderedLoad')] onDestroyed: [ (-> 'onDestroyedLoad')] autorun: [ (-> 'autorunLoad')] onCreated: [ (-> 'onCreatedBase')] onRendered: [ (-> 'onRenderedBase')] onDestroyed: [ (-> 'onDestroyedBase')] autorun: [ (-> 'autorunBase')] return it "adds hooks to onCreated", -> assert.equal @viewmodel.vmOnCreated.length, 4 assert.equal @viewmodel.vmOnCreated[0](), 'onCreatedShare' assert.equal @viewmodel.vmOnCreated[1](), 'onCreatedMixin' assert.equal @viewmodel.vmOnCreated[2](), 'onCreatedLoad' assert.equal @viewmodel.vmOnCreated[3](), 'onCreatedBase' it "adds hooks to onRendered", -> assert.equal @viewmodel.vmOnRendered.length, 4 assert.equal @viewmodel.vmOnRendered[0](), 'onRenderedShare' assert.equal @viewmodel.vmOnRendered[1](), 'onRenderedMixin' assert.equal @viewmodel.vmOnRendered[2](), 'onRenderedLoad' assert.equal @viewmodel.vmOnRendered[3](), 'onRenderedBase' it "adds hooks to onDestroyed", -> assert.equal @viewmodel.vmOnDestroyed.length, 4 assert.equal @viewmodel.vmOnDestroyed[0](), 'onDestroyedShare' assert.equal @viewmodel.vmOnDestroyed[1](), 'onDestroyedMixin' assert.equal @viewmodel.vmOnDestroyed[2](), 'onDestroyedLoad' assert.equal @viewmodel.vmOnDestroyed[3](), 'onDestroyedBase' it "adds hooks to autorun", -> assert.equal @viewmodel.vmAutorun.length, 4 assert.equal @viewmodel.vmAutorun[0](), 'autorunShare' assert.equal @viewmodel.vmAutorun[1](), 'autorunMixin' assert.equal @viewmodel.vmAutorun[2](), 'autorunLoad' assert.equal @viewmodel.vmAutorun[3](), 'autorunBase' describe "load order", -> beforeEach -> ViewModel.mixins = {} ViewModel.mixin name: name: 'mixin' ViewModel.shared = {} ViewModel.share name: name: 'share' ViewModel.signals = {} ViewModel.signal name: name: target: document event: 'keydown' it "loads base name last", -> vm = new ViewModel({ name: 'base', load: { name: 'load' }, mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "base" it "loads from load 2nd to last", -> vm = new ViewModel({ load: { name: 'load' }, mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "load" it "loads from mixin 3rd to last", -> vm = new ViewModel({ mixin: 'name', share: 'name', signal: 'name' }) assert.equal vm.name(), "mixin" it "loads from share 4th to last", -> vm = new ViewModel({ share: 'name', signal: 'name' }) assert.equal vm.name(), "share" it "loads from signal first", -> vm = new ViewModel({ signal: 'name' }) assert.equal _.keys(vm.name()).length, 0 describe "#bind", -> beforeEach -> @bindSingleStub = sinon.stub ViewModel, 'bindSingle' it "calls bindSingle for each entry in bindObject", -> bindObject = a: 1 b: 2 vm = {} bindings = a: 1 b: 2 @viewmodel.bind.call vm, bindObject, 'templateInstance', 'element', bindings assert.isTrue @bindSingleStub.calledTwice assert.isTrue @bindSingleStub.calledWith 'templateInstance', 'element', 'a', 1, bindObject, vm, bindings assert.isTrue @bindSingleStub.calledWith 'templateInstance', 'element', 'b', 2, bindObject, vm, bindings it "returns undefined", -> bindObject = {} ret = @viewmodel.bind bindObject, 'templateInstance', 'element', 'bindings' assert.isUndefined ret describe "validation", -> it "vm is valid with an undefined", -> @viewmodel.load({ name: undefined }) assert.equal true, @viewmodel.valid() return describe "#load", -> it "adds a property to the view model", -> @viewmodel.load({ name: 'PI:NAME:<NAME>END_PI' }) assert.equal 'PI:NAME:<NAME>END_PI', @viewmodel.name() it "adds onRendered from an array", -> f = -> @viewmodel.load([ onRendered: f ]) assert.equal f, @viewmodel.vmOnRendered[0] it "adds a properties from an array", -> @viewmodel.load([{ name: 'PI:NAME:<NAME>END_PI' },{ two: 'PI:NAME:<NAME>END_PI' }]) assert.equal 'PI:NAME:<NAME>END_PI', @viewmodel.name() assert.equal 'PI:NAME:<NAME>END_PI', @viewmodel.two() it "adds function to the view model", -> f = -> @viewmodel.load({ fun: f }) assert.equal f, @viewmodel.fun it "doesn't create a new property when extending the same name", -> @viewmodel.load({ name: 'PI:NAME:<NAME>END_PI' }) old = @viewmodel.name @viewmodel.load({ name: 'PI:NAME:<NAME>END_PI' }) assert.equal 'PI:NAME:<NAME>END_PI', @viewmodel.name() assert.equal old, @viewmodel.name it "overwrite existing functions", -> @viewmodel.load({ name: -> 'PI:NAME:<NAME>END_PI' }) old = @viewmodel.name @viewmodel.load({ name: 'PI:NAME:<NAME>END_PI' }) theNew = @viewmodel.name assert.equal 'PI:NAME:<NAME>END_PI', @viewmodel.name() assert.equal theNew, @viewmodel.name assert.notEqual old, theNew it "doesn't add events", -> @viewmodel.load({ events: { 'click one' : -> } }) assert.equal 0, @viewmodel.vmEvents.length it "adds events", -> @viewmodel.load({ events: { 'click one' : -> } }, true) assert.equal 1, @viewmodel.vmEvents.length it "doesn't do anything with null and undefined", -> @viewmodel.load(undefined ) @viewmodel.load(null) describe "#parent", -> beforeEach -> @viewmodel.templateInstance = view: parentView: name: 'Template.A' templateInstance: -> viewmodel: "X" it "returns the view model of the parent template", -> parent = @viewmodel.parent() assert.equal "X", parent it "returns the first view model up the chain", -> @viewmodel.templateInstance = view: parentView: name: 'Template.something' templateInstance: -> view: parentView: name: 'Template.A' templateInstance: -> viewmodel: "Y" parent = @viewmodel.parent() assert.equal "Y", parent it "checks the arguments", -> @viewmodel.parent('X') assert.isTrue @checkStub.calledWith '#parent', 'X' describe "#children", -> beforeEach -> @viewmodel.children().push age: -> 1 name: -> "PI:NAME:<NAME>END_PI" templateInstance: view: name: 'Template.A' @viewmodel.children().push age: -> 2 name: -> "PI:NAME:<NAME>END_PI" templateInstance: view: name: 'Template.B' @viewmodel.children().push age: -> 1 templateInstance: view: name: 'Template.A' it "returns all without arguments", -> assert.equal 3, @viewmodel.children().length @viewmodel.children().push("X") assert.equal 4, @viewmodel.children().length assert.equal "X", @viewmodel.children()[3] it "returns by template when passed a string", -> arr = @viewmodel.children('A') assert.equal 2, arr.length assert.equal 1, arr[0].age() assert.equal 1, arr[1].age() it "returns array from a predicate", -> arr = @viewmodel.children((vm) -> vm.age() is 2) assert.equal 1, arr.length assert.equal "BB", arr[0].name() it "calls .depend", -> array = @viewmodel.children() spy = sinon.spy array, 'depend' @viewmodel.children() assert.isTrue spy.called it "doesn't check without arguments", -> @viewmodel.children() assert.isFalse @checkStub.calledWith '#children' it "checks with arguments", -> @viewmodel.children('X') assert.isTrue @checkStub.calledWith '#children', 'X' describe "#reset", -> beforeEach -> @viewmodel.templateInstance = view: name: 'body' @viewmodel.load name: 'A' arr: ['A'] it "resets a string", -> @viewmodel.name('B') @viewmodel.reset() assert.equal "A", @viewmodel.name() it "resets an array", -> @viewmodel.arr().push('B') @viewmodel.reset() assert.equal 1, @viewmodel.arr().length assert.equal 'A', @viewmodel.arr()[0] describe "#data", -> beforeEach -> @viewmodel.load name: 'A' arr: ['B'] it "creates js object", -> obj = @viewmodel.data() assert.equal 'A', obj.name assert.equal 'B', obj.arr[0] return it "only loads fields specified", -> obj = @viewmodel.data(['name']) assert.equal 'A', obj.name assert.isUndefined obj.arr return describe "#load", -> beforeEach -> @viewmodel.load name: 'A' age: 2 f: -> 'X' it "loads js object", -> @viewmodel.load name: 'B' f: -> 'Y' assert.equal 'B', @viewmodel.name() assert.equal 2, @viewmodel.age() assert.equal 'Y', @viewmodel.f() return describe "mixin", -> beforeEach -> ViewModel.mixin house: address: 'A' person: name: 'X' glob: mixin: 'person' prom: mixin: scoped: 'glob' bland: mixin: [ { subGlob: 'glob'}, 'house'] it "sub-mixin adds property to vm", -> vm = new ViewModel mixin: 'glob' assert.equal 'X', vm.name() it "sub-mixin adds sub-property to vm", -> vm = new ViewModel mixin: scoped: 'glob' assert.equal 'X', vm.scoped.name() it "sub-mixin adds sub-property to vm prom", -> vm = new ViewModel mixin: 'prom' assert.equal 'X', vm.scoped.name() it "sub-mixin adds sub-property to vm bland", -> vm = new ViewModel mixin: 'bland' assert.equal 'A', vm.address() assert.equal 'X', vm.subGlob.name() it "sub-mixin adds sub-property to vm bland scoped", -> vm = new ViewModel mixin: scoped: 'bland' assert.equal 'A', vm.scoped.address() assert.equal 'X', vm.scoped.subGlob.name() it "adds property to vm", -> vm = new ViewModel mixin: 'house' assert.equal 'A', vm.address() it "adds property to vm from array", -> vm = new ViewModel mixin: ['house'] assert.equal 'A', vm.address() it "doesn't share the property", -> vm1 = new ViewModel mixin: 'house' vm2 = new ViewModel mixin: 'house' vm2.address 'B' assert.equal 'A', vm1.address() assert.equal 'B', vm2.address() it "adds object to vm", -> vm = new ViewModel mixin: location: 'house' assert.equal 'A', vm.location.address() it "adds array to vm", -> vm = new ViewModel mixin: location: ['house', 'person'] assert.equal 'A', vm.location.address() assert.equal 'X', vm.location.name() it "adds mix to vm", -> vm = new ViewModel mixin: [ { location: 'house' }, 'PI:NAME:<NAME>END_PI' ] assert.equal 'A', vm.location.address() assert.equal 'X', vm.name() describe "share", -> beforeEach -> ViewModel.share house: address: 'A' person: name: 'PI:NAME:<NAME>END_PI' it "adds property to vm", -> vm = new ViewModel share: 'house' assert.equal 'A', vm.address() it "adds property to vm from array", -> vm = new ViewModel share: ['house'] assert.equal 'A', vm.address() it "adds object to vm", -> vm = new ViewModel share: location: 'house' assert.equal 'A', vm.location.address() it "shares the property", -> vm1 = new ViewModel share: 'house' vm2 = new ViewModel share: 'house' vm2.address 'B' assert.equal 'B', vm1.address() assert.equal 'B', vm2.address() assert.equal vm1.address, vm1.address it "adds array to vm", -> vm = new ViewModel share: location: ['house', 'person'] assert.equal 'A', vm.location.address() assert.equal 'X', vm.location.name() it "adds mix to vm", -> vm = new ViewModel share: [ { location: 'house' }, 'person' ] assert.equal 'A', vm.location.address() assert.equal 'X', vm.name()
[ { "context": "ount 'verbose'\n .alias\n l: 'loginurl'\n u: 'username'\n p: 'password'\n v: 'verbose'\n .describe\n ", "end": 432, "score": 0.9987084269523621, "start": 424, "tag": "USERNAME", "value": "username" }, { "context": "describe\n loginurl: 'Login URL'\n ...
src/argv.coffee
jdcrensh/force-coverage
2
{apiVersion} = require '../package.json' logger = require './logger' yargs = require 'yargs' argv = yargs .usage 'Usage: $0 [options]' .help 'help' .default loginurl: 'https://test.salesforce.com' version: apiVersion target: 0.76 class: 'CoverageInflation' pollTimeout: 600 * 1000 pollInterval: 5 * 1000 .demand ['username', 'password'] .count 'verbose' .alias l: 'loginurl' u: 'username' p: 'password' v: 'verbose' .describe loginurl: 'Login URL' username: 'Username' password: 'Password + Security Token' version: 'Package version' verbose: 'Sets node logging level' class: 'Change the default coverage class name' target: 'Percent coverage required (0.01-0.99)' .wrap yargs.terminalWidth() .argv constrainTargetCoverage = (argv) -> if 0.76 < argv.targetCoverage < 0.99 argv.targetCoverage = Math.max 0.76, Math.min 0.99, argv.targetCoverage logger.warn 'Adjusted target coverage to %d. Valid range is 0.76-0.99.', argv.targetCoverage setLogLevel = (argv) -> argv.logLevel = switch argv.verbose when 0 then 'info' when 1 then 'verbose' when 2 then 'debug' when 3 then 'silly' else 'info' # post-init constrainTargetCoverage argv setLogLevel argv module.exports = argv
26329
{apiVersion} = require '../package.json' logger = require './logger' yargs = require 'yargs' argv = yargs .usage 'Usage: $0 [options]' .help 'help' .default loginurl: 'https://test.salesforce.com' version: apiVersion target: 0.76 class: 'CoverageInflation' pollTimeout: 600 * 1000 pollInterval: 5 * 1000 .demand ['username', 'password'] .count 'verbose' .alias l: 'loginurl' u: 'username' p: 'password' v: 'verbose' .describe loginurl: 'Login URL' username: 'Username' password: '<PASSWORD>' version: 'Package version' verbose: 'Sets node logging level' class: 'Change the default coverage class name' target: 'Percent coverage required (0.01-0.99)' .wrap yargs.terminalWidth() .argv constrainTargetCoverage = (argv) -> if 0.76 < argv.targetCoverage < 0.99 argv.targetCoverage = Math.max 0.76, Math.min 0.99, argv.targetCoverage logger.warn 'Adjusted target coverage to %d. Valid range is 0.76-0.99.', argv.targetCoverage setLogLevel = (argv) -> argv.logLevel = switch argv.verbose when 0 then 'info' when 1 then 'verbose' when 2 then 'debug' when 3 then 'silly' else 'info' # post-init constrainTargetCoverage argv setLogLevel argv module.exports = argv
true
{apiVersion} = require '../package.json' logger = require './logger' yargs = require 'yargs' argv = yargs .usage 'Usage: $0 [options]' .help 'help' .default loginurl: 'https://test.salesforce.com' version: apiVersion target: 0.76 class: 'CoverageInflation' pollTimeout: 600 * 1000 pollInterval: 5 * 1000 .demand ['username', 'password'] .count 'verbose' .alias l: 'loginurl' u: 'username' p: 'password' v: 'verbose' .describe loginurl: 'Login URL' username: 'Username' password: 'PI:PASSWORD:<PASSWORD>END_PI' version: 'Package version' verbose: 'Sets node logging level' class: 'Change the default coverage class name' target: 'Percent coverage required (0.01-0.99)' .wrap yargs.terminalWidth() .argv constrainTargetCoverage = (argv) -> if 0.76 < argv.targetCoverage < 0.99 argv.targetCoverage = Math.max 0.76, Math.min 0.99, argv.targetCoverage logger.warn 'Adjusted target coverage to %d. Valid range is 0.76-0.99.', argv.targetCoverage setLogLevel = (argv) -> argv.logLevel = switch argv.verbose when 0 then 'info' when 1 then 'verbose' when 2 then 'debug' when 3 then 'silly' else 'info' # post-init constrainTargetCoverage argv setLogLevel argv module.exports = argv
[ { "context": "\n\ndnschain\nhttp://dnschain.net\n\nCopyright (c) 2013 Greg Slepak\nLicensed under the BSD 3-Clause license.\n\n###\n\nmo", "end": 65, "score": 0.999869167804718, "start": 54, "tag": "NAME", "value": "Greg Slepak" }, { "context": "ged into NodeJS in the future: https:/...
src/lib/globals.coffee
wartron/dnschain
1
### dnschain http://dnschain.net Copyright (c) 2013 Greg Slepak Licensed under the BSD 3-Clause license. ### module.exports = (dnschain) -> # 1. global dependencies dnschain.globals = rpc : 'json-rpc2' _ : 'lodash-contrib' S : 'string' dns2 : 'native-dns' es : 'event-stream' sa : 'stream-array' # no renaming done for these for d in ['net', 'dns', 'http', 'url', 'util', 'os', 'path', 'winston'] dnschain.globals[d] = d # replace all the string values in dnschain.globals with the module they represent # and expose them into this function's namespace for k,v of dnschain.globals eval "var #{k} = dnschain.globals.#{k} = require('#{v}');" # 2. global constants _.assign dnschain.globals, consts: # for questions that the blockchain cannot answer # (hopefully these will disappear with time) oldDNS: # USE THIS METHOD! NATIVE_DNS: 0 # Use 'native-dns' module (current default). Hopefully merged into NodeJS in the future: https://github.com/joyent/node/issues/6864#issuecomment-32229852 # !! WARNING !! # > USING 'NODE_DNS' IS __STRONGLY DISCOURAGED!__ < # > BECAUSE IT DOES NOT PROVIDE PROVIDE TTL VALUES! < # !! WARNING !! NODE_DNS: 1 # Prior to node 0.11.x will ignore dnsOpts.oldDNS and use OS-specified DNS. Currently ignores 'dnsOpts.oldDNS' in favor of OS-specified DNS even in node 0.11.x (simply needs to be implemented). TODO: <- this! # 3. create global functions, and then return the entire globals object _.assign dnschain.globals, { externalIP: do -> cachedIP = null faces = os.networkInterfaces() default_iface = switch when os.type() is 'Darwin' and faces.en0? then 'en0' when os.type() is 'Linux' and faces.eth0? then 'eth0' else _(faces).keys().find (x)-> !x.match /lo/ (iface=default_iface, cached=true,fam='IPv4',internal=false) -> cachedIP = switch when cached and cachedIP then cachedIP else unless ips = (faces = os.networkInterfaces())[iface] throw new Error util.format("No such interface '%s'. Available: %j", iface, faces) _.find(ips, {family:fam, internal:internal}).address newLogger: (name) -> new winston.Logger levels: winston.config.cli.levels colors: winston.config.cli.lcolors transports: [ new winston.transports.Console label:name level: config.get 'log:level' colorize: config.get 'log:cli' prettyPrint: config.get 'log:pretty' timestamp: config.get 'log:timestamp' ] tErr: (args...) -> msg = util.format args... e = new Error msg @log?.error e.stack throw e ip2type: (d, ttl, type='A') -> (ip)-> dns2[type] {name:d, address:ip, ttl:ttl} } # 4. config config = dnschain.globals.config = require('./config')(dnschain) # 5. return the globals object dnschain.globals
120368
### dnschain http://dnschain.net Copyright (c) 2013 <NAME> Licensed under the BSD 3-Clause license. ### module.exports = (dnschain) -> # 1. global dependencies dnschain.globals = rpc : 'json-rpc2' _ : 'lodash-contrib' S : 'string' dns2 : 'native-dns' es : 'event-stream' sa : 'stream-array' # no renaming done for these for d in ['net', 'dns', 'http', 'url', 'util', 'os', 'path', 'winston'] dnschain.globals[d] = d # replace all the string values in dnschain.globals with the module they represent # and expose them into this function's namespace for k,v of dnschain.globals eval "var #{k} = dnschain.globals.#{k} = require('#{v}');" # 2. global constants _.assign dnschain.globals, consts: # for questions that the blockchain cannot answer # (hopefully these will disappear with time) oldDNS: # USE THIS METHOD! NATIVE_DNS: 0 # Use 'native-dns' module (current default). Hopefully merged into NodeJS in the future: https://github.com/joyent/node/issues/6864#issuecomment-32229852 # !! WARNING !! # > USING 'NODE_DNS' IS __STRONGLY DISCOURAGED!__ < # > BECAUSE IT DOES NOT PROVIDE PROVIDE TTL VALUES! < # !! WARNING !! NODE_DNS: 1 # Prior to node 0.11.x will ignore dnsOpts.oldDNS and use OS-specified DNS. Currently ignores 'dnsOpts.oldDNS' in favor of OS-specified DNS even in node 0.11.x (simply needs to be implemented). TODO: <- this! # 3. create global functions, and then return the entire globals object _.assign dnschain.globals, { externalIP: do -> cachedIP = null faces = os.networkInterfaces() default_iface = switch when os.type() is 'Darwin' and faces.en0? then 'en0' when os.type() is 'Linux' and faces.eth0? then 'eth0' else _(faces).keys().find (x)-> !x.match /lo/ (iface=default_iface, cached=true,fam='IPv4',internal=false) -> cachedIP = switch when cached and cachedIP then cachedIP else unless ips = (faces = os.networkInterfaces())[iface] throw new Error util.format("No such interface '%s'. Available: %j", iface, faces) _.find(ips, {family:fam, internal:internal}).address newLogger: (name) -> new winston.Logger levels: winston.config.cli.levels colors: winston.config.cli.lcolors transports: [ new winston.transports.Console label:name level: config.get 'log:level' colorize: config.get 'log:cli' prettyPrint: config.get 'log:pretty' timestamp: config.get 'log:timestamp' ] tErr: (args...) -> msg = util.format args... e = new Error msg @log?.error e.stack throw e ip2type: (d, ttl, type='A') -> (ip)-> dns2[type] {name:d, address:ip, ttl:ttl} } # 4. config config = dnschain.globals.config = require('./config')(dnschain) # 5. return the globals object dnschain.globals
true
### dnschain http://dnschain.net Copyright (c) 2013 PI:NAME:<NAME>END_PI Licensed under the BSD 3-Clause license. ### module.exports = (dnschain) -> # 1. global dependencies dnschain.globals = rpc : 'json-rpc2' _ : 'lodash-contrib' S : 'string' dns2 : 'native-dns' es : 'event-stream' sa : 'stream-array' # no renaming done for these for d in ['net', 'dns', 'http', 'url', 'util', 'os', 'path', 'winston'] dnschain.globals[d] = d # replace all the string values in dnschain.globals with the module they represent # and expose them into this function's namespace for k,v of dnschain.globals eval "var #{k} = dnschain.globals.#{k} = require('#{v}');" # 2. global constants _.assign dnschain.globals, consts: # for questions that the blockchain cannot answer # (hopefully these will disappear with time) oldDNS: # USE THIS METHOD! NATIVE_DNS: 0 # Use 'native-dns' module (current default). Hopefully merged into NodeJS in the future: https://github.com/joyent/node/issues/6864#issuecomment-32229852 # !! WARNING !! # > USING 'NODE_DNS' IS __STRONGLY DISCOURAGED!__ < # > BECAUSE IT DOES NOT PROVIDE PROVIDE TTL VALUES! < # !! WARNING !! NODE_DNS: 1 # Prior to node 0.11.x will ignore dnsOpts.oldDNS and use OS-specified DNS. Currently ignores 'dnsOpts.oldDNS' in favor of OS-specified DNS even in node 0.11.x (simply needs to be implemented). TODO: <- this! # 3. create global functions, and then return the entire globals object _.assign dnschain.globals, { externalIP: do -> cachedIP = null faces = os.networkInterfaces() default_iface = switch when os.type() is 'Darwin' and faces.en0? then 'en0' when os.type() is 'Linux' and faces.eth0? then 'eth0' else _(faces).keys().find (x)-> !x.match /lo/ (iface=default_iface, cached=true,fam='IPv4',internal=false) -> cachedIP = switch when cached and cachedIP then cachedIP else unless ips = (faces = os.networkInterfaces())[iface] throw new Error util.format("No such interface '%s'. Available: %j", iface, faces) _.find(ips, {family:fam, internal:internal}).address newLogger: (name) -> new winston.Logger levels: winston.config.cli.levels colors: winston.config.cli.lcolors transports: [ new winston.transports.Console label:name level: config.get 'log:level' colorize: config.get 'log:cli' prettyPrint: config.get 'log:pretty' timestamp: config.get 'log:timestamp' ] tErr: (args...) -> msg = util.format args... e = new Error msg @log?.error e.stack throw e ip2type: (d, ttl, type='A') -> (ip)-> dns2[type] {name:d, address:ip, ttl:ttl} } # 4. config config = dnschain.globals.config = require('./config')(dnschain) # 5. return the globals object dnschain.globals
[ { "context": "returnValue field of the response object.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass SynchronizeSlav", "end": 712, "score": 0.9998800158500671, "start": 700, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/router/routes/rpc/admin/SynchronizeSlaveDbRoute.coffee
qrefdev/qref
0
RpcRoute = require('../../../RpcRoute') QRefSlaveManager = require('../../../../db/QRefSlaveManager') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author Nathan Klick @copyright QRef 2012 ### class SynchronizeSlaveDbRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/syncSlaveDb' }, { method: 'GET', path: '/syncSlaveDb' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.param('token') UserAuth.isInRole(token, 'Administrators', (err, hasRole) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not hasRole resp = new RpcResponse(null) resp.failure('Not Authorized', 403) res.json(resp, 200) return @.synchronizeModels((err) => if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return @.synchronize((err) => if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ) ### async.forEach(QRefSlaveManager.getSlaves(), (item, cb) => @.upgradeProductVersions(item, cb) ,(err) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ### ) synchronizeModels: (callback) => masterDb = QRefSlaveManager.getSlave('master') slaveDb = QRefSlaveManager.getSlave('slave') async.series( [ (sCb) => masterDb.AircraftManufacturer .find((err, arrMasterMfg) => if err? sCb(err) return async.forEach(arrMasterMfg, (mMfg, aCb) => slaveDb.AircraftManufacturer .where('name') .equals(mMfg.name) .count((err, cntExisting) => if err? aCb(err) return if cntExisting > 0 aCb(null) return sMfg = new slaveDb.AircraftManufacturer() sMfg._id = mMfg._id sMfg.name = mMfg.name sMfg.description = mMfg.description sMfg.models = mMfg.models sMfg.save(aCb) ) ,(err) => if err? sCb(err) return sCb(null) ) ) ,(sCb) => masterDb.AircraftModel .find((err, arrMasterMdl) => if err? sCb(err) return async.forEach(arrMasterMdl, (mMdl, aCb) => slaveDb.AircraftModel .where('name') .equals(mMdl.name) .where('manufacturer') .equals(mMdl.manufacturer) .where('modelYear') .equals(mMdl.modelYear) .count((err, cntExisting) => if err? aCb(err) return if cntExisting > 0 aCb(null) return sMdl = new slaveDb.AircraftModel() sMdl._id = mMdl._id sMdl.name = mMdl.name sMdl.manufacturer = mMdl.manufacturer sMdl.modelYear = mMdl.modelYear sMdl.description = mMdl.description sMdl.save(aCb) ) ,(err) => if err? sCb(err) return sCb(null) ) ) ], (err) => if err? callback(err) return callback(null) ) synchronize: (callback) => masterDb = QRefSlaveManager.getSlave('master') slaveDb = QRefSlaveManager.getSlave('slave') masterDb.AircraftChecklist .where('user') .equals(null) .where('isDeleted') .equals(false) .find((err, arrMasterChecklists) => if err? callback(err) return arrTargetVersions = [] removalTargets = [] backupObjects = [] async.series( [ (sCb) => async.forEach(arrMasterChecklists, (mChkLst, cb) => slaveDb.AircraftChecklist .where('manufacturer') .equals(mChkLst.manufacturer) .where('model') .equals(mChkLst.model) .where('user') .equals(null) .sort('+version') .find((err, arrSlaveChecklists) => if err? cb(err) return @.backupChecklists(slaveDb, arrSlaveChecklists, (err, targets, backups) => if err? cb(err) return backupObjects = backupObjects.concat(backups) removalTargets = removalTargets.concat(targets) cb(null) ) ) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(backupObjects, (bo, cb) => bo.save(cb) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(removalTargets, (rt, cb) => slaveDb.AircraftChecklist.remove({ _id: rt }, cb) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(arrMasterChecklists, (mChkLst, cb) => mChkLst = mChkLst.toObject() sNewChkLst = new slaveDb.AircraftChecklist() sNewChkLst.manufacturer = mChkLst.manufacturer sNewChkLst.model = mChkLst.model sNewChkLst.preflight = mChkLst.preflight sNewChkLst.takeoff = mChkLst.takeoff sNewChkLst.landing = mChkLst.landing sNewChkLst.emergencies = mChkLst.emergencies sNewChkLst.tailNumber = mChkLst.tailNumber sNewChkLst.index = mChkLst.index sNewChkLst.user = mChkLst.user sNewChkLst.version = mChkLst.version sNewChkLst.productIcon = mChkLst.productIcon sNewChkLst.currentSerialNumber = mChkLst.currentSerialNumber sNewChkLst.knownSerialNumbers = mChkLst.knownSerialNumbers sNewChkLst.lastCheckpointSerialNumber = mChkLst.lastCheckpointSerialNumber sNewChkLst.save((err)=> if err? cb(err) return cb(null) ) ,(err) => if err? sCb(err) return sCb(null) ) ], (err) => if err? callback(err) return @.upgradeProductVersions(slaveDb, callback) ) ) upgradeProductVersions: (db, callback) => db.Product.find((err, arrProducts) => if err? callback(err) return if not arrProducts? or arrProducts.length == 0 callback(null) return async.forEach(arrProducts, (product, cb) => db.AircraftChecklist .where('manufacturer') .equals(product.manufacturer) .where('model') .equals(product.model) .where('user') .equals(null) .where('isDeleted') .equals(false) .sort('-version') .findOne((err, latestChecklist) => if err? cb(err) return if not latestChecklist? cb(new Error('No checklist found for the product.')) return if product.aircraftChecklist.toString() != latestChecklist._id.toString() product.aircraftChecklist = latestChecklist._id product.save(cb) ) ,(err) => callback(err) ) ) backupChecklists: (db, arrSlaveChecklists, callback) => removalTargets = [] backupObjects = [] async.forEach(arrSlaveChecklists, (sChkLst, cb) => osChkLst = sChkLst.toObject() bNewChkLst = new db.AircraftBackupChecklist() bNewChkLst.manufacturer = osChkLst.manufacturer bNewChkLst.model = osChkLst.model bNewChkLst.preflight = osChkLst.preflight bNewChkLst.takeoff = osChkLst.takeoff bNewChkLst.landing = osChkLst.landing bNewChkLst.emergencies = osChkLst.emergencies bNewChkLst.tailNumber = osChkLst.tailNumber bNewChkLst.index = osChkLst.index bNewChkLst.user = osChkLst.user bNewChkLst.version = osChkLst.version bNewChkLst.productIcon = osChkLst.productIcon bNewChkLst.tailNumber = osChkLst.tailNumber bNewChkLst.isDeleted = osChkLst.isDeleted bNewChkLst.timestamp = osChkLst.timestamp bNewChkLst.currentSerialNumber = osChkLst.currentSerialNumber bNewChkLst.knownSerialNumbers = osChkLst.knownSerialNumbers bNewChkLst.lastCheckpointSerialNumber = osChkLst.lastCheckpointSerialNumber backupObjects.push(bNewChkLst) removalTargets.push(sChkLst._id) cb(null) ,(err) => if err? callback(err, null, null) return callback(null, removalTargets, backupObjects) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new SynchronizeSlaveDbRoute()
70363
RpcRoute = require('../../../RpcRoute') QRefSlaveManager = require('../../../../db/QRefSlaveManager') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author <NAME> @copyright QRef 2012 ### class SynchronizeSlaveDbRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/syncSlaveDb' }, { method: 'GET', path: '/syncSlaveDb' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.param('token') UserAuth.isInRole(token, 'Administrators', (err, hasRole) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not hasRole resp = new RpcResponse(null) resp.failure('Not Authorized', 403) res.json(resp, 200) return @.synchronizeModels((err) => if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return @.synchronize((err) => if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ) ### async.forEach(QRefSlaveManager.getSlaves(), (item, cb) => @.upgradeProductVersions(item, cb) ,(err) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ### ) synchronizeModels: (callback) => masterDb = QRefSlaveManager.getSlave('master') slaveDb = QRefSlaveManager.getSlave('slave') async.series( [ (sCb) => masterDb.AircraftManufacturer .find((err, arrMasterMfg) => if err? sCb(err) return async.forEach(arrMasterMfg, (mMfg, aCb) => slaveDb.AircraftManufacturer .where('name') .equals(mMfg.name) .count((err, cntExisting) => if err? aCb(err) return if cntExisting > 0 aCb(null) return sMfg = new slaveDb.AircraftManufacturer() sMfg._id = mMfg._id sMfg.name = mMfg.name sMfg.description = mMfg.description sMfg.models = mMfg.models sMfg.save(aCb) ) ,(err) => if err? sCb(err) return sCb(null) ) ) ,(sCb) => masterDb.AircraftModel .find((err, arrMasterMdl) => if err? sCb(err) return async.forEach(arrMasterMdl, (mMdl, aCb) => slaveDb.AircraftModel .where('name') .equals(mMdl.name) .where('manufacturer') .equals(mMdl.manufacturer) .where('modelYear') .equals(mMdl.modelYear) .count((err, cntExisting) => if err? aCb(err) return if cntExisting > 0 aCb(null) return sMdl = new slaveDb.AircraftModel() sMdl._id = mMdl._id sMdl.name = mMdl.name sMdl.manufacturer = mMdl.manufacturer sMdl.modelYear = mMdl.modelYear sMdl.description = mMdl.description sMdl.save(aCb) ) ,(err) => if err? sCb(err) return sCb(null) ) ) ], (err) => if err? callback(err) return callback(null) ) synchronize: (callback) => masterDb = QRefSlaveManager.getSlave('master') slaveDb = QRefSlaveManager.getSlave('slave') masterDb.AircraftChecklist .where('user') .equals(null) .where('isDeleted') .equals(false) .find((err, arrMasterChecklists) => if err? callback(err) return arrTargetVersions = [] removalTargets = [] backupObjects = [] async.series( [ (sCb) => async.forEach(arrMasterChecklists, (mChkLst, cb) => slaveDb.AircraftChecklist .where('manufacturer') .equals(mChkLst.manufacturer) .where('model') .equals(mChkLst.model) .where('user') .equals(null) .sort('+version') .find((err, arrSlaveChecklists) => if err? cb(err) return @.backupChecklists(slaveDb, arrSlaveChecklists, (err, targets, backups) => if err? cb(err) return backupObjects = backupObjects.concat(backups) removalTargets = removalTargets.concat(targets) cb(null) ) ) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(backupObjects, (bo, cb) => bo.save(cb) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(removalTargets, (rt, cb) => slaveDb.AircraftChecklist.remove({ _id: rt }, cb) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(arrMasterChecklists, (mChkLst, cb) => mChkLst = mChkLst.toObject() sNewChkLst = new slaveDb.AircraftChecklist() sNewChkLst.manufacturer = mChkLst.manufacturer sNewChkLst.model = mChkLst.model sNewChkLst.preflight = mChkLst.preflight sNewChkLst.takeoff = mChkLst.takeoff sNewChkLst.landing = mChkLst.landing sNewChkLst.emergencies = mChkLst.emergencies sNewChkLst.tailNumber = mChkLst.tailNumber sNewChkLst.index = mChkLst.index sNewChkLst.user = mChkLst.user sNewChkLst.version = mChkLst.version sNewChkLst.productIcon = mChkLst.productIcon sNewChkLst.currentSerialNumber = mChkLst.currentSerialNumber sNewChkLst.knownSerialNumbers = mChkLst.knownSerialNumbers sNewChkLst.lastCheckpointSerialNumber = mChkLst.lastCheckpointSerialNumber sNewChkLst.save((err)=> if err? cb(err) return cb(null) ) ,(err) => if err? sCb(err) return sCb(null) ) ], (err) => if err? callback(err) return @.upgradeProductVersions(slaveDb, callback) ) ) upgradeProductVersions: (db, callback) => db.Product.find((err, arrProducts) => if err? callback(err) return if not arrProducts? or arrProducts.length == 0 callback(null) return async.forEach(arrProducts, (product, cb) => db.AircraftChecklist .where('manufacturer') .equals(product.manufacturer) .where('model') .equals(product.model) .where('user') .equals(null) .where('isDeleted') .equals(false) .sort('-version') .findOne((err, latestChecklist) => if err? cb(err) return if not latestChecklist? cb(new Error('No checklist found for the product.')) return if product.aircraftChecklist.toString() != latestChecklist._id.toString() product.aircraftChecklist = latestChecklist._id product.save(cb) ) ,(err) => callback(err) ) ) backupChecklists: (db, arrSlaveChecklists, callback) => removalTargets = [] backupObjects = [] async.forEach(arrSlaveChecklists, (sChkLst, cb) => osChkLst = sChkLst.toObject() bNewChkLst = new db.AircraftBackupChecklist() bNewChkLst.manufacturer = osChkLst.manufacturer bNewChkLst.model = osChkLst.model bNewChkLst.preflight = osChkLst.preflight bNewChkLst.takeoff = osChkLst.takeoff bNewChkLst.landing = osChkLst.landing bNewChkLst.emergencies = osChkLst.emergencies bNewChkLst.tailNumber = osChkLst.tailNumber bNewChkLst.index = osChkLst.index bNewChkLst.user = osChkLst.user bNewChkLst.version = osChkLst.version bNewChkLst.productIcon = osChkLst.productIcon bNewChkLst.tailNumber = osChkLst.tailNumber bNewChkLst.isDeleted = osChkLst.isDeleted bNewChkLst.timestamp = osChkLst.timestamp bNewChkLst.currentSerialNumber = osChkLst.currentSerialNumber bNewChkLst.knownSerialNumbers = osChkLst.knownSerialNumbers bNewChkLst.lastCheckpointSerialNumber = osChkLst.lastCheckpointSerialNumber backupObjects.push(bNewChkLst) removalTargets.push(sChkLst._id) cb(null) ,(err) => if err? callback(err, null, null) return callback(null, removalTargets, backupObjects) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new SynchronizeSlaveDbRoute()
true
RpcRoute = require('../../../RpcRoute') QRefSlaveManager = require('../../../../db/QRefSlaveManager') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class SynchronizeSlaveDbRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/syncSlaveDb' }, { method: 'GET', path: '/syncSlaveDb' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return token = req.param('token') UserAuth.isInRole(token, 'Administrators', (err, hasRole) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not hasRole resp = new RpcResponse(null) resp.failure('Not Authorized', 403) res.json(resp, 200) return @.synchronizeModels((err) => if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return @.synchronize((err) => if err? resp = new RpcResponse(null) resp.failure(err, 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ) ### async.forEach(QRefSlaveManager.getSlaves(), (item, cb) => @.upgradeProductVersions(item, cb) ,(err) => if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return resp = new RpcResponse(null) res.json(resp, 200) return ) ### ) synchronizeModels: (callback) => masterDb = QRefSlaveManager.getSlave('master') slaveDb = QRefSlaveManager.getSlave('slave') async.series( [ (sCb) => masterDb.AircraftManufacturer .find((err, arrMasterMfg) => if err? sCb(err) return async.forEach(arrMasterMfg, (mMfg, aCb) => slaveDb.AircraftManufacturer .where('name') .equals(mMfg.name) .count((err, cntExisting) => if err? aCb(err) return if cntExisting > 0 aCb(null) return sMfg = new slaveDb.AircraftManufacturer() sMfg._id = mMfg._id sMfg.name = mMfg.name sMfg.description = mMfg.description sMfg.models = mMfg.models sMfg.save(aCb) ) ,(err) => if err? sCb(err) return sCb(null) ) ) ,(sCb) => masterDb.AircraftModel .find((err, arrMasterMdl) => if err? sCb(err) return async.forEach(arrMasterMdl, (mMdl, aCb) => slaveDb.AircraftModel .where('name') .equals(mMdl.name) .where('manufacturer') .equals(mMdl.manufacturer) .where('modelYear') .equals(mMdl.modelYear) .count((err, cntExisting) => if err? aCb(err) return if cntExisting > 0 aCb(null) return sMdl = new slaveDb.AircraftModel() sMdl._id = mMdl._id sMdl.name = mMdl.name sMdl.manufacturer = mMdl.manufacturer sMdl.modelYear = mMdl.modelYear sMdl.description = mMdl.description sMdl.save(aCb) ) ,(err) => if err? sCb(err) return sCb(null) ) ) ], (err) => if err? callback(err) return callback(null) ) synchronize: (callback) => masterDb = QRefSlaveManager.getSlave('master') slaveDb = QRefSlaveManager.getSlave('slave') masterDb.AircraftChecklist .where('user') .equals(null) .where('isDeleted') .equals(false) .find((err, arrMasterChecklists) => if err? callback(err) return arrTargetVersions = [] removalTargets = [] backupObjects = [] async.series( [ (sCb) => async.forEach(arrMasterChecklists, (mChkLst, cb) => slaveDb.AircraftChecklist .where('manufacturer') .equals(mChkLst.manufacturer) .where('model') .equals(mChkLst.model) .where('user') .equals(null) .sort('+version') .find((err, arrSlaveChecklists) => if err? cb(err) return @.backupChecklists(slaveDb, arrSlaveChecklists, (err, targets, backups) => if err? cb(err) return backupObjects = backupObjects.concat(backups) removalTargets = removalTargets.concat(targets) cb(null) ) ) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(backupObjects, (bo, cb) => bo.save(cb) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(removalTargets, (rt, cb) => slaveDb.AircraftChecklist.remove({ _id: rt }, cb) ,(err) => if err? sCb(err) return sCb(null) ) ,(sCb) => async.forEach(arrMasterChecklists, (mChkLst, cb) => mChkLst = mChkLst.toObject() sNewChkLst = new slaveDb.AircraftChecklist() sNewChkLst.manufacturer = mChkLst.manufacturer sNewChkLst.model = mChkLst.model sNewChkLst.preflight = mChkLst.preflight sNewChkLst.takeoff = mChkLst.takeoff sNewChkLst.landing = mChkLst.landing sNewChkLst.emergencies = mChkLst.emergencies sNewChkLst.tailNumber = mChkLst.tailNumber sNewChkLst.index = mChkLst.index sNewChkLst.user = mChkLst.user sNewChkLst.version = mChkLst.version sNewChkLst.productIcon = mChkLst.productIcon sNewChkLst.currentSerialNumber = mChkLst.currentSerialNumber sNewChkLst.knownSerialNumbers = mChkLst.knownSerialNumbers sNewChkLst.lastCheckpointSerialNumber = mChkLst.lastCheckpointSerialNumber sNewChkLst.save((err)=> if err? cb(err) return cb(null) ) ,(err) => if err? sCb(err) return sCb(null) ) ], (err) => if err? callback(err) return @.upgradeProductVersions(slaveDb, callback) ) ) upgradeProductVersions: (db, callback) => db.Product.find((err, arrProducts) => if err? callback(err) return if not arrProducts? or arrProducts.length == 0 callback(null) return async.forEach(arrProducts, (product, cb) => db.AircraftChecklist .where('manufacturer') .equals(product.manufacturer) .where('model') .equals(product.model) .where('user') .equals(null) .where('isDeleted') .equals(false) .sort('-version') .findOne((err, latestChecklist) => if err? cb(err) return if not latestChecklist? cb(new Error('No checklist found for the product.')) return if product.aircraftChecklist.toString() != latestChecklist._id.toString() product.aircraftChecklist = latestChecklist._id product.save(cb) ) ,(err) => callback(err) ) ) backupChecklists: (db, arrSlaveChecklists, callback) => removalTargets = [] backupObjects = [] async.forEach(arrSlaveChecklists, (sChkLst, cb) => osChkLst = sChkLst.toObject() bNewChkLst = new db.AircraftBackupChecklist() bNewChkLst.manufacturer = osChkLst.manufacturer bNewChkLst.model = osChkLst.model bNewChkLst.preflight = osChkLst.preflight bNewChkLst.takeoff = osChkLst.takeoff bNewChkLst.landing = osChkLst.landing bNewChkLst.emergencies = osChkLst.emergencies bNewChkLst.tailNumber = osChkLst.tailNumber bNewChkLst.index = osChkLst.index bNewChkLst.user = osChkLst.user bNewChkLst.version = osChkLst.version bNewChkLst.productIcon = osChkLst.productIcon bNewChkLst.tailNumber = osChkLst.tailNumber bNewChkLst.isDeleted = osChkLst.isDeleted bNewChkLst.timestamp = osChkLst.timestamp bNewChkLst.currentSerialNumber = osChkLst.currentSerialNumber bNewChkLst.knownSerialNumbers = osChkLst.knownSerialNumbers bNewChkLst.lastCheckpointSerialNumber = osChkLst.lastCheckpointSerialNumber backupObjects.push(bNewChkLst) removalTargets.push(sChkLst._id) cb(null) ,(err) => if err? callback(err, null, null) return callback(null, removalTargets, backupObjects) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.token? true else false module.exports = new SynchronizeSlaveDbRoute()
[ { "context": "ldweatheronline.com/free/v2/weather.ashx\"\n key: \"55f1fdd05fba23be0a18043d0a017\"", "end": 118, "score": 0.9997535347938538, "start": 89, "tag": "KEY", "value": "55f1fdd05fba23be0a18043d0a017" } ]
config.coffee
destec/Node-Weather-CLI
0
module.exports = url: "http://api.worldweatheronline.com/free/v2/weather.ashx" key: "55f1fdd05fba23be0a18043d0a017"
106044
module.exports = url: "http://api.worldweatheronline.com/free/v2/weather.ashx" key: "<KEY>"
true
module.exports = url: "http://api.worldweatheronline.com/free/v2/weather.ashx" key: "PI:KEY:<KEY>END_PI"
[ { "context": "\n GooglePlusProvider.init\n clientId: '1069600990715-qr2quvqt0nl1nr8vkdtljtu0jnb22igv.apps.googleusercontent.com'\n apiKey: 'AIzaSyCmqKjIhh5ySTPDprOkfKHkKdP", "end": 700, "score": 0.9983994960784912, "start": 627, "tag": "KEY", "value": "1069600990715-qr2quv...
src/coffee/app.coffee
KinveyApps/Gulper-AngularJS
2
angular.module 'app', [ 'app.control', 'app.state', 'app.templates', 'app.service', 'ui.router', 'facebook', 'kinvey', 'ngStorage', 'angularMoment' 'pubnub.angular.service', 'googleplus' 'ui.bootstrap' ] .config ['$urlRouterProvider', '$facebookProvider', '$kinveyProvider', '$httpProvider', 'GooglePlusProvider', '$peerProvider', ($urlRouterProvider, $facebookProvider, $kinveyProvider, $httpProvider, GooglePlusProvider, $peerProvider) -> $urlRouterProvider.otherwise '/login' $facebookProvider.init appId: '229011427294758' GooglePlusProvider.init clientId: '1069600990715-qr2quvqt0nl1nr8vkdtljtu0jnb22igv.apps.googleusercontent.com' apiKey: 'AIzaSyCmqKjIhh5ySTPDprOkfKHkKdPq6_FFR1Y' $kinveyProvider.init appKey: 'kid_eeM4Dtly69' appSecret: 'f7b5cd34caa047c286e6a3ba09204117' storage: 'local' $httpProvider.interceptors.push 'v3yk1n-interceptor' $peerProvider.init '3x0jom3i17fd2t9' ] .run ['$kinvey', ($kinvey) -> $kinvey.alias 'room', 'Room' $kinvey.alias 'message', 'Message' ]
185692
angular.module 'app', [ 'app.control', 'app.state', 'app.templates', 'app.service', 'ui.router', 'facebook', 'kinvey', 'ngStorage', 'angularMoment' 'pubnub.angular.service', 'googleplus' 'ui.bootstrap' ] .config ['$urlRouterProvider', '$facebookProvider', '$kinveyProvider', '$httpProvider', 'GooglePlusProvider', '$peerProvider', ($urlRouterProvider, $facebookProvider, $kinveyProvider, $httpProvider, GooglePlusProvider, $peerProvider) -> $urlRouterProvider.otherwise '/login' $facebookProvider.init appId: '229011427294758' GooglePlusProvider.init clientId: '<KEY>' apiKey: '<KEY>' $kinveyProvider.init appKey: '<KEY>' appSecret: '<KEY>' storage: 'local' $httpProvider.interceptors.push 'v3yk1n-interceptor' $peerProvider.init '3x0jom3i17fd2t9' ] .run ['$kinvey', ($kinvey) -> $kinvey.alias 'room', 'Room' $kinvey.alias 'message', 'Message' ]
true
angular.module 'app', [ 'app.control', 'app.state', 'app.templates', 'app.service', 'ui.router', 'facebook', 'kinvey', 'ngStorage', 'angularMoment' 'pubnub.angular.service', 'googleplus' 'ui.bootstrap' ] .config ['$urlRouterProvider', '$facebookProvider', '$kinveyProvider', '$httpProvider', 'GooglePlusProvider', '$peerProvider', ($urlRouterProvider, $facebookProvider, $kinveyProvider, $httpProvider, GooglePlusProvider, $peerProvider) -> $urlRouterProvider.otherwise '/login' $facebookProvider.init appId: '229011427294758' GooglePlusProvider.init clientId: 'PI:KEY:<KEY>END_PI' apiKey: 'PI:KEY:<KEY>END_PI' $kinveyProvider.init appKey: 'PI:KEY:<KEY>END_PI' appSecret: 'PI:KEY:<KEY>END_PI' storage: 'local' $httpProvider.interceptors.push 'v3yk1n-interceptor' $peerProvider.init '3x0jom3i17fd2t9' ] .run ['$kinvey', ($kinvey) -> $kinvey.alias 'room', 'Room' $kinvey.alias 'message', 'Message' ]
[ { "context": "ppi.util\n# @description utility services\n# @author Michael Lin, Snaphappi Inc.\n###\n\n\nangular.module 'snappi.util", "end": 109, "score": 0.9993659257888794, "start": 98, "tag": "NAME", "value": "Michael Lin" }, { "context": "timeSpan\n\n\n]\n\n\n# borrowed from htt...
app/js/services/util.coffee
mixersoft/ionic-parse-facebook-scaffold
5
'use strict' ###* # @ngdoc service # @name snappi.util # @description utility services # @author Michael Lin, Snaphappi Inc. ### angular.module 'snappi.util', [ 'ionic', 'ngCordova', # 'ngStorage' ] .factory 'deviceReady', [ '$q', '$timeout', '$ionicPlatform' ($q, $timeout, $ionicPlatform)-> _promise = null _timeout = 2000 _contentWidth = null _device = { } self = { device: ($platform)-> if typeof $platform != 'undefined' # restore from localStorage _device = angular.copy $platform return _device contentWidth: (force)-> return _contentWidth if _contentWidth && !force return _contentWidth = document.getElementsByTagName('ion-side-menu-content')[0]?.clientWidth waitP: ()-> return _promise if _promise dfd = $q.defer() _cancel = $timeout ()-> _promise = null return dfd.reject("ERROR: ionicPlatform.ready does not respond") , _timeout $ionicPlatform.ready ()-> $timeout.cancel _cancel device = ionic.Platform.device() if _.isEmpty(device) && ionic.Platform.isWebView() # WARNING: make sure you run `ionic plugin add org.apache.cordova.device` device = { cordova: true uuid: 'emulator' id: 'emulator' } platform = _.defaults device, { available: false cordova: false uuid: 'browser' isDevice: ionic.Platform.isWebView() isBrowser: ionic.Platform.isWebView() == false } platform['id'] = platform['uuid'] platform = self.device(platform) return dfd.resolve( platform ) return _promise = dfd.promise } return self ] .service 'snappiTemplate', [ '$q', '$http', '$templateCache' ($q, $http, $templateCache)-> self = this # templateUrl same as directive, do NOT use SCRIPT tags this.load = (templateUrl)-> $http.get(templateUrl, { cache: $templateCache}) .then (result)-> console.log 'HTML Template loaded, src=', templateUrl return ] .filter 'timeago', [ ()-> return (time, local, raw)-> return '' if !time time = new Date(time) if _.isString time time = time.getTime() if _.isDate time local = Date.now() if `local==null` local = local.getTime() if _.isDate local return '' if !_.isNumber(time) || !_.isNumber(local) offset = Math.abs((local - time) / 1000) span = [] MINUTE = 60 HOUR = 3600 DAY = 86400 WEEK = 604800 MONTH = 2629744 YEAR = 31556926 DECADE = 315569260 if Math.floor( offset/DAY ) > 2 timeSpan = { ' days': Math.floor( offset/DAY ) } else timeSpan = { # 'days ': Math.floor( offset/DAY ) 'h': Math.floor( (offset % DAY)/HOUR ) + Math.floor( offset/DAY )*24 'm': Math.floor( (offset % HOUR)/MINUTE ) # 's': timeSpan.push Math.floor( (offset % MINUTE) ) } timeSpan = _.reduce timeSpan, (result, v,k)-> result += v+k if v return result , "" return if time <= local then timeSpan + ' ago' else 'in ' + timeSpan ] # borrowed from https://github.com/urish/angular-load/blob/master/angular-load.js .service 'angularLoad', [ '$document', '$q', '$timeout' ($document, $q, $timeout)-> promises = {} this.loadScriptP = (src)-> if !promises[src] dfd = $q.defer() script = $document[0].createElement('script'); script.src = src element = script # event handlers onreadystatechange deprecatd for SCRIPT tags element.addEventListener 'load', (e)-> return $timeout ()-> dfd.resolve(e) element.addEventListener 'error', (e)-> return $timeout ()-> dfd.reject(e) promises[src] = dfd.promise $document[0].body.appendChild(element); # console.log "loadScriptP=", promises return promises[src] return ] # notify DOM element to show a notification message in app with # timeout and close # TODO: make a controller for directive:notify .service 'notifyService', [ '$timeout', '$rootScope' ($timeout, $rootScope, $compile)-> CFG = { debug: true timeout: 5000 messageTimeout: 5000 } ### template: <div id="notify" class="notify overlay"> <alert ng-repeat="alert in notify.alert()" type="alert.type" close="notify.close(alert.key)" ><div ng-bind-html="alert.msg"></div></alert> </div> <div id="message" class="notify inline"> <alert ng-repeat="alert in notify.message()" type="alert.type" close="notify.close(alert.key)" > <div ng-if="!alert.template" ng-bind-html="alert.msg"></div> <ng-include ng-if="alert.template" src="alert.template || null"></ng-include> </alert> </div> ### this._cfg = CFG this.alerts = {} this.messages = {} this.timeouts = [] this.alert = (msg=null, type='info', timeout)-> return this.alerts if !CFG.debug || CFG.debug=='off' if msg? timeout = timeout || CFG.timeout now = new Date().getTime() `while (this.alerts[now]) { now += 0.1; }` this.alerts[now] = {msg: msg, type:type, key:now} if msg? this.timeouts.push({key: now, value: timeout}) else # start timeouts on ng-repeat this.timerStart() return this.alerts # same as alert, but always show, ignore CFG.debug this.message = (msg=null, type='info', timeout)-> if msg? timeout = timeout || CFG.messageTimeout now = new Date().getTime() `while (this.alerts[now]) { now += 0.1; }` notification = {type:type, key:now} if _.isObject(msg) if msg.template? notification['template'] = msg.template else if msg.title? notification['msg'] = "<h4>"+msg.title+"</h4><p>"+msg.message+"</p>" else notification['msg'] = msg.message else notification['msg'] = msg this.messages[now] = notification this.timeouts.push({key: now, value: timeout}) $rootScope.$apply() if !$rootScope.$$phase else # start timeouts on ng-repeat this.timerStart() return this.messages this.clearMessages = ()-> this.messages = {} this.close = (key)-> delete this.alerts[key] if this.alerts[key] delete this.messages[key] if this.messages[key] this.timerStart = ()-> _.each this.timeouts, (o)=> $timeout (()=> delete this.alerts[o.key] if this.alerts[o.key] delete this.messages[o.key] if this.messages[o.key] ), o.value this.timeouts = [] return ]
132318
'use strict' ###* # @ngdoc service # @name snappi.util # @description utility services # @author <NAME>, Snaphappi Inc. ### angular.module 'snappi.util', [ 'ionic', 'ngCordova', # 'ngStorage' ] .factory 'deviceReady', [ '$q', '$timeout', '$ionicPlatform' ($q, $timeout, $ionicPlatform)-> _promise = null _timeout = 2000 _contentWidth = null _device = { } self = { device: ($platform)-> if typeof $platform != 'undefined' # restore from localStorage _device = angular.copy $platform return _device contentWidth: (force)-> return _contentWidth if _contentWidth && !force return _contentWidth = document.getElementsByTagName('ion-side-menu-content')[0]?.clientWidth waitP: ()-> return _promise if _promise dfd = $q.defer() _cancel = $timeout ()-> _promise = null return dfd.reject("ERROR: ionicPlatform.ready does not respond") , _timeout $ionicPlatform.ready ()-> $timeout.cancel _cancel device = ionic.Platform.device() if _.isEmpty(device) && ionic.Platform.isWebView() # WARNING: make sure you run `ionic plugin add org.apache.cordova.device` device = { cordova: true uuid: 'emulator' id: 'emulator' } platform = _.defaults device, { available: false cordova: false uuid: 'browser' isDevice: ionic.Platform.isWebView() isBrowser: ionic.Platform.isWebView() == false } platform['id'] = platform['uuid'] platform = self.device(platform) return dfd.resolve( platform ) return _promise = dfd.promise } return self ] .service 'snappiTemplate', [ '$q', '$http', '$templateCache' ($q, $http, $templateCache)-> self = this # templateUrl same as directive, do NOT use SCRIPT tags this.load = (templateUrl)-> $http.get(templateUrl, { cache: $templateCache}) .then (result)-> console.log 'HTML Template loaded, src=', templateUrl return ] .filter 'timeago', [ ()-> return (time, local, raw)-> return '' if !time time = new Date(time) if _.isString time time = time.getTime() if _.isDate time local = Date.now() if `local==null` local = local.getTime() if _.isDate local return '' if !_.isNumber(time) || !_.isNumber(local) offset = Math.abs((local - time) / 1000) span = [] MINUTE = 60 HOUR = 3600 DAY = 86400 WEEK = 604800 MONTH = 2629744 YEAR = 31556926 DECADE = 315569260 if Math.floor( offset/DAY ) > 2 timeSpan = { ' days': Math.floor( offset/DAY ) } else timeSpan = { # 'days ': Math.floor( offset/DAY ) 'h': Math.floor( (offset % DAY)/HOUR ) + Math.floor( offset/DAY )*24 'm': Math.floor( (offset % HOUR)/MINUTE ) # 's': timeSpan.push Math.floor( (offset % MINUTE) ) } timeSpan = _.reduce timeSpan, (result, v,k)-> result += v+k if v return result , "" return if time <= local then timeSpan + ' ago' else 'in ' + timeSpan ] # borrowed from https://github.com/urish/angular-load/blob/master/angular-load.js .service 'angularLoad', [ '$document', '$q', '$timeout' ($document, $q, $timeout)-> promises = {} this.loadScriptP = (src)-> if !promises[src] dfd = $q.defer() script = $document[0].createElement('script'); script.src = src element = script # event handlers onreadystatechange deprecatd for SCRIPT tags element.addEventListener 'load', (e)-> return $timeout ()-> dfd.resolve(e) element.addEventListener 'error', (e)-> return $timeout ()-> dfd.reject(e) promises[src] = dfd.promise $document[0].body.appendChild(element); # console.log "loadScriptP=", promises return promises[src] return ] # notify DOM element to show a notification message in app with # timeout and close # TODO: make a controller for directive:notify .service 'notifyService', [ '$timeout', '$rootScope' ($timeout, $rootScope, $compile)-> CFG = { debug: true timeout: 5000 messageTimeout: 5000 } ### template: <div id="notify" class="notify overlay"> <alert ng-repeat="alert in notify.alert()" type="alert.type" close="notify.close(alert.key)" ><div ng-bind-html="alert.msg"></div></alert> </div> <div id="message" class="notify inline"> <alert ng-repeat="alert in notify.message()" type="alert.type" close="notify.close(alert.key)" > <div ng-if="!alert.template" ng-bind-html="alert.msg"></div> <ng-include ng-if="alert.template" src="alert.template || null"></ng-include> </alert> </div> ### this._cfg = CFG this.alerts = {} this.messages = {} this.timeouts = [] this.alert = (msg=null, type='info', timeout)-> return this.alerts if !CFG.debug || CFG.debug=='off' if msg? timeout = timeout || CFG.timeout now = new Date().getTime() `while (this.alerts[now]) { now += 0.1; }` this.alerts[now] = {msg: msg, type:type, key:now} if msg? this.timeouts.push({key: now, value: timeout}) else # start timeouts on ng-repeat this.timerStart() return this.alerts # same as alert, but always show, ignore CFG.debug this.message = (msg=null, type='info', timeout)-> if msg? timeout = timeout || CFG.messageTimeout now = new Date().getTime() `while (this.alerts[now]) { now += 0.1; }` notification = {type:type, key:now} if _.isObject(msg) if msg.template? notification['template'] = msg.template else if msg.title? notification['msg'] = "<h4>"+msg.title+"</h4><p>"+msg.message+"</p>" else notification['msg'] = msg.message else notification['msg'] = msg this.messages[now] = notification this.timeouts.push({key: now, value: timeout}) $rootScope.$apply() if !$rootScope.$$phase else # start timeouts on ng-repeat this.timerStart() return this.messages this.clearMessages = ()-> this.messages = {} this.close = (key)-> delete this.alerts[key] if this.alerts[key] delete this.messages[key] if this.messages[key] this.timerStart = ()-> _.each this.timeouts, (o)=> $timeout (()=> delete this.alerts[o.key] if this.alerts[o.key] delete this.messages[o.key] if this.messages[o.key] ), o.value this.timeouts = [] return ]
true
'use strict' ###* # @ngdoc service # @name snappi.util # @description utility services # @author PI:NAME:<NAME>END_PI, Snaphappi Inc. ### angular.module 'snappi.util', [ 'ionic', 'ngCordova', # 'ngStorage' ] .factory 'deviceReady', [ '$q', '$timeout', '$ionicPlatform' ($q, $timeout, $ionicPlatform)-> _promise = null _timeout = 2000 _contentWidth = null _device = { } self = { device: ($platform)-> if typeof $platform != 'undefined' # restore from localStorage _device = angular.copy $platform return _device contentWidth: (force)-> return _contentWidth if _contentWidth && !force return _contentWidth = document.getElementsByTagName('ion-side-menu-content')[0]?.clientWidth waitP: ()-> return _promise if _promise dfd = $q.defer() _cancel = $timeout ()-> _promise = null return dfd.reject("ERROR: ionicPlatform.ready does not respond") , _timeout $ionicPlatform.ready ()-> $timeout.cancel _cancel device = ionic.Platform.device() if _.isEmpty(device) && ionic.Platform.isWebView() # WARNING: make sure you run `ionic plugin add org.apache.cordova.device` device = { cordova: true uuid: 'emulator' id: 'emulator' } platform = _.defaults device, { available: false cordova: false uuid: 'browser' isDevice: ionic.Platform.isWebView() isBrowser: ionic.Platform.isWebView() == false } platform['id'] = platform['uuid'] platform = self.device(platform) return dfd.resolve( platform ) return _promise = dfd.promise } return self ] .service 'snappiTemplate', [ '$q', '$http', '$templateCache' ($q, $http, $templateCache)-> self = this # templateUrl same as directive, do NOT use SCRIPT tags this.load = (templateUrl)-> $http.get(templateUrl, { cache: $templateCache}) .then (result)-> console.log 'HTML Template loaded, src=', templateUrl return ] .filter 'timeago', [ ()-> return (time, local, raw)-> return '' if !time time = new Date(time) if _.isString time time = time.getTime() if _.isDate time local = Date.now() if `local==null` local = local.getTime() if _.isDate local return '' if !_.isNumber(time) || !_.isNumber(local) offset = Math.abs((local - time) / 1000) span = [] MINUTE = 60 HOUR = 3600 DAY = 86400 WEEK = 604800 MONTH = 2629744 YEAR = 31556926 DECADE = 315569260 if Math.floor( offset/DAY ) > 2 timeSpan = { ' days': Math.floor( offset/DAY ) } else timeSpan = { # 'days ': Math.floor( offset/DAY ) 'h': Math.floor( (offset % DAY)/HOUR ) + Math.floor( offset/DAY )*24 'm': Math.floor( (offset % HOUR)/MINUTE ) # 's': timeSpan.push Math.floor( (offset % MINUTE) ) } timeSpan = _.reduce timeSpan, (result, v,k)-> result += v+k if v return result , "" return if time <= local then timeSpan + ' ago' else 'in ' + timeSpan ] # borrowed from https://github.com/urish/angular-load/blob/master/angular-load.js .service 'angularLoad', [ '$document', '$q', '$timeout' ($document, $q, $timeout)-> promises = {} this.loadScriptP = (src)-> if !promises[src] dfd = $q.defer() script = $document[0].createElement('script'); script.src = src element = script # event handlers onreadystatechange deprecatd for SCRIPT tags element.addEventListener 'load', (e)-> return $timeout ()-> dfd.resolve(e) element.addEventListener 'error', (e)-> return $timeout ()-> dfd.reject(e) promises[src] = dfd.promise $document[0].body.appendChild(element); # console.log "loadScriptP=", promises return promises[src] return ] # notify DOM element to show a notification message in app with # timeout and close # TODO: make a controller for directive:notify .service 'notifyService', [ '$timeout', '$rootScope' ($timeout, $rootScope, $compile)-> CFG = { debug: true timeout: 5000 messageTimeout: 5000 } ### template: <div id="notify" class="notify overlay"> <alert ng-repeat="alert in notify.alert()" type="alert.type" close="notify.close(alert.key)" ><div ng-bind-html="alert.msg"></div></alert> </div> <div id="message" class="notify inline"> <alert ng-repeat="alert in notify.message()" type="alert.type" close="notify.close(alert.key)" > <div ng-if="!alert.template" ng-bind-html="alert.msg"></div> <ng-include ng-if="alert.template" src="alert.template || null"></ng-include> </alert> </div> ### this._cfg = CFG this.alerts = {} this.messages = {} this.timeouts = [] this.alert = (msg=null, type='info', timeout)-> return this.alerts if !CFG.debug || CFG.debug=='off' if msg? timeout = timeout || CFG.timeout now = new Date().getTime() `while (this.alerts[now]) { now += 0.1; }` this.alerts[now] = {msg: msg, type:type, key:now} if msg? this.timeouts.push({key: now, value: timeout}) else # start timeouts on ng-repeat this.timerStart() return this.alerts # same as alert, but always show, ignore CFG.debug this.message = (msg=null, type='info', timeout)-> if msg? timeout = timeout || CFG.messageTimeout now = new Date().getTime() `while (this.alerts[now]) { now += 0.1; }` notification = {type:type, key:now} if _.isObject(msg) if msg.template? notification['template'] = msg.template else if msg.title? notification['msg'] = "<h4>"+msg.title+"</h4><p>"+msg.message+"</p>" else notification['msg'] = msg.message else notification['msg'] = msg this.messages[now] = notification this.timeouts.push({key: now, value: timeout}) $rootScope.$apply() if !$rootScope.$$phase else # start timeouts on ng-repeat this.timerStart() return this.messages this.clearMessages = ()-> this.messages = {} this.close = (key)-> delete this.alerts[key] if this.alerts[key] delete this.messages[key] if this.messages[key] this.timerStart = ()-> _.each this.timeouts, (o)=> $timeout (()=> delete this.alerts[o.key] if this.alerts[o.key] delete this.messages[o.key] if this.messages[o.key] ), o.value this.timeouts = [] return ]
[ { "context": " title: \"Catty Art\"\n },\n {\n gene_id: \"percy\",\n medium: \"*\",\n title: \"Art by Percy\"\n", "end": 292, "score": 0.9321757555007935, "start": 287, "tag": "NAME", "value": "percy" }, { "context": "n the filter matches', ->\n query = { gen...
src/desktop/apps/collect/test/helpers.coffee
kanaabe/force
0
sinon = require 'sinon' Backbone = require 'backbone' pageTitle = require '../../../components/commercial_filter/page_title.coffee' describe 'Page title helper', -> filters = [ { gene_id: "*", medium: "catty-art", title: "Catty Art" }, { gene_id: "percy", medium: "*", title: "Art by Percy" } ] it 'returns a specified page title when the filter matches', -> query = { gene_id: "percy" } title = pageTitle(query, filters) title.should.equal 'Art By Percy for Sale' query = { medium: "catty-art" } title = pageTitle(query, filters) title.should.equal 'Catty Art for Sale' it 'returns a default page title when the filter doesnt match', -> query = { medium: "dog-art" } title = pageTitle(query, filters) title.should.equal 'Collect | Artsy'
193483
sinon = require 'sinon' Backbone = require 'backbone' pageTitle = require '../../../components/commercial_filter/page_title.coffee' describe 'Page title helper', -> filters = [ { gene_id: "*", medium: "catty-art", title: "Catty Art" }, { gene_id: "<NAME>", medium: "*", title: "Art by Percy" } ] it 'returns a specified page title when the filter matches', -> query = { gene_id: "<NAME>" } title = pageTitle(query, filters) title.should.equal 'Art By Percy for Sale' query = { medium: "catty-art" } title = pageTitle(query, filters) title.should.equal 'Catty Art for Sale' it 'returns a default page title when the filter doesnt match', -> query = { medium: "dog-art" } title = pageTitle(query, filters) title.should.equal 'Collect | Artsy'
true
sinon = require 'sinon' Backbone = require 'backbone' pageTitle = require '../../../components/commercial_filter/page_title.coffee' describe 'Page title helper', -> filters = [ { gene_id: "*", medium: "catty-art", title: "Catty Art" }, { gene_id: "PI:NAME:<NAME>END_PI", medium: "*", title: "Art by Percy" } ] it 'returns a specified page title when the filter matches', -> query = { gene_id: "PI:NAME:<NAME>END_PI" } title = pageTitle(query, filters) title.should.equal 'Art By Percy for Sale' query = { medium: "catty-art" } title = pageTitle(query, filters) title.should.equal 'Catty Art for Sale' it 'returns a default page title when the filter doesnt match', -> query = { medium: "dog-art" } title = pageTitle(query, filters) title.should.equal 'Collect | Artsy'
[ { "context": "x}.js\"])\n headerVars.externalScripts = ['https://134.147.198.48:7021/scripts/kmswrapper.js']\n res.render('secret", "end": 560, "score": 0.9996628761291504, "start": 546, "tag": "IP_ADDRESS", "value": "134.147.198.48" } ]
src/server/routes/index.coffee
RUB-NDS/SECRET
5
express = require('express') router = express.Router() DEBUG = false suffix = '' suffix = '.uncompressed' if DEBUG defaultHeaderVars = { scripts: ['bcsocket.js', "webclient/share#{suffix}.js"] title: 'SECRET - Secure Live Collaboration' } renderSECRET = (req, res) -> headerVars = Object.assign({}, defaultHeaderVars) # clone headerVars.scripts = headerVars.scripts.concat(["webclient/xml#{suffix}.js", "xmlEnc#{suffix}.js", "plainDoc#{suffix}.js", "encDoc#{suffix}.js", "secret#{suffix}.js"]) headerVars.externalScripts = ['https://134.147.198.48:7021/scripts/kmswrapper.js'] res.render('secret', { header: headerVars docId : 'encDoc' }) # GET home page router.get '/', renderSECRET router.get '/secret', renderSECRET router.get '/secret_plain', (req, res) -> headerVars = Object.assign({}, defaultHeaderVars) # clone headerVars.scripts = defaultHeaderVars.scripts.concat(["webclient/xml#{suffix}.js", "viewXML#{suffix}.js"]) res.render('secret_plain', { header: headerVars basePage: 'secret' docId : 'encDoc' docType : 'xml' }) module.exports = router;
76312
express = require('express') router = express.Router() DEBUG = false suffix = '' suffix = '.uncompressed' if DEBUG defaultHeaderVars = { scripts: ['bcsocket.js', "webclient/share#{suffix}.js"] title: 'SECRET - Secure Live Collaboration' } renderSECRET = (req, res) -> headerVars = Object.assign({}, defaultHeaderVars) # clone headerVars.scripts = headerVars.scripts.concat(["webclient/xml#{suffix}.js", "xmlEnc#{suffix}.js", "plainDoc#{suffix}.js", "encDoc#{suffix}.js", "secret#{suffix}.js"]) headerVars.externalScripts = ['https://172.16.17.32:7021/scripts/kmswrapper.js'] res.render('secret', { header: headerVars docId : 'encDoc' }) # GET home page router.get '/', renderSECRET router.get '/secret', renderSECRET router.get '/secret_plain', (req, res) -> headerVars = Object.assign({}, defaultHeaderVars) # clone headerVars.scripts = defaultHeaderVars.scripts.concat(["webclient/xml#{suffix}.js", "viewXML#{suffix}.js"]) res.render('secret_plain', { header: headerVars basePage: 'secret' docId : 'encDoc' docType : 'xml' }) module.exports = router;
true
express = require('express') router = express.Router() DEBUG = false suffix = '' suffix = '.uncompressed' if DEBUG defaultHeaderVars = { scripts: ['bcsocket.js', "webclient/share#{suffix}.js"] title: 'SECRET - Secure Live Collaboration' } renderSECRET = (req, res) -> headerVars = Object.assign({}, defaultHeaderVars) # clone headerVars.scripts = headerVars.scripts.concat(["webclient/xml#{suffix}.js", "xmlEnc#{suffix}.js", "plainDoc#{suffix}.js", "encDoc#{suffix}.js", "secret#{suffix}.js"]) headerVars.externalScripts = ['https://PI:IP_ADDRESS:172.16.17.32END_PI:7021/scripts/kmswrapper.js'] res.render('secret', { header: headerVars docId : 'encDoc' }) # GET home page router.get '/', renderSECRET router.get '/secret', renderSECRET router.get '/secret_plain', (req, res) -> headerVars = Object.assign({}, defaultHeaderVars) # clone headerVars.scripts = defaultHeaderVars.scripts.concat(["webclient/xml#{suffix}.js", "viewXML#{suffix}.js"]) res.render('secret_plain', { header: headerVars basePage: 'secret' docId : 'encDoc' docType : 'xml' }) module.exports = router;
[ { "context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nshallowEquals = require 's", "end": 35, "score": 0.9997667074203491, "start": 21, "tag": "NAME", "value": "Jesse Grosjean" } ]
atom/packages/foldingtext-for-atom/lib/editor/selection.coffee
prookie/dotfiles-1
0
# Copyright (c) 2015 Jesse Grosjean. All rights reserved. shallowEquals = require 'shallow-equals' Item = require '../core/item' assert = require 'assert' ItemRenderer = null # Public: The selection returned by {OutlineEditor::selection}. # # The anchor of a selection is the beginning point of the selection. When # making a selection with a mouse, the anchor is where in the document the # mouse button is initially pressed. As the user changes the selection using # the mouse or the keyboard, the anchor does not move. # # The focus of a selection is the end point of the selection. When making a # selection with a mouse, the focus is where in the document the mouse button # is released. As the user changes the selection using the mouse or the # keyboard, the focus is the end of the selection that moves. # # The start of a selection is the boundary closest to the beginning of the # document. The end of a selection is the boundary closest to the end of the # document. class Selection @ItemAffinityAbove: 'ItemAffinityAbove' @ItemAffinityTopHalf: 'ItemAffinityTopHalf' @ItemAffinityBottomHalf: 'ItemAffinityBottomHalf' @ItemAffinityBelow: 'ItemAffinityBelow' @SelectionAffinityUpstream: 'SelectionAffinityUpstream' @SelectionAffinityDownstream: 'SelectionAffinityDownstream' ### Section: Anchor and Focus ### # Public: Read-only {Item} where the selection is anchored. anchorItem: null # Public: Read-only text offset in the anchor {Item} where the selection is anchored. anchorOffset: undefined # Public: Read-only {Item} where the selection is focused. focusItem: null # Public: Read-only text offset in the focus {Item} where the selection is focused. focusOffset: undefined ### Section: Start and End ### # Public: Read-only first selected {Item} in outline order. startItem: null # Public: Read-only text offset in the start {Item} where selection starts. startOffset: undefined # Public: Read-only last selected {Item} in outline order. endItem: null # Public: Read-only text offset in the end {Item} where selection end. endOffset: undefined ### Section: Items ### # Public: Read only {Array} of selected {Item}s. items: null # Public: Read only {Array} of common ancestors of selected {Item}s. itemsCommonAncestors: null @isUpstreamDirection: (direction) -> direction is 'backward' or direction is 'left' or direction is 'up' @isDownstreamDirection: (direction) -> direction is 'forward' or direction is 'right' or direction is 'down' @nextSelectionIndexFrom: (item, index, direction, granularity) -> text = item.bodyText assert(index >= 0 and index <= text.length, 'Invalid Index') if text.length is 0 return 0 iframe = document.getElementById('ft-text-calculation-frame') unless iframe iframe = document.createElement("iframe") iframe.id = 'ft-text-calculation-frame' document.body.appendChild(iframe) iframe.contentWindow.document.body.appendChild(iframe.contentWindow.document.createElement('P')) iframeWindow = iframe.contentWindow iframeDocument = iframeWindow.document selection = iframeDocument.getSelection() range = iframeDocument.createRange() iframeBody = iframeDocument.body p = iframeBody.firstChild p.textContent = text range.setStart(p.firstChild, index) selection.removeAllRanges() selection.addRange(range) selection.modify('move', direction, granularity) selection.focusOffset constructor: (editor, focusItem, focusOffset, anchorItem, anchorOffset, selectionAffinity) -> if focusItem instanceof Selection selection = focusItem editor = selection.editor focusItem = selection.focusItem focusOffset = selection.focusOffset anchorItem = selection.anchorItem anchorOffset = selection.anchorOffset selectionAffinity = selection.selectionAffinity @editor = editor @focusItem = focusItem or null @focusOffset = focusOffset @selectionAffinity = selectionAffinity or null @anchorItem = anchorItem or null @anchorOffset = anchorOffset unless anchorItem @anchorItem = @focusItem @anchorOffset = @focusOffset editor.makeVisible(anchorItem) editor.makeVisible(focusItem) unless @isValid @focusItem = null @focusOffset = undefined @anchorItem = null @anchorOffset = undefined @_calculateSelectionItems() ### Section: Selection State ### isValid: null Object.defineProperty @::, 'isValid', get: -> _isValidSelectionOffset(@editor, @focusItem, @focusOffset) and _isValidSelectionOffset(@editor, @anchorItem, @anchorOffset) # Public: Read-only indicating whether the selection's start and end points # are at the same position. isCollapsed: null Object.defineProperty @::, 'isCollapsed', get: -> @isTextMode and @focusOffset is @anchorOffset Object.defineProperty @::, 'isUpstreamAffinity', get: -> @selectionAffinity is Selection.SelectionAffinityUpstream Object.defineProperty @::, 'isOutlineMode', get: -> @isValid and ( !!@anchorItem and !!@focusItem and (@anchorItem isnt @focusItem or @anchorOffset is undefined and @focusOffset is undefined) ) Object.defineProperty @::, 'isTextMode', get: -> @isValid and ( !!@anchorItem and @anchorItem is @focusItem and @anchorOffset isnt undefined and @focusOffset isnt undefined ) Object.defineProperty @::, 'isReversed', get: -> focusItem = @focusItem anchorItem = @anchorItem if focusItem is anchorItem return ( @focusOffset isnt undefined and @anchorOffset isnt undefined and @focusOffset < @anchorOffset ) return ( focusItem and anchorItem and !!(focusItem.comparePosition(anchorItem) & Node.DOCUMENT_POSITION_FOLLOWING) ) Object.defineProperty @::, 'focusClientRect', get: -> @editor.getClientRectForItemOffset @focusItem, @focusOffset Object.defineProperty @::, 'anchorClientRect', get: -> @editor.getClientRectForItemOffset @anchorItem, @anchorOffset Object.defineProperty @::, 'selectionClientRect', get: -> @editor.getClientRectForItemRange @anchorItem, @anchorOffset, @focusItem, @focusOffset equals: (otherSelection) -> @focusItem is otherSelection.focusItem and @focusOffset is otherSelection.focusOffset and @anchorItem is otherSelection.anchorItem and @anchorOffset is otherSelection.anchorOffset and @selectionAffinity is otherSelection.selectionAffinity and shallowEquals(@items, otherSelection.items) contains: (item, offset) -> if item in @items if offset? and @isTextMode if item is @startItem and offset < @startOffset false else if item is @endItem and offset > @endOffset false else true else true else false selectionByExtending: (newFocusItem, newFocusOffset, newSelectionAffinity) -> new Selection( @editor, newFocusItem, newFocusOffset, @anchorItem, @anchorOffset, newSelectionAffinity or @selectionAffinity ) selectionByModifying: (alter, direction, granularity) -> extending = alter is 'extend' next = @nextItemOffsetInDirection(direction, granularity, extending) if extending @selectionByExtending(next.offsetItem, next.offset, next.selectionAffinity); else new Selection( @editor, next.offsetItem, next.offset, next.offsetItem, next.offset, next.selectionAffinity ) selectionByRevalidating: -> editor = @editor visibleItems = @items.filter (each) -> editor.isVisible each visibleSortedItems = visibleItems.sort (a, b) -> a.comparePosition(b) & Node.DOCUMENT_POSITION_PRECEDING if shallowEquals @items, visibleSortedItems return this focusItem = visibleSortedItems[0] anchorItem = visibleSortedItems[visibleSortedItems.length - 1] result = new Selection( @editor, focusItem, undefined, anchorItem, undefined, @selectionAffinity ) result._calculateSelectionItems(visibleSortedItems) result nextItemOffsetInDirection: (direction, granularity, extending) -> if @isOutlineMode switch granularity when 'sentenceboundary', 'lineboundary', 'character', 'word', 'sentence', 'line' granularity = 'paragraphboundary' editor = @editor focusItem = @focusItem focusOffset = @focusOffset anchorOffset = @anchorOffset outlineEditorElement = @editor.outlineEditorElement upstream = Selection.isUpstreamDirection(direction) next = selectionAffinity: Selection.SelectionAffinityDownstream # All movements have downstream affinity except for line and lineboundary if focusItem unless extending focusItem = if upstream then @startItem else @endItem next.offsetItem = focusItem else next.offsetItem = if upstream then editor.getLastVisibleItem() else editor.getFirstVisibleItem() switch granularity when 'sentenceboundary' next.offset = Selection.nextSelectionIndexFrom( focusItem, focusOffset, if upstream then 'backward' else 'forward', granularity ) when 'lineboundary' currentRect = editor.getClientRectForItemOffset focusItem, focusOffset if currentRect next = outlineEditorElement.pick( if upstream then Number.MIN_VALUE else Number.MAX_VALUE, currentRect.top + currentRect.height / 2.0 ).itemCaretPosition when 'paragraphboundary' next.offset = if upstream then 0 else focusItem?.bodyText.length when 'character' if upstream if not @isCollapsed and not extending if focusOffset < anchorOffset next.offset = focusOffset else next.offset = anchorOffset else if focusOffset > 0 next.offset = focusOffset - 1 else prevItem = editor.getPreviousVisibleItem(focusItem) if prevItem next.offsetItem = prevItem next.offset = prevItem.bodyText.length else if not @isCollapsed and not extending if focusOffset > anchorOffset next.offset = focusOffset else next.offset = anchorOffset else if focusOffset < focusItem.bodyText.length next.offset = focusOffset + 1 else nextItem = editor.getNextVisibleItem(focusItem) if nextItem next.offsetItem = nextItem next.offset = 0 when 'word', 'sentence' next.offset = Selection.nextSelectionIndexFrom( focusItem, focusOffset, if upstream then 'backward' else 'forward', granularity ) if next.offset is focusOffset nextItem = if upstream then editor.getPreviousVisibleItem(focusItem) else editor.getNextVisibleItem(focusItem) if nextItem direction = if upstream then 'backward' else 'forward' editorSelection = new Selection(@editor, nextItem, if upstream then nextItem.bodyText.length else 0) editorSelection = editorSelection.selectionByModifying('move', direction, granularity) next = offsetItem: editorSelection.focusItem offset: editorSelection.focusOffset selectionAffinity: editorSelection.selectionAffinity when 'line' next = @nextItemOffsetByLineFromFocus(focusItem, focusOffset, direction) when 'paragraph' prevItem = if upstream then editor.getPreviousVisibleItem(focusItem) else editor.getNextVisibleItem(focusItem) if prevItem next.offsetItem = prevItem when 'branch' prevItem = if upstream then editor.getPreviousVisibleBranch(focusItem) else editor.getNextVisibleBranch(focusItem) if prevItem next.offsetItem = prevItem when 'list' if upstream next.offsetItem = editor.getFirstVisibleChild(focusItem.parent) unless next.offsetItem next = @nextItemOffsetUpstream(direction, 'branch', extending) else next.offsetItem = editor.getLastVisibleChild(focusItem.parent) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'parent' next.offsetItem = editor.getVisibleParent(focusItem) unless next.offsetItem next = @nextItemOffsetUpstream(direction, 'branch', extending) when 'firstchild' next.offsetItem = editor.getFirstVisibleChild(focusItem) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'lastchild' next.offsetItem = editor.getLastVisibleChild(focusItem) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'documentboundary' next.offsetItem = if upstream then editor.getFirstVisibleItem() else editor.getLastVisibleItem() else throw new Error 'Unexpected Granularity ' + granularity if not extending and not next.offsetItem next.offsetItem = focusItem if @isTextMode and next.offset is undefined next.offset = if upstream then 0 else next.offsetItem.bodyText.length next nextItemOffsetByLineFromFocus: (focusItem, focusOffset, direction) -> editor = @editor outlineEditorElement = editor.outlineEditorElement upstream = Selection.isUpstreamDirection(direction) renderedBodyText = outlineEditorElement.renderedBodyTextSPANForItem focusItem renderedBodyTextRect = renderedBodyText.getBoundingClientRect() renderedBodyTextStyle = window.getComputedStyle(renderedBodyText) viewLineHeight = parseInt(renderedBodyTextStyle.lineHeight, 10) viewPaddingTop = parseInt(renderedBodyTextStyle.paddingTop, 10) viewPaddingBottom = parseInt(renderedBodyTextStyle.paddingBottom, 10) focusCaretRect = editor.getClientRectForItemOffset(focusItem, focusOffset) x = editor.selectionVerticalAnchor() picked y if upstream y = focusCaretRect.bottom - (viewLineHeight * 1.5) else y = focusCaretRect.bottom + (viewLineHeight / 2.0) if y >= (renderedBodyTextRect.top + viewPaddingTop) and y <= (renderedBodyTextRect.bottom - viewPaddingBottom) picked = outlineEditorElement.pick(x, y).itemCaretPosition else nextItem if upstream nextItem = editor.getPreviousVisibleItem(focusItem) else nextItem = editor.getNextVisibleItem(focusItem) if nextItem editor.scrollToItemIfNeeded(nextItem) # pick breaks for offscreen items nextItemTextRect = outlineEditorElement.renderedBodyTextSPANForItem(nextItem).getBoundingClientRect() if upstream y = nextItemTextRect.bottom - 1 else y = nextItemTextRect.top + 1 picked = outlineEditorElement.pick(x, y).itemCaretPosition else if upstream picked = offsetItem: focusItem offset: 0 else picked = offsetItem: focusItem offset: focusItem.bodyText.length picked _calculateSelectionItems: (overRideSelectionItems) -> items = overRideSelectionItems or [] if @isValid and not overRideSelectionItems editor = @editor focusItem = @focusItem anchorItem = @anchorItem startItem = anchorItem endItem = focusItem if @isReversed startItem = focusItem endItem = anchorItem each = startItem while each items.push(each) if each is endItem break each = editor.getNextVisibleItem(each) @items = items @itemsCommonAncestors = Item.getCommonAncestors(items) @startItem = items[0] @endItem = items[items.length - 1] if @isReversed @startOffset = @focusOffset @endOffset = @anchorOffset else @startOffset = @anchorOffset @endOffset = @focusOffset if @isTextMode if @startOffset > @endOffset throw new Error 'Unexpected' toString: -> "anchor:#{@anchorItem?.id},#{@anchorOffset} focus:#{@focusItem?.id},#{@focusOffset}" _isValidSelectionOffset = (editor, item, itemOffset) -> if item and editor.isVisible(item) if itemOffset is undefined true else itemOffset <= item.bodyText.length else false module.exports = Selection
160432
# Copyright (c) 2015 <NAME>. All rights reserved. shallowEquals = require 'shallow-equals' Item = require '../core/item' assert = require 'assert' ItemRenderer = null # Public: The selection returned by {OutlineEditor::selection}. # # The anchor of a selection is the beginning point of the selection. When # making a selection with a mouse, the anchor is where in the document the # mouse button is initially pressed. As the user changes the selection using # the mouse or the keyboard, the anchor does not move. # # The focus of a selection is the end point of the selection. When making a # selection with a mouse, the focus is where in the document the mouse button # is released. As the user changes the selection using the mouse or the # keyboard, the focus is the end of the selection that moves. # # The start of a selection is the boundary closest to the beginning of the # document. The end of a selection is the boundary closest to the end of the # document. class Selection @ItemAffinityAbove: 'ItemAffinityAbove' @ItemAffinityTopHalf: 'ItemAffinityTopHalf' @ItemAffinityBottomHalf: 'ItemAffinityBottomHalf' @ItemAffinityBelow: 'ItemAffinityBelow' @SelectionAffinityUpstream: 'SelectionAffinityUpstream' @SelectionAffinityDownstream: 'SelectionAffinityDownstream' ### Section: Anchor and Focus ### # Public: Read-only {Item} where the selection is anchored. anchorItem: null # Public: Read-only text offset in the anchor {Item} where the selection is anchored. anchorOffset: undefined # Public: Read-only {Item} where the selection is focused. focusItem: null # Public: Read-only text offset in the focus {Item} where the selection is focused. focusOffset: undefined ### Section: Start and End ### # Public: Read-only first selected {Item} in outline order. startItem: null # Public: Read-only text offset in the start {Item} where selection starts. startOffset: undefined # Public: Read-only last selected {Item} in outline order. endItem: null # Public: Read-only text offset in the end {Item} where selection end. endOffset: undefined ### Section: Items ### # Public: Read only {Array} of selected {Item}s. items: null # Public: Read only {Array} of common ancestors of selected {Item}s. itemsCommonAncestors: null @isUpstreamDirection: (direction) -> direction is 'backward' or direction is 'left' or direction is 'up' @isDownstreamDirection: (direction) -> direction is 'forward' or direction is 'right' or direction is 'down' @nextSelectionIndexFrom: (item, index, direction, granularity) -> text = item.bodyText assert(index >= 0 and index <= text.length, 'Invalid Index') if text.length is 0 return 0 iframe = document.getElementById('ft-text-calculation-frame') unless iframe iframe = document.createElement("iframe") iframe.id = 'ft-text-calculation-frame' document.body.appendChild(iframe) iframe.contentWindow.document.body.appendChild(iframe.contentWindow.document.createElement('P')) iframeWindow = iframe.contentWindow iframeDocument = iframeWindow.document selection = iframeDocument.getSelection() range = iframeDocument.createRange() iframeBody = iframeDocument.body p = iframeBody.firstChild p.textContent = text range.setStart(p.firstChild, index) selection.removeAllRanges() selection.addRange(range) selection.modify('move', direction, granularity) selection.focusOffset constructor: (editor, focusItem, focusOffset, anchorItem, anchorOffset, selectionAffinity) -> if focusItem instanceof Selection selection = focusItem editor = selection.editor focusItem = selection.focusItem focusOffset = selection.focusOffset anchorItem = selection.anchorItem anchorOffset = selection.anchorOffset selectionAffinity = selection.selectionAffinity @editor = editor @focusItem = focusItem or null @focusOffset = focusOffset @selectionAffinity = selectionAffinity or null @anchorItem = anchorItem or null @anchorOffset = anchorOffset unless anchorItem @anchorItem = @focusItem @anchorOffset = @focusOffset editor.makeVisible(anchorItem) editor.makeVisible(focusItem) unless @isValid @focusItem = null @focusOffset = undefined @anchorItem = null @anchorOffset = undefined @_calculateSelectionItems() ### Section: Selection State ### isValid: null Object.defineProperty @::, 'isValid', get: -> _isValidSelectionOffset(@editor, @focusItem, @focusOffset) and _isValidSelectionOffset(@editor, @anchorItem, @anchorOffset) # Public: Read-only indicating whether the selection's start and end points # are at the same position. isCollapsed: null Object.defineProperty @::, 'isCollapsed', get: -> @isTextMode and @focusOffset is @anchorOffset Object.defineProperty @::, 'isUpstreamAffinity', get: -> @selectionAffinity is Selection.SelectionAffinityUpstream Object.defineProperty @::, 'isOutlineMode', get: -> @isValid and ( !!@anchorItem and !!@focusItem and (@anchorItem isnt @focusItem or @anchorOffset is undefined and @focusOffset is undefined) ) Object.defineProperty @::, 'isTextMode', get: -> @isValid and ( !!@anchorItem and @anchorItem is @focusItem and @anchorOffset isnt undefined and @focusOffset isnt undefined ) Object.defineProperty @::, 'isReversed', get: -> focusItem = @focusItem anchorItem = @anchorItem if focusItem is anchorItem return ( @focusOffset isnt undefined and @anchorOffset isnt undefined and @focusOffset < @anchorOffset ) return ( focusItem and anchorItem and !!(focusItem.comparePosition(anchorItem) & Node.DOCUMENT_POSITION_FOLLOWING) ) Object.defineProperty @::, 'focusClientRect', get: -> @editor.getClientRectForItemOffset @focusItem, @focusOffset Object.defineProperty @::, 'anchorClientRect', get: -> @editor.getClientRectForItemOffset @anchorItem, @anchorOffset Object.defineProperty @::, 'selectionClientRect', get: -> @editor.getClientRectForItemRange @anchorItem, @anchorOffset, @focusItem, @focusOffset equals: (otherSelection) -> @focusItem is otherSelection.focusItem and @focusOffset is otherSelection.focusOffset and @anchorItem is otherSelection.anchorItem and @anchorOffset is otherSelection.anchorOffset and @selectionAffinity is otherSelection.selectionAffinity and shallowEquals(@items, otherSelection.items) contains: (item, offset) -> if item in @items if offset? and @isTextMode if item is @startItem and offset < @startOffset false else if item is @endItem and offset > @endOffset false else true else true else false selectionByExtending: (newFocusItem, newFocusOffset, newSelectionAffinity) -> new Selection( @editor, newFocusItem, newFocusOffset, @anchorItem, @anchorOffset, newSelectionAffinity or @selectionAffinity ) selectionByModifying: (alter, direction, granularity) -> extending = alter is 'extend' next = @nextItemOffsetInDirection(direction, granularity, extending) if extending @selectionByExtending(next.offsetItem, next.offset, next.selectionAffinity); else new Selection( @editor, next.offsetItem, next.offset, next.offsetItem, next.offset, next.selectionAffinity ) selectionByRevalidating: -> editor = @editor visibleItems = @items.filter (each) -> editor.isVisible each visibleSortedItems = visibleItems.sort (a, b) -> a.comparePosition(b) & Node.DOCUMENT_POSITION_PRECEDING if shallowEquals @items, visibleSortedItems return this focusItem = visibleSortedItems[0] anchorItem = visibleSortedItems[visibleSortedItems.length - 1] result = new Selection( @editor, focusItem, undefined, anchorItem, undefined, @selectionAffinity ) result._calculateSelectionItems(visibleSortedItems) result nextItemOffsetInDirection: (direction, granularity, extending) -> if @isOutlineMode switch granularity when 'sentenceboundary', 'lineboundary', 'character', 'word', 'sentence', 'line' granularity = 'paragraphboundary' editor = @editor focusItem = @focusItem focusOffset = @focusOffset anchorOffset = @anchorOffset outlineEditorElement = @editor.outlineEditorElement upstream = Selection.isUpstreamDirection(direction) next = selectionAffinity: Selection.SelectionAffinityDownstream # All movements have downstream affinity except for line and lineboundary if focusItem unless extending focusItem = if upstream then @startItem else @endItem next.offsetItem = focusItem else next.offsetItem = if upstream then editor.getLastVisibleItem() else editor.getFirstVisibleItem() switch granularity when 'sentenceboundary' next.offset = Selection.nextSelectionIndexFrom( focusItem, focusOffset, if upstream then 'backward' else 'forward', granularity ) when 'lineboundary' currentRect = editor.getClientRectForItemOffset focusItem, focusOffset if currentRect next = outlineEditorElement.pick( if upstream then Number.MIN_VALUE else Number.MAX_VALUE, currentRect.top + currentRect.height / 2.0 ).itemCaretPosition when 'paragraphboundary' next.offset = if upstream then 0 else focusItem?.bodyText.length when 'character' if upstream if not @isCollapsed and not extending if focusOffset < anchorOffset next.offset = focusOffset else next.offset = anchorOffset else if focusOffset > 0 next.offset = focusOffset - 1 else prevItem = editor.getPreviousVisibleItem(focusItem) if prevItem next.offsetItem = prevItem next.offset = prevItem.bodyText.length else if not @isCollapsed and not extending if focusOffset > anchorOffset next.offset = focusOffset else next.offset = anchorOffset else if focusOffset < focusItem.bodyText.length next.offset = focusOffset + 1 else nextItem = editor.getNextVisibleItem(focusItem) if nextItem next.offsetItem = nextItem next.offset = 0 when 'word', 'sentence' next.offset = Selection.nextSelectionIndexFrom( focusItem, focusOffset, if upstream then 'backward' else 'forward', granularity ) if next.offset is focusOffset nextItem = if upstream then editor.getPreviousVisibleItem(focusItem) else editor.getNextVisibleItem(focusItem) if nextItem direction = if upstream then 'backward' else 'forward' editorSelection = new Selection(@editor, nextItem, if upstream then nextItem.bodyText.length else 0) editorSelection = editorSelection.selectionByModifying('move', direction, granularity) next = offsetItem: editorSelection.focusItem offset: editorSelection.focusOffset selectionAffinity: editorSelection.selectionAffinity when 'line' next = @nextItemOffsetByLineFromFocus(focusItem, focusOffset, direction) when 'paragraph' prevItem = if upstream then editor.getPreviousVisibleItem(focusItem) else editor.getNextVisibleItem(focusItem) if prevItem next.offsetItem = prevItem when 'branch' prevItem = if upstream then editor.getPreviousVisibleBranch(focusItem) else editor.getNextVisibleBranch(focusItem) if prevItem next.offsetItem = prevItem when 'list' if upstream next.offsetItem = editor.getFirstVisibleChild(focusItem.parent) unless next.offsetItem next = @nextItemOffsetUpstream(direction, 'branch', extending) else next.offsetItem = editor.getLastVisibleChild(focusItem.parent) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'parent' next.offsetItem = editor.getVisibleParent(focusItem) unless next.offsetItem next = @nextItemOffsetUpstream(direction, 'branch', extending) when 'firstchild' next.offsetItem = editor.getFirstVisibleChild(focusItem) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'lastchild' next.offsetItem = editor.getLastVisibleChild(focusItem) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'documentboundary' next.offsetItem = if upstream then editor.getFirstVisibleItem() else editor.getLastVisibleItem() else throw new Error 'Unexpected Granularity ' + granularity if not extending and not next.offsetItem next.offsetItem = focusItem if @isTextMode and next.offset is undefined next.offset = if upstream then 0 else next.offsetItem.bodyText.length next nextItemOffsetByLineFromFocus: (focusItem, focusOffset, direction) -> editor = @editor outlineEditorElement = editor.outlineEditorElement upstream = Selection.isUpstreamDirection(direction) renderedBodyText = outlineEditorElement.renderedBodyTextSPANForItem focusItem renderedBodyTextRect = renderedBodyText.getBoundingClientRect() renderedBodyTextStyle = window.getComputedStyle(renderedBodyText) viewLineHeight = parseInt(renderedBodyTextStyle.lineHeight, 10) viewPaddingTop = parseInt(renderedBodyTextStyle.paddingTop, 10) viewPaddingBottom = parseInt(renderedBodyTextStyle.paddingBottom, 10) focusCaretRect = editor.getClientRectForItemOffset(focusItem, focusOffset) x = editor.selectionVerticalAnchor() picked y if upstream y = focusCaretRect.bottom - (viewLineHeight * 1.5) else y = focusCaretRect.bottom + (viewLineHeight / 2.0) if y >= (renderedBodyTextRect.top + viewPaddingTop) and y <= (renderedBodyTextRect.bottom - viewPaddingBottom) picked = outlineEditorElement.pick(x, y).itemCaretPosition else nextItem if upstream nextItem = editor.getPreviousVisibleItem(focusItem) else nextItem = editor.getNextVisibleItem(focusItem) if nextItem editor.scrollToItemIfNeeded(nextItem) # pick breaks for offscreen items nextItemTextRect = outlineEditorElement.renderedBodyTextSPANForItem(nextItem).getBoundingClientRect() if upstream y = nextItemTextRect.bottom - 1 else y = nextItemTextRect.top + 1 picked = outlineEditorElement.pick(x, y).itemCaretPosition else if upstream picked = offsetItem: focusItem offset: 0 else picked = offsetItem: focusItem offset: focusItem.bodyText.length picked _calculateSelectionItems: (overRideSelectionItems) -> items = overRideSelectionItems or [] if @isValid and not overRideSelectionItems editor = @editor focusItem = @focusItem anchorItem = @anchorItem startItem = anchorItem endItem = focusItem if @isReversed startItem = focusItem endItem = anchorItem each = startItem while each items.push(each) if each is endItem break each = editor.getNextVisibleItem(each) @items = items @itemsCommonAncestors = Item.getCommonAncestors(items) @startItem = items[0] @endItem = items[items.length - 1] if @isReversed @startOffset = @focusOffset @endOffset = @anchorOffset else @startOffset = @anchorOffset @endOffset = @focusOffset if @isTextMode if @startOffset > @endOffset throw new Error 'Unexpected' toString: -> "anchor:#{@anchorItem?.id},#{@anchorOffset} focus:#{@focusItem?.id},#{@focusOffset}" _isValidSelectionOffset = (editor, item, itemOffset) -> if item and editor.isVisible(item) if itemOffset is undefined true else itemOffset <= item.bodyText.length else false module.exports = Selection
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. shallowEquals = require 'shallow-equals' Item = require '../core/item' assert = require 'assert' ItemRenderer = null # Public: The selection returned by {OutlineEditor::selection}. # # The anchor of a selection is the beginning point of the selection. When # making a selection with a mouse, the anchor is where in the document the # mouse button is initially pressed. As the user changes the selection using # the mouse or the keyboard, the anchor does not move. # # The focus of a selection is the end point of the selection. When making a # selection with a mouse, the focus is where in the document the mouse button # is released. As the user changes the selection using the mouse or the # keyboard, the focus is the end of the selection that moves. # # The start of a selection is the boundary closest to the beginning of the # document. The end of a selection is the boundary closest to the end of the # document. class Selection @ItemAffinityAbove: 'ItemAffinityAbove' @ItemAffinityTopHalf: 'ItemAffinityTopHalf' @ItemAffinityBottomHalf: 'ItemAffinityBottomHalf' @ItemAffinityBelow: 'ItemAffinityBelow' @SelectionAffinityUpstream: 'SelectionAffinityUpstream' @SelectionAffinityDownstream: 'SelectionAffinityDownstream' ### Section: Anchor and Focus ### # Public: Read-only {Item} where the selection is anchored. anchorItem: null # Public: Read-only text offset in the anchor {Item} where the selection is anchored. anchorOffset: undefined # Public: Read-only {Item} where the selection is focused. focusItem: null # Public: Read-only text offset in the focus {Item} where the selection is focused. focusOffset: undefined ### Section: Start and End ### # Public: Read-only first selected {Item} in outline order. startItem: null # Public: Read-only text offset in the start {Item} where selection starts. startOffset: undefined # Public: Read-only last selected {Item} in outline order. endItem: null # Public: Read-only text offset in the end {Item} where selection end. endOffset: undefined ### Section: Items ### # Public: Read only {Array} of selected {Item}s. items: null # Public: Read only {Array} of common ancestors of selected {Item}s. itemsCommonAncestors: null @isUpstreamDirection: (direction) -> direction is 'backward' or direction is 'left' or direction is 'up' @isDownstreamDirection: (direction) -> direction is 'forward' or direction is 'right' or direction is 'down' @nextSelectionIndexFrom: (item, index, direction, granularity) -> text = item.bodyText assert(index >= 0 and index <= text.length, 'Invalid Index') if text.length is 0 return 0 iframe = document.getElementById('ft-text-calculation-frame') unless iframe iframe = document.createElement("iframe") iframe.id = 'ft-text-calculation-frame' document.body.appendChild(iframe) iframe.contentWindow.document.body.appendChild(iframe.contentWindow.document.createElement('P')) iframeWindow = iframe.contentWindow iframeDocument = iframeWindow.document selection = iframeDocument.getSelection() range = iframeDocument.createRange() iframeBody = iframeDocument.body p = iframeBody.firstChild p.textContent = text range.setStart(p.firstChild, index) selection.removeAllRanges() selection.addRange(range) selection.modify('move', direction, granularity) selection.focusOffset constructor: (editor, focusItem, focusOffset, anchorItem, anchorOffset, selectionAffinity) -> if focusItem instanceof Selection selection = focusItem editor = selection.editor focusItem = selection.focusItem focusOffset = selection.focusOffset anchorItem = selection.anchorItem anchorOffset = selection.anchorOffset selectionAffinity = selection.selectionAffinity @editor = editor @focusItem = focusItem or null @focusOffset = focusOffset @selectionAffinity = selectionAffinity or null @anchorItem = anchorItem or null @anchorOffset = anchorOffset unless anchorItem @anchorItem = @focusItem @anchorOffset = @focusOffset editor.makeVisible(anchorItem) editor.makeVisible(focusItem) unless @isValid @focusItem = null @focusOffset = undefined @anchorItem = null @anchorOffset = undefined @_calculateSelectionItems() ### Section: Selection State ### isValid: null Object.defineProperty @::, 'isValid', get: -> _isValidSelectionOffset(@editor, @focusItem, @focusOffset) and _isValidSelectionOffset(@editor, @anchorItem, @anchorOffset) # Public: Read-only indicating whether the selection's start and end points # are at the same position. isCollapsed: null Object.defineProperty @::, 'isCollapsed', get: -> @isTextMode and @focusOffset is @anchorOffset Object.defineProperty @::, 'isUpstreamAffinity', get: -> @selectionAffinity is Selection.SelectionAffinityUpstream Object.defineProperty @::, 'isOutlineMode', get: -> @isValid and ( !!@anchorItem and !!@focusItem and (@anchorItem isnt @focusItem or @anchorOffset is undefined and @focusOffset is undefined) ) Object.defineProperty @::, 'isTextMode', get: -> @isValid and ( !!@anchorItem and @anchorItem is @focusItem and @anchorOffset isnt undefined and @focusOffset isnt undefined ) Object.defineProperty @::, 'isReversed', get: -> focusItem = @focusItem anchorItem = @anchorItem if focusItem is anchorItem return ( @focusOffset isnt undefined and @anchorOffset isnt undefined and @focusOffset < @anchorOffset ) return ( focusItem and anchorItem and !!(focusItem.comparePosition(anchorItem) & Node.DOCUMENT_POSITION_FOLLOWING) ) Object.defineProperty @::, 'focusClientRect', get: -> @editor.getClientRectForItemOffset @focusItem, @focusOffset Object.defineProperty @::, 'anchorClientRect', get: -> @editor.getClientRectForItemOffset @anchorItem, @anchorOffset Object.defineProperty @::, 'selectionClientRect', get: -> @editor.getClientRectForItemRange @anchorItem, @anchorOffset, @focusItem, @focusOffset equals: (otherSelection) -> @focusItem is otherSelection.focusItem and @focusOffset is otherSelection.focusOffset and @anchorItem is otherSelection.anchorItem and @anchorOffset is otherSelection.anchorOffset and @selectionAffinity is otherSelection.selectionAffinity and shallowEquals(@items, otherSelection.items) contains: (item, offset) -> if item in @items if offset? and @isTextMode if item is @startItem and offset < @startOffset false else if item is @endItem and offset > @endOffset false else true else true else false selectionByExtending: (newFocusItem, newFocusOffset, newSelectionAffinity) -> new Selection( @editor, newFocusItem, newFocusOffset, @anchorItem, @anchorOffset, newSelectionAffinity or @selectionAffinity ) selectionByModifying: (alter, direction, granularity) -> extending = alter is 'extend' next = @nextItemOffsetInDirection(direction, granularity, extending) if extending @selectionByExtending(next.offsetItem, next.offset, next.selectionAffinity); else new Selection( @editor, next.offsetItem, next.offset, next.offsetItem, next.offset, next.selectionAffinity ) selectionByRevalidating: -> editor = @editor visibleItems = @items.filter (each) -> editor.isVisible each visibleSortedItems = visibleItems.sort (a, b) -> a.comparePosition(b) & Node.DOCUMENT_POSITION_PRECEDING if shallowEquals @items, visibleSortedItems return this focusItem = visibleSortedItems[0] anchorItem = visibleSortedItems[visibleSortedItems.length - 1] result = new Selection( @editor, focusItem, undefined, anchorItem, undefined, @selectionAffinity ) result._calculateSelectionItems(visibleSortedItems) result nextItemOffsetInDirection: (direction, granularity, extending) -> if @isOutlineMode switch granularity when 'sentenceboundary', 'lineboundary', 'character', 'word', 'sentence', 'line' granularity = 'paragraphboundary' editor = @editor focusItem = @focusItem focusOffset = @focusOffset anchorOffset = @anchorOffset outlineEditorElement = @editor.outlineEditorElement upstream = Selection.isUpstreamDirection(direction) next = selectionAffinity: Selection.SelectionAffinityDownstream # All movements have downstream affinity except for line and lineboundary if focusItem unless extending focusItem = if upstream then @startItem else @endItem next.offsetItem = focusItem else next.offsetItem = if upstream then editor.getLastVisibleItem() else editor.getFirstVisibleItem() switch granularity when 'sentenceboundary' next.offset = Selection.nextSelectionIndexFrom( focusItem, focusOffset, if upstream then 'backward' else 'forward', granularity ) when 'lineboundary' currentRect = editor.getClientRectForItemOffset focusItem, focusOffset if currentRect next = outlineEditorElement.pick( if upstream then Number.MIN_VALUE else Number.MAX_VALUE, currentRect.top + currentRect.height / 2.0 ).itemCaretPosition when 'paragraphboundary' next.offset = if upstream then 0 else focusItem?.bodyText.length when 'character' if upstream if not @isCollapsed and not extending if focusOffset < anchorOffset next.offset = focusOffset else next.offset = anchorOffset else if focusOffset > 0 next.offset = focusOffset - 1 else prevItem = editor.getPreviousVisibleItem(focusItem) if prevItem next.offsetItem = prevItem next.offset = prevItem.bodyText.length else if not @isCollapsed and not extending if focusOffset > anchorOffset next.offset = focusOffset else next.offset = anchorOffset else if focusOffset < focusItem.bodyText.length next.offset = focusOffset + 1 else nextItem = editor.getNextVisibleItem(focusItem) if nextItem next.offsetItem = nextItem next.offset = 0 when 'word', 'sentence' next.offset = Selection.nextSelectionIndexFrom( focusItem, focusOffset, if upstream then 'backward' else 'forward', granularity ) if next.offset is focusOffset nextItem = if upstream then editor.getPreviousVisibleItem(focusItem) else editor.getNextVisibleItem(focusItem) if nextItem direction = if upstream then 'backward' else 'forward' editorSelection = new Selection(@editor, nextItem, if upstream then nextItem.bodyText.length else 0) editorSelection = editorSelection.selectionByModifying('move', direction, granularity) next = offsetItem: editorSelection.focusItem offset: editorSelection.focusOffset selectionAffinity: editorSelection.selectionAffinity when 'line' next = @nextItemOffsetByLineFromFocus(focusItem, focusOffset, direction) when 'paragraph' prevItem = if upstream then editor.getPreviousVisibleItem(focusItem) else editor.getNextVisibleItem(focusItem) if prevItem next.offsetItem = prevItem when 'branch' prevItem = if upstream then editor.getPreviousVisibleBranch(focusItem) else editor.getNextVisibleBranch(focusItem) if prevItem next.offsetItem = prevItem when 'list' if upstream next.offsetItem = editor.getFirstVisibleChild(focusItem.parent) unless next.offsetItem next = @nextItemOffsetUpstream(direction, 'branch', extending) else next.offsetItem = editor.getLastVisibleChild(focusItem.parent) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'parent' next.offsetItem = editor.getVisibleParent(focusItem) unless next.offsetItem next = @nextItemOffsetUpstream(direction, 'branch', extending) when 'firstchild' next.offsetItem = editor.getFirstVisibleChild(focusItem) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'lastchild' next.offsetItem = editor.getLastVisibleChild(focusItem) unless next.offsetItem next = @nextItemOffsetDownstream(direction, 'branch', extending) when 'documentboundary' next.offsetItem = if upstream then editor.getFirstVisibleItem() else editor.getLastVisibleItem() else throw new Error 'Unexpected Granularity ' + granularity if not extending and not next.offsetItem next.offsetItem = focusItem if @isTextMode and next.offset is undefined next.offset = if upstream then 0 else next.offsetItem.bodyText.length next nextItemOffsetByLineFromFocus: (focusItem, focusOffset, direction) -> editor = @editor outlineEditorElement = editor.outlineEditorElement upstream = Selection.isUpstreamDirection(direction) renderedBodyText = outlineEditorElement.renderedBodyTextSPANForItem focusItem renderedBodyTextRect = renderedBodyText.getBoundingClientRect() renderedBodyTextStyle = window.getComputedStyle(renderedBodyText) viewLineHeight = parseInt(renderedBodyTextStyle.lineHeight, 10) viewPaddingTop = parseInt(renderedBodyTextStyle.paddingTop, 10) viewPaddingBottom = parseInt(renderedBodyTextStyle.paddingBottom, 10) focusCaretRect = editor.getClientRectForItemOffset(focusItem, focusOffset) x = editor.selectionVerticalAnchor() picked y if upstream y = focusCaretRect.bottom - (viewLineHeight * 1.5) else y = focusCaretRect.bottom + (viewLineHeight / 2.0) if y >= (renderedBodyTextRect.top + viewPaddingTop) and y <= (renderedBodyTextRect.bottom - viewPaddingBottom) picked = outlineEditorElement.pick(x, y).itemCaretPosition else nextItem if upstream nextItem = editor.getPreviousVisibleItem(focusItem) else nextItem = editor.getNextVisibleItem(focusItem) if nextItem editor.scrollToItemIfNeeded(nextItem) # pick breaks for offscreen items nextItemTextRect = outlineEditorElement.renderedBodyTextSPANForItem(nextItem).getBoundingClientRect() if upstream y = nextItemTextRect.bottom - 1 else y = nextItemTextRect.top + 1 picked = outlineEditorElement.pick(x, y).itemCaretPosition else if upstream picked = offsetItem: focusItem offset: 0 else picked = offsetItem: focusItem offset: focusItem.bodyText.length picked _calculateSelectionItems: (overRideSelectionItems) -> items = overRideSelectionItems or [] if @isValid and not overRideSelectionItems editor = @editor focusItem = @focusItem anchorItem = @anchorItem startItem = anchorItem endItem = focusItem if @isReversed startItem = focusItem endItem = anchorItem each = startItem while each items.push(each) if each is endItem break each = editor.getNextVisibleItem(each) @items = items @itemsCommonAncestors = Item.getCommonAncestors(items) @startItem = items[0] @endItem = items[items.length - 1] if @isReversed @startOffset = @focusOffset @endOffset = @anchorOffset else @startOffset = @anchorOffset @endOffset = @focusOffset if @isTextMode if @startOffset > @endOffset throw new Error 'Unexpected' toString: -> "anchor:#{@anchorItem?.id},#{@anchorOffset} focus:#{@focusItem?.id},#{@focusOffset}" _isValidSelectionOffset = (editor, item, itemOffset) -> if item and editor.isVisible(item) if itemOffset is undefined true else itemOffset <= item.bodyText.length else false module.exports = Selection
[ { "context": "###\n * cena_auth\n * https://github.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Li", "end": 46, "score": 0.998560905456543, "start": 39, "tag": "USERNAME", "value": "1egoman" }, { "context": "thub.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan G...
src/frontend/controllers/foodstuff.coffee
1egoman/cena_app
0
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 Ryan Gaus * Licensed under the MIT license. ### 'use strict'; # foodstuff controller @app.controller 'FsController', ($scope, $routeParams, FoodStuff, Shop, Tag, $rootScope, $modal) -> root = $scope root.isData = false # get all tags Tag.query (tags) -> root.tags = tags root.getDeals() # deal storage root.deals = [] # place to store incoming list data root.newFs = {} # foodstuff drawer root.foodstuffhidden = true # get all foodstuffs, initially... FoodStuff.query (all) -> root.isData = true # no refresh spinner root.foodstuffs = all # add new foodstuff root.add = (fs) -> # format tags correctly fs.tags = fs.tags or (fs.pretags or "").split(' ') # make sure $ amount doesn't start with a $ fs.price = fs.price.substr(1) if fs.price[0] is '$' # add and push item to backend resource foodstuff = new FoodStuff fs foodstuff.$save -> root.foodstuffs.push fs # delete a foodstuff root.remove = (fs) -> FoodStuff.remove _id: fs._id, -> root.foodstuffs = _.without root.foodstuffs, fs # update a foodstuff price / tags / other attribute root.update = (list, pretags="") -> # format tags list.tags = pretags.split ' ' if pretags.length # update list on backend FoodStuff.update list, -> # close modal $("#edit-foodstuff-#{list._id}").modal 'hide' # add the tag, and delimit it with spaces root.addTagToNewFoodstuff = (tag) -> root.newFs.pretags = (root.newFs.pretags or '') + ' ' + tag root.newFs.pretags = root.newFs.pretags.trim() $('input#fs-tags').focus() true # list fuzzy searching root.matchesSearchString = (list, filter) -> # if there's no filter, return true if !filter return true # make filter lowercase filter = filter.toLowerCase() # create a corpus of the important parts of each list item corpus = _.compact _.map([ 'name' 'desc' 'tags' ], (key) -> JSON.stringify list[key] ).join(' ').toLowerCase().split /[ ,\[\]"-]/gi # how many matching words are there between the corpus # and the filter string? score = _.intersection(corpus, filter.split(' ')).length score > 0 ######### # Deals # ######### # combine all shop deals into one master array root.getDeals = -> # get all shop tags tags = _.filter root.tags, (t) -> t.name.indexOf('shop-') isnt -1 # get deals for each specified shop tag _.each tags, (t) -> Shop.doCache t.name.slice(5), (d) -> if d and d.deals dealsToAdd = _.map d.deals, (e) -> e.shop = t.name.slice(5) e root.deals = root.deals.concat(dealsToAdd) root.findDeals = (name) -> _.filter root.deals, (d) -> d.relatesTo.indexOf(name) != -1
74947
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. ### 'use strict'; # foodstuff controller @app.controller 'FsController', ($scope, $routeParams, FoodStuff, Shop, Tag, $rootScope, $modal) -> root = $scope root.isData = false # get all tags Tag.query (tags) -> root.tags = tags root.getDeals() # deal storage root.deals = [] # place to store incoming list data root.newFs = {} # foodstuff drawer root.foodstuffhidden = true # get all foodstuffs, initially... FoodStuff.query (all) -> root.isData = true # no refresh spinner root.foodstuffs = all # add new foodstuff root.add = (fs) -> # format tags correctly fs.tags = fs.tags or (fs.pretags or "").split(' ') # make sure $ amount doesn't start with a $ fs.price = fs.price.substr(1) if fs.price[0] is '$' # add and push item to backend resource foodstuff = new FoodStuff fs foodstuff.$save -> root.foodstuffs.push fs # delete a foodstuff root.remove = (fs) -> FoodStuff.remove _id: fs._id, -> root.foodstuffs = _.without root.foodstuffs, fs # update a foodstuff price / tags / other attribute root.update = (list, pretags="") -> # format tags list.tags = pretags.split ' ' if pretags.length # update list on backend FoodStuff.update list, -> # close modal $("#edit-foodstuff-#{list._id}").modal 'hide' # add the tag, and delimit it with spaces root.addTagToNewFoodstuff = (tag) -> root.newFs.pretags = (root.newFs.pretags or '') + ' ' + tag root.newFs.pretags = root.newFs.pretags.trim() $('input#fs-tags').focus() true # list fuzzy searching root.matchesSearchString = (list, filter) -> # if there's no filter, return true if !filter return true # make filter lowercase filter = filter.toLowerCase() # create a corpus of the important parts of each list item corpus = _.compact _.map([ 'name' 'desc' 'tags' ], (key) -> JSON.stringify list[key] ).join(' ').toLowerCase().split /[ ,\[\]"-]/gi # how many matching words are there between the corpus # and the filter string? score = _.intersection(corpus, filter.split(' ')).length score > 0 ######### # Deals # ######### # combine all shop deals into one master array root.getDeals = -> # get all shop tags tags = _.filter root.tags, (t) -> t.name.indexOf('shop-') isnt -1 # get deals for each specified shop tag _.each tags, (t) -> Shop.doCache t.name.slice(5), (d) -> if d and d.deals dealsToAdd = _.map d.deals, (e) -> e.shop = t.name.slice(5) e root.deals = root.deals.concat(dealsToAdd) root.findDeals = (name) -> _.filter root.deals, (d) -> d.relatesTo.indexOf(name) != -1
true
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### 'use strict'; # foodstuff controller @app.controller 'FsController', ($scope, $routeParams, FoodStuff, Shop, Tag, $rootScope, $modal) -> root = $scope root.isData = false # get all tags Tag.query (tags) -> root.tags = tags root.getDeals() # deal storage root.deals = [] # place to store incoming list data root.newFs = {} # foodstuff drawer root.foodstuffhidden = true # get all foodstuffs, initially... FoodStuff.query (all) -> root.isData = true # no refresh spinner root.foodstuffs = all # add new foodstuff root.add = (fs) -> # format tags correctly fs.tags = fs.tags or (fs.pretags or "").split(' ') # make sure $ amount doesn't start with a $ fs.price = fs.price.substr(1) if fs.price[0] is '$' # add and push item to backend resource foodstuff = new FoodStuff fs foodstuff.$save -> root.foodstuffs.push fs # delete a foodstuff root.remove = (fs) -> FoodStuff.remove _id: fs._id, -> root.foodstuffs = _.without root.foodstuffs, fs # update a foodstuff price / tags / other attribute root.update = (list, pretags="") -> # format tags list.tags = pretags.split ' ' if pretags.length # update list on backend FoodStuff.update list, -> # close modal $("#edit-foodstuff-#{list._id}").modal 'hide' # add the tag, and delimit it with spaces root.addTagToNewFoodstuff = (tag) -> root.newFs.pretags = (root.newFs.pretags or '') + ' ' + tag root.newFs.pretags = root.newFs.pretags.trim() $('input#fs-tags').focus() true # list fuzzy searching root.matchesSearchString = (list, filter) -> # if there's no filter, return true if !filter return true # make filter lowercase filter = filter.toLowerCase() # create a corpus of the important parts of each list item corpus = _.compact _.map([ 'name' 'desc' 'tags' ], (key) -> JSON.stringify list[key] ).join(' ').toLowerCase().split /[ ,\[\]"-]/gi # how many matching words are there between the corpus # and the filter string? score = _.intersection(corpus, filter.split(' ')).length score > 0 ######### # Deals # ######### # combine all shop deals into one master array root.getDeals = -> # get all shop tags tags = _.filter root.tags, (t) -> t.name.indexOf('shop-') isnt -1 # get deals for each specified shop tag _.each tags, (t) -> Shop.doCache t.name.slice(5), (d) -> if d and d.deals dealsToAdd = _.map d.deals, (e) -> e.shop = t.name.slice(5) e root.deals = root.deals.concat(dealsToAdd) root.findDeals = (name) -> _.filter root.deals, (d) -> d.relatesTo.indexOf(name) != -1
[ { "context": "topology\n\n properties =\n listenOn: \"tcp://127.0.0.1:1221\",\n broadcastOn: \"tcp://127.0.0.1:2998\",", "end": 1915, "score": 0.9991652369499207, "start": 1906, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "\"tcp://127.0.0.1:1221\",\n b...
test/hUnsubscribe.coffee
fredpottier/hubiquitus
2
# # * Copyright (c) Novedia Group 2012. # * # * This file is part of Hubiquitus # * # * 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. # * # * You should have received a copy of the MIT License along with Hubiquitus. # * If not, see <http://opensource.org/licenses/mit-license.php>. # should = require("should") config = require("./_config") # # NEEDS BEFORE hSubscribe # describe "hUnsubscribe", -> cmd = undefined hActor = undefined hChannel = undefined status = require("../lib/codes").hResultStatus Actor = require "../lib/actors/hactor" existingCHID = "urn:localhost:#{config.getUUID()}" existingCHID2 = "urn:localhost:#{config.getUUID()}" before () -> topology = { actor: config.logins[0].urn, type: "hactor" } hActor = new Actor topology properties = listenOn: "tcp://127.0.0.1:1221", broadcastOn: "tcp://127.0.0.1:2998", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "test" }, collection: existingCHID.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child properties = listenOn: "tcp://127.0.0.1:2112", broadcastOn: "tcp://127.0.0.1:8992", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "test" }, collection: existingCHID2.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child after () -> hActor.h_tearDown() hActor = null #Subscribe to channel before (done) -> hActor.subscribe existingCHID, "",(statusCode) -> statusCode.should.be.equal(status.OK) done() it "should return hResult error MISSING_ATTR when actor is missing", (done) -> hActor.unsubscribe undefined, (statuses, result) -> statuses.should.be.equal(status.MISSING_ATTR) result.should.match(/channel/) done() it "should return hResult error NOT_AVAILABLE with actor not a channel", (done) -> hActor.unsubscribe hActor.actor, (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) done() it "should return hResult NOT_AVAILABLE if not subscribed and no subscriptions", (done) -> hActor.unsubscribe existingCHID2, (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) result.should.match(/not subscribed/) done() it "should return hResult OK when correct", (done) -> hActor.unsubscribe existingCHID, (statuses, result) -> statuses.should.be.equal(status.OK) done() describe "hUnsubscribe with quickFilter", -> #Subscribe to channel with quickfilter before (done) -> hActor.subscribe existingCHID, "quickfilter1",(statusCode) -> statusCode.should.be.equal(status.OK) done() before (done) -> hActor.subscribe existingCHID, "quickfilter2",(statusCode) -> statusCode.should.be.equal(status.OK) done() it "should return hResult OK if removed correctly a quickfilter", (done) -> hActor.unsubscribe existingCHID, "quickfilter1", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("QuickFilter removed") done() it "should return hResult OK if unsubscribe after removed the last quickfilter", (done) -> hActor.unsubscribe existingCHID, "quickfilter2", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("Unsubscribe from channel") done()
67312
# # * Copyright (c) Novedia Group 2012. # * # * This file is part of Hubiquitus # * # * 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. # * # * You should have received a copy of the MIT License along with Hubiquitus. # * If not, see <http://opensource.org/licenses/mit-license.php>. # should = require("should") config = require("./_config") # # NEEDS BEFORE hSubscribe # describe "hUnsubscribe", -> cmd = undefined hActor = undefined hChannel = undefined status = require("../lib/codes").hResultStatus Actor = require "../lib/actors/hactor" existingCHID = "urn:localhost:#{config.getUUID()}" existingCHID2 = "urn:localhost:#{config.getUUID()}" before () -> topology = { actor: config.logins[0].urn, type: "hactor" } hActor = new Actor topology properties = listenOn: "tcp://127.0.0.1:1221", broadcastOn: "tcp://127.0.0.1:2998", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "<NAME>" }, collection: existingCHID.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child properties = listenOn: "tcp://127.0.0.1:2112", broadcastOn: "tcp://127.0.0.1:8992", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "<NAME>" }, collection: existingCHID2.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child after () -> hActor.h_tearDown() hActor = null #Subscribe to channel before (done) -> hActor.subscribe existingCHID, "",(statusCode) -> statusCode.should.be.equal(status.OK) done() it "should return hResult error MISSING_ATTR when actor is missing", (done) -> hActor.unsubscribe undefined, (statuses, result) -> statuses.should.be.equal(status.MISSING_ATTR) result.should.match(/channel/) done() it "should return hResult error NOT_AVAILABLE with actor not a channel", (done) -> hActor.unsubscribe hActor.actor, (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) done() it "should return hResult NOT_AVAILABLE if not subscribed and no subscriptions", (done) -> hActor.unsubscribe existingCHID2, (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) result.should.match(/not subscribed/) done() it "should return hResult OK when correct", (done) -> hActor.unsubscribe existingCHID, (statuses, result) -> statuses.should.be.equal(status.OK) done() describe "hUnsubscribe with quickFilter", -> #Subscribe to channel with quickfilter before (done) -> hActor.subscribe existingCHID, "quickfilter1",(statusCode) -> statusCode.should.be.equal(status.OK) done() before (done) -> hActor.subscribe existingCHID, "quickfilter2",(statusCode) -> statusCode.should.be.equal(status.OK) done() it "should return hResult OK if removed correctly a quickfilter", (done) -> hActor.unsubscribe existingCHID, "quickfilter1", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("QuickFilter removed") done() it "should return hResult OK if unsubscribe after removed the last quickfilter", (done) -> hActor.unsubscribe existingCHID, "quickfilter2", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("Unsubscribe from channel") done()
true
# # * Copyright (c) Novedia Group 2012. # * # * This file is part of Hubiquitus # * # * 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. # * # * You should have received a copy of the MIT License along with Hubiquitus. # * If not, see <http://opensource.org/licenses/mit-license.php>. # should = require("should") config = require("./_config") # # NEEDS BEFORE hSubscribe # describe "hUnsubscribe", -> cmd = undefined hActor = undefined hChannel = undefined status = require("../lib/codes").hResultStatus Actor = require "../lib/actors/hactor" existingCHID = "urn:localhost:#{config.getUUID()}" existingCHID2 = "urn:localhost:#{config.getUUID()}" before () -> topology = { actor: config.logins[0].urn, type: "hactor" } hActor = new Actor topology properties = listenOn: "tcp://127.0.0.1:1221", broadcastOn: "tcp://127.0.0.1:2998", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "PI:NAME:<NAME>END_PI" }, collection: existingCHID.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child properties = listenOn: "tcp://127.0.0.1:2112", broadcastOn: "tcp://127.0.0.1:8992", subscribers: [config.logins[0].urn], db:{ host: "localhost", port: 27017, name: "PI:NAME:<NAME>END_PI" }, collection: existingCHID2.replace(/[-.]/g, "") hActor.createChild "hchannel", "inproc", {actor: existingCHID, type : "hActor", properties: properties}, (child) => hChannel = child after () -> hActor.h_tearDown() hActor = null #Subscribe to channel before (done) -> hActor.subscribe existingCHID, "",(statusCode) -> statusCode.should.be.equal(status.OK) done() it "should return hResult error MISSING_ATTR when actor is missing", (done) -> hActor.unsubscribe undefined, (statuses, result) -> statuses.should.be.equal(status.MISSING_ATTR) result.should.match(/channel/) done() it "should return hResult error NOT_AVAILABLE with actor not a channel", (done) -> hActor.unsubscribe hActor.actor, (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) done() it "should return hResult NOT_AVAILABLE if not subscribed and no subscriptions", (done) -> hActor.unsubscribe existingCHID2, (statuses, result) -> statuses.should.be.equal(status.NOT_AVAILABLE) result.should.match(/not subscribed/) done() it "should return hResult OK when correct", (done) -> hActor.unsubscribe existingCHID, (statuses, result) -> statuses.should.be.equal(status.OK) done() describe "hUnsubscribe with quickFilter", -> #Subscribe to channel with quickfilter before (done) -> hActor.subscribe existingCHID, "quickfilter1",(statusCode) -> statusCode.should.be.equal(status.OK) done() before (done) -> hActor.subscribe existingCHID, "quickfilter2",(statusCode) -> statusCode.should.be.equal(status.OK) done() it "should return hResult OK if removed correctly a quickfilter", (done) -> hActor.unsubscribe existingCHID, "quickfilter1", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("QuickFilter removed") done() it "should return hResult OK if unsubscribe after removed the last quickfilter", (done) -> hActor.unsubscribe existingCHID, "quickfilter2", (statuses, result) -> statuses.should.be.equal(status.OK) result.should.be.equal("Unsubscribe from channel") done()
[ { "context": "el: 'remote'\n sudo: true\n ssh:\n host: '127.0.0.1', username: process.env.USER,\n private_key_p", "end": 302, "score": 0.9997696280479431, "start": 293, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "sername: process.env.USER,\n privat...
packages/service/env/ubuntu/test.coffee
wdavidw/node-mecano
0
module.exports = tags: service_install: true service_startup: true service_systemctl: false service: name: 'nginx-light' srv_name: 'nginx' chk_name: 'nginx' config: [ label: 'local' sudo: true , label: 'remote' sudo: true ssh: host: '127.0.0.1', username: process.env.USER, private_key_path: '~/.ssh/id_ed25519' ]
169766
module.exports = tags: service_install: true service_startup: true service_systemctl: false service: name: 'nginx-light' srv_name: 'nginx' chk_name: 'nginx' config: [ label: 'local' sudo: true , label: 'remote' sudo: true ssh: host: '127.0.0.1', username: process.env.USER, private_key_path: <KEY>' ]
true
module.exports = tags: service_install: true service_startup: true service_systemctl: false service: name: 'nginx-light' srv_name: 'nginx' chk_name: 'nginx' config: [ label: 'local' sudo: true , label: 'remote' sudo: true ssh: host: '127.0.0.1', username: process.env.USER, private_key_path: PI:KEY:<KEY>END_PI' ]
[ { "context": " Chaplin.EventBroker.publishEvent 'tell_user', 'Brak kontaktu z serwerem'\n @publishEvent('log:debug', \"s", "end": 8458, "score": 0.9787797331809998, "start": 8445, "tag": "NAME", "value": "Brak kontaktu" } ]
app/views/list-view.coffee
zzart/mp_old
0
View = require 'views/base/view' #SubView = require 'views/list-items-view' NavigationView = require 'views/navigation-view' mediator = require 'mediator' module.exports = class ListView extends View autoRender: true containerMethod: "html" #attributes: { 'data-role':'content' } initialize: (params) -> super @params = params id: params.id or 'content' #params.id for subview or content for all rest className: "iu-#{params.class}" or 'ui-content' # the same as above @filter = {} @selected_items = [] @mobile = params.mobile or bowser.mobile @route_params = @params.route_params ? false @selected_items_pictures = {} # to keep icons of selected items @collection_hard = @params.collection # @collection = @params.collection @collection = _.clone(@params.collection) @listing_type = @params.listing_type ? false @navigation = require "views/templates/#{@params.template}_navigation" # when we on mobile we want lists and not tables if @mobile # look for mobile template and use default if not found try @template = require "views/templates/#{@params.template}_mobile" catch e @publishEvent('log:debug', "#{e} template not found. Going with non-mobile template") @template = require "views/templates/#{@params.template}" else @template = require "views/templates/#{@params.template}" # NOTE: this catches clicks from navigation subview! @subscribeEvent('navigation:refresh', @refresh_action) @subscribeEvent('navigation:search_reveal', @search_reveal_action) @subscribeEvent('navigation:filter_action', @filter_action) @subscribeEvent('navigation:query_action', @query_action) @subscribeEvent('navigation:select_action', @select_action) @delegate 'change', '#all', @select_all_action @delegate 'change', ':checkbox', @select_items #@delegate 'change', ':checkbox', @open_right_panel @delegate 'click', 'a', @select_single #@delegate 'click', ".ui-table-columntoggle-btn", @column_action #@delegate 'tablecreate' , @table_create #for column toggle #@delegate 'click', "[href='#list-table-popup']", @open_column_popup @publishEvent('log:debug', @params) @navigation_rendered = false # --- debug window._col_hard = @collection_hard if mediator.online is false window._col = @collection if mediator.online is false window._route_params = @route_params if mediator.online is false #init_events: => # @delegate 'click', ".ui-table-columntoggle-btn", @column_action # @delegate 'click', "[href='#list-table-popup']", @column_action filter_action: (event) => @publishEvent("log:debug", "filter_action_called") # event.stopPropagation() # event.stopImmediatePropagation() # always start with fresh collection @collection = _.clone(@collection_hard) # needs data-filter attribute on select emelemt # we can apply one or more filters key = event.target.dataset.filter id = event.target.id @undelegate 'change', "##{id}", @filter_action #@unsubscribeEvent('navigation:filter_action', @) #for booleans if event.target.type == 'checkbox' @publishEvent("log:info", event.target.type ) value = event.target.checked else if event.target.type == 'select-one' @publishEvent("log:info", event.target.type ) value = parseInt(event.target.value) else value = event.target.value if _.isNaN(value) @filter = _.omit(@filter, key) @publishEvent("log:info", "omiting #{key}" ) @publishEvent("log:info", @filter) else @filter[key] = value @publishEvent('log:debug', key) @publishEvent('log:debug', value) # console.log(@filter) if _.isEmpty(@filter) #TODO: test this @render() else list_of_models = @collection_hard.where(@filter) @collection.reset(list_of_models) #$("input[type='radio'] ##{id}" ).prop( "checked", value ).checkboxradio( "refresh" ) #$("input[type='checkbox'] ##{id}" ).prop( "checked", value ).checkboxradio( "refresh" ) @render() query_action: (event) => @publishEvent("log:debug", "query_action called") #reset filter @filter= {} # NOTE: to be inherited from list views selects_refresh: => if @collection.query for k,v of @collection.query $("[data-query=\'#{k}\']").val(v) $("[data-query=\'#{k}\']").selectmenu('refresh') select_items: (e) => # for checkboxes to bring some sanity into the world # everytime a checkbox is checked we need to adjust @selected_items array @publishEvent("log:debug", "select_items called") @selected_items = [] self = @ selected = $("#list-table>tbody input:checked") for i in selected if $(i).attr('id') isnt 'all' self.selected_items.push($(i).attr('id')) @selected_items = _.uniq(@selected_items) @publishEvent("log:debug", "select_items array #{@selected_items}") select_single: (e) => if e.target.tagName is 'IMG' e.preventDefault() @publishEvent("log:debug", "IMG click!") id = parseInt(e.currentTarget.dataset.id) if _.contains(@selected_items, id) #get its index index = @selected_items.indexOf(id) #remove it from array (index , number of items after) @selected_items.splice(index, 1) $(e.target).replaceWith(@selected_items_pictures[id]) @publishEvent("log:debug", "Removed from selected_items list: #{@selected_items}") #TODO: change image to something else else i = new Image() i.src = @get_image() #save picture for unchecks @selected_items_pictures[id] = $(e.target) $(e.target).replaceWith(i) @selected_items.push(id) @publishEvent("log:debug", "moved to selected_items list: #{@selected_items}") @publishEvent("log:debug", "replaced #{@selected_items}") @selected_items = _.uniq(@selected_items) @publishEvent("log:debug", "with #{@selected_items}") select_all_action: => @publishEvent('jqm_refersh:render') # need this - jqm has to annoyingly initalize checkboxes @publishEvent("log:debug", "select all action") selected = $('#list-table>thead input:checkbox').prop('checked') $('#list-table>tbody input:checkbox').prop('checked', selected).checkboxradio("refresh") open_right_panel: (event) => # NOT USED !!!! #@publishEvent("log:debug", "open_right_panel") #if $(event.target).is(':checked') # @publishEvent('rightpanel:open') filter_apply: => @publishEvent('log:debug', 'filter apply') #TODO: doesn't work for multiple filter objects if obj[@filter] isnt false @publishEvent("log:info", obj) @publishEvent('log:debug', 'filter apply') list_of_models = @collection_hard.where(obj) @collection.reset(list_of_models) else @publishEvent('log:debug', 'filter reset') @collection = _.clone(@collection_hard) @render() refresh_action: (e) => e.preventDefault() @publishEvent('log:debug', 'refresh_action cougth') @collection_hard.fetch data: @collection_hard.query or {} success: => @publishEvent 'tell_user', 'Odświeżam listę elementów' @collection = _.clone(@collection_hard) @render() error:(model, response, options) => if response.responseJSON? Chaplin.EventBroker.publishEvent 'tell_user', response.responseJSON['title'] else Chaplin.EventBroker.publishEvent 'tell_user', 'Brak kontaktu z serwerem' @publishEvent('log:debug', "selected_items : #{@selected_items}") search_reveal_action: (e) => e.preventDefault() @publishEvent('log:debug', 'search_reveal_action cougth') #toggle() isn't supported anymore $("#search-list").css('display', 'block') getTemplateData: => collection: @collection.toJSON() listing_type: @listing_type agents: localStorage.getObjectNames('agents') clients: localStorage.getObjectNames('clients') branches: localStorage.getObject('branches') render: => super #remove any previously created table column toggle popups ( important for new rendering ) #$("#list-table-popup").remove() #$("#list-table-popup-popup").remove() if @navigation_rendered is false @render_subview() render_subview: => @publishEvent('log:debug', "render sub_view with #{@params.template}") @subview "navigation", new NavigationView template: @navigation, listing_type: @listing_type @subview("navigation").render() @publishEvent('jqm_refersh:render') #so we only render nav once ! @navigation_rendered = true attach: => super @publishEvent('log:debug', 'view: list-view afterRender()') #initialize sorting tables http://tablesorter.com/docs/ #można sortować wielokolumnowo przytrzymując shift ;) @publishEvent('log:info', "collection has a length of : #{@collection.length}") if @collection.length >= 1 $("#list-table").tablesorter({sortList:[[4,0]], headers:{0:{'sorter':false}, 1:{'sorter':false}}}) # @publishEvent 'tell_user', 'Nic nie znaleźiono!<br />Aby dodać pierwszy element naciśnij <a class="ui-btn ui-shadow ui-corner-all ui-icon-edit ui-btn-icon-notext ui-btn-inline">Dodaj</a>' @publishEvent('jqm_refersh:render') @selects_refresh() @publishEvent 'table_refresh' clean_after_action: => @publishEvent("log:debug", "clean_after_action called") if bowser.mobile? isnt true # for table THEAD # @publishEvent('rightpanel:close') # for JQM so it doesn't complain $('#list-table>tbody').enhanceWithin() #Once action is done clear selected items checkboxes $('#list-table>tbody input:checkbox').prop('checked', false).checkboxradio("refresh") # Clear dropdown menu $("#select-action :selected").removeAttr('selected') # this should work but it doesn't #$("#select-action option:first").attr('selected', 'selected') # this seem to work instead $("#select-action").val('') # refresh dropdown $("#select-action").selectmenu('refresh') @publishEvent('jqm_refersh:render') #restore all icons for key, val of @selected_items_pictures $("[data-id=#{key}] img").replaceWith(@selected_items_pictures[key]) #clear data @selected_items = [] @selected_items_pictures = [] if @collection.length = 0 $("#list-table").tablesorter() select_action: (event) => @publishEvent("log:debug", "select_action with selected_items : #{@selected_items}") self = @ @publishEvent('log:debug', "performing action #{event.target.value} for offers #{self.selected_items}") if self.selected_items.length > 0 if event.target.value == 'usun' $("#confirm").popup('open') # unbind is for stopping it firing multiple times $("#confirmed").unbind().click -> for id in self.selected_items model = self.collection_hard.get(id) #model = mediator.collections.branches.get($(i).attr('id')) # TODO: przepisać oferty tego brancha do innego ? model.destroy # we would like confirmation from server before removing it from the collection wait: true success: (event) => Chaplin.EventBroker.publishEvent('log:info', "Element usunięty id#{model.get('id')}") self.collection_hard.remove(model) self.render() Chaplin.EventBroker.publishEvent 'tell_user', 'Element został usunięty' error:(model, response, options) => if response.responseJSON? Chaplin.EventBroker.publishEvent 'tell_user', response.responseJSON['title'] else Chaplin.EventBroker.publishEvent 'tell_user', 'Brak kontaktu z serwerem' # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() #clean only after the CLICK event self.clean_after_action() if event.target.value == 'wygeneruj_ids' @model = @collection.models[0] for id in self.selected_items url = "#{@model.urlRoot}/odswiez_ids/#{id}" @mp_request(@model, url, 'GET', 'Wszystkie numery ID dla tego oddzaiłu zostaną ponownie wygenerowane a oferty zaznaczone do całościowych eksportów. To może potrwać ok. 2 minuty.') $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'zmien_agenta' str = "" for agent in localStorage.getObject('agents') str = "#{str}<li value='#{agent.id}' data-filtertext='#{agent.first_name} #{agent.surname} #{agent.username} #{agent.email}'><a id='#{agent.id}'>#{agent.first_name} #{agent.surname}</a></li>" val = """<h5>Wybierz Agenta</h5> <form class='ui-filterable'> <input id='agent-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='agent-choose' data-filter='true' data-input='#agent-choose-input' >#{str}</ul>""" $('#popgeneric').html(val) $ul = $("#popgeneric") try $ul.enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#agent-choose li").unbind().click -> $('#popgeneric').popup('close') # inside click f() we can reference attributes of element # on which click was established # so @value is list item 'value' attribute for id in self.selected_items # TODO: this might take a while so we could do progress bar of some sorts.... #console.log(@value, id) model = self.collection_hard.get(id) # add query params so that server knows that we INTEND to change owner # set (change:agent) will trigger sync on model model.set('agent', @value) # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() # show client a listing if event.target.value == 'show-listing-client' str = "" for client in localStorage.getObject('clients') str = "#{str}<li value='#{client.id}' data-filtertext='#{client.first_name} #{client.surname} #{client.email} #{client.notes} #{client.pesel} #{client.phone} #{client.company_name} #{client.requirements}'><a id='#{client.id}'>#{client.first_name} #{client.surname}</a></li>" val = """<h5>Wybierz Klienta</h5> <form class='ui-filterable'><input id='client-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='client-choose' data-filter='true' data-input='#client-choose-input' >#{str}</ul>""" try $('#popgeneric').html(val).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#client-choose li").unbind().click -> $('#popgeneric').popup('close') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items # console.log(@value, i.id) model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/pokaz/#{@value}" self.mp_request(model, url, 'GET', 'Oferta zaznaczona do pokazania') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() # send email to client if event.target.value == 'send-listing-client' str = "" for client in localStorage.getObject('clients') str = "#{str}<li value='#{client.id}' data-filtertext='#{client.first_name} #{client.surname} #{client.email} #{client.notes} #{client.pesel} #{client.phone} #{client.company_name} #{client.requirements}'><a id='#{client.id}'>#{client.first_name} #{client.surname}</a></li>" val = """<h5>Wybierz Klienta</h5> <form class='ui-filterable'><input id='client-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='client-choose' data-filter='true' data-input='#client-choose-input' >#{str}</ul>""" try $('#popgeneric').html(val).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#client-choose li").unbind().click -> $('#popgeneric').popup('close') self.publishEvent("tell_user", 'Przygotowuje email...') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items # console.log(@value, i.id) model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/email/#{@value}?private=false" self.mp_request(model, url, 'GET', 'Email został wysłany') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'send-listing-address' form = ''' <form> <label for="email_send" class="ui-hidden-accessible">Email:</label> <input name="email_send" id="email_send" placeholder="Wprowadź email" value="" type="text" /> <button data-icon="mail" id="address_submit">Wyślij</button> </form> ''' try $('#popgeneric').html(form).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # # unbind is for stopping it firing multiple times $("#address_submit").unbind().click (e)-> e.preventDefault() $('#popgeneric').popup('close') self.publishEvent("tell_user", 'Przygotowuje email...') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/email/#{$("#email_send").val()}?private=false" self.mp_request(model, url, 'GET', 'Email został wysłany') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'wydruk-wewnetrzny' or event.target.value == 'wydruk-klienta' # get model for id in self.selected_items model = @collection_hard.get(id) if event.target.value == 'wydruk-wewnetrzny' url = "#{model.urlRoot}/#{id}/#{mediator.models.user.get('company_name')}?private=true" if event.target.value == 'wydruk-klienta' url = "#{model.urlRoot}/#{id}/#{mediator.models.user.get('company_name')}?private=false" # NOTE: instead of doing ajax request we need to do window.location # and set the right db # Ajax would just swallow the response from serwer ..... window.location = url # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() else @publishEvent 'tell_user', 'Musisz zaznaczyć przynajmniej jeden element!' self.clean_after_action() #column_action: (event) => # console.log('click') # event.preventDefault() # $("#list-table-popup").popup('open') #table_create: (event) => # @publishEvent 'table_refresh' # window.collection = @collection_hard #open_column_popup:(event) => # @publishEvent("log:debug", "coumn toggle popup") # event.preventDefault() # $('#list-table-popup').popup('open')
171782
View = require 'views/base/view' #SubView = require 'views/list-items-view' NavigationView = require 'views/navigation-view' mediator = require 'mediator' module.exports = class ListView extends View autoRender: true containerMethod: "html" #attributes: { 'data-role':'content' } initialize: (params) -> super @params = params id: params.id or 'content' #params.id for subview or content for all rest className: "iu-#{params.class}" or 'ui-content' # the same as above @filter = {} @selected_items = [] @mobile = params.mobile or bowser.mobile @route_params = @params.route_params ? false @selected_items_pictures = {} # to keep icons of selected items @collection_hard = @params.collection # @collection = @params.collection @collection = _.clone(@params.collection) @listing_type = @params.listing_type ? false @navigation = require "views/templates/#{@params.template}_navigation" # when we on mobile we want lists and not tables if @mobile # look for mobile template and use default if not found try @template = require "views/templates/#{@params.template}_mobile" catch e @publishEvent('log:debug', "#{e} template not found. Going with non-mobile template") @template = require "views/templates/#{@params.template}" else @template = require "views/templates/#{@params.template}" # NOTE: this catches clicks from navigation subview! @subscribeEvent('navigation:refresh', @refresh_action) @subscribeEvent('navigation:search_reveal', @search_reveal_action) @subscribeEvent('navigation:filter_action', @filter_action) @subscribeEvent('navigation:query_action', @query_action) @subscribeEvent('navigation:select_action', @select_action) @delegate 'change', '#all', @select_all_action @delegate 'change', ':checkbox', @select_items #@delegate 'change', ':checkbox', @open_right_panel @delegate 'click', 'a', @select_single #@delegate 'click', ".ui-table-columntoggle-btn", @column_action #@delegate 'tablecreate' , @table_create #for column toggle #@delegate 'click', "[href='#list-table-popup']", @open_column_popup @publishEvent('log:debug', @params) @navigation_rendered = false # --- debug window._col_hard = @collection_hard if mediator.online is false window._col = @collection if mediator.online is false window._route_params = @route_params if mediator.online is false #init_events: => # @delegate 'click', ".ui-table-columntoggle-btn", @column_action # @delegate 'click', "[href='#list-table-popup']", @column_action filter_action: (event) => @publishEvent("log:debug", "filter_action_called") # event.stopPropagation() # event.stopImmediatePropagation() # always start with fresh collection @collection = _.clone(@collection_hard) # needs data-filter attribute on select emelemt # we can apply one or more filters key = event.target.dataset.filter id = event.target.id @undelegate 'change', "##{id}", @filter_action #@unsubscribeEvent('navigation:filter_action', @) #for booleans if event.target.type == 'checkbox' @publishEvent("log:info", event.target.type ) value = event.target.checked else if event.target.type == 'select-one' @publishEvent("log:info", event.target.type ) value = parseInt(event.target.value) else value = event.target.value if _.isNaN(value) @filter = _.omit(@filter, key) @publishEvent("log:info", "omiting #{key}" ) @publishEvent("log:info", @filter) else @filter[key] = value @publishEvent('log:debug', key) @publishEvent('log:debug', value) # console.log(@filter) if _.isEmpty(@filter) #TODO: test this @render() else list_of_models = @collection_hard.where(@filter) @collection.reset(list_of_models) #$("input[type='radio'] ##{id}" ).prop( "checked", value ).checkboxradio( "refresh" ) #$("input[type='checkbox'] ##{id}" ).prop( "checked", value ).checkboxradio( "refresh" ) @render() query_action: (event) => @publishEvent("log:debug", "query_action called") #reset filter @filter= {} # NOTE: to be inherited from list views selects_refresh: => if @collection.query for k,v of @collection.query $("[data-query=\'#{k}\']").val(v) $("[data-query=\'#{k}\']").selectmenu('refresh') select_items: (e) => # for checkboxes to bring some sanity into the world # everytime a checkbox is checked we need to adjust @selected_items array @publishEvent("log:debug", "select_items called") @selected_items = [] self = @ selected = $("#list-table>tbody input:checked") for i in selected if $(i).attr('id') isnt 'all' self.selected_items.push($(i).attr('id')) @selected_items = _.uniq(@selected_items) @publishEvent("log:debug", "select_items array #{@selected_items}") select_single: (e) => if e.target.tagName is 'IMG' e.preventDefault() @publishEvent("log:debug", "IMG click!") id = parseInt(e.currentTarget.dataset.id) if _.contains(@selected_items, id) #get its index index = @selected_items.indexOf(id) #remove it from array (index , number of items after) @selected_items.splice(index, 1) $(e.target).replaceWith(@selected_items_pictures[id]) @publishEvent("log:debug", "Removed from selected_items list: #{@selected_items}") #TODO: change image to something else else i = new Image() i.src = @get_image() #save picture for unchecks @selected_items_pictures[id] = $(e.target) $(e.target).replaceWith(i) @selected_items.push(id) @publishEvent("log:debug", "moved to selected_items list: #{@selected_items}") @publishEvent("log:debug", "replaced #{@selected_items}") @selected_items = _.uniq(@selected_items) @publishEvent("log:debug", "with #{@selected_items}") select_all_action: => @publishEvent('jqm_refersh:render') # need this - jqm has to annoyingly initalize checkboxes @publishEvent("log:debug", "select all action") selected = $('#list-table>thead input:checkbox').prop('checked') $('#list-table>tbody input:checkbox').prop('checked', selected).checkboxradio("refresh") open_right_panel: (event) => # NOT USED !!!! #@publishEvent("log:debug", "open_right_panel") #if $(event.target).is(':checked') # @publishEvent('rightpanel:open') filter_apply: => @publishEvent('log:debug', 'filter apply') #TODO: doesn't work for multiple filter objects if obj[@filter] isnt false @publishEvent("log:info", obj) @publishEvent('log:debug', 'filter apply') list_of_models = @collection_hard.where(obj) @collection.reset(list_of_models) else @publishEvent('log:debug', 'filter reset') @collection = _.clone(@collection_hard) @render() refresh_action: (e) => e.preventDefault() @publishEvent('log:debug', 'refresh_action cougth') @collection_hard.fetch data: @collection_hard.query or {} success: => @publishEvent 'tell_user', 'Odświeżam listę elementów' @collection = _.clone(@collection_hard) @render() error:(model, response, options) => if response.responseJSON? Chaplin.EventBroker.publishEvent 'tell_user', response.responseJSON['title'] else Chaplin.EventBroker.publishEvent 'tell_user', '<NAME> z serwerem' @publishEvent('log:debug', "selected_items : #{@selected_items}") search_reveal_action: (e) => e.preventDefault() @publishEvent('log:debug', 'search_reveal_action cougth') #toggle() isn't supported anymore $("#search-list").css('display', 'block') getTemplateData: => collection: @collection.toJSON() listing_type: @listing_type agents: localStorage.getObjectNames('agents') clients: localStorage.getObjectNames('clients') branches: localStorage.getObject('branches') render: => super #remove any previously created table column toggle popups ( important for new rendering ) #$("#list-table-popup").remove() #$("#list-table-popup-popup").remove() if @navigation_rendered is false @render_subview() render_subview: => @publishEvent('log:debug', "render sub_view with #{@params.template}") @subview "navigation", new NavigationView template: @navigation, listing_type: @listing_type @subview("navigation").render() @publishEvent('jqm_refersh:render') #so we only render nav once ! @navigation_rendered = true attach: => super @publishEvent('log:debug', 'view: list-view afterRender()') #initialize sorting tables http://tablesorter.com/docs/ #można sortować wielokolumnowo przytrzymując shift ;) @publishEvent('log:info', "collection has a length of : #{@collection.length}") if @collection.length >= 1 $("#list-table").tablesorter({sortList:[[4,0]], headers:{0:{'sorter':false}, 1:{'sorter':false}}}) # @publishEvent 'tell_user', 'Nic nie znaleźiono!<br />Aby dodać pierwszy element naciśnij <a class="ui-btn ui-shadow ui-corner-all ui-icon-edit ui-btn-icon-notext ui-btn-inline">Dodaj</a>' @publishEvent('jqm_refersh:render') @selects_refresh() @publishEvent 'table_refresh' clean_after_action: => @publishEvent("log:debug", "clean_after_action called") if bowser.mobile? isnt true # for table THEAD # @publishEvent('rightpanel:close') # for JQM so it doesn't complain $('#list-table>tbody').enhanceWithin() #Once action is done clear selected items checkboxes $('#list-table>tbody input:checkbox').prop('checked', false).checkboxradio("refresh") # Clear dropdown menu $("#select-action :selected").removeAttr('selected') # this should work but it doesn't #$("#select-action option:first").attr('selected', 'selected') # this seem to work instead $("#select-action").val('') # refresh dropdown $("#select-action").selectmenu('refresh') @publishEvent('jqm_refersh:render') #restore all icons for key, val of @selected_items_pictures $("[data-id=#{key}] img").replaceWith(@selected_items_pictures[key]) #clear data @selected_items = [] @selected_items_pictures = [] if @collection.length = 0 $("#list-table").tablesorter() select_action: (event) => @publishEvent("log:debug", "select_action with selected_items : #{@selected_items}") self = @ @publishEvent('log:debug', "performing action #{event.target.value} for offers #{self.selected_items}") if self.selected_items.length > 0 if event.target.value == 'usun' $("#confirm").popup('open') # unbind is for stopping it firing multiple times $("#confirmed").unbind().click -> for id in self.selected_items model = self.collection_hard.get(id) #model = mediator.collections.branches.get($(i).attr('id')) # TODO: przepisać oferty tego brancha do innego ? model.destroy # we would like confirmation from server before removing it from the collection wait: true success: (event) => Chaplin.EventBroker.publishEvent('log:info', "Element usunięty id#{model.get('id')}") self.collection_hard.remove(model) self.render() Chaplin.EventBroker.publishEvent 'tell_user', 'Element został usunięty' error:(model, response, options) => if response.responseJSON? Chaplin.EventBroker.publishEvent 'tell_user', response.responseJSON['title'] else Chaplin.EventBroker.publishEvent 'tell_user', 'Brak kontaktu z serwerem' # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() #clean only after the CLICK event self.clean_after_action() if event.target.value == 'wygeneruj_ids' @model = @collection.models[0] for id in self.selected_items url = "#{@model.urlRoot}/odswiez_ids/#{id}" @mp_request(@model, url, 'GET', 'Wszystkie numery ID dla tego oddzaiłu zostaną ponownie wygenerowane a oferty zaznaczone do całościowych eksportów. To może potrwać ok. 2 minuty.') $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'zmien_agenta' str = "" for agent in localStorage.getObject('agents') str = "#{str}<li value='#{agent.id}' data-filtertext='#{agent.first_name} #{agent.surname} #{agent.username} #{agent.email}'><a id='#{agent.id}'>#{agent.first_name} #{agent.surname}</a></li>" val = """<h5>Wybierz Agenta</h5> <form class='ui-filterable'> <input id='agent-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='agent-choose' data-filter='true' data-input='#agent-choose-input' >#{str}</ul>""" $('#popgeneric').html(val) $ul = $("#popgeneric") try $ul.enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#agent-choose li").unbind().click -> $('#popgeneric').popup('close') # inside click f() we can reference attributes of element # on which click was established # so @value is list item 'value' attribute for id in self.selected_items # TODO: this might take a while so we could do progress bar of some sorts.... #console.log(@value, id) model = self.collection_hard.get(id) # add query params so that server knows that we INTEND to change owner # set (change:agent) will trigger sync on model model.set('agent', @value) # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() # show client a listing if event.target.value == 'show-listing-client' str = "" for client in localStorage.getObject('clients') str = "#{str}<li value='#{client.id}' data-filtertext='#{client.first_name} #{client.surname} #{client.email} #{client.notes} #{client.pesel} #{client.phone} #{client.company_name} #{client.requirements}'><a id='#{client.id}'>#{client.first_name} #{client.surname}</a></li>" val = """<h5>Wybierz Klienta</h5> <form class='ui-filterable'><input id='client-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='client-choose' data-filter='true' data-input='#client-choose-input' >#{str}</ul>""" try $('#popgeneric').html(val).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#client-choose li").unbind().click -> $('#popgeneric').popup('close') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items # console.log(@value, i.id) model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/pokaz/#{@value}" self.mp_request(model, url, 'GET', 'Oferta zaznaczona do pokazania') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() # send email to client if event.target.value == 'send-listing-client' str = "" for client in localStorage.getObject('clients') str = "#{str}<li value='#{client.id}' data-filtertext='#{client.first_name} #{client.surname} #{client.email} #{client.notes} #{client.pesel} #{client.phone} #{client.company_name} #{client.requirements}'><a id='#{client.id}'>#{client.first_name} #{client.surname}</a></li>" val = """<h5>Wybierz Klienta</h5> <form class='ui-filterable'><input id='client-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='client-choose' data-filter='true' data-input='#client-choose-input' >#{str}</ul>""" try $('#popgeneric').html(val).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#client-choose li").unbind().click -> $('#popgeneric').popup('close') self.publishEvent("tell_user", 'Przygotowuje email...') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items # console.log(@value, i.id) model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/email/#{@value}?private=false" self.mp_request(model, url, 'GET', 'Email został wysłany') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'send-listing-address' form = ''' <form> <label for="email_send" class="ui-hidden-accessible">Email:</label> <input name="email_send" id="email_send" placeholder="Wprowadź email" value="" type="text" /> <button data-icon="mail" id="address_submit">Wyślij</button> </form> ''' try $('#popgeneric').html(form).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # # unbind is for stopping it firing multiple times $("#address_submit").unbind().click (e)-> e.preventDefault() $('#popgeneric').popup('close') self.publishEvent("tell_user", 'Przygotowuje email...') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/email/#{$("#email_send").val()}?private=false" self.mp_request(model, url, 'GET', 'Email został wysłany') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'wydruk-wewnetrzny' or event.target.value == 'wydruk-klienta' # get model for id in self.selected_items model = @collection_hard.get(id) if event.target.value == 'wydruk-wewnetrzny' url = "#{model.urlRoot}/#{id}/#{mediator.models.user.get('company_name')}?private=true" if event.target.value == 'wydruk-klienta' url = "#{model.urlRoot}/#{id}/#{mediator.models.user.get('company_name')}?private=false" # NOTE: instead of doing ajax request we need to do window.location # and set the right db # Ajax would just swallow the response from serwer ..... window.location = url # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() else @publishEvent 'tell_user', 'Musisz zaznaczyć przynajmniej jeden element!' self.clean_after_action() #column_action: (event) => # console.log('click') # event.preventDefault() # $("#list-table-popup").popup('open') #table_create: (event) => # @publishEvent 'table_refresh' # window.collection = @collection_hard #open_column_popup:(event) => # @publishEvent("log:debug", "coumn toggle popup") # event.preventDefault() # $('#list-table-popup').popup('open')
true
View = require 'views/base/view' #SubView = require 'views/list-items-view' NavigationView = require 'views/navigation-view' mediator = require 'mediator' module.exports = class ListView extends View autoRender: true containerMethod: "html" #attributes: { 'data-role':'content' } initialize: (params) -> super @params = params id: params.id or 'content' #params.id for subview or content for all rest className: "iu-#{params.class}" or 'ui-content' # the same as above @filter = {} @selected_items = [] @mobile = params.mobile or bowser.mobile @route_params = @params.route_params ? false @selected_items_pictures = {} # to keep icons of selected items @collection_hard = @params.collection # @collection = @params.collection @collection = _.clone(@params.collection) @listing_type = @params.listing_type ? false @navigation = require "views/templates/#{@params.template}_navigation" # when we on mobile we want lists and not tables if @mobile # look for mobile template and use default if not found try @template = require "views/templates/#{@params.template}_mobile" catch e @publishEvent('log:debug', "#{e} template not found. Going with non-mobile template") @template = require "views/templates/#{@params.template}" else @template = require "views/templates/#{@params.template}" # NOTE: this catches clicks from navigation subview! @subscribeEvent('navigation:refresh', @refresh_action) @subscribeEvent('navigation:search_reveal', @search_reveal_action) @subscribeEvent('navigation:filter_action', @filter_action) @subscribeEvent('navigation:query_action', @query_action) @subscribeEvent('navigation:select_action', @select_action) @delegate 'change', '#all', @select_all_action @delegate 'change', ':checkbox', @select_items #@delegate 'change', ':checkbox', @open_right_panel @delegate 'click', 'a', @select_single #@delegate 'click', ".ui-table-columntoggle-btn", @column_action #@delegate 'tablecreate' , @table_create #for column toggle #@delegate 'click', "[href='#list-table-popup']", @open_column_popup @publishEvent('log:debug', @params) @navigation_rendered = false # --- debug window._col_hard = @collection_hard if mediator.online is false window._col = @collection if mediator.online is false window._route_params = @route_params if mediator.online is false #init_events: => # @delegate 'click', ".ui-table-columntoggle-btn", @column_action # @delegate 'click', "[href='#list-table-popup']", @column_action filter_action: (event) => @publishEvent("log:debug", "filter_action_called") # event.stopPropagation() # event.stopImmediatePropagation() # always start with fresh collection @collection = _.clone(@collection_hard) # needs data-filter attribute on select emelemt # we can apply one or more filters key = event.target.dataset.filter id = event.target.id @undelegate 'change', "##{id}", @filter_action #@unsubscribeEvent('navigation:filter_action', @) #for booleans if event.target.type == 'checkbox' @publishEvent("log:info", event.target.type ) value = event.target.checked else if event.target.type == 'select-one' @publishEvent("log:info", event.target.type ) value = parseInt(event.target.value) else value = event.target.value if _.isNaN(value) @filter = _.omit(@filter, key) @publishEvent("log:info", "omiting #{key}" ) @publishEvent("log:info", @filter) else @filter[key] = value @publishEvent('log:debug', key) @publishEvent('log:debug', value) # console.log(@filter) if _.isEmpty(@filter) #TODO: test this @render() else list_of_models = @collection_hard.where(@filter) @collection.reset(list_of_models) #$("input[type='radio'] ##{id}" ).prop( "checked", value ).checkboxradio( "refresh" ) #$("input[type='checkbox'] ##{id}" ).prop( "checked", value ).checkboxradio( "refresh" ) @render() query_action: (event) => @publishEvent("log:debug", "query_action called") #reset filter @filter= {} # NOTE: to be inherited from list views selects_refresh: => if @collection.query for k,v of @collection.query $("[data-query=\'#{k}\']").val(v) $("[data-query=\'#{k}\']").selectmenu('refresh') select_items: (e) => # for checkboxes to bring some sanity into the world # everytime a checkbox is checked we need to adjust @selected_items array @publishEvent("log:debug", "select_items called") @selected_items = [] self = @ selected = $("#list-table>tbody input:checked") for i in selected if $(i).attr('id') isnt 'all' self.selected_items.push($(i).attr('id')) @selected_items = _.uniq(@selected_items) @publishEvent("log:debug", "select_items array #{@selected_items}") select_single: (e) => if e.target.tagName is 'IMG' e.preventDefault() @publishEvent("log:debug", "IMG click!") id = parseInt(e.currentTarget.dataset.id) if _.contains(@selected_items, id) #get its index index = @selected_items.indexOf(id) #remove it from array (index , number of items after) @selected_items.splice(index, 1) $(e.target).replaceWith(@selected_items_pictures[id]) @publishEvent("log:debug", "Removed from selected_items list: #{@selected_items}") #TODO: change image to something else else i = new Image() i.src = @get_image() #save picture for unchecks @selected_items_pictures[id] = $(e.target) $(e.target).replaceWith(i) @selected_items.push(id) @publishEvent("log:debug", "moved to selected_items list: #{@selected_items}") @publishEvent("log:debug", "replaced #{@selected_items}") @selected_items = _.uniq(@selected_items) @publishEvent("log:debug", "with #{@selected_items}") select_all_action: => @publishEvent('jqm_refersh:render') # need this - jqm has to annoyingly initalize checkboxes @publishEvent("log:debug", "select all action") selected = $('#list-table>thead input:checkbox').prop('checked') $('#list-table>tbody input:checkbox').prop('checked', selected).checkboxradio("refresh") open_right_panel: (event) => # NOT USED !!!! #@publishEvent("log:debug", "open_right_panel") #if $(event.target).is(':checked') # @publishEvent('rightpanel:open') filter_apply: => @publishEvent('log:debug', 'filter apply') #TODO: doesn't work for multiple filter objects if obj[@filter] isnt false @publishEvent("log:info", obj) @publishEvent('log:debug', 'filter apply') list_of_models = @collection_hard.where(obj) @collection.reset(list_of_models) else @publishEvent('log:debug', 'filter reset') @collection = _.clone(@collection_hard) @render() refresh_action: (e) => e.preventDefault() @publishEvent('log:debug', 'refresh_action cougth') @collection_hard.fetch data: @collection_hard.query or {} success: => @publishEvent 'tell_user', 'Odświeżam listę elementów' @collection = _.clone(@collection_hard) @render() error:(model, response, options) => if response.responseJSON? Chaplin.EventBroker.publishEvent 'tell_user', response.responseJSON['title'] else Chaplin.EventBroker.publishEvent 'tell_user', 'PI:NAME:<NAME>END_PI z serwerem' @publishEvent('log:debug', "selected_items : #{@selected_items}") search_reveal_action: (e) => e.preventDefault() @publishEvent('log:debug', 'search_reveal_action cougth') #toggle() isn't supported anymore $("#search-list").css('display', 'block') getTemplateData: => collection: @collection.toJSON() listing_type: @listing_type agents: localStorage.getObjectNames('agents') clients: localStorage.getObjectNames('clients') branches: localStorage.getObject('branches') render: => super #remove any previously created table column toggle popups ( important for new rendering ) #$("#list-table-popup").remove() #$("#list-table-popup-popup").remove() if @navigation_rendered is false @render_subview() render_subview: => @publishEvent('log:debug', "render sub_view with #{@params.template}") @subview "navigation", new NavigationView template: @navigation, listing_type: @listing_type @subview("navigation").render() @publishEvent('jqm_refersh:render') #so we only render nav once ! @navigation_rendered = true attach: => super @publishEvent('log:debug', 'view: list-view afterRender()') #initialize sorting tables http://tablesorter.com/docs/ #można sortować wielokolumnowo przytrzymując shift ;) @publishEvent('log:info', "collection has a length of : #{@collection.length}") if @collection.length >= 1 $("#list-table").tablesorter({sortList:[[4,0]], headers:{0:{'sorter':false}, 1:{'sorter':false}}}) # @publishEvent 'tell_user', 'Nic nie znaleźiono!<br />Aby dodać pierwszy element naciśnij <a class="ui-btn ui-shadow ui-corner-all ui-icon-edit ui-btn-icon-notext ui-btn-inline">Dodaj</a>' @publishEvent('jqm_refersh:render') @selects_refresh() @publishEvent 'table_refresh' clean_after_action: => @publishEvent("log:debug", "clean_after_action called") if bowser.mobile? isnt true # for table THEAD # @publishEvent('rightpanel:close') # for JQM so it doesn't complain $('#list-table>tbody').enhanceWithin() #Once action is done clear selected items checkboxes $('#list-table>tbody input:checkbox').prop('checked', false).checkboxradio("refresh") # Clear dropdown menu $("#select-action :selected").removeAttr('selected') # this should work but it doesn't #$("#select-action option:first").attr('selected', 'selected') # this seem to work instead $("#select-action").val('') # refresh dropdown $("#select-action").selectmenu('refresh') @publishEvent('jqm_refersh:render') #restore all icons for key, val of @selected_items_pictures $("[data-id=#{key}] img").replaceWith(@selected_items_pictures[key]) #clear data @selected_items = [] @selected_items_pictures = [] if @collection.length = 0 $("#list-table").tablesorter() select_action: (event) => @publishEvent("log:debug", "select_action with selected_items : #{@selected_items}") self = @ @publishEvent('log:debug', "performing action #{event.target.value} for offers #{self.selected_items}") if self.selected_items.length > 0 if event.target.value == 'usun' $("#confirm").popup('open') # unbind is for stopping it firing multiple times $("#confirmed").unbind().click -> for id in self.selected_items model = self.collection_hard.get(id) #model = mediator.collections.branches.get($(i).attr('id')) # TODO: przepisać oferty tego brancha do innego ? model.destroy # we would like confirmation from server before removing it from the collection wait: true success: (event) => Chaplin.EventBroker.publishEvent('log:info', "Element usunięty id#{model.get('id')}") self.collection_hard.remove(model) self.render() Chaplin.EventBroker.publishEvent 'tell_user', 'Element został usunięty' error:(model, response, options) => if response.responseJSON? Chaplin.EventBroker.publishEvent 'tell_user', response.responseJSON['title'] else Chaplin.EventBroker.publishEvent 'tell_user', 'Brak kontaktu z serwerem' # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() #clean only after the CLICK event self.clean_after_action() if event.target.value == 'wygeneruj_ids' @model = @collection.models[0] for id in self.selected_items url = "#{@model.urlRoot}/odswiez_ids/#{id}" @mp_request(@model, url, 'GET', 'Wszystkie numery ID dla tego oddzaiłu zostaną ponownie wygenerowane a oferty zaznaczone do całościowych eksportów. To może potrwać ok. 2 minuty.') $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'zmien_agenta' str = "" for agent in localStorage.getObject('agents') str = "#{str}<li value='#{agent.id}' data-filtertext='#{agent.first_name} #{agent.surname} #{agent.username} #{agent.email}'><a id='#{agent.id}'>#{agent.first_name} #{agent.surname}</a></li>" val = """<h5>Wybierz Agenta</h5> <form class='ui-filterable'> <input id='agent-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='agent-choose' data-filter='true' data-input='#agent-choose-input' >#{str}</ul>""" $('#popgeneric').html(val) $ul = $("#popgeneric") try $ul.enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#agent-choose li").unbind().click -> $('#popgeneric').popup('close') # inside click f() we can reference attributes of element # on which click was established # so @value is list item 'value' attribute for id in self.selected_items # TODO: this might take a while so we could do progress bar of some sorts.... #console.log(@value, id) model = self.collection_hard.get(id) # add query params so that server knows that we INTEND to change owner # set (change:agent) will trigger sync on model model.set('agent', @value) # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() # show client a listing if event.target.value == 'show-listing-client' str = "" for client in localStorage.getObject('clients') str = "#{str}<li value='#{client.id}' data-filtertext='#{client.first_name} #{client.surname} #{client.email} #{client.notes} #{client.pesel} #{client.phone} #{client.company_name} #{client.requirements}'><a id='#{client.id}'>#{client.first_name} #{client.surname}</a></li>" val = """<h5>Wybierz Klienta</h5> <form class='ui-filterable'><input id='client-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='client-choose' data-filter='true' data-input='#client-choose-input' >#{str}</ul>""" try $('#popgeneric').html(val).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#client-choose li").unbind().click -> $('#popgeneric').popup('close') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items # console.log(@value, i.id) model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/pokaz/#{@value}" self.mp_request(model, url, 'GET', 'Oferta zaznaczona do pokazania') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() # send email to client if event.target.value == 'send-listing-client' str = "" for client in localStorage.getObject('clients') str = "#{str}<li value='#{client.id}' data-filtertext='#{client.first_name} #{client.surname} #{client.email} #{client.notes} #{client.pesel} #{client.phone} #{client.company_name} #{client.requirements}'><a id='#{client.id}'>#{client.first_name} #{client.surname}</a></li>" val = """<h5>Wybierz Klienta</h5> <form class='ui-filterable'><input id='client-choose-input' data-type='search' data-theme='a'></form> <ul data-role='listview' id='client-choose' data-filter='true' data-input='#client-choose-input' >#{str}</ul>""" try $('#popgeneric').html(val).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # unbind is for stopping it firing multiple times $("#client-choose li").unbind().click -> $('#popgeneric').popup('close') self.publishEvent("tell_user", 'Przygotowuje email...') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items # console.log(@value, i.id) model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/email/#{@value}?private=false" self.mp_request(model, url, 'GET', 'Email został wysłany') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'send-listing-address' form = ''' <form> <label for="email_send" class="ui-hidden-accessible">Email:</label> <input name="email_send" id="email_send" placeholder="Wprowadź email" value="" type="text" /> <button data-icon="mail" id="address_submit">Wyślij</button> </form> ''' try $('#popgeneric').html(form).enhanceWithin() catch error @publishEvent("log:warn", error) $('#popgeneric').popup('open',{ transition:"fade" }) # # unbind is for stopping it firing multiple times $("#address_submit").unbind().click (e)-> e.preventDefault() $('#popgeneric').popup('close') self.publishEvent("tell_user", 'Przygotowuje email...') # inside click f() we can reference attributes of element on which click was established # so @value is list item 'value' attribute for id in self.selected_items model = self.collection_hard.get(id) url = "#{model.urlRoot}/#{id}/email/#{$("#email_send").val()}?private=false" self.mp_request(model, url, 'GET', 'Email został wysłany') # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() if event.target.value == 'wydruk-wewnetrzny' or event.target.value == 'wydruk-klienta' # get model for id in self.selected_items model = @collection_hard.get(id) if event.target.value == 'wydruk-wewnetrzny' url = "#{model.urlRoot}/#{id}/#{mediator.models.user.get('company_name')}?private=true" if event.target.value == 'wydruk-klienta' url = "#{model.urlRoot}/#{id}/#{mediator.models.user.get('company_name')}?private=false" # NOTE: instead of doing ajax request we need to do window.location # and set the right db # Ajax would just swallow the response from serwer ..... window.location = url # Remove click event !!!!!!!!!!!!!!!!! $(@).off('click') self.render() self.clean_after_action() else @publishEvent 'tell_user', 'Musisz zaznaczyć przynajmniej jeden element!' self.clean_after_action() #column_action: (event) => # console.log('click') # event.preventDefault() # $("#list-table-popup").popup('open') #table_create: (event) => # @publishEvent 'table_refresh' # window.collection = @collection_hard #open_column_popup:(event) => # @publishEvent("log:debug", "coumn toggle popup") # event.preventDefault() # $('#list-table-popup').popup('open')
[ { "context": "': @options.port\n }\n @auth = {\n 'username': @options.username\n 'password': @options.", "end": 2334, "score": 0.9941346049308777, "start": 2326, "tag": "USERNAME", "value": "username" }, { "context": " }\n @auth = {\n 'username':...
index.coffee
octoblu/meshblu-xenmobile
0
{EventEmitter} = require 'events' debug = require('debug')('meshblu-connector-meshblu-xenmobile:index') _ = require 'lodash' schemas = require './legacySchemas.json' channelJson = require './channelJson' request = require 'request' OctobluRequestFormatter = require 'octoblu-request-formatter' format = new OctobluRequestFormatter(channelJson) class MeshbluXenmobile extends EventEmitter constructor: -> debug 'MeshbluXenmobile constructed' @options = {} close: (callback) => debug 'on close' callback() onMessage: (message) => debug 'onMessage', message.payload return unless message.payload.endpoint? requestParams = format.processMessage message.payload, @auth, @defaultUrlParams requestParams.headers.auth_token = @auth_token if @auth_token? debug 'formatted request', requestParams if @auth_token? debug 'Sending Request' request requestParams, (error, response, body) => if error? errorResponse = { fromUuid: message.fromUuid fromNodeId: message.metadata.flow.fromNodeId error: error } return @sendError errorResponse body = JSON.parse(body) if @isJson body response = { fromUuid: message.fromUuid fromNodeId: message.metadata.flow.fromNodeId metadata: message.metadata data: body } @sendResponse response debug 'Body: ', body sendResponse: ({fromUuid, fromNodeId, metadata, data}) => @emit 'message', { devices: [fromUuid] payload: from: fromNodeId metadata: metadata data: data } sendError: ({fromUuid, fromNodeId, error}) => code = error.code ? 500 @emit 'message', { devices: [fromUuid] payload: from: fromNodeId metadata: code: code status: http.STATUS_CODES[code] error: message: error.message ? 'Unknown Error' } onConfig: (config) => debug 'on config', @device.uuid @options = config.options if _.has @options, 'host' @defaultUrlParams = { ':hostname': @options.host ':port': @options.port } @auth = { 'username': @options.username 'password': @options.password } return @login() unless config.xenmobile_auth_token? @auth_token = config.xenmobile_auth_token start: (@device) => debug 'started', @device.uuid update = _.extend schemas, format.buildSchema() update.octoblu ?= {} update.octoblu.flow ?= {} update.octoblu.flow.forwardMetadata = true @emit 'update', update login: () => { host, port } = @options url = host + ':' + port + '/xenmobile/api/v1/authentication/login' debug 'url', url request.post { url: url json: login: @auth.username password: @auth.password }, (error, response, body) => debug(error) if error? return error if error? @auth_token = body.auth_token @updateAuth body.auth_token updateAuth: (newAuth) => @emit 'update', xenmobile_auth_token: newAuth isJson: (str) -> try JSON.parse str catch e return false true module.exports = MeshbluXenmobile
17300
{EventEmitter} = require 'events' debug = require('debug')('meshblu-connector-meshblu-xenmobile:index') _ = require 'lodash' schemas = require './legacySchemas.json' channelJson = require './channelJson' request = require 'request' OctobluRequestFormatter = require 'octoblu-request-formatter' format = new OctobluRequestFormatter(channelJson) class MeshbluXenmobile extends EventEmitter constructor: -> debug 'MeshbluXenmobile constructed' @options = {} close: (callback) => debug 'on close' callback() onMessage: (message) => debug 'onMessage', message.payload return unless message.payload.endpoint? requestParams = format.processMessage message.payload, @auth, @defaultUrlParams requestParams.headers.auth_token = @auth_token if @auth_token? debug 'formatted request', requestParams if @auth_token? debug 'Sending Request' request requestParams, (error, response, body) => if error? errorResponse = { fromUuid: message.fromUuid fromNodeId: message.metadata.flow.fromNodeId error: error } return @sendError errorResponse body = JSON.parse(body) if @isJson body response = { fromUuid: message.fromUuid fromNodeId: message.metadata.flow.fromNodeId metadata: message.metadata data: body } @sendResponse response debug 'Body: ', body sendResponse: ({fromUuid, fromNodeId, metadata, data}) => @emit 'message', { devices: [fromUuid] payload: from: fromNodeId metadata: metadata data: data } sendError: ({fromUuid, fromNodeId, error}) => code = error.code ? 500 @emit 'message', { devices: [fromUuid] payload: from: fromNodeId metadata: code: code status: http.STATUS_CODES[code] error: message: error.message ? 'Unknown Error' } onConfig: (config) => debug 'on config', @device.uuid @options = config.options if _.has @options, 'host' @defaultUrlParams = { ':hostname': @options.host ':port': @options.port } @auth = { 'username': @options.username '<PASSWORD>': <PASSWORD> } return @login() unless config.xenmobile_auth_token? @auth_token = config.xenmobile_auth_token start: (@device) => debug 'started', @device.uuid update = _.extend schemas, format.buildSchema() update.octoblu ?= {} update.octoblu.flow ?= {} update.octoblu.flow.forwardMetadata = true @emit 'update', update login: () => { host, port } = @options url = host + ':' + port + '/xenmobile/api/v1/authentication/login' debug 'url', url request.post { url: url json: login: @auth.username password: <PASSWORD> }, (error, response, body) => debug(error) if error? return error if error? @auth_token = body.auth_token @updateAuth body.auth_token updateAuth: (newAuth) => @emit 'update', xenmobile_auth_token: newAuth isJson: (str) -> try JSON.parse str catch e return false true module.exports = MeshbluXenmobile
true
{EventEmitter} = require 'events' debug = require('debug')('meshblu-connector-meshblu-xenmobile:index') _ = require 'lodash' schemas = require './legacySchemas.json' channelJson = require './channelJson' request = require 'request' OctobluRequestFormatter = require 'octoblu-request-formatter' format = new OctobluRequestFormatter(channelJson) class MeshbluXenmobile extends EventEmitter constructor: -> debug 'MeshbluXenmobile constructed' @options = {} close: (callback) => debug 'on close' callback() onMessage: (message) => debug 'onMessage', message.payload return unless message.payload.endpoint? requestParams = format.processMessage message.payload, @auth, @defaultUrlParams requestParams.headers.auth_token = @auth_token if @auth_token? debug 'formatted request', requestParams if @auth_token? debug 'Sending Request' request requestParams, (error, response, body) => if error? errorResponse = { fromUuid: message.fromUuid fromNodeId: message.metadata.flow.fromNodeId error: error } return @sendError errorResponse body = JSON.parse(body) if @isJson body response = { fromUuid: message.fromUuid fromNodeId: message.metadata.flow.fromNodeId metadata: message.metadata data: body } @sendResponse response debug 'Body: ', body sendResponse: ({fromUuid, fromNodeId, metadata, data}) => @emit 'message', { devices: [fromUuid] payload: from: fromNodeId metadata: metadata data: data } sendError: ({fromUuid, fromNodeId, error}) => code = error.code ? 500 @emit 'message', { devices: [fromUuid] payload: from: fromNodeId metadata: code: code status: http.STATUS_CODES[code] error: message: error.message ? 'Unknown Error' } onConfig: (config) => debug 'on config', @device.uuid @options = config.options if _.has @options, 'host' @defaultUrlParams = { ':hostname': @options.host ':port': @options.port } @auth = { 'username': @options.username 'PI:PASSWORD:<PASSWORD>END_PI': PI:PASSWORD:<PASSWORD>END_PI } return @login() unless config.xenmobile_auth_token? @auth_token = config.xenmobile_auth_token start: (@device) => debug 'started', @device.uuid update = _.extend schemas, format.buildSchema() update.octoblu ?= {} update.octoblu.flow ?= {} update.octoblu.flow.forwardMetadata = true @emit 'update', update login: () => { host, port } = @options url = host + ':' + port + '/xenmobile/api/v1/authentication/login' debug 'url', url request.post { url: url json: login: @auth.username password: PI:PASSWORD:<PASSWORD>END_PI }, (error, response, body) => debug(error) if error? return error if error? @auth_token = body.auth_token @updateAuth body.auth_token updateAuth: (newAuth) => @emit 'update', xenmobile_auth_token: newAuth isJson: (str) -> try JSON.parse str catch e return false true module.exports = MeshbluXenmobile
[ { "context": "'use strict'\n# Neanderthal JS\n# Pedro Lucas Porcellis - pedrolucasporcellis@gmail.com\n# 20/06/2016\n# MI", "end": 53, "score": 0.9998588562011719, "start": 32, "tag": "NAME", "value": "Pedro Lucas Porcellis" }, { "context": "strict'\n# Neanderthal JS\n# Pedro Lucas P...
neanderthal.coffee
pedrolucasp/neanderthal-js
1
'use strict' # Neanderthal JS # Pedro Lucas Porcellis - pedrolucasporcellis@gmail.com # 20/06/2016 # MIT License (see LICENSE) class @Neanderthal # TODO: refactor the structure of execution of steps # and general organization of program memory ### # programSteps : Array { # [ "LDA", "128", "ADD", "10", "STA", 130, "HLT" ] # } # # programMemory : Array { # { memoryPosition: "128", value: "10" } # } ### constructor: -> @programCounter = 0 @accumulator = 0 @programSteps = [] @programMemory = [] @mnemonicsCodes = [ { integerCode: 0, code: "NOP", needsParams: false, value: -> }, { integerCode: 16, code: "STA", needsParams: true, value: (position) -> addData(position, @accumulator) }, { integerCode: 32, code: "LDA", needsParams: true, value: (position) -> @accumulator = getDataValue(position) return }, { integerCode: 48, code: "ADD", needsParams: true, value: (position) -> @accumulator += getDataValue(position) return }, { integerCode: 64, code: "OR", needsParams: true, value: (position) -> @accumulator || getDataValue(position) }, { integerCode: 80, code: "AND", needsParams: true, value: (position) -> @accumulator && getDataValue(position) }, { integerCode: 96, code: "NOT", needsParams: false, value: -> @accumulator = !@accumulator return }, { integerCode: 128, code: "JMP", needsParams: true, value: (position) -> execute(position); }, { integerCode: 144, code: "JN", needsParams: true, value: (position) -> execute(position) if @accumulator < 0 }, { integerCode: 160, code: "JZ", needsParams: true, value: (position) -> execute(position) if @accumulator == 0 }, { integerCode: 244, code: "HLT", needsParams: false, value: -> exit(); } ] # Instance Methods addNewStep: (code, memoryPosition) -> if typeof code is Number and code in (@mnemonicsCodes.map (o) -> return o.integerCode) @programSteps.push(code) @programSteps.push(memoryPosition) @isUsingMnemonics = false return else if typeof code is String and code in (@mnemonicsCodes.map (o) -> return o.value) @programSteps.push(code) @programSteps.push(memoryPosition) @isUsingMnemonics = true return addData: (memoryPosition, value) -> data = { memory: memoryPosition, value: value } index = @programMemory.map (programObject, index) -> return index if programObject.memoryPosition == memoryPosition and programObject.value != 0 if index > 0 or index isnt null @programMemory.push data else @programMemory.splice index, 0, data getData: (memoryPosition) -> filteredProgramMemory = @programMemory.filter (programObject) -> return programObject if programObject.memory is memoryPosition return filteredProgramMemory[0] getDataValue: (memoryPosition) -> return 0 if this.getData(memoryPosition).value is null return this.getData(memoryPosition).value executeStep: (stepObject) -> if typeOfStep(stepObject) is "instruction" ### # find out what instruction is # execute the instruction code ### else ### # load the data referent to this memoryPosition # if programSteps(stepIndex - 1) is an instruction # that require a parameter, pass it to the function ### typeOfStep: (stepObject) -> if @isUsingMnemonics if isMnemonic(stepObject) then "instruction" else "data" else if isMnemonicIntegerCode(stepObject) then "instruction" else "data" isMnemonicIntegerCode: (code) -> return (code in @mnemonicsCodes.map (o) -> return o.integerCode) isMnemonic: (code) -> return (code in @mnemonicsCodes.map (o) -> return o.code) # Alias of #run() execute: -> run() run: -> # Implement exit: -> # Implement getProgramCounter: -> @programCounter getAccumulator: -> @accumulator getMemory: -> @programMemory resetProgram: (deep) -> @programCounter = 0 @accumulator = 0 @programSteps = [] if deep isnt null return reset: -> resetProgram(deep = true)
132801
'use strict' # Neanderthal JS # <NAME> - <EMAIL> # 20/06/2016 # MIT License (see LICENSE) class @Neanderthal # TODO: refactor the structure of execution of steps # and general organization of program memory ### # programSteps : Array { # [ "LDA", "128", "ADD", "10", "STA", 130, "HLT" ] # } # # programMemory : Array { # { memoryPosition: "128", value: "10" } # } ### constructor: -> @programCounter = 0 @accumulator = 0 @programSteps = [] @programMemory = [] @mnemonicsCodes = [ { integerCode: 0, code: "NOP", needsParams: false, value: -> }, { integerCode: 16, code: "STA", needsParams: true, value: (position) -> addData(position, @accumulator) }, { integerCode: 32, code: "LDA", needsParams: true, value: (position) -> @accumulator = getDataValue(position) return }, { integerCode: 48, code: "ADD", needsParams: true, value: (position) -> @accumulator += getDataValue(position) return }, { integerCode: 64, code: "OR", needsParams: true, value: (position) -> @accumulator || getDataValue(position) }, { integerCode: 80, code: "AND", needsParams: true, value: (position) -> @accumulator && getDataValue(position) }, { integerCode: 96, code: "NOT", needsParams: false, value: -> @accumulator = !@accumulator return }, { integerCode: 128, code: "JMP", needsParams: true, value: (position) -> execute(position); }, { integerCode: 144, code: "JN", needsParams: true, value: (position) -> execute(position) if @accumulator < 0 }, { integerCode: 160, code: "JZ", needsParams: true, value: (position) -> execute(position) if @accumulator == 0 }, { integerCode: 244, code: "HLT", needsParams: false, value: -> exit(); } ] # Instance Methods addNewStep: (code, memoryPosition) -> if typeof code is Number and code in (@mnemonicsCodes.map (o) -> return o.integerCode) @programSteps.push(code) @programSteps.push(memoryPosition) @isUsingMnemonics = false return else if typeof code is String and code in (@mnemonicsCodes.map (o) -> return o.value) @programSteps.push(code) @programSteps.push(memoryPosition) @isUsingMnemonics = true return addData: (memoryPosition, value) -> data = { memory: memoryPosition, value: value } index = @programMemory.map (programObject, index) -> return index if programObject.memoryPosition == memoryPosition and programObject.value != 0 if index > 0 or index isnt null @programMemory.push data else @programMemory.splice index, 0, data getData: (memoryPosition) -> filteredProgramMemory = @programMemory.filter (programObject) -> return programObject if programObject.memory is memoryPosition return filteredProgramMemory[0] getDataValue: (memoryPosition) -> return 0 if this.getData(memoryPosition).value is null return this.getData(memoryPosition).value executeStep: (stepObject) -> if typeOfStep(stepObject) is "instruction" ### # find out what instruction is # execute the instruction code ### else ### # load the data referent to this memoryPosition # if programSteps(stepIndex - 1) is an instruction # that require a parameter, pass it to the function ### typeOfStep: (stepObject) -> if @isUsingMnemonics if isMnemonic(stepObject) then "instruction" else "data" else if isMnemonicIntegerCode(stepObject) then "instruction" else "data" isMnemonicIntegerCode: (code) -> return (code in @mnemonicsCodes.map (o) -> return o.integerCode) isMnemonic: (code) -> return (code in @mnemonicsCodes.map (o) -> return o.code) # Alias of #run() execute: -> run() run: -> # Implement exit: -> # Implement getProgramCounter: -> @programCounter getAccumulator: -> @accumulator getMemory: -> @programMemory resetProgram: (deep) -> @programCounter = 0 @accumulator = 0 @programSteps = [] if deep isnt null return reset: -> resetProgram(deep = true)
true
'use strict' # Neanderthal JS # PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI # 20/06/2016 # MIT License (see LICENSE) class @Neanderthal # TODO: refactor the structure of execution of steps # and general organization of program memory ### # programSteps : Array { # [ "LDA", "128", "ADD", "10", "STA", 130, "HLT" ] # } # # programMemory : Array { # { memoryPosition: "128", value: "10" } # } ### constructor: -> @programCounter = 0 @accumulator = 0 @programSteps = [] @programMemory = [] @mnemonicsCodes = [ { integerCode: 0, code: "NOP", needsParams: false, value: -> }, { integerCode: 16, code: "STA", needsParams: true, value: (position) -> addData(position, @accumulator) }, { integerCode: 32, code: "LDA", needsParams: true, value: (position) -> @accumulator = getDataValue(position) return }, { integerCode: 48, code: "ADD", needsParams: true, value: (position) -> @accumulator += getDataValue(position) return }, { integerCode: 64, code: "OR", needsParams: true, value: (position) -> @accumulator || getDataValue(position) }, { integerCode: 80, code: "AND", needsParams: true, value: (position) -> @accumulator && getDataValue(position) }, { integerCode: 96, code: "NOT", needsParams: false, value: -> @accumulator = !@accumulator return }, { integerCode: 128, code: "JMP", needsParams: true, value: (position) -> execute(position); }, { integerCode: 144, code: "JN", needsParams: true, value: (position) -> execute(position) if @accumulator < 0 }, { integerCode: 160, code: "JZ", needsParams: true, value: (position) -> execute(position) if @accumulator == 0 }, { integerCode: 244, code: "HLT", needsParams: false, value: -> exit(); } ] # Instance Methods addNewStep: (code, memoryPosition) -> if typeof code is Number and code in (@mnemonicsCodes.map (o) -> return o.integerCode) @programSteps.push(code) @programSteps.push(memoryPosition) @isUsingMnemonics = false return else if typeof code is String and code in (@mnemonicsCodes.map (o) -> return o.value) @programSteps.push(code) @programSteps.push(memoryPosition) @isUsingMnemonics = true return addData: (memoryPosition, value) -> data = { memory: memoryPosition, value: value } index = @programMemory.map (programObject, index) -> return index if programObject.memoryPosition == memoryPosition and programObject.value != 0 if index > 0 or index isnt null @programMemory.push data else @programMemory.splice index, 0, data getData: (memoryPosition) -> filteredProgramMemory = @programMemory.filter (programObject) -> return programObject if programObject.memory is memoryPosition return filteredProgramMemory[0] getDataValue: (memoryPosition) -> return 0 if this.getData(memoryPosition).value is null return this.getData(memoryPosition).value executeStep: (stepObject) -> if typeOfStep(stepObject) is "instruction" ### # find out what instruction is # execute the instruction code ### else ### # load the data referent to this memoryPosition # if programSteps(stepIndex - 1) is an instruction # that require a parameter, pass it to the function ### typeOfStep: (stepObject) -> if @isUsingMnemonics if isMnemonic(stepObject) then "instruction" else "data" else if isMnemonicIntegerCode(stepObject) then "instruction" else "data" isMnemonicIntegerCode: (code) -> return (code in @mnemonicsCodes.map (o) -> return o.integerCode) isMnemonic: (code) -> return (code in @mnemonicsCodes.map (o) -> return o.code) # Alias of #run() execute: -> run() run: -> # Implement exit: -> # Implement getProgramCounter: -> @programCounter getAccumulator: -> @accumulator getMemory: -> @programMemory resetProgram: (deep) -> @programCounter = 0 @accumulator = 0 @programSteps = [] if deep isnt null return reset: -> resetProgram(deep = true)
[ { "context": "#\n# Autocompleter main file\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\n\n# hook up dependencies\ncore = require('core", "end": 68, "score": 0.9998884797096252, "start": 51, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/autocompleter/main.coffee
lovely-io/lovely.io-stl
2
# # Autocompleter main file # # Copyright (C) 2012 Nikolay Nemshilov # # hook up dependencies core = require('core') $ = require('dom') UI = require('ui') Ajax = require('ajax') # local variables assignments ext = core.ext Class = core.Class Element = $.Element isArray = core.isArray # glue in your files include 'src/autocompleter' include 'src/document' # export your objects in the module exports = ext Autocompleter, version: '%{version}'
182969
# # Autocompleter main file # # Copyright (C) 2012 <NAME> # # hook up dependencies core = require('core') $ = require('dom') UI = require('ui') Ajax = require('ajax') # local variables assignments ext = core.ext Class = core.Class Element = $.Element isArray = core.isArray # glue in your files include 'src/autocompleter' include 'src/document' # export your objects in the module exports = ext Autocompleter, version: '%{version}'
true
# # Autocompleter main file # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # # hook up dependencies core = require('core') $ = require('dom') UI = require('ui') Ajax = require('ajax') # local variables assignments ext = core.ext Class = core.Class Element = $.Element isArray = core.isArray # glue in your files include 'src/autocompleter' include 'src/document' # export your objects in the module exports = ext Autocompleter, version: '%{version}'
[ { "context": "rc = \"https://maps.googleapis.com/maps/api/js?key=AIzaSyAxUiFoRbIsNrZo-NW_QSbIQfE-R7QcB4k&sensor=false&callback=window.initialiseMaps\"\n do", "end": 8618, "score": 0.9996122717857361, "start": 8579, "tag": "KEY", "value": "AIzaSyAxUiFoRbIsNrZo-NW_QSbIQfE-R7QcB4k" }, { ...
source/javascripts/site.js.coffee
oneiota/oneiota
1
#= require vendor/waypoints2.0.2.min #= require vendor/jquery-ui-1.9.2.custom #= require vendor/jquery.color-2.1.2.min.js #= require vendor/jquery.ui.touch-punch.min #= require feed #= require intro window.isTouch = if ($('html').hasClass('touch')) then true else false window.isCanvas = if ($('html').hasClass('canvas')) then true else false window.isIndex = if $('body').hasClass('index') then true else false window.isFeed = if $('body').hasClass('feed') then true else false window.isPortfolio = if $('body').hasClass('portfolio') then true else false window.isBlood = if $('body').hasClass('blood') then true else false window.isSingle = if $('body').hasClass('singleProject') or $('body').hasClass('singlePost') then true else false window.isIE = if $('html').hasClass('lt-ie9') then true else false window.mapLoaded = false window.cantanimate = if $('html').hasClass('no-cssanimations') then true else false ## New Constructors HistoryController = -> @slugArray = [] @popped = false @prevSlug @currSlug @inMenu @scrollingBack = false historyController = new HistoryController() WaypointCheck = -> @filteredItems = [] @articesLoaded = false @isLoading = false @currentProject = 0 @nextProject @hudTimer @currentDirection @projectSlug = $('article:eq(0)').attr('id') @projectTitle = $('article:eq(0)').data('title') @ogfg = $('article:eq(0)').data('foreground') @ogbg = $('article:eq(0)').data('background') @lastProject = $('article').length - 1 @lastFg @projects @showArrow @hideArrow @resetArrow @footerOpen = false @lastIndex = 0 @arrowTab = '<div class="arrow-tab"><a href="#"></a><span>' waypointCheck = new WaypointCheck() ImageLoader = -> @loadArray = [] @screenSize = if (screen.width > 880) then 'desktop' else 'mobile' @loadTimer = null @retryLoad = false imageLoader = new ImageLoader() MainMenu = -> @ogbg = '#262626' @ogfg = '#ffffff' mainMenu = new MainMenu() ObjectLoader = -> @fadeArray = ['fadeInSlide','fadeInSlideR','fadeInSlideL'] @lastFade if window.isBlood @objectTarget = 'section' @objectSubTarget = '.content' else @objectTarget = 'article' @objectSubTarget = '.project' objectLoader = new ObjectLoader() CanvasArrow = (location, arrowWidth) -> element = document.createElement('canvas') $(element) .attr('width', arrowWidth + 40).attr('height', '40') if arrowWidth >= 160 arrowWidth = Math.abs(arrowWidth - 160) else arrowWidth = Math.abs(arrowWidth - 160) * -1 context = element.getContext("2d") context.fillStyle = waypointCheck.ogfg context.bezierCurveTo((179.965+arrowWidth),0.945,(177.65+arrowWidth),0,(176+arrowWidth),0) context.lineTo((171+arrowWidth),0) context.lineTo(7,0) context.bezierCurveTo(3.15,0,0,3.15,0,7) context.lineTo(0,33) context.bezierCurveTo(0,36.85,3.15,40,7,40) context.lineTo((171+arrowWidth),40) context.lineTo((176+arrowWidth),40) context.bezierCurveTo((177.65+arrowWidth),40,(179.965+arrowWidth),39.055,(181.143+arrowWidth),37.9) context.lineTo((197.269+arrowWidth),22.1) context.bezierCurveTo((198.447+arrowWidth),20.945,(198.447+arrowWidth),19.055,(197.269+arrowWidth),17.9) context.closePath() context.fill() return element waypointCheck.updateColors = (foreground, background) -> waypointCheck.lastFg = foreground if waypointCheck.footerOpen closeColor = background else closeColor = foreground $('nav').stop().animate({ color: foreground }, 500) $('.indexNav .icon-info').stop().animate({ color: closeColor }, 500, () -> if window.isIE $('.indexNav .icon-info').trigger('focus') setTimeout -> $('.indexNav .icon-info').blur() 10 ) $('.navCounters .navPanel').stop().animate({ backgroundColor: background }, 500 ) if window.isCanvas waypointCheck.updateCanvas() else $('.arrow-tab').css('color', foreground) waypointCheck.endofline = (foreground) -> $('.indexNav .icon-info').stop().animate({ color: foreground }, 500 ) waypointCheck.makeCanvas = -> $('.navCounters ul li .arrow-tab').each(-> liWidth = $(this).width() liIndex = $(this).parent().index() canvasArrow = new CanvasArrow(liIndex, liWidth) $(canvasArrow) .addClass('canvasArrow') .text('unsupported browser') .appendTo($(this)) ) waypointCheck.updateCanvas = -> $('.arrow-tab').css({'color':waypointCheck.ogbg}) $('.canvasArrow').remove() waypointCheck.makeCanvas() waypointCheck.relativeSpeed = (scrollTarget) -> topDistance = $(document).scrollTop() scrollSpeed = Math.abs((Math.abs(scrollTarget) - $(document).scrollTop())/10) scrollSpeed # console.log scrollSpeed * 100 window.initialiseMaps = () -> # Bris Map MY_MAPTYPE_ID = 'custom_style'; brisMapOptions = zoom: 16 center: new google.maps.LatLng(-27.45480, 153.03905) disableDefaultUI: true zoomControl: false scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false draggable: if window.isTouch and imageLoader.screenSize is 'mobile' then false else true backgroundColor: '#262626' zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL position: google.maps.ControlPosition.TOP_RIGHT mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID] }, mapTypeId: MY_MAPTYPE_ID featureOpts = [ featureType: 'all' elementType: 'all' stylers: [ invert_lightness: true , saturation: -100 , lightness: 5 ] ] brismap = new google.maps.Map(document.getElementById("brismap"), brisMapOptions) if window.isCanvas iotaImage = '../images/iotaMarker.svg'; else iotaImage = '../images/iotaMarker.png'; iotaLatLng = new google.maps.LatLng(-27.45480, 153.03905); iotaMarker = new google.maps.Marker( clickable: false position: iotaLatLng map: brismap icon: iotaImage title: 'One Iota Brisbane' ) styledMapOptions = name: 'Custom Style' customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions) brismap.mapTypes.set(MY_MAPTYPE_ID, customMapType) # Syd Map SYD_MAPTYPE_ID = 'sydney_custom_style'; sydMapOptions = zoom: 16 center: new google.maps.LatLng(-33.861468, 151.209180) disableDefaultUI: true zoomControl: false scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false draggable: if window.isTouch and imageLoader.screenSize is 'mobile' then false else true backgroundColor: '#58585a' zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL position: google.maps.ControlPosition.TOP_RIGHT mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, SYD_MAPTYPE_ID] }, mapTypeId: SYD_MAPTYPE_ID sydFeatureOpts = [ {"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#58585a"},{"lightness":-25},{"saturation":-97}]} ] sydmap = new google.maps.Map(document.getElementById("sydmap"), sydMapOptions) if window.isCanvas sydIotaImage = '../images/iotaMarkerSyd.svg'; else sydIotaImage = '../images/iotaMarkerSyd.png'; iotaLatLng = new google.maps.LatLng(-33.861468, 151.209180); iotaMarker = new google.maps.Marker( clickable: false position: iotaLatLng map: sydmap icon: sydIotaImage title: 'One Iota Sydney' ) sydStyledMapOptions = name: 'Custom Style' sydCustomMapType = new google.maps.StyledMapType(sydFeatureOpts, sydStyledMapOptions) sydmap.mapTypes.set(SYD_MAPTYPE_ID, sydCustomMapType) loadGoogleMaps = () -> googleMaps = document.createElement("script") googleMaps.type = "text/javascript" googleMaps.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyAxUiFoRbIsNrZo-NW_QSbIQfE-R7QcB4k&sensor=false&callback=window.initialiseMaps" document.body.appendChild googleMaps mainMenu.updateColors = (foreground, background) -> $(".overlay").stop().animate({ backgroundColor: background }, 300 ) imageLoader.imageLoaded = (img) -> targetArticle = $('article').eq(img.imgParent) targetPlaceholder = targetArticle.find('span.placeholder-bg').eq(0) targetParentIndex = targetPlaceholder.parent().index() targetAlt = targetArticle.find('span.placeholder-alt').eq(0) targetPlaceholder.after($(img)) if targetParentIndex is 0 $(img).addClass('loaded fadeInSlide') else fadeInEffect = objectLoader.randomFade() $(img).addClass('loaded ' + fadeInEffect) targetPlaceholder.remove() targetAlt.remove() imageLoader.loadImage() imageLoader.loadImage = -> if imageLoader.loadArray.length isnt 0 imgItem = imageLoader.loadArray.shift() img = new Image() imgTimer = undefined img.src = imgItem.imgSrc img.title = img.alt = imgItem.imgTitle img.imgParent = imgItem.imgParent if img.complete or img.readyState is 4 imageLoader.imageLoaded(img) else imgTimer = setTimeout -> if !imageLoader.retryLoad imageLoader.retryLoad = true imageLoader.loadArray.unshift(imgItem) imageLoader.loadImage() else imageLoader.retryLoad = false $(img).unbind 'error load onreadystate' imageLoader.loadImage() if imgItem.length isnt 0 , 15000 $(img).bind 'error load onreadystatechange', (e) -> clearTimeout imgTimer if e.type isnt 'error' imageLoader.imageLoaded(img) else imageLoader.loadImage() imageLoader.addImages = (articleIndex) -> if !$('article').eq(articleIndex).hasClass('loaded') targetArticles = $('article').eq(articleIndex).find('span.placeholder-bg') targetArticles.each (index) -> imgItem = {} imgItem.imgSrc = targetArticles.eq(index).data(imageLoader.screenSize) imgItem.imgTitle = targetArticles.eq(index).attr('alt') imgItem.imgParent = articleIndex imageLoader.loadArray.push(imgItem) if index == targetArticles.length - 1 imageLoader.loadImage() $('article').eq(articleIndex).addClass('loaded') #Index Specific if window.isIndex FlipSquare = -> @colArr = ['#d83b65','#e55d87','#e55d87','#5fc3e4','#5ec4e5','#50d97a','#edde5d','#f09819','#ff512f','#dd2476','#1b0109'] @sqrArr = [] @hozDivs = 4 @screenW = $(window).width() @screenH = $(window).height() @squareW = @screenW / @hozDivs @squareH = $(window).height() / Math.floor($(window).height() / @squareW) @numSq = @hozDivs * ($(window).height() / @squareH) @tester = true @tester2 = true flipSquare = new FlipSquare() waypointCheck.footerWaypoint = -> # $('body').waypoint $('body').waypoint triggerOnce: false offset: 'bottom-in-view' handler: (direction) -> fgColor = $('.checkout-feed').data('fgcolor') if direction is 'down' if window.isTouch && waypointCheck.nextProject != waypointCheck.lastProject return false else waypointCheck.endofline(fgColor) if !waypointCheck.footerOpen $('.checkout-feed').removeClass('slideUpFooter slideDownFooter').addClass('slideUpFooter') addFade = setTimeout -> $('.checkout-feed h3').addClass('fadeIn') , 200 waypointCheck.footerOpen = true else waypointCheck.endofline(waypointCheck.lastFg) if waypointCheck.footerOpen $('.checkout-feed').removeClass('slideUpFooter slideDownFooter').addClass('slideDownFooter') $('.checkout-feed h3').removeClass('fadeIn') waypointCheck.footerOpen = false #Non Touch Handlers # CHANGE FOR TOUCH DEBUG - DONE if !window.isTouch waypointCheck.resetFilter = () -> $.each waypointCheck.filteredItems, (i) -> tarLi = waypointCheck.filteredItems[i].filteredLi tarArt = waypointCheck.filteredItems[i].filteredArticle tarID = waypointCheck.filteredItems[i].lastID if !tarID $(".navCounters ul li").eq(0).before(tarLi) $('article').eq(0).before(tarArt) else $('a[href="/' + tarID + '"]').parent().after(tarLi) $('article[id="' + tarID + '"]').after(tarArt) waypointCheck.filteredItems = [] $.waypoints('enable') $.waypoints('refresh') objectLoader.assignAnimationWaypoints() $('.filterMenu a').bind 'click', (event) -> event.preventDefault() if not $(this).parent().hasClass("eyeButton") if not $(this).parent().hasClass("active") $('.filterMenu li').removeClass('active') $(this).parent().addClass('active') tarFilter = $(this).data('filter') $('.navCounters').css('visibility','hidden') if waypointCheck.filteredItems.length isnt 0 if tarFilter == 'all' $('html, body').stop().animate({ scrollTop: 0 }, 750, -> if this.nodeName == "BODY" return waypointCheck.resetFilter() $.waypoints('refresh') $('.navCounters').css('visibility','visible') ) else waypointCheck.resetFilter() if tarFilter isnt 'all' $('html, body').stop().animate({ scrollTop: 0 }, 750, -> if this.nodeName == "BODY" return historyController.scrollingBack = true $('article').each( -> if !$(this).attr('data-'+ tarFilter) $(this).waypoint('disable') tarFilterIndex = $(this).index() tarLastId = $(this).prev().attr('id') filteredItem = lastID: tarLastId filteredArticle: $(this).detach() filteredLi: $(".navCounters ul li").eq(tarFilterIndex).removeClass('active').detach() waypointCheck.filteredItems.push(filteredItem) ) historyController.scrollingBack = false $.waypoints('refresh') $('.navCounters').css('visibility','visible') ) waypointCheck.updateTitle = (articleId, popped, navLiHit) -> if !historyController.scrollingBack currentArticle = $('#'+ articleId) currentIndex = currentArticle.index() waypointCheck.projectSlug = currentArticle.attr('id') waypointCheck.projectTitle = currentArticle.data('title') @.ogfg = waypointCheck.ogfg = currentArticle.data('foreground') @.ogbg = waypointCheck.ogbg = currentArticle.data('background') waypointCheck.updateColors(@.ogfg, @.ogbg) newTitle = 'One Iota — ' + waypointCheck.projectTitle document.title = newTitle $('.navCounters ul li').removeClass('active scaleIn slideIn') if waypointCheck.lastIndex != currentIndex $('.navCounters ul li').eq(waypointCheck.lastIndex).addClass('scaleIn') $('.navCounters ul li').eq(currentIndex).addClass('active slideIn') else $('.navCounters ul li').eq(currentIndex).addClass('active slideIn') if !navLiHit clearTimeout(waypointCheck.showArrow) clearTimeout(waypointCheck.hideArrow) clearTimeout(waypointCheck.resetArrow) targetArrow = $('.navCounters ul li').eq(currentIndex).find('.arrow-tab') $('.arrow-tab').css('visibility','hidden') targetArrow.css('visibility','visible') waypointCheck.showArrow = setTimeout(-> targetArrow.removeClass('hideArrow').addClass('showArrow scaleIn') waypointCheck.hideArrow = setTimeout(-> targetArrow.removeClass('scaleIn').addClass('scaleOut') waypointCheck.resetArrow = setTimeout(-> $('.arrow-tab').removeClass('scaleOut showArrow').addClass('scaleIn hideArrow').css('visibility','visible') ,500) ,2000) ,1000) if not popped history.pushState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) else history.replaceState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) waypointCheck.lastIndex = currentIndex ## Assign Waypoints waypointCheck.assignArticleWaypoints = -> $('article:gt(0)').waypoint triggerOnce: false offset: '100%' handler: (direction) -> if !historyController.scrollingBack articleIndex = ($('article').index($('#' + @id))) if direction is 'down' waypointCheck.updateTitle(@id) imageLoader.addImages(articleIndex) else waypointCheck.updateTitle($('article').eq(articleIndex-1).attr('id')) imageLoader.addImages(articleIndex-1) #Touch Handlers else $('.main article').css('background','transparent') window.addEventListener 'load', -> setTimeout -> window.scrollTo(0, 1) , 0 waypointCheck.resetFilter = (isAll) -> if isAll $('.filterMenu li').removeClass('active') $('.filterMenu li').eq(1).addClass('active') $(".navCounters ul li").each( -> $(this).removeClass('scaleHide slideIn').addClass('scaleIn') ) $('.filterMenu a').bind 'click', (event) -> event.preventDefault() if not $(this).parent().hasClass("eyeButton") if not $(this).parent().hasClass("active") $('.filterMenu li').removeClass('active') $(this).parent().addClass('active') tarFilter = $(this).data('filter') currentProject = $('.navCounters li.active').index() nextProject = $('article[data-' + tarFilter + '="true"]').first().index() if tarFilter == 'all' waypointCheck.resetFilter() else #Hide li isCurrentActive = $('article').eq(currentProject).attr('data-'+ tarFilter) $('article').each( () -> tarRemoveIndex = $(this).index() tarRemoveLi = $(".navCounters ul li").eq(tarRemoveIndex) if !$(this).attr('data-'+ tarFilter) tarRemoveLi.removeClass('active scaleIn slideIn').addClass('scaleHide') else if isCurrentActive and tarRemoveIndex is currentProject tarRemoveLi.removeClass('slideIn scaleHide').addClass('scaleIn') else tarRemoveLi.removeClass('active slideIn scaleHide').addClass('scaleIn') ) #Is the current article being viewed in the filter? -> if not traverse if !isCurrentActive waypointCheck.currentProject = currentProject waypointCheck.nextProject = nextProject waypointCheck.traverseProject(false,true) $('.arrow-tab').addClass('hideArrow') waypointCheck.traverseProject = (goingBack, filterHit) -> waypointCheck.projectSlug = $('.main article').eq(@.nextProject).attr('id') waypointCheck.projectTitle = $('.main article').eq(@.nextProject).data('title') waypointCheck.ogfg = $('.main article').eq(@.nextProject).data('foreground') waypointCheck.ogbg = $('.main article').eq(@.nextProject).data('background') newTitle = 'One Iota — ' + waypointCheck.projectTitle if filterHit $('.main article').removeClass() $('.main article').eq(waypointCheck.currentProject).addClass('fadeOut') $('.navCounters ul li').eq(waypointCheck.nextProject).addClass('active') else $('.main article').removeClass() $('.main article').eq(waypointCheck.currentProject).addClass('fadeOut') $('.navCounters ul li').removeClass('active scaleIn slideIn') $('.navCounters ul li').eq(waypointCheck.currentProject).addClass('scaleIn') $('.navCounters ul li').eq(waypointCheck.nextProject).addClass('active slideIn') $("nav, .indexNav .icon-info").delay(100).stop().animate({ color: waypointCheck.ogfg }, 500, -> waypointCheck.lastFg = waypointCheck.ogfg $('html, body').stop().animate({ scrollTop: 0 backgroundColor: waypointCheck.ogbg }, 750, -> if this.nodeName == "BODY" return document.title = newTitle $('.main article').eq(waypointCheck.currentProject).hide() $('.main article').eq(waypointCheck.nextProject).show().addClass('slideInProject') waypointCheck.updateCanvas() if !goingBack history.pushState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) $.waypoints('refresh') removeSlide = setTimeout -> $('.main article').eq(waypointCheck.nextProject).removeClass('slideInProject') imageLoader.addImages(waypointCheck.nextProject) , 1000 ) ) waypointCheck.killArrowHelper = (timer) -> if timer killArrow = setTimeout -> $('.arrow-tab').removeClass('scaleIn').addClass('scaleOut') removeInt = setTimeout -> $('.arrow-tab').removeClass('showArrow').addClass('scaleIn hideArrow') , 500 , 3000 else $('.arrow-tab').removeClass('scaleIn').addClass('scaleOut') removeInt = setTimeout -> $('.arrow-tab').removeClass('showArrow scaleOut').addClass('scaleIn hideArrow') , 500 waypointCheck.touchWaypoints = -> $('body').waypoint triggerOnce: false offset: 'bottom-in-view' handler: (direction) -> if direction is 'down' targetLi = $('.navCounters li.active').next() targetLi.find('.arrow-tab').removeClass('hideArrow').addClass('0') clearTimeout(removeAni) removeAni = setTimeout -> waypointCheck.killArrowHelper(true) $('.arrow-tab').unbind('click') $('.arrow-tab').bind 'click', (event) -> event.preventDefault() waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.nextProject = $(this).parent().index() waypointCheck.traverseProject() $('.arrow-tab').removeClass('showArrow').addClass('hideArrow') , 500 else if direction is 'up' waypointCheck.killArrowHelper(false) $('ul.filterMenu li a').bind 'click', (event) -> #use toggle class $('li.eyeButton i.scaleInSevenFive').toggleClass('scaleOutSevenFive') $('ul.filterMenu li.scaleInMenu').toggle() waypointCheck.touchWaypoints() #Blood specific functions if window.isBlood BloodLoader = -> @bloogBG = 'images/blood.jpg' @teamShotz = [] @testimonialTimer @lastClass @instyCounter = 0 @teamCounter = 0 @groupTracker = true @stateTracker = 0 @iotaPics = [] @retryLoad = false @iotaInstySpots = ['.iotaInsty1','.iotaInsty2','.iotaInsty2','.iotaInsty2','.iotaInsty3','.iotaInsty4','.iotaInsty4','.iotaInsty4','.iotaInsty5'] @iotaInsty = 'https://api.instagram.com/v1/users/12427052/media/recent/?access_token=12427052.4e63227.ed7622088af644ffb3146a3f15b50063&count=9' bloodLoader = new BloodLoader() bloodLoader.instyAnimation = () -> if bloodLoader.groupTracker targetGroup = '.iotaInsty2' targetTeam = '.iotaTeam1' bloodLoader.groupTracker = false else targetGroup = '.iotaInsty4' targetTeam = '.iotaTeam2' bloodLoader.groupTracker = true switch bloodLoader.stateTracker when 0 $(targetGroup + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideDown') $(targetGroup + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideRight') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideRight') $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') teamTimeout1 = setTimeout -> $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideDown') ,1000 teamTimeout2 = setTimeout -> $(targetTeam + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideRight') ,1000 when 1 $(targetGroup + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideLeft') teamTimeout1 = setTimeout -> $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') ,1000 teamTimeout2 = setTimeout -> $(targetTeam + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideLeft') ,1000 else $(targetGroup + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideLeft') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideRight') if bloodLoader.groupTracker if bloodLoader.stateTracker < 2 bloodLoader.stateTracker++ else bloodLoader.stateTracker = 0 bloodLoader.loadInstyImages = (feed) -> instySpots = bloodLoader.iotaInstySpots instyPics = bloodLoader.iotaPics if instyPics.length isnt 0 imgItem = instyPics.shift() imgClass = instySpots.shift() if imgClass == bloodLoader.lastClass bloodLoader.instyCounter++ else bloodLoader.instyCounter = 0 bloodLoader.lastClass = imgClass img = new Image() timer = undefined img.src = imgItem img.title = img.alt = feed if img.complete or img.readyState is 4 $(img).addClass('instagram-pic scaleIn instyAni' + bloodLoader.instyCounter) $(img).appendTo(imgClass) bloodLoader.loadInstyImages(feed) else # handle 404 using setTimeout set at 10 seconds, adjust as needed timer = setTimeout(-> #bloodLoader.loadInstyImages() if imgItem.length isnt 0 $(img).unbind 'error load onreadystate' , 10000) $(img).bind 'error load onreadystatechange', (e) -> clearTimeout timer if e.type isnt 'error' #ADD IMAGE IN HERE $(img).addClass('instagram-pic scaleIn instyAni' + bloodLoader.instyCounter) $(img).appendTo(imgClass) bloodLoader.loadInstyImages(feed) else bloodLoader.loadInstyImages(feed) else animationInit = setInterval( -> bloodLoader.instyAnimation() , 4000) bloodLoader.loadTeamShotz = () -> if bloodLoader.teamShotz.length isnt 0 teamImg = bloodLoader.teamShotz.shift() img = new Image() teamTimer = undefined # if !window.location.origin # window.location.origin = window.location.protocol+"//"+window.location.host; # img.src = window.location.origin+'/'+teamImg.src img.src = teamImg.src img.title = img.alt = teamImg.title img.parentz = teamImg.parentz if img.complete or img.readyState is 4 $(''+img.parentz+'').find('.team-instagram').append(img) $(img).addClass('instagram-pic team-pic scaleIn instyAni' + bloodLoader.teamCounter) (if bloodLoader.teamCounter is 0 then bloodLoader.teamCounter++ else bloodLoader.teamCounter = 0) bloodLoader.loadTeamShotz() else teamTimer = setTimeout -> if !bloodLoader.retryLoad bloodLoader.retryLoad = true bloodLoader.teamShotz.unshift(teamImg) bloodLoader.loadTeamShotz() else bloodLoader.retryLoad = false $(img).unbind 'error load onreadystate' bloodLoader.loadTeamShotz() if teamImg.length isnt 0 , 15000 $(img).bind 'error load onreadystatechange', (e) -> clearTimeout teamTimer if e.type isnt 'error' $(''+img.parentz+'').find('.team-instagram').append(img) $(img).addClass('instagram-pic team-pic scaleIn instyAni' + bloodLoader.teamCounter) (if bloodLoader.teamCounter is 0 then bloodLoader.teamCounter++ else bloodLoader.teamCounter = 0) bloodLoader.loadTeamShotz() else bloodLoader.loadTeamShotz() bloodLoader.getInsty = () -> $.ajax url: bloodLoader.iotaInsty dataType: 'jsonp' cache: false success: (iotaImages) -> $.each(iotaImages.data, (index) -> bloodLoader.iotaPics.push(this.images.low_resolution.url) ) bloodLoader.loadInstyImages('@oneiota_') error: -> console.log 'run backup pics' bloodLoader.getTeamShotz = () -> $('.team-member').each( -> shotOne = {src : $(this).data('shot1'), title : $(this).data('imgalt'), parentz : $(this).data('parent')} shotTwo = {src : $(this).data('shot2'), title : $(this).data('imgalt'), parentz : $(this).data('parent')} bloodLoader.teamShotz.push(shotOne,shotTwo) ) bloodLoader.loadTeamShotz() bloodLoader.newsletterSignup = () -> $.ajax type: $('#newsletter-subscribe').attr('method') url: $('#newsletter-subscribe').attr('action') dataType: 'jsonp' data: $('#newsletter-subscribe').serialize() cache: false contentType: "application/json; charset=utf-8" error: (err) -> $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","*Sorry, please try again") success: (data) -> unless data.result is "success" $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder",data.msg) else $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","Thanks, stay tuned!") bloodLoader.isValidEmailAddress = () -> emailAddress = $('#newsletter-subscribe-email').val() pattern = new RegExp(/^((([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) pattern.test emailAddress #Load google map if !window.mapLoaded loadMap = setTimeout -> loadGoogleMaps() , 1000 window.mapLoaded = true #Blood Binds $('.icon-right-arrow-bare').bind('click', (event) -> event.preventDefault() clearInterval(bloodLoader.testimonialTimer) if $('.current-testimonial').index() != ($('.client-testimonial').length - 1) nextTest = $('.current-testimonial').next() else nextTest = $('.client-testimonial').eq(0) $('.current-testimonial').stop().animate({ left: '-100%' }, 100, -> $(this).toggleClass('current-testimonial') nextTest.css({'left':'100%'}).toggleClass('current-testimonial').stop().animate({ left: '0%' }, 100) ) ) $('.icon-left-arrow-bare').bind('click', (event) -> event.preventDefault() clearInterval(bloodLoader.testimonialTimer) if $('.current-testimonial').index() != 0 nextTest = $('.current-testimonial').prev() else nextTest = $('.client-testimonial').eq($('.client-testimonial').length - 1) $('.current-testimonial').stop().animate({ left: '100%' }, 100, -> $(this).toggleClass('current-testimonial') nextTest.css({'left':'-100%'}).toggleClass('current-testimonial').stop().animate({ left: '0%' }, 100) ) ) $("form input[type='email']").keypress (event) -> if event.which is 13 $("form input[type='submit']").trigger('click') return false $("form input[type='submit']").bind('click', (event) -> event.preventDefault() if event if bloodLoader.isValidEmailAddress() bloodLoader.newsletterSignup() else $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","*Sorry, give it another go") ) bloodLoader.testimonialTimer = setInterval -> $('.icon-right-arrow-bare').trigger('click') , 6000 #Elegant page object animation objectLoader.randomFade = () -> getRandomFade = () -> randomFade = objectLoader.fadeArray[Math.floor(Math.random() * objectLoader.fadeArray.length)] if randomFade != objectLoader.lastFade objectLoader.lastFade = randomFade randomFade else getRandomFade() getRandomFade() objectLoader.assignAnimationWaypoints = () -> if window.isBlood $(objectLoader.objectTarget).waypoint triggerOnce: true offset: '80%' handler: (direction) -> $(this).find(objectLoader.objectSubTarget).addClass('loaded') objectLoader.loadInternals($(this).index()) else if window.isPortfolio $(objectLoader.objectSubTarget).children().each( -> if $(this).hasClass('project-details') $(this).waypoint triggerOnce: true offset: '80%' handler: (direction) -> objectLoader.loadInternals($(this).parent().parent().index()) # else # $(this).waypoint # triggerOnce: true # offset: '50%' # handler: (direction) -> # if $(this).index() == 0 # $(this).addClass('loaded fadeInSlide') # else # fadeInEffect = objectLoader.randomFade() # $(this).addClass('loaded ' + fadeInEffect) ) objectLoader.loadInternals = (targetIndex) -> if window.isBlood targetContent = $(objectLoader.objectTarget).eq(targetIndex).find(objectLoader.objectSubTarget) else if window.isPortfolio targetContent = $(objectLoader.objectTarget).eq(targetIndex).find('.project-details') childArray = [] targetContent.children().each( (index) -> childArray.push(index) ) animateChildren = -> if childArray.length isnt 0 currChild = childArray.shift() if targetContent.children().eq(currChild).get(0).tagName == 'UL' subChildArray = [] parentTarget = targetContent.children().eq(currChild) parentTarget.children().each( (index) -> subChildArray.push(index) ) animateSubChildren = -> if subChildArray.length isnt 0 currSubChild = subChildArray.shift() parentTarget.children().eq(currSubChild).addClass('scaleIn') animateSubChildTimer = setTimeout -> animateSubChildren() , 100 else animateChildren() animateSubChildren() else targetContent.children().eq(currChild).addClass('fadeInSlide') animateChildTimer = setTimeout -> animateChildren() , 100 animateChildren() waypointCheck.showPortBtns = () -> showDistance = -20 $('.main').waypoint triggerOnce: true, offset: showDistance handler: (direction) -> if direction is 'down' $('body').removeClass('noNav') $('.explore').addClass('fadeOutSlow') killExplore = setTimeout () -> $('.explore').remove() , 700 if !window.isIE waypointCheck.makeCanvas() objectLoader.pageLoaded = () -> if !window.isTouch objectLoader.assignAnimationWaypoints() if !window.isPortfolio or window.isSingle $('nav').show() else # if sessionStorage.playedAlready == 'true' # $('.explore, .intro').remove() # $('nav').show() # $('.checkout-feed').show() # if !window.isIE # waypointCheck.makeCanvas() # else $('body').addClass('noNav') showMain = setTimeout -> if !window.isTouch $('.intro').removeClass('fadeIn').addClass('introOut') $('.main').addClass('scaleInBig') else $('.intro').removeClass('fadeIn').addClass('introOutTouch') showNav = setTimeout -> $('nav').show() waypointCheck.showPortBtns() $('.intro').remove() $('.main').removeClass('scaleInBig') $('.checkout-feed').show() if !window.isIE waypointCheck.makeCanvas() , 1200 if window.isBlood bloodLoader.getInsty() bloodLoader.getTeamShotz() #Binds historyController.bindPopstate = () -> $('.main article').each( -> historyController.slugArray.push($(this).attr('id')) ) $(window).bind 'popstate', () -> if historyController.popped historyController.prevSlug = window.location.pathname.slice(1) if historyController.prevSlug == 'bloodsweattears' if historyController.inMenu == true $('.icon-left-arrow').trigger('click') else $('.icon-info').trigger('click') else if historyController.prevSlug == 'contact' $('.icon-contact').trigger('click') else if historyController.inMenu == true $('.icon-close').trigger('click') else if window.isIndex #CHANGE FOR TOUCH DEBUG - DONE if window.isTouch if historyController.prevSlug == -1 || historyController.prevSlug == '' waypointCheck.nextProject = 0 else waypointCheck.nextProject = $.inArray(historyController.prevSlug,historyController.slugArray) waypointCheck.resetFilter(true) waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.traverseProject(true) else if $('#' + historyController.prevSlug).length || historyController.prevSlug == '' if historyController.prevSlug != '' scrollTarget = $('#' + historyController.prevSlug).position().top else scrollTarget = 0 historyController.scrollingBack = true $('html, body').stop().animate({ scrollTop: scrollTarget }, 'slow', -> if this.nodeName == "BODY" return historyController.scrollingBack = false if historyController.prevSlug == -1 || historyController.prevSlug == '' waypointCheck.updateTitle($('article').eq(0).attr('id'), true) else waypointCheck.updateTitle(historyController.prevSlug, true) ) else window.location.href = '/' + historyController.prevSlug else window.location.href = '/' historyController.popped = true #Doc deady $ -> $('a.nav-item').bind 'click', (event) -> event.preventDefault() if !$(this).parent().hasClass('active') # CHANGE FOR TOUCH DEBUG - DONE if window.isTouch waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.nextProject = $(this).parent().index() waypointCheck.traverseProject() $('.arrow-tab').addClass('hideArrow') else thisSlug = $(this).attr('href').slice(1) targetIndex = $(this).parent().index() scrollTarget = $('#' + thisSlug).position().top scrollSpeed = waypointCheck.relativeSpeed(scrollTarget) articleID = $('article').eq(targetIndex).attr('id') historyController.scrollingBack = true $('.arrow-tab').removeClass('showArrow').addClass('hideArrow').css('visibility','hidden') $('html, body').stop().animate({ scrollTop: scrollTarget }, scrollSpeed, -> if this.nodeName == "BODY" return historyController.scrollingBack = false imageLoader.addImages(targetIndex) waypointCheck.updateTitle(articleID, false, true) $('.arrow-tab').css('visibility','visible') ) $('.description').one 'click', (event) -> $(this).toggleClass('expand') $('.icon-info').bind 'click', (event) -> event.preventDefault() historyController.inMenu = true history.pushState(null, 'iota &#8212; blood,sweat,tears', '') $('.main').addClass('openmenu') $('body').addClass('menu') $('.bottom-hud ul').removeClass('scaleIn') $('.menuNav').addClass('scaleIn') $('.overlay').removeClass('closemenu').addClass('openmenu') waypointCheck.updateColors('#ffffff','#262626') if window.isTouch hideMain = setTimeout -> $('.main').hide() , 500 $('.icon-close').bind 'click', (event) -> event.preventDefault() historyController.inMenu = false history.replaceState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) $('.main').show().removeClass('openmenu') $('body').removeClass('menu') $('.bottom-hud ul').removeClass('scaleIn') $('.indexNav').addClass('scaleIn') $('.overlay').removeClass('openmenu').addClass('closemenu') waypointCheck.updateColors(waypointCheck.ogfg,waypointCheck.ogbg) $('.icon-contact').bind 'click', (event) -> event.preventDefault() history.pushState(null, 'iota &#8212; contact', '') $('.contact, .mainmenu, body').removeClass('closecontact') $('.contact, .mainmenu, body').addClass('opencontact') $('.bottom-hud ul').removeClass('scaleIn') $('.infoNav').addClass('scaleIn') $('.icon-left-arrow').bind 'click', (event) -> event.preventDefault() history.replaceState(null, 'iota &#8212; blood,sweat,tears', '') $('.contact, .mainmenu, body').removeClass('opencontact') $('.contact, .mainmenu, body').addClass('closecontact') $('.bottom-hud ul').removeClass('scaleIn') $('.menuNav').addClass('scaleIn') $('.icon-down-arrow-bare').bind 'click', (event) -> event.preventDefault() $('.navCounters ul li').toggleClass('mobile-hide').addClass('scaleIn') $('.icon-up-arrow-bare').css('display','block') $('.icon-up-arrow-bare').bind 'click', (event) -> event.preventDefault() $('.navCounters ul li').toggleClass('mobile-hide').addClass('scaleIn') if !window.isTouch $('.menuItem').not('.active').hover (-> foreground = $(this).data('foreground') background = $(this).data('background') $('.menuItem.active span').css('opacity','0.2') mainMenu.updateColors(foreground, background) $(this).find('.meaning').addClass('fadeIn') ), -> mainMenu.updateColors(mainMenu.ogfg, mainMenu.ogbg) $('.menuItem.active span').css('opacity','1') window.getItStarted = () -> $('.main').show() ##Index specific startup functions if window.isPortfolio and !window.isTouch and !window.isSingle waypointCheck.assignArticleWaypoints() if window.isIndex waypointCheck.footerWaypoint() ##Site wide startup functions imageLoader.addImages(0) objectLoader.pageLoaded() historyController.bindPopstate() if window.isPortfolio and !window.isSingle and !window.isIE window.loadGame() else if window.isFeed window.loadFeed() else window.getItStarted()
182464
#= require vendor/waypoints2.0.2.min #= require vendor/jquery-ui-1.9.2.custom #= require vendor/jquery.color-2.1.2.min.js #= require vendor/jquery.ui.touch-punch.min #= require feed #= require intro window.isTouch = if ($('html').hasClass('touch')) then true else false window.isCanvas = if ($('html').hasClass('canvas')) then true else false window.isIndex = if $('body').hasClass('index') then true else false window.isFeed = if $('body').hasClass('feed') then true else false window.isPortfolio = if $('body').hasClass('portfolio') then true else false window.isBlood = if $('body').hasClass('blood') then true else false window.isSingle = if $('body').hasClass('singleProject') or $('body').hasClass('singlePost') then true else false window.isIE = if $('html').hasClass('lt-ie9') then true else false window.mapLoaded = false window.cantanimate = if $('html').hasClass('no-cssanimations') then true else false ## New Constructors HistoryController = -> @slugArray = [] @popped = false @prevSlug @currSlug @inMenu @scrollingBack = false historyController = new HistoryController() WaypointCheck = -> @filteredItems = [] @articesLoaded = false @isLoading = false @currentProject = 0 @nextProject @hudTimer @currentDirection @projectSlug = $('article:eq(0)').attr('id') @projectTitle = $('article:eq(0)').data('title') @ogfg = $('article:eq(0)').data('foreground') @ogbg = $('article:eq(0)').data('background') @lastProject = $('article').length - 1 @lastFg @projects @showArrow @hideArrow @resetArrow @footerOpen = false @lastIndex = 0 @arrowTab = '<div class="arrow-tab"><a href="#"></a><span>' waypointCheck = new WaypointCheck() ImageLoader = -> @loadArray = [] @screenSize = if (screen.width > 880) then 'desktop' else 'mobile' @loadTimer = null @retryLoad = false imageLoader = new ImageLoader() MainMenu = -> @ogbg = '#262626' @ogfg = '#ffffff' mainMenu = new MainMenu() ObjectLoader = -> @fadeArray = ['fadeInSlide','fadeInSlideR','fadeInSlideL'] @lastFade if window.isBlood @objectTarget = 'section' @objectSubTarget = '.content' else @objectTarget = 'article' @objectSubTarget = '.project' objectLoader = new ObjectLoader() CanvasArrow = (location, arrowWidth) -> element = document.createElement('canvas') $(element) .attr('width', arrowWidth + 40).attr('height', '40') if arrowWidth >= 160 arrowWidth = Math.abs(arrowWidth - 160) else arrowWidth = Math.abs(arrowWidth - 160) * -1 context = element.getContext("2d") context.fillStyle = waypointCheck.ogfg context.bezierCurveTo((179.965+arrowWidth),0.945,(177.65+arrowWidth),0,(176+arrowWidth),0) context.lineTo((171+arrowWidth),0) context.lineTo(7,0) context.bezierCurveTo(3.15,0,0,3.15,0,7) context.lineTo(0,33) context.bezierCurveTo(0,36.85,3.15,40,7,40) context.lineTo((171+arrowWidth),40) context.lineTo((176+arrowWidth),40) context.bezierCurveTo((177.65+arrowWidth),40,(179.965+arrowWidth),39.055,(181.143+arrowWidth),37.9) context.lineTo((197.269+arrowWidth),22.1) context.bezierCurveTo((198.447+arrowWidth),20.945,(198.447+arrowWidth),19.055,(197.269+arrowWidth),17.9) context.closePath() context.fill() return element waypointCheck.updateColors = (foreground, background) -> waypointCheck.lastFg = foreground if waypointCheck.footerOpen closeColor = background else closeColor = foreground $('nav').stop().animate({ color: foreground }, 500) $('.indexNav .icon-info').stop().animate({ color: closeColor }, 500, () -> if window.isIE $('.indexNav .icon-info').trigger('focus') setTimeout -> $('.indexNav .icon-info').blur() 10 ) $('.navCounters .navPanel').stop().animate({ backgroundColor: background }, 500 ) if window.isCanvas waypointCheck.updateCanvas() else $('.arrow-tab').css('color', foreground) waypointCheck.endofline = (foreground) -> $('.indexNav .icon-info').stop().animate({ color: foreground }, 500 ) waypointCheck.makeCanvas = -> $('.navCounters ul li .arrow-tab').each(-> liWidth = $(this).width() liIndex = $(this).parent().index() canvasArrow = new CanvasArrow(liIndex, liWidth) $(canvasArrow) .addClass('canvasArrow') .text('unsupported browser') .appendTo($(this)) ) waypointCheck.updateCanvas = -> $('.arrow-tab').css({'color':waypointCheck.ogbg}) $('.canvasArrow').remove() waypointCheck.makeCanvas() waypointCheck.relativeSpeed = (scrollTarget) -> topDistance = $(document).scrollTop() scrollSpeed = Math.abs((Math.abs(scrollTarget) - $(document).scrollTop())/10) scrollSpeed # console.log scrollSpeed * 100 window.initialiseMaps = () -> # Bris Map MY_MAPTYPE_ID = 'custom_style'; brisMapOptions = zoom: 16 center: new google.maps.LatLng(-27.45480, 153.03905) disableDefaultUI: true zoomControl: false scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false draggable: if window.isTouch and imageLoader.screenSize is 'mobile' then false else true backgroundColor: '#262626' zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL position: google.maps.ControlPosition.TOP_RIGHT mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID] }, mapTypeId: MY_MAPTYPE_ID featureOpts = [ featureType: 'all' elementType: 'all' stylers: [ invert_lightness: true , saturation: -100 , lightness: 5 ] ] brismap = new google.maps.Map(document.getElementById("brismap"), brisMapOptions) if window.isCanvas iotaImage = '../images/iotaMarker.svg'; else iotaImage = '../images/iotaMarker.png'; iotaLatLng = new google.maps.LatLng(-27.45480, 153.03905); iotaMarker = new google.maps.Marker( clickable: false position: iotaLatLng map: brismap icon: iotaImage title: 'One Iota Brisbane' ) styledMapOptions = name: 'Custom Style' customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions) brismap.mapTypes.set(MY_MAPTYPE_ID, customMapType) # Syd Map SYD_MAPTYPE_ID = 'sydney_custom_style'; sydMapOptions = zoom: 16 center: new google.maps.LatLng(-33.861468, 151.209180) disableDefaultUI: true zoomControl: false scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false draggable: if window.isTouch and imageLoader.screenSize is 'mobile' then false else true backgroundColor: '#58585a' zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL position: google.maps.ControlPosition.TOP_RIGHT mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, SYD_MAPTYPE_ID] }, mapTypeId: SYD_MAPTYPE_ID sydFeatureOpts = [ {"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#58585a"},{"lightness":-25},{"saturation":-97}]} ] sydmap = new google.maps.Map(document.getElementById("sydmap"), sydMapOptions) if window.isCanvas sydIotaImage = '../images/iotaMarkerSyd.svg'; else sydIotaImage = '../images/iotaMarkerSyd.png'; iotaLatLng = new google.maps.LatLng(-33.861468, 151.209180); iotaMarker = new google.maps.Marker( clickable: false position: iotaLatLng map: sydmap icon: sydIotaImage title: 'One Iota Sydney' ) sydStyledMapOptions = name: 'Custom Style' sydCustomMapType = new google.maps.StyledMapType(sydFeatureOpts, sydStyledMapOptions) sydmap.mapTypes.set(SYD_MAPTYPE_ID, sydCustomMapType) loadGoogleMaps = () -> googleMaps = document.createElement("script") googleMaps.type = "text/javascript" googleMaps.src = "https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false&callback=window.initialiseMaps" document.body.appendChild googleMaps mainMenu.updateColors = (foreground, background) -> $(".overlay").stop().animate({ backgroundColor: background }, 300 ) imageLoader.imageLoaded = (img) -> targetArticle = $('article').eq(img.imgParent) targetPlaceholder = targetArticle.find('span.placeholder-bg').eq(0) targetParentIndex = targetPlaceholder.parent().index() targetAlt = targetArticle.find('span.placeholder-alt').eq(0) targetPlaceholder.after($(img)) if targetParentIndex is 0 $(img).addClass('loaded fadeInSlide') else fadeInEffect = objectLoader.randomFade() $(img).addClass('loaded ' + fadeInEffect) targetPlaceholder.remove() targetAlt.remove() imageLoader.loadImage() imageLoader.loadImage = -> if imageLoader.loadArray.length isnt 0 imgItem = imageLoader.loadArray.shift() img = new Image() imgTimer = undefined img.src = imgItem.imgSrc img.title = img.alt = imgItem.imgTitle img.imgParent = imgItem.imgParent if img.complete or img.readyState is 4 imageLoader.imageLoaded(img) else imgTimer = setTimeout -> if !imageLoader.retryLoad imageLoader.retryLoad = true imageLoader.loadArray.unshift(imgItem) imageLoader.loadImage() else imageLoader.retryLoad = false $(img).unbind 'error load onreadystate' imageLoader.loadImage() if imgItem.length isnt 0 , 15000 $(img).bind 'error load onreadystatechange', (e) -> clearTimeout imgTimer if e.type isnt 'error' imageLoader.imageLoaded(img) else imageLoader.loadImage() imageLoader.addImages = (articleIndex) -> if !$('article').eq(articleIndex).hasClass('loaded') targetArticles = $('article').eq(articleIndex).find('span.placeholder-bg') targetArticles.each (index) -> imgItem = {} imgItem.imgSrc = targetArticles.eq(index).data(imageLoader.screenSize) imgItem.imgTitle = targetArticles.eq(index).attr('alt') imgItem.imgParent = articleIndex imageLoader.loadArray.push(imgItem) if index == targetArticles.length - 1 imageLoader.loadImage() $('article').eq(articleIndex).addClass('loaded') #Index Specific if window.isIndex FlipSquare = -> @colArr = ['#d83b65','#e55d87','#e55d87','#5fc3e4','#5ec4e5','#50d97a','#edde5d','#f09819','#ff512f','#dd2476','#1b0109'] @sqrArr = [] @hozDivs = 4 @screenW = $(window).width() @screenH = $(window).height() @squareW = @screenW / @hozDivs @squareH = $(window).height() / Math.floor($(window).height() / @squareW) @numSq = @hozDivs * ($(window).height() / @squareH) @tester = true @tester2 = true flipSquare = new FlipSquare() waypointCheck.footerWaypoint = -> # $('body').waypoint $('body').waypoint triggerOnce: false offset: 'bottom-in-view' handler: (direction) -> fgColor = $('.checkout-feed').data('fgcolor') if direction is 'down' if window.isTouch && waypointCheck.nextProject != waypointCheck.lastProject return false else waypointCheck.endofline(fgColor) if !waypointCheck.footerOpen $('.checkout-feed').removeClass('slideUpFooter slideDownFooter').addClass('slideUpFooter') addFade = setTimeout -> $('.checkout-feed h3').addClass('fadeIn') , 200 waypointCheck.footerOpen = true else waypointCheck.endofline(waypointCheck.lastFg) if waypointCheck.footerOpen $('.checkout-feed').removeClass('slideUpFooter slideDownFooter').addClass('slideDownFooter') $('.checkout-feed h3').removeClass('fadeIn') waypointCheck.footerOpen = false #Non Touch Handlers # CHANGE FOR TOUCH DEBUG - DONE if !window.isTouch waypointCheck.resetFilter = () -> $.each waypointCheck.filteredItems, (i) -> tarLi = waypointCheck.filteredItems[i].filteredLi tarArt = waypointCheck.filteredItems[i].filteredArticle tarID = waypointCheck.filteredItems[i].lastID if !tarID $(".navCounters ul li").eq(0).before(tarLi) $('article').eq(0).before(tarArt) else $('a[href="/' + tarID + '"]').parent().after(tarLi) $('article[id="' + tarID + '"]').after(tarArt) waypointCheck.filteredItems = [] $.waypoints('enable') $.waypoints('refresh') objectLoader.assignAnimationWaypoints() $('.filterMenu a').bind 'click', (event) -> event.preventDefault() if not $(this).parent().hasClass("eyeButton") if not $(this).parent().hasClass("active") $('.filterMenu li').removeClass('active') $(this).parent().addClass('active') tarFilter = $(this).data('filter') $('.navCounters').css('visibility','hidden') if waypointCheck.filteredItems.length isnt 0 if tarFilter == 'all' $('html, body').stop().animate({ scrollTop: 0 }, 750, -> if this.nodeName == "BODY" return waypointCheck.resetFilter() $.waypoints('refresh') $('.navCounters').css('visibility','visible') ) else waypointCheck.resetFilter() if tarFilter isnt 'all' $('html, body').stop().animate({ scrollTop: 0 }, 750, -> if this.nodeName == "BODY" return historyController.scrollingBack = true $('article').each( -> if !$(this).attr('data-'+ tarFilter) $(this).waypoint('disable') tarFilterIndex = $(this).index() tarLastId = $(this).prev().attr('id') filteredItem = lastID: tarLastId filteredArticle: $(this).detach() filteredLi: $(".navCounters ul li").eq(tarFilterIndex).removeClass('active').detach() waypointCheck.filteredItems.push(filteredItem) ) historyController.scrollingBack = false $.waypoints('refresh') $('.navCounters').css('visibility','visible') ) waypointCheck.updateTitle = (articleId, popped, navLiHit) -> if !historyController.scrollingBack currentArticle = $('#'+ articleId) currentIndex = currentArticle.index() waypointCheck.projectSlug = currentArticle.attr('id') waypointCheck.projectTitle = currentArticle.data('title') @.ogfg = waypointCheck.ogfg = currentArticle.data('foreground') @.ogbg = waypointCheck.ogbg = currentArticle.data('background') waypointCheck.updateColors(@.ogfg, @.ogbg) newTitle = 'One Iota — ' + waypointCheck.projectTitle document.title = newTitle $('.navCounters ul li').removeClass('active scaleIn slideIn') if waypointCheck.lastIndex != currentIndex $('.navCounters ul li').eq(waypointCheck.lastIndex).addClass('scaleIn') $('.navCounters ul li').eq(currentIndex).addClass('active slideIn') else $('.navCounters ul li').eq(currentIndex).addClass('active slideIn') if !navLiHit clearTimeout(waypointCheck.showArrow) clearTimeout(waypointCheck.hideArrow) clearTimeout(waypointCheck.resetArrow) targetArrow = $('.navCounters ul li').eq(currentIndex).find('.arrow-tab') $('.arrow-tab').css('visibility','hidden') targetArrow.css('visibility','visible') waypointCheck.showArrow = setTimeout(-> targetArrow.removeClass('hideArrow').addClass('showArrow scaleIn') waypointCheck.hideArrow = setTimeout(-> targetArrow.removeClass('scaleIn').addClass('scaleOut') waypointCheck.resetArrow = setTimeout(-> $('.arrow-tab').removeClass('scaleOut showArrow').addClass('scaleIn hideArrow').css('visibility','visible') ,500) ,2000) ,1000) if not popped history.pushState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) else history.replaceState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) waypointCheck.lastIndex = currentIndex ## Assign Waypoints waypointCheck.assignArticleWaypoints = -> $('article:gt(0)').waypoint triggerOnce: false offset: '100%' handler: (direction) -> if !historyController.scrollingBack articleIndex = ($('article').index($('#' + @id))) if direction is 'down' waypointCheck.updateTitle(@id) imageLoader.addImages(articleIndex) else waypointCheck.updateTitle($('article').eq(articleIndex-1).attr('id')) imageLoader.addImages(articleIndex-1) #Touch Handlers else $('.main article').css('background','transparent') window.addEventListener 'load', -> setTimeout -> window.scrollTo(0, 1) , 0 waypointCheck.resetFilter = (isAll) -> if isAll $('.filterMenu li').removeClass('active') $('.filterMenu li').eq(1).addClass('active') $(".navCounters ul li").each( -> $(this).removeClass('scaleHide slideIn').addClass('scaleIn') ) $('.filterMenu a').bind 'click', (event) -> event.preventDefault() if not $(this).parent().hasClass("eyeButton") if not $(this).parent().hasClass("active") $('.filterMenu li').removeClass('active') $(this).parent().addClass('active') tarFilter = $(this).data('filter') currentProject = $('.navCounters li.active').index() nextProject = $('article[data-' + tarFilter + '="true"]').first().index() if tarFilter == 'all' waypointCheck.resetFilter() else #Hide li isCurrentActive = $('article').eq(currentProject).attr('data-'+ tarFilter) $('article').each( () -> tarRemoveIndex = $(this).index() tarRemoveLi = $(".navCounters ul li").eq(tarRemoveIndex) if !$(this).attr('data-'+ tarFilter) tarRemoveLi.removeClass('active scaleIn slideIn').addClass('scaleHide') else if isCurrentActive and tarRemoveIndex is currentProject tarRemoveLi.removeClass('slideIn scaleHide').addClass('scaleIn') else tarRemoveLi.removeClass('active slideIn scaleHide').addClass('scaleIn') ) #Is the current article being viewed in the filter? -> if not traverse if !isCurrentActive waypointCheck.currentProject = currentProject waypointCheck.nextProject = nextProject waypointCheck.traverseProject(false,true) $('.arrow-tab').addClass('hideArrow') waypointCheck.traverseProject = (goingBack, filterHit) -> waypointCheck.projectSlug = $('.main article').eq(@.nextProject).attr('id') waypointCheck.projectTitle = $('.main article').eq(@.nextProject).data('title') waypointCheck.ogfg = $('.main article').eq(@.nextProject).data('foreground') waypointCheck.ogbg = $('.main article').eq(@.nextProject).data('background') newTitle = 'One Iota — ' + waypointCheck.projectTitle if filterHit $('.main article').removeClass() $('.main article').eq(waypointCheck.currentProject).addClass('fadeOut') $('.navCounters ul li').eq(waypointCheck.nextProject).addClass('active') else $('.main article').removeClass() $('.main article').eq(waypointCheck.currentProject).addClass('fadeOut') $('.navCounters ul li').removeClass('active scaleIn slideIn') $('.navCounters ul li').eq(waypointCheck.currentProject).addClass('scaleIn') $('.navCounters ul li').eq(waypointCheck.nextProject).addClass('active slideIn') $("nav, .indexNav .icon-info").delay(100).stop().animate({ color: waypointCheck.ogfg }, 500, -> waypointCheck.lastFg = waypointCheck.ogfg $('html, body').stop().animate({ scrollTop: 0 backgroundColor: waypointCheck.ogbg }, 750, -> if this.nodeName == "BODY" return document.title = newTitle $('.main article').eq(waypointCheck.currentProject).hide() $('.main article').eq(waypointCheck.nextProject).show().addClass('slideInProject') waypointCheck.updateCanvas() if !goingBack history.pushState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) $.waypoints('refresh') removeSlide = setTimeout -> $('.main article').eq(waypointCheck.nextProject).removeClass('slideInProject') imageLoader.addImages(waypointCheck.nextProject) , 1000 ) ) waypointCheck.killArrowHelper = (timer) -> if timer killArrow = setTimeout -> $('.arrow-tab').removeClass('scaleIn').addClass('scaleOut') removeInt = setTimeout -> $('.arrow-tab').removeClass('showArrow').addClass('scaleIn hideArrow') , 500 , 3000 else $('.arrow-tab').removeClass('scaleIn').addClass('scaleOut') removeInt = setTimeout -> $('.arrow-tab').removeClass('showArrow scaleOut').addClass('scaleIn hideArrow') , 500 waypointCheck.touchWaypoints = -> $('body').waypoint triggerOnce: false offset: 'bottom-in-view' handler: (direction) -> if direction is 'down' targetLi = $('.navCounters li.active').next() targetLi.find('.arrow-tab').removeClass('hideArrow').addClass('0') clearTimeout(removeAni) removeAni = setTimeout -> waypointCheck.killArrowHelper(true) $('.arrow-tab').unbind('click') $('.arrow-tab').bind 'click', (event) -> event.preventDefault() waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.nextProject = $(this).parent().index() waypointCheck.traverseProject() $('.arrow-tab').removeClass('showArrow').addClass('hideArrow') , 500 else if direction is 'up' waypointCheck.killArrowHelper(false) $('ul.filterMenu li a').bind 'click', (event) -> #use toggle class $('li.eyeButton i.scaleInSevenFive').toggleClass('scaleOutSevenFive') $('ul.filterMenu li.scaleInMenu').toggle() waypointCheck.touchWaypoints() #Blood specific functions if window.isBlood BloodLoader = -> @bloogBG = 'images/blood.jpg' @teamShotz = [] @testimonialTimer @lastClass @instyCounter = 0 @teamCounter = 0 @groupTracker = true @stateTracker = 0 @iotaPics = [] @retryLoad = false @iotaInstySpots = ['.iotaInsty1','.iotaInsty2','.iotaInsty2','.iotaInsty2','.iotaInsty3','.iotaInsty4','.iotaInsty4','.iotaInsty4','.iotaInsty5'] @iotaInsty = 'https://api.instagram.com/v1/users/12427052/media/recent/?access_token=<PASSWORD>&count=9' bloodLoader = new BloodLoader() bloodLoader.instyAnimation = () -> if bloodLoader.groupTracker targetGroup = '.iotaInsty2' targetTeam = '.iotaTeam1' bloodLoader.groupTracker = false else targetGroup = '.iotaInsty4' targetTeam = '.iotaTeam2' bloodLoader.groupTracker = true switch bloodLoader.stateTracker when 0 $(targetGroup + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideDown') $(targetGroup + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideRight') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideRight') $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') teamTimeout1 = setTimeout -> $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideDown') ,1000 teamTimeout2 = setTimeout -> $(targetTeam + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideRight') ,1000 when 1 $(targetGroup + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideLeft') teamTimeout1 = setTimeout -> $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') ,1000 teamTimeout2 = setTimeout -> $(targetTeam + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideLeft') ,1000 else $(targetGroup + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideLeft') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideRight') if bloodLoader.groupTracker if bloodLoader.stateTracker < 2 bloodLoader.stateTracker++ else bloodLoader.stateTracker = 0 bloodLoader.loadInstyImages = (feed) -> instySpots = bloodLoader.iotaInstySpots instyPics = bloodLoader.iotaPics if instyPics.length isnt 0 imgItem = instyPics.shift() imgClass = instySpots.shift() if imgClass == bloodLoader.lastClass bloodLoader.instyCounter++ else bloodLoader.instyCounter = 0 bloodLoader.lastClass = imgClass img = new Image() timer = undefined img.src = imgItem img.title = img.alt = feed if img.complete or img.readyState is 4 $(img).addClass('instagram-pic scaleIn instyAni' + bloodLoader.instyCounter) $(img).appendTo(imgClass) bloodLoader.loadInstyImages(feed) else # handle 404 using setTimeout set at 10 seconds, adjust as needed timer = setTimeout(-> #bloodLoader.loadInstyImages() if imgItem.length isnt 0 $(img).unbind 'error load onreadystate' , 10000) $(img).bind 'error load onreadystatechange', (e) -> clearTimeout timer if e.type isnt 'error' #ADD IMAGE IN HERE $(img).addClass('instagram-pic scaleIn instyAni' + bloodLoader.instyCounter) $(img).appendTo(imgClass) bloodLoader.loadInstyImages(feed) else bloodLoader.loadInstyImages(feed) else animationInit = setInterval( -> bloodLoader.instyAnimation() , 4000) bloodLoader.loadTeamShotz = () -> if bloodLoader.teamShotz.length isnt 0 teamImg = bloodLoader.teamShotz.shift() img = new Image() teamTimer = undefined # if !window.location.origin # window.location.origin = window.location.protocol+"//"+window.location.host; # img.src = window.location.origin+'/'+teamImg.src img.src = teamImg.src img.title = img.alt = teamImg.title img.parentz = teamImg.parentz if img.complete or img.readyState is 4 $(''+img.parentz+'').find('.team-instagram').append(img) $(img).addClass('instagram-pic team-pic scaleIn instyAni' + bloodLoader.teamCounter) (if bloodLoader.teamCounter is 0 then bloodLoader.teamCounter++ else bloodLoader.teamCounter = 0) bloodLoader.loadTeamShotz() else teamTimer = setTimeout -> if !bloodLoader.retryLoad bloodLoader.retryLoad = true bloodLoader.teamShotz.unshift(teamImg) bloodLoader.loadTeamShotz() else bloodLoader.retryLoad = false $(img).unbind 'error load onreadystate' bloodLoader.loadTeamShotz() if teamImg.length isnt 0 , 15000 $(img).bind 'error load onreadystatechange', (e) -> clearTimeout teamTimer if e.type isnt 'error' $(''+img.parentz+'').find('.team-instagram').append(img) $(img).addClass('instagram-pic team-pic scaleIn instyAni' + bloodLoader.teamCounter) (if bloodLoader.teamCounter is 0 then bloodLoader.teamCounter++ else bloodLoader.teamCounter = 0) bloodLoader.loadTeamShotz() else bloodLoader.loadTeamShotz() bloodLoader.getInsty = () -> $.ajax url: bloodLoader.iotaInsty dataType: 'jsonp' cache: false success: (iotaImages) -> $.each(iotaImages.data, (index) -> bloodLoader.iotaPics.push(this.images.low_resolution.url) ) bloodLoader.loadInstyImages('@oneiota_') error: -> console.log 'run backup pics' bloodLoader.getTeamShotz = () -> $('.team-member').each( -> shotOne = {src : $(this).data('shot1'), title : $(this).data('imgalt'), parentz : $(this).data('parent')} shotTwo = {src : $(this).data('shot2'), title : $(this).data('imgalt'), parentz : $(this).data('parent')} bloodLoader.teamShotz.push(shotOne,shotTwo) ) bloodLoader.loadTeamShotz() bloodLoader.newsletterSignup = () -> $.ajax type: $('#newsletter-subscribe').attr('method') url: $('#newsletter-subscribe').attr('action') dataType: 'jsonp' data: $('#newsletter-subscribe').serialize() cache: false contentType: "application/json; charset=utf-8" error: (err) -> $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","*Sorry, please try again") success: (data) -> unless data.result is "success" $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder",data.msg) else $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","Thanks, stay tuned!") bloodLoader.isValidEmailAddress = () -> emailAddress = $('#newsletter-subscribe-email').val() pattern = new RegExp(/^((([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) pattern.test emailAddress #Load google map if !window.mapLoaded loadMap = setTimeout -> loadGoogleMaps() , 1000 window.mapLoaded = true #Blood Binds $('.icon-right-arrow-bare').bind('click', (event) -> event.preventDefault() clearInterval(bloodLoader.testimonialTimer) if $('.current-testimonial').index() != ($('.client-testimonial').length - 1) nextTest = $('.current-testimonial').next() else nextTest = $('.client-testimonial').eq(0) $('.current-testimonial').stop().animate({ left: '-100%' }, 100, -> $(this).toggleClass('current-testimonial') nextTest.css({'left':'100%'}).toggleClass('current-testimonial').stop().animate({ left: '0%' }, 100) ) ) $('.icon-left-arrow-bare').bind('click', (event) -> event.preventDefault() clearInterval(bloodLoader.testimonialTimer) if $('.current-testimonial').index() != 0 nextTest = $('.current-testimonial').prev() else nextTest = $('.client-testimonial').eq($('.client-testimonial').length - 1) $('.current-testimonial').stop().animate({ left: '100%' }, 100, -> $(this).toggleClass('current-testimonial') nextTest.css({'left':'-100%'}).toggleClass('current-testimonial').stop().animate({ left: '0%' }, 100) ) ) $("form input[type='email']").keypress (event) -> if event.which is 13 $("form input[type='submit']").trigger('click') return false $("form input[type='submit']").bind('click', (event) -> event.preventDefault() if event if bloodLoader.isValidEmailAddress() bloodLoader.newsletterSignup() else $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","*Sorry, give it another go") ) bloodLoader.testimonialTimer = setInterval -> $('.icon-right-arrow-bare').trigger('click') , 6000 #Elegant page object animation objectLoader.randomFade = () -> getRandomFade = () -> randomFade = objectLoader.fadeArray[Math.floor(Math.random() * objectLoader.fadeArray.length)] if randomFade != objectLoader.lastFade objectLoader.lastFade = randomFade randomFade else getRandomFade() getRandomFade() objectLoader.assignAnimationWaypoints = () -> if window.isBlood $(objectLoader.objectTarget).waypoint triggerOnce: true offset: '80%' handler: (direction) -> $(this).find(objectLoader.objectSubTarget).addClass('loaded') objectLoader.loadInternals($(this).index()) else if window.isPortfolio $(objectLoader.objectSubTarget).children().each( -> if $(this).hasClass('project-details') $(this).waypoint triggerOnce: true offset: '80%' handler: (direction) -> objectLoader.loadInternals($(this).parent().parent().index()) # else # $(this).waypoint # triggerOnce: true # offset: '50%' # handler: (direction) -> # if $(this).index() == 0 # $(this).addClass('loaded fadeInSlide') # else # fadeInEffect = objectLoader.randomFade() # $(this).addClass('loaded ' + fadeInEffect) ) objectLoader.loadInternals = (targetIndex) -> if window.isBlood targetContent = $(objectLoader.objectTarget).eq(targetIndex).find(objectLoader.objectSubTarget) else if window.isPortfolio targetContent = $(objectLoader.objectTarget).eq(targetIndex).find('.project-details') childArray = [] targetContent.children().each( (index) -> childArray.push(index) ) animateChildren = -> if childArray.length isnt 0 currChild = childArray.shift() if targetContent.children().eq(currChild).get(0).tagName == 'UL' subChildArray = [] parentTarget = targetContent.children().eq(currChild) parentTarget.children().each( (index) -> subChildArray.push(index) ) animateSubChildren = -> if subChildArray.length isnt 0 currSubChild = subChildArray.shift() parentTarget.children().eq(currSubChild).addClass('scaleIn') animateSubChildTimer = setTimeout -> animateSubChildren() , 100 else animateChildren() animateSubChildren() else targetContent.children().eq(currChild).addClass('fadeInSlide') animateChildTimer = setTimeout -> animateChildren() , 100 animateChildren() waypointCheck.showPortBtns = () -> showDistance = -20 $('.main').waypoint triggerOnce: true, offset: showDistance handler: (direction) -> if direction is 'down' $('body').removeClass('noNav') $('.explore').addClass('fadeOutSlow') killExplore = setTimeout () -> $('.explore').remove() , 700 if !window.isIE waypointCheck.makeCanvas() objectLoader.pageLoaded = () -> if !window.isTouch objectLoader.assignAnimationWaypoints() if !window.isPortfolio or window.isSingle $('nav').show() else # if sessionStorage.playedAlready == 'true' # $('.explore, .intro').remove() # $('nav').show() # $('.checkout-feed').show() # if !window.isIE # waypointCheck.makeCanvas() # else $('body').addClass('noNav') showMain = setTimeout -> if !window.isTouch $('.intro').removeClass('fadeIn').addClass('introOut') $('.main').addClass('scaleInBig') else $('.intro').removeClass('fadeIn').addClass('introOutTouch') showNav = setTimeout -> $('nav').show() waypointCheck.showPortBtns() $('.intro').remove() $('.main').removeClass('scaleInBig') $('.checkout-feed').show() if !window.isIE waypointCheck.makeCanvas() , 1200 if window.isBlood bloodLoader.getInsty() bloodLoader.getTeamShotz() #Binds historyController.bindPopstate = () -> $('.main article').each( -> historyController.slugArray.push($(this).attr('id')) ) $(window).bind 'popstate', () -> if historyController.popped historyController.prevSlug = window.location.pathname.slice(1) if historyController.prevSlug == 'bloodsweattears' if historyController.inMenu == true $('.icon-left-arrow').trigger('click') else $('.icon-info').trigger('click') else if historyController.prevSlug == 'contact' $('.icon-contact').trigger('click') else if historyController.inMenu == true $('.icon-close').trigger('click') else if window.isIndex #CHANGE FOR TOUCH DEBUG - DONE if window.isTouch if historyController.prevSlug == -1 || historyController.prevSlug == '' waypointCheck.nextProject = 0 else waypointCheck.nextProject = $.inArray(historyController.prevSlug,historyController.slugArray) waypointCheck.resetFilter(true) waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.traverseProject(true) else if $('#' + historyController.prevSlug).length || historyController.prevSlug == '' if historyController.prevSlug != '' scrollTarget = $('#' + historyController.prevSlug).position().top else scrollTarget = 0 historyController.scrollingBack = true $('html, body').stop().animate({ scrollTop: scrollTarget }, 'slow', -> if this.nodeName == "BODY" return historyController.scrollingBack = false if historyController.prevSlug == -1 || historyController.prevSlug == '' waypointCheck.updateTitle($('article').eq(0).attr('id'), true) else waypointCheck.updateTitle(historyController.prevSlug, true) ) else window.location.href = '/' + historyController.prevSlug else window.location.href = '/' historyController.popped = true #Doc deady $ -> $('a.nav-item').bind 'click', (event) -> event.preventDefault() if !$(this).parent().hasClass('active') # CHANGE FOR TOUCH DEBUG - DONE if window.isTouch waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.nextProject = $(this).parent().index() waypointCheck.traverseProject() $('.arrow-tab').addClass('hideArrow') else thisSlug = $(this).attr('href').slice(1) targetIndex = $(this).parent().index() scrollTarget = $('#' + thisSlug).position().top scrollSpeed = waypointCheck.relativeSpeed(scrollTarget) articleID = $('article').eq(targetIndex).attr('id') historyController.scrollingBack = true $('.arrow-tab').removeClass('showArrow').addClass('hideArrow').css('visibility','hidden') $('html, body').stop().animate({ scrollTop: scrollTarget }, scrollSpeed, -> if this.nodeName == "BODY" return historyController.scrollingBack = false imageLoader.addImages(targetIndex) waypointCheck.updateTitle(articleID, false, true) $('.arrow-tab').css('visibility','visible') ) $('.description').one 'click', (event) -> $(this).toggleClass('expand') $('.icon-info').bind 'click', (event) -> event.preventDefault() historyController.inMenu = true history.pushState(null, 'iota &#8212; blood,sweat,tears', '') $('.main').addClass('openmenu') $('body').addClass('menu') $('.bottom-hud ul').removeClass('scaleIn') $('.menuNav').addClass('scaleIn') $('.overlay').removeClass('closemenu').addClass('openmenu') waypointCheck.updateColors('#ffffff','#262626') if window.isTouch hideMain = setTimeout -> $('.main').hide() , 500 $('.icon-close').bind 'click', (event) -> event.preventDefault() historyController.inMenu = false history.replaceState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) $('.main').show().removeClass('openmenu') $('body').removeClass('menu') $('.bottom-hud ul').removeClass('scaleIn') $('.indexNav').addClass('scaleIn') $('.overlay').removeClass('openmenu').addClass('closemenu') waypointCheck.updateColors(waypointCheck.ogfg,waypointCheck.ogbg) $('.icon-contact').bind 'click', (event) -> event.preventDefault() history.pushState(null, 'iota &#8212; contact', '') $('.contact, .mainmenu, body').removeClass('closecontact') $('.contact, .mainmenu, body').addClass('opencontact') $('.bottom-hud ul').removeClass('scaleIn') $('.infoNav').addClass('scaleIn') $('.icon-left-arrow').bind 'click', (event) -> event.preventDefault() history.replaceState(null, 'iota &#8212; blood,sweat,tears', '') $('.contact, .mainmenu, body').removeClass('opencontact') $('.contact, .mainmenu, body').addClass('closecontact') $('.bottom-hud ul').removeClass('scaleIn') $('.menuNav').addClass('scaleIn') $('.icon-down-arrow-bare').bind 'click', (event) -> event.preventDefault() $('.navCounters ul li').toggleClass('mobile-hide').addClass('scaleIn') $('.icon-up-arrow-bare').css('display','block') $('.icon-up-arrow-bare').bind 'click', (event) -> event.preventDefault() $('.navCounters ul li').toggleClass('mobile-hide').addClass('scaleIn') if !window.isTouch $('.menuItem').not('.active').hover (-> foreground = $(this).data('foreground') background = $(this).data('background') $('.menuItem.active span').css('opacity','0.2') mainMenu.updateColors(foreground, background) $(this).find('.meaning').addClass('fadeIn') ), -> mainMenu.updateColors(mainMenu.ogfg, mainMenu.ogbg) $('.menuItem.active span').css('opacity','1') window.getItStarted = () -> $('.main').show() ##Index specific startup functions if window.isPortfolio and !window.isTouch and !window.isSingle waypointCheck.assignArticleWaypoints() if window.isIndex waypointCheck.footerWaypoint() ##Site wide startup functions imageLoader.addImages(0) objectLoader.pageLoaded() historyController.bindPopstate() if window.isPortfolio and !window.isSingle and !window.isIE window.loadGame() else if window.isFeed window.loadFeed() else window.getItStarted()
true
#= require vendor/waypoints2.0.2.min #= require vendor/jquery-ui-1.9.2.custom #= require vendor/jquery.color-2.1.2.min.js #= require vendor/jquery.ui.touch-punch.min #= require feed #= require intro window.isTouch = if ($('html').hasClass('touch')) then true else false window.isCanvas = if ($('html').hasClass('canvas')) then true else false window.isIndex = if $('body').hasClass('index') then true else false window.isFeed = if $('body').hasClass('feed') then true else false window.isPortfolio = if $('body').hasClass('portfolio') then true else false window.isBlood = if $('body').hasClass('blood') then true else false window.isSingle = if $('body').hasClass('singleProject') or $('body').hasClass('singlePost') then true else false window.isIE = if $('html').hasClass('lt-ie9') then true else false window.mapLoaded = false window.cantanimate = if $('html').hasClass('no-cssanimations') then true else false ## New Constructors HistoryController = -> @slugArray = [] @popped = false @prevSlug @currSlug @inMenu @scrollingBack = false historyController = new HistoryController() WaypointCheck = -> @filteredItems = [] @articesLoaded = false @isLoading = false @currentProject = 0 @nextProject @hudTimer @currentDirection @projectSlug = $('article:eq(0)').attr('id') @projectTitle = $('article:eq(0)').data('title') @ogfg = $('article:eq(0)').data('foreground') @ogbg = $('article:eq(0)').data('background') @lastProject = $('article').length - 1 @lastFg @projects @showArrow @hideArrow @resetArrow @footerOpen = false @lastIndex = 0 @arrowTab = '<div class="arrow-tab"><a href="#"></a><span>' waypointCheck = new WaypointCheck() ImageLoader = -> @loadArray = [] @screenSize = if (screen.width > 880) then 'desktop' else 'mobile' @loadTimer = null @retryLoad = false imageLoader = new ImageLoader() MainMenu = -> @ogbg = '#262626' @ogfg = '#ffffff' mainMenu = new MainMenu() ObjectLoader = -> @fadeArray = ['fadeInSlide','fadeInSlideR','fadeInSlideL'] @lastFade if window.isBlood @objectTarget = 'section' @objectSubTarget = '.content' else @objectTarget = 'article' @objectSubTarget = '.project' objectLoader = new ObjectLoader() CanvasArrow = (location, arrowWidth) -> element = document.createElement('canvas') $(element) .attr('width', arrowWidth + 40).attr('height', '40') if arrowWidth >= 160 arrowWidth = Math.abs(arrowWidth - 160) else arrowWidth = Math.abs(arrowWidth - 160) * -1 context = element.getContext("2d") context.fillStyle = waypointCheck.ogfg context.bezierCurveTo((179.965+arrowWidth),0.945,(177.65+arrowWidth),0,(176+arrowWidth),0) context.lineTo((171+arrowWidth),0) context.lineTo(7,0) context.bezierCurveTo(3.15,0,0,3.15,0,7) context.lineTo(0,33) context.bezierCurveTo(0,36.85,3.15,40,7,40) context.lineTo((171+arrowWidth),40) context.lineTo((176+arrowWidth),40) context.bezierCurveTo((177.65+arrowWidth),40,(179.965+arrowWidth),39.055,(181.143+arrowWidth),37.9) context.lineTo((197.269+arrowWidth),22.1) context.bezierCurveTo((198.447+arrowWidth),20.945,(198.447+arrowWidth),19.055,(197.269+arrowWidth),17.9) context.closePath() context.fill() return element waypointCheck.updateColors = (foreground, background) -> waypointCheck.lastFg = foreground if waypointCheck.footerOpen closeColor = background else closeColor = foreground $('nav').stop().animate({ color: foreground }, 500) $('.indexNav .icon-info').stop().animate({ color: closeColor }, 500, () -> if window.isIE $('.indexNav .icon-info').trigger('focus') setTimeout -> $('.indexNav .icon-info').blur() 10 ) $('.navCounters .navPanel').stop().animate({ backgroundColor: background }, 500 ) if window.isCanvas waypointCheck.updateCanvas() else $('.arrow-tab').css('color', foreground) waypointCheck.endofline = (foreground) -> $('.indexNav .icon-info').stop().animate({ color: foreground }, 500 ) waypointCheck.makeCanvas = -> $('.navCounters ul li .arrow-tab').each(-> liWidth = $(this).width() liIndex = $(this).parent().index() canvasArrow = new CanvasArrow(liIndex, liWidth) $(canvasArrow) .addClass('canvasArrow') .text('unsupported browser') .appendTo($(this)) ) waypointCheck.updateCanvas = -> $('.arrow-tab').css({'color':waypointCheck.ogbg}) $('.canvasArrow').remove() waypointCheck.makeCanvas() waypointCheck.relativeSpeed = (scrollTarget) -> topDistance = $(document).scrollTop() scrollSpeed = Math.abs((Math.abs(scrollTarget) - $(document).scrollTop())/10) scrollSpeed # console.log scrollSpeed * 100 window.initialiseMaps = () -> # Bris Map MY_MAPTYPE_ID = 'custom_style'; brisMapOptions = zoom: 16 center: new google.maps.LatLng(-27.45480, 153.03905) disableDefaultUI: true zoomControl: false scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false draggable: if window.isTouch and imageLoader.screenSize is 'mobile' then false else true backgroundColor: '#262626' zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL position: google.maps.ControlPosition.TOP_RIGHT mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID] }, mapTypeId: MY_MAPTYPE_ID featureOpts = [ featureType: 'all' elementType: 'all' stylers: [ invert_lightness: true , saturation: -100 , lightness: 5 ] ] brismap = new google.maps.Map(document.getElementById("brismap"), brisMapOptions) if window.isCanvas iotaImage = '../images/iotaMarker.svg'; else iotaImage = '../images/iotaMarker.png'; iotaLatLng = new google.maps.LatLng(-27.45480, 153.03905); iotaMarker = new google.maps.Marker( clickable: false position: iotaLatLng map: brismap icon: iotaImage title: 'One Iota Brisbane' ) styledMapOptions = name: 'Custom Style' customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions) brismap.mapTypes.set(MY_MAPTYPE_ID, customMapType) # Syd Map SYD_MAPTYPE_ID = 'sydney_custom_style'; sydMapOptions = zoom: 16 center: new google.maps.LatLng(-33.861468, 151.209180) disableDefaultUI: true zoomControl: false scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false draggable: if window.isTouch and imageLoader.screenSize is 'mobile' then false else true backgroundColor: '#58585a' zoomControlOptions: style: google.maps.ZoomControlStyle.SMALL position: google.maps.ControlPosition.TOP_RIGHT mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, SYD_MAPTYPE_ID] }, mapTypeId: SYD_MAPTYPE_ID sydFeatureOpts = [ {"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#58585a"},{"lightness":-25},{"saturation":-97}]} ] sydmap = new google.maps.Map(document.getElementById("sydmap"), sydMapOptions) if window.isCanvas sydIotaImage = '../images/iotaMarkerSyd.svg'; else sydIotaImage = '../images/iotaMarkerSyd.png'; iotaLatLng = new google.maps.LatLng(-33.861468, 151.209180); iotaMarker = new google.maps.Marker( clickable: false position: iotaLatLng map: sydmap icon: sydIotaImage title: 'One Iota Sydney' ) sydStyledMapOptions = name: 'Custom Style' sydCustomMapType = new google.maps.StyledMapType(sydFeatureOpts, sydStyledMapOptions) sydmap.mapTypes.set(SYD_MAPTYPE_ID, sydCustomMapType) loadGoogleMaps = () -> googleMaps = document.createElement("script") googleMaps.type = "text/javascript" googleMaps.src = "https://maps.googleapis.com/maps/api/js?key=PI:KEY:<KEY>END_PI&sensor=false&callback=window.initialiseMaps" document.body.appendChild googleMaps mainMenu.updateColors = (foreground, background) -> $(".overlay").stop().animate({ backgroundColor: background }, 300 ) imageLoader.imageLoaded = (img) -> targetArticle = $('article').eq(img.imgParent) targetPlaceholder = targetArticle.find('span.placeholder-bg').eq(0) targetParentIndex = targetPlaceholder.parent().index() targetAlt = targetArticle.find('span.placeholder-alt').eq(0) targetPlaceholder.after($(img)) if targetParentIndex is 0 $(img).addClass('loaded fadeInSlide') else fadeInEffect = objectLoader.randomFade() $(img).addClass('loaded ' + fadeInEffect) targetPlaceholder.remove() targetAlt.remove() imageLoader.loadImage() imageLoader.loadImage = -> if imageLoader.loadArray.length isnt 0 imgItem = imageLoader.loadArray.shift() img = new Image() imgTimer = undefined img.src = imgItem.imgSrc img.title = img.alt = imgItem.imgTitle img.imgParent = imgItem.imgParent if img.complete or img.readyState is 4 imageLoader.imageLoaded(img) else imgTimer = setTimeout -> if !imageLoader.retryLoad imageLoader.retryLoad = true imageLoader.loadArray.unshift(imgItem) imageLoader.loadImage() else imageLoader.retryLoad = false $(img).unbind 'error load onreadystate' imageLoader.loadImage() if imgItem.length isnt 0 , 15000 $(img).bind 'error load onreadystatechange', (e) -> clearTimeout imgTimer if e.type isnt 'error' imageLoader.imageLoaded(img) else imageLoader.loadImage() imageLoader.addImages = (articleIndex) -> if !$('article').eq(articleIndex).hasClass('loaded') targetArticles = $('article').eq(articleIndex).find('span.placeholder-bg') targetArticles.each (index) -> imgItem = {} imgItem.imgSrc = targetArticles.eq(index).data(imageLoader.screenSize) imgItem.imgTitle = targetArticles.eq(index).attr('alt') imgItem.imgParent = articleIndex imageLoader.loadArray.push(imgItem) if index == targetArticles.length - 1 imageLoader.loadImage() $('article').eq(articleIndex).addClass('loaded') #Index Specific if window.isIndex FlipSquare = -> @colArr = ['#d83b65','#e55d87','#e55d87','#5fc3e4','#5ec4e5','#50d97a','#edde5d','#f09819','#ff512f','#dd2476','#1b0109'] @sqrArr = [] @hozDivs = 4 @screenW = $(window).width() @screenH = $(window).height() @squareW = @screenW / @hozDivs @squareH = $(window).height() / Math.floor($(window).height() / @squareW) @numSq = @hozDivs * ($(window).height() / @squareH) @tester = true @tester2 = true flipSquare = new FlipSquare() waypointCheck.footerWaypoint = -> # $('body').waypoint $('body').waypoint triggerOnce: false offset: 'bottom-in-view' handler: (direction) -> fgColor = $('.checkout-feed').data('fgcolor') if direction is 'down' if window.isTouch && waypointCheck.nextProject != waypointCheck.lastProject return false else waypointCheck.endofline(fgColor) if !waypointCheck.footerOpen $('.checkout-feed').removeClass('slideUpFooter slideDownFooter').addClass('slideUpFooter') addFade = setTimeout -> $('.checkout-feed h3').addClass('fadeIn') , 200 waypointCheck.footerOpen = true else waypointCheck.endofline(waypointCheck.lastFg) if waypointCheck.footerOpen $('.checkout-feed').removeClass('slideUpFooter slideDownFooter').addClass('slideDownFooter') $('.checkout-feed h3').removeClass('fadeIn') waypointCheck.footerOpen = false #Non Touch Handlers # CHANGE FOR TOUCH DEBUG - DONE if !window.isTouch waypointCheck.resetFilter = () -> $.each waypointCheck.filteredItems, (i) -> tarLi = waypointCheck.filteredItems[i].filteredLi tarArt = waypointCheck.filteredItems[i].filteredArticle tarID = waypointCheck.filteredItems[i].lastID if !tarID $(".navCounters ul li").eq(0).before(tarLi) $('article').eq(0).before(tarArt) else $('a[href="/' + tarID + '"]').parent().after(tarLi) $('article[id="' + tarID + '"]').after(tarArt) waypointCheck.filteredItems = [] $.waypoints('enable') $.waypoints('refresh') objectLoader.assignAnimationWaypoints() $('.filterMenu a').bind 'click', (event) -> event.preventDefault() if not $(this).parent().hasClass("eyeButton") if not $(this).parent().hasClass("active") $('.filterMenu li').removeClass('active') $(this).parent().addClass('active') tarFilter = $(this).data('filter') $('.navCounters').css('visibility','hidden') if waypointCheck.filteredItems.length isnt 0 if tarFilter == 'all' $('html, body').stop().animate({ scrollTop: 0 }, 750, -> if this.nodeName == "BODY" return waypointCheck.resetFilter() $.waypoints('refresh') $('.navCounters').css('visibility','visible') ) else waypointCheck.resetFilter() if tarFilter isnt 'all' $('html, body').stop().animate({ scrollTop: 0 }, 750, -> if this.nodeName == "BODY" return historyController.scrollingBack = true $('article').each( -> if !$(this).attr('data-'+ tarFilter) $(this).waypoint('disable') tarFilterIndex = $(this).index() tarLastId = $(this).prev().attr('id') filteredItem = lastID: tarLastId filteredArticle: $(this).detach() filteredLi: $(".navCounters ul li").eq(tarFilterIndex).removeClass('active').detach() waypointCheck.filteredItems.push(filteredItem) ) historyController.scrollingBack = false $.waypoints('refresh') $('.navCounters').css('visibility','visible') ) waypointCheck.updateTitle = (articleId, popped, navLiHit) -> if !historyController.scrollingBack currentArticle = $('#'+ articleId) currentIndex = currentArticle.index() waypointCheck.projectSlug = currentArticle.attr('id') waypointCheck.projectTitle = currentArticle.data('title') @.ogfg = waypointCheck.ogfg = currentArticle.data('foreground') @.ogbg = waypointCheck.ogbg = currentArticle.data('background') waypointCheck.updateColors(@.ogfg, @.ogbg) newTitle = 'One Iota — ' + waypointCheck.projectTitle document.title = newTitle $('.navCounters ul li').removeClass('active scaleIn slideIn') if waypointCheck.lastIndex != currentIndex $('.navCounters ul li').eq(waypointCheck.lastIndex).addClass('scaleIn') $('.navCounters ul li').eq(currentIndex).addClass('active slideIn') else $('.navCounters ul li').eq(currentIndex).addClass('active slideIn') if !navLiHit clearTimeout(waypointCheck.showArrow) clearTimeout(waypointCheck.hideArrow) clearTimeout(waypointCheck.resetArrow) targetArrow = $('.navCounters ul li').eq(currentIndex).find('.arrow-tab') $('.arrow-tab').css('visibility','hidden') targetArrow.css('visibility','visible') waypointCheck.showArrow = setTimeout(-> targetArrow.removeClass('hideArrow').addClass('showArrow scaleIn') waypointCheck.hideArrow = setTimeout(-> targetArrow.removeClass('scaleIn').addClass('scaleOut') waypointCheck.resetArrow = setTimeout(-> $('.arrow-tab').removeClass('scaleOut showArrow').addClass('scaleIn hideArrow').css('visibility','visible') ,500) ,2000) ,1000) if not popped history.pushState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) else history.replaceState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) waypointCheck.lastIndex = currentIndex ## Assign Waypoints waypointCheck.assignArticleWaypoints = -> $('article:gt(0)').waypoint triggerOnce: false offset: '100%' handler: (direction) -> if !historyController.scrollingBack articleIndex = ($('article').index($('#' + @id))) if direction is 'down' waypointCheck.updateTitle(@id) imageLoader.addImages(articleIndex) else waypointCheck.updateTitle($('article').eq(articleIndex-1).attr('id')) imageLoader.addImages(articleIndex-1) #Touch Handlers else $('.main article').css('background','transparent') window.addEventListener 'load', -> setTimeout -> window.scrollTo(0, 1) , 0 waypointCheck.resetFilter = (isAll) -> if isAll $('.filterMenu li').removeClass('active') $('.filterMenu li').eq(1).addClass('active') $(".navCounters ul li").each( -> $(this).removeClass('scaleHide slideIn').addClass('scaleIn') ) $('.filterMenu a').bind 'click', (event) -> event.preventDefault() if not $(this).parent().hasClass("eyeButton") if not $(this).parent().hasClass("active") $('.filterMenu li').removeClass('active') $(this).parent().addClass('active') tarFilter = $(this).data('filter') currentProject = $('.navCounters li.active').index() nextProject = $('article[data-' + tarFilter + '="true"]').first().index() if tarFilter == 'all' waypointCheck.resetFilter() else #Hide li isCurrentActive = $('article').eq(currentProject).attr('data-'+ tarFilter) $('article').each( () -> tarRemoveIndex = $(this).index() tarRemoveLi = $(".navCounters ul li").eq(tarRemoveIndex) if !$(this).attr('data-'+ tarFilter) tarRemoveLi.removeClass('active scaleIn slideIn').addClass('scaleHide') else if isCurrentActive and tarRemoveIndex is currentProject tarRemoveLi.removeClass('slideIn scaleHide').addClass('scaleIn') else tarRemoveLi.removeClass('active slideIn scaleHide').addClass('scaleIn') ) #Is the current article being viewed in the filter? -> if not traverse if !isCurrentActive waypointCheck.currentProject = currentProject waypointCheck.nextProject = nextProject waypointCheck.traverseProject(false,true) $('.arrow-tab').addClass('hideArrow') waypointCheck.traverseProject = (goingBack, filterHit) -> waypointCheck.projectSlug = $('.main article').eq(@.nextProject).attr('id') waypointCheck.projectTitle = $('.main article').eq(@.nextProject).data('title') waypointCheck.ogfg = $('.main article').eq(@.nextProject).data('foreground') waypointCheck.ogbg = $('.main article').eq(@.nextProject).data('background') newTitle = 'One Iota — ' + waypointCheck.projectTitle if filterHit $('.main article').removeClass() $('.main article').eq(waypointCheck.currentProject).addClass('fadeOut') $('.navCounters ul li').eq(waypointCheck.nextProject).addClass('active') else $('.main article').removeClass() $('.main article').eq(waypointCheck.currentProject).addClass('fadeOut') $('.navCounters ul li').removeClass('active scaleIn slideIn') $('.navCounters ul li').eq(waypointCheck.currentProject).addClass('scaleIn') $('.navCounters ul li').eq(waypointCheck.nextProject).addClass('active slideIn') $("nav, .indexNav .icon-info").delay(100).stop().animate({ color: waypointCheck.ogfg }, 500, -> waypointCheck.lastFg = waypointCheck.ogfg $('html, body').stop().animate({ scrollTop: 0 backgroundColor: waypointCheck.ogbg }, 750, -> if this.nodeName == "BODY" return document.title = newTitle $('.main article').eq(waypointCheck.currentProject).hide() $('.main article').eq(waypointCheck.nextProject).show().addClass('slideInProject') waypointCheck.updateCanvas() if !goingBack history.pushState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) $.waypoints('refresh') removeSlide = setTimeout -> $('.main article').eq(waypointCheck.nextProject).removeClass('slideInProject') imageLoader.addImages(waypointCheck.nextProject) , 1000 ) ) waypointCheck.killArrowHelper = (timer) -> if timer killArrow = setTimeout -> $('.arrow-tab').removeClass('scaleIn').addClass('scaleOut') removeInt = setTimeout -> $('.arrow-tab').removeClass('showArrow').addClass('scaleIn hideArrow') , 500 , 3000 else $('.arrow-tab').removeClass('scaleIn').addClass('scaleOut') removeInt = setTimeout -> $('.arrow-tab').removeClass('showArrow scaleOut').addClass('scaleIn hideArrow') , 500 waypointCheck.touchWaypoints = -> $('body').waypoint triggerOnce: false offset: 'bottom-in-view' handler: (direction) -> if direction is 'down' targetLi = $('.navCounters li.active').next() targetLi.find('.arrow-tab').removeClass('hideArrow').addClass('0') clearTimeout(removeAni) removeAni = setTimeout -> waypointCheck.killArrowHelper(true) $('.arrow-tab').unbind('click') $('.arrow-tab').bind 'click', (event) -> event.preventDefault() waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.nextProject = $(this).parent().index() waypointCheck.traverseProject() $('.arrow-tab').removeClass('showArrow').addClass('hideArrow') , 500 else if direction is 'up' waypointCheck.killArrowHelper(false) $('ul.filterMenu li a').bind 'click', (event) -> #use toggle class $('li.eyeButton i.scaleInSevenFive').toggleClass('scaleOutSevenFive') $('ul.filterMenu li.scaleInMenu').toggle() waypointCheck.touchWaypoints() #Blood specific functions if window.isBlood BloodLoader = -> @bloogBG = 'images/blood.jpg' @teamShotz = [] @testimonialTimer @lastClass @instyCounter = 0 @teamCounter = 0 @groupTracker = true @stateTracker = 0 @iotaPics = [] @retryLoad = false @iotaInstySpots = ['.iotaInsty1','.iotaInsty2','.iotaInsty2','.iotaInsty2','.iotaInsty3','.iotaInsty4','.iotaInsty4','.iotaInsty4','.iotaInsty5'] @iotaInsty = 'https://api.instagram.com/v1/users/12427052/media/recent/?access_token=PI:PASSWORD:<PASSWORD>END_PI&count=9' bloodLoader = new BloodLoader() bloodLoader.instyAnimation = () -> if bloodLoader.groupTracker targetGroup = '.iotaInsty2' targetTeam = '.iotaTeam1' bloodLoader.groupTracker = false else targetGroup = '.iotaInsty4' targetTeam = '.iotaTeam2' bloodLoader.groupTracker = true switch bloodLoader.stateTracker when 0 $(targetGroup + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideDown') $(targetGroup + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideRight') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideRight') $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') teamTimeout1 = setTimeout -> $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideDown') ,1000 teamTimeout2 = setTimeout -> $(targetTeam + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideRight') ,1000 when 1 $(targetGroup + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideLeft') teamTimeout1 = setTimeout -> $(targetTeam + ' .instyAni0').removeClass('slideDown slideUp').addClass('slideUp') ,1000 teamTimeout2 = setTimeout -> $(targetTeam + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideLeft') ,1000 else $(targetGroup + ' .instyAni1').removeClass('slideLeft slideRight').addClass('slideLeft') $(targetGroup + ' .instyAni2').removeClass('slideLeft slideRight').addClass('slideRight') if bloodLoader.groupTracker if bloodLoader.stateTracker < 2 bloodLoader.stateTracker++ else bloodLoader.stateTracker = 0 bloodLoader.loadInstyImages = (feed) -> instySpots = bloodLoader.iotaInstySpots instyPics = bloodLoader.iotaPics if instyPics.length isnt 0 imgItem = instyPics.shift() imgClass = instySpots.shift() if imgClass == bloodLoader.lastClass bloodLoader.instyCounter++ else bloodLoader.instyCounter = 0 bloodLoader.lastClass = imgClass img = new Image() timer = undefined img.src = imgItem img.title = img.alt = feed if img.complete or img.readyState is 4 $(img).addClass('instagram-pic scaleIn instyAni' + bloodLoader.instyCounter) $(img).appendTo(imgClass) bloodLoader.loadInstyImages(feed) else # handle 404 using setTimeout set at 10 seconds, adjust as needed timer = setTimeout(-> #bloodLoader.loadInstyImages() if imgItem.length isnt 0 $(img).unbind 'error load onreadystate' , 10000) $(img).bind 'error load onreadystatechange', (e) -> clearTimeout timer if e.type isnt 'error' #ADD IMAGE IN HERE $(img).addClass('instagram-pic scaleIn instyAni' + bloodLoader.instyCounter) $(img).appendTo(imgClass) bloodLoader.loadInstyImages(feed) else bloodLoader.loadInstyImages(feed) else animationInit = setInterval( -> bloodLoader.instyAnimation() , 4000) bloodLoader.loadTeamShotz = () -> if bloodLoader.teamShotz.length isnt 0 teamImg = bloodLoader.teamShotz.shift() img = new Image() teamTimer = undefined # if !window.location.origin # window.location.origin = window.location.protocol+"//"+window.location.host; # img.src = window.location.origin+'/'+teamImg.src img.src = teamImg.src img.title = img.alt = teamImg.title img.parentz = teamImg.parentz if img.complete or img.readyState is 4 $(''+img.parentz+'').find('.team-instagram').append(img) $(img).addClass('instagram-pic team-pic scaleIn instyAni' + bloodLoader.teamCounter) (if bloodLoader.teamCounter is 0 then bloodLoader.teamCounter++ else bloodLoader.teamCounter = 0) bloodLoader.loadTeamShotz() else teamTimer = setTimeout -> if !bloodLoader.retryLoad bloodLoader.retryLoad = true bloodLoader.teamShotz.unshift(teamImg) bloodLoader.loadTeamShotz() else bloodLoader.retryLoad = false $(img).unbind 'error load onreadystate' bloodLoader.loadTeamShotz() if teamImg.length isnt 0 , 15000 $(img).bind 'error load onreadystatechange', (e) -> clearTimeout teamTimer if e.type isnt 'error' $(''+img.parentz+'').find('.team-instagram').append(img) $(img).addClass('instagram-pic team-pic scaleIn instyAni' + bloodLoader.teamCounter) (if bloodLoader.teamCounter is 0 then bloodLoader.teamCounter++ else bloodLoader.teamCounter = 0) bloodLoader.loadTeamShotz() else bloodLoader.loadTeamShotz() bloodLoader.getInsty = () -> $.ajax url: bloodLoader.iotaInsty dataType: 'jsonp' cache: false success: (iotaImages) -> $.each(iotaImages.data, (index) -> bloodLoader.iotaPics.push(this.images.low_resolution.url) ) bloodLoader.loadInstyImages('@oneiota_') error: -> console.log 'run backup pics' bloodLoader.getTeamShotz = () -> $('.team-member').each( -> shotOne = {src : $(this).data('shot1'), title : $(this).data('imgalt'), parentz : $(this).data('parent')} shotTwo = {src : $(this).data('shot2'), title : $(this).data('imgalt'), parentz : $(this).data('parent')} bloodLoader.teamShotz.push(shotOne,shotTwo) ) bloodLoader.loadTeamShotz() bloodLoader.newsletterSignup = () -> $.ajax type: $('#newsletter-subscribe').attr('method') url: $('#newsletter-subscribe').attr('action') dataType: 'jsonp' data: $('#newsletter-subscribe').serialize() cache: false contentType: "application/json; charset=utf-8" error: (err) -> $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","*Sorry, please try again") success: (data) -> unless data.result is "success" $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder",data.msg) else $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","Thanks, stay tuned!") bloodLoader.isValidEmailAddress = () -> emailAddress = $('#newsletter-subscribe-email').val() pattern = new RegExp(/^((([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) pattern.test emailAddress #Load google map if !window.mapLoaded loadMap = setTimeout -> loadGoogleMaps() , 1000 window.mapLoaded = true #Blood Binds $('.icon-right-arrow-bare').bind('click', (event) -> event.preventDefault() clearInterval(bloodLoader.testimonialTimer) if $('.current-testimonial').index() != ($('.client-testimonial').length - 1) nextTest = $('.current-testimonial').next() else nextTest = $('.client-testimonial').eq(0) $('.current-testimonial').stop().animate({ left: '-100%' }, 100, -> $(this).toggleClass('current-testimonial') nextTest.css({'left':'100%'}).toggleClass('current-testimonial').stop().animate({ left: '0%' }, 100) ) ) $('.icon-left-arrow-bare').bind('click', (event) -> event.preventDefault() clearInterval(bloodLoader.testimonialTimer) if $('.current-testimonial').index() != 0 nextTest = $('.current-testimonial').prev() else nextTest = $('.client-testimonial').eq($('.client-testimonial').length - 1) $('.current-testimonial').stop().animate({ left: '100%' }, 100, -> $(this).toggleClass('current-testimonial') nextTest.css({'left':'-100%'}).toggleClass('current-testimonial').stop().animate({ left: '0%' }, 100) ) ) $("form input[type='email']").keypress (event) -> if event.which is 13 $("form input[type='submit']").trigger('click') return false $("form input[type='submit']").bind('click', (event) -> event.preventDefault() if event if bloodLoader.isValidEmailAddress() bloodLoader.newsletterSignup() else $('#newsletter-subscribe-email').val('') $('#newsletter-subscribe-email').attr("placeholder","*Sorry, give it another go") ) bloodLoader.testimonialTimer = setInterval -> $('.icon-right-arrow-bare').trigger('click') , 6000 #Elegant page object animation objectLoader.randomFade = () -> getRandomFade = () -> randomFade = objectLoader.fadeArray[Math.floor(Math.random() * objectLoader.fadeArray.length)] if randomFade != objectLoader.lastFade objectLoader.lastFade = randomFade randomFade else getRandomFade() getRandomFade() objectLoader.assignAnimationWaypoints = () -> if window.isBlood $(objectLoader.objectTarget).waypoint triggerOnce: true offset: '80%' handler: (direction) -> $(this).find(objectLoader.objectSubTarget).addClass('loaded') objectLoader.loadInternals($(this).index()) else if window.isPortfolio $(objectLoader.objectSubTarget).children().each( -> if $(this).hasClass('project-details') $(this).waypoint triggerOnce: true offset: '80%' handler: (direction) -> objectLoader.loadInternals($(this).parent().parent().index()) # else # $(this).waypoint # triggerOnce: true # offset: '50%' # handler: (direction) -> # if $(this).index() == 0 # $(this).addClass('loaded fadeInSlide') # else # fadeInEffect = objectLoader.randomFade() # $(this).addClass('loaded ' + fadeInEffect) ) objectLoader.loadInternals = (targetIndex) -> if window.isBlood targetContent = $(objectLoader.objectTarget).eq(targetIndex).find(objectLoader.objectSubTarget) else if window.isPortfolio targetContent = $(objectLoader.objectTarget).eq(targetIndex).find('.project-details') childArray = [] targetContent.children().each( (index) -> childArray.push(index) ) animateChildren = -> if childArray.length isnt 0 currChild = childArray.shift() if targetContent.children().eq(currChild).get(0).tagName == 'UL' subChildArray = [] parentTarget = targetContent.children().eq(currChild) parentTarget.children().each( (index) -> subChildArray.push(index) ) animateSubChildren = -> if subChildArray.length isnt 0 currSubChild = subChildArray.shift() parentTarget.children().eq(currSubChild).addClass('scaleIn') animateSubChildTimer = setTimeout -> animateSubChildren() , 100 else animateChildren() animateSubChildren() else targetContent.children().eq(currChild).addClass('fadeInSlide') animateChildTimer = setTimeout -> animateChildren() , 100 animateChildren() waypointCheck.showPortBtns = () -> showDistance = -20 $('.main').waypoint triggerOnce: true, offset: showDistance handler: (direction) -> if direction is 'down' $('body').removeClass('noNav') $('.explore').addClass('fadeOutSlow') killExplore = setTimeout () -> $('.explore').remove() , 700 if !window.isIE waypointCheck.makeCanvas() objectLoader.pageLoaded = () -> if !window.isTouch objectLoader.assignAnimationWaypoints() if !window.isPortfolio or window.isSingle $('nav').show() else # if sessionStorage.playedAlready == 'true' # $('.explore, .intro').remove() # $('nav').show() # $('.checkout-feed').show() # if !window.isIE # waypointCheck.makeCanvas() # else $('body').addClass('noNav') showMain = setTimeout -> if !window.isTouch $('.intro').removeClass('fadeIn').addClass('introOut') $('.main').addClass('scaleInBig') else $('.intro').removeClass('fadeIn').addClass('introOutTouch') showNav = setTimeout -> $('nav').show() waypointCheck.showPortBtns() $('.intro').remove() $('.main').removeClass('scaleInBig') $('.checkout-feed').show() if !window.isIE waypointCheck.makeCanvas() , 1200 if window.isBlood bloodLoader.getInsty() bloodLoader.getTeamShotz() #Binds historyController.bindPopstate = () -> $('.main article').each( -> historyController.slugArray.push($(this).attr('id')) ) $(window).bind 'popstate', () -> if historyController.popped historyController.prevSlug = window.location.pathname.slice(1) if historyController.prevSlug == 'bloodsweattears' if historyController.inMenu == true $('.icon-left-arrow').trigger('click') else $('.icon-info').trigger('click') else if historyController.prevSlug == 'contact' $('.icon-contact').trigger('click') else if historyController.inMenu == true $('.icon-close').trigger('click') else if window.isIndex #CHANGE FOR TOUCH DEBUG - DONE if window.isTouch if historyController.prevSlug == -1 || historyController.prevSlug == '' waypointCheck.nextProject = 0 else waypointCheck.nextProject = $.inArray(historyController.prevSlug,historyController.slugArray) waypointCheck.resetFilter(true) waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.traverseProject(true) else if $('#' + historyController.prevSlug).length || historyController.prevSlug == '' if historyController.prevSlug != '' scrollTarget = $('#' + historyController.prevSlug).position().top else scrollTarget = 0 historyController.scrollingBack = true $('html, body').stop().animate({ scrollTop: scrollTarget }, 'slow', -> if this.nodeName == "BODY" return historyController.scrollingBack = false if historyController.prevSlug == -1 || historyController.prevSlug == '' waypointCheck.updateTitle($('article').eq(0).attr('id'), true) else waypointCheck.updateTitle(historyController.prevSlug, true) ) else window.location.href = '/' + historyController.prevSlug else window.location.href = '/' historyController.popped = true #Doc deady $ -> $('a.nav-item').bind 'click', (event) -> event.preventDefault() if !$(this).parent().hasClass('active') # CHANGE FOR TOUCH DEBUG - DONE if window.isTouch waypointCheck.currentProject = $('.navCounters li.active').index() waypointCheck.nextProject = $(this).parent().index() waypointCheck.traverseProject() $('.arrow-tab').addClass('hideArrow') else thisSlug = $(this).attr('href').slice(1) targetIndex = $(this).parent().index() scrollTarget = $('#' + thisSlug).position().top scrollSpeed = waypointCheck.relativeSpeed(scrollTarget) articleID = $('article').eq(targetIndex).attr('id') historyController.scrollingBack = true $('.arrow-tab').removeClass('showArrow').addClass('hideArrow').css('visibility','hidden') $('html, body').stop().animate({ scrollTop: scrollTarget }, scrollSpeed, -> if this.nodeName == "BODY" return historyController.scrollingBack = false imageLoader.addImages(targetIndex) waypointCheck.updateTitle(articleID, false, true) $('.arrow-tab').css('visibility','visible') ) $('.description').one 'click', (event) -> $(this).toggleClass('expand') $('.icon-info').bind 'click', (event) -> event.preventDefault() historyController.inMenu = true history.pushState(null, 'iota &#8212; blood,sweat,tears', '') $('.main').addClass('openmenu') $('body').addClass('menu') $('.bottom-hud ul').removeClass('scaleIn') $('.menuNav').addClass('scaleIn') $('.overlay').removeClass('closemenu').addClass('openmenu') waypointCheck.updateColors('#ffffff','#262626') if window.isTouch hideMain = setTimeout -> $('.main').hide() , 500 $('.icon-close').bind 'click', (event) -> event.preventDefault() historyController.inMenu = false history.replaceState(null, waypointCheck.projectTitle, waypointCheck.projectSlug) $('.main').show().removeClass('openmenu') $('body').removeClass('menu') $('.bottom-hud ul').removeClass('scaleIn') $('.indexNav').addClass('scaleIn') $('.overlay').removeClass('openmenu').addClass('closemenu') waypointCheck.updateColors(waypointCheck.ogfg,waypointCheck.ogbg) $('.icon-contact').bind 'click', (event) -> event.preventDefault() history.pushState(null, 'iota &#8212; contact', '') $('.contact, .mainmenu, body').removeClass('closecontact') $('.contact, .mainmenu, body').addClass('opencontact') $('.bottom-hud ul').removeClass('scaleIn') $('.infoNav').addClass('scaleIn') $('.icon-left-arrow').bind 'click', (event) -> event.preventDefault() history.replaceState(null, 'iota &#8212; blood,sweat,tears', '') $('.contact, .mainmenu, body').removeClass('opencontact') $('.contact, .mainmenu, body').addClass('closecontact') $('.bottom-hud ul').removeClass('scaleIn') $('.menuNav').addClass('scaleIn') $('.icon-down-arrow-bare').bind 'click', (event) -> event.preventDefault() $('.navCounters ul li').toggleClass('mobile-hide').addClass('scaleIn') $('.icon-up-arrow-bare').css('display','block') $('.icon-up-arrow-bare').bind 'click', (event) -> event.preventDefault() $('.navCounters ul li').toggleClass('mobile-hide').addClass('scaleIn') if !window.isTouch $('.menuItem').not('.active').hover (-> foreground = $(this).data('foreground') background = $(this).data('background') $('.menuItem.active span').css('opacity','0.2') mainMenu.updateColors(foreground, background) $(this).find('.meaning').addClass('fadeIn') ), -> mainMenu.updateColors(mainMenu.ogfg, mainMenu.ogbg) $('.menuItem.active span').css('opacity','1') window.getItStarted = () -> $('.main').show() ##Index specific startup functions if window.isPortfolio and !window.isTouch and !window.isSingle waypointCheck.assignArticleWaypoints() if window.isIndex waypointCheck.footerWaypoint() ##Site wide startup functions imageLoader.addImages(0) objectLoader.pageLoaded() historyController.bindPopstate() if window.isPortfolio and !window.isSingle and !window.isIE window.loadGame() else if window.isFeed window.loadFeed() else window.getItStarted()
[ { "context": "# Alexander Danylchenko\n# BMC tpl\\tplre language settings.\n# 2017-08-14 -", "end": 23, "score": 0.9998248815536499, "start": 2, "tag": "NAME", "value": "Alexander Danylchenko" } ]
settings/language-tplpre.cson
triaglesis/language-tplpre
1
# Alexander Danylchenko # BMC tpl\tplre language settings. # 2017-08-14 - Latest version. # experimental: '.source.tplpre': 'editor': 'autoIndentOnPaste': true 'softTabs': true 'tabLength': 4 'commentStart': '// ' 'increaseIndentPattern': '(if|elif).*(\\S+\\s+then)\\b.*$' 'increaseIndentPattern': '(for).*(\\S+\\s+do)\\b.*$' 'decreaseIndentPattern': '(end\\sif;|end\\sfor;)$' 'decreaseNextIndentPattern': '^\\s*(pass;|break;)\\b.*$'
2642
# <NAME> # BMC tpl\tplre language settings. # 2017-08-14 - Latest version. # experimental: '.source.tplpre': 'editor': 'autoIndentOnPaste': true 'softTabs': true 'tabLength': 4 'commentStart': '// ' 'increaseIndentPattern': '(if|elif).*(\\S+\\s+then)\\b.*$' 'increaseIndentPattern': '(for).*(\\S+\\s+do)\\b.*$' 'decreaseIndentPattern': '(end\\sif;|end\\sfor;)$' 'decreaseNextIndentPattern': '^\\s*(pass;|break;)\\b.*$'
true
# PI:NAME:<NAME>END_PI # BMC tpl\tplre language settings. # 2017-08-14 - Latest version. # experimental: '.source.tplpre': 'editor': 'autoIndentOnPaste': true 'softTabs': true 'tabLength': 4 'commentStart': '// ' 'increaseIndentPattern': '(if|elif).*(\\S+\\s+then)\\b.*$' 'increaseIndentPattern': '(for).*(\\S+\\s+do)\\b.*$' 'decreaseIndentPattern': '(end\\sif;|end\\sfor;)$' 'decreaseNextIndentPattern': '^\\s*(pass;|break;)\\b.*$'
[ { "context": "class Paladin\n key: 'paladin'\n name: 'paladin'\n\n genders: ['male', 'female']", "end": 29, "score": 0.9667465686798096, "start": 22, "tag": "USERNAME", "value": "paladin" }, { "context": "class Paladin\n key: 'paladin'\n name: 'paladin'\n\n genders: ['male', 'f...
js/classes/paladin.coffee
ktchernov/7drl-lion.github.io
27
class Paladin key: 'paladin' name: 'paladin' genders: ['male', 'female'] alignments: ['good'] races: ['human', 'giant', 'angel', 'elf', 'dwarf', 'hobbit'] base_hp: 10 base_mp: 10 base_speed: -30 base_attack: 4 base_sight_range: 0 skills: [ 'healing_aura' 'smite' 'shield_bash' 'divine_shield' 'retribution' 'blessing' 'sanctuary' 'beacon_of_light' 'blinding_light' 'healing_touch' ] register_class Paladin
41470
class Paladin key: 'paladin' name: '<NAME>' genders: ['male', 'female'] alignments: ['good'] races: ['human', 'giant', 'angel', 'elf', 'dwarf', 'hobbit'] base_hp: 10 base_mp: 10 base_speed: -30 base_attack: 4 base_sight_range: 0 skills: [ 'healing_aura' 'smite' 'shield_bash' 'divine_shield' 'retribution' 'blessing' 'sanctuary' 'beacon_of_light' 'blinding_light' 'healing_touch' ] register_class Paladin
true
class Paladin key: 'paladin' name: 'PI:NAME:<NAME>END_PI' genders: ['male', 'female'] alignments: ['good'] races: ['human', 'giant', 'angel', 'elf', 'dwarf', 'hobbit'] base_hp: 10 base_mp: 10 base_speed: -30 base_attack: 4 base_sight_range: 0 skills: [ 'healing_aura' 'smite' 'shield_bash' 'divine_shield' 'retribution' 'blessing' 'sanctuary' 'beacon_of_light' 'blinding_light' 'healing_touch' ] register_class Paladin
[ { "context": "peer dependencies yourself.”\n# https://github.com/roughcoder/grunt-humans-txt/pull/7\n# @robinpokorny version:\n", "end": 401, "score": 0.9992612600326538, "start": 391, "tag": "USERNAME", "value": "roughcoder" }, { "context": "://github.com/roughcoder/grunt-humans-txt...
grunt/humans_txt.coffee
Kristinita/---
6
###################### ## grunt-humans-txt ## ###################### # Generate humans.txt file: # https://www.npmjs.com/package/grunt-humans-txt # http://humanstxt.org/ # [WARNING] Generator outdated, you get a warning in console: # “npm WARN grunt-humans-txt@0.2.1 requires a peer of grunt@~0.4.1 but none is installed. # You must install peer dependencies yourself.” # https://github.com/roughcoder/grunt-humans-txt/pull/7 # @robinpokorny version: # https://stackoverflow.com/a/21918559/5951529 # https://github.com/roughcoder/grunt-humans-txt/issues/3#issuecomment-375207928 # I use my own fork. Reasons: # https://github.com/Kristinita/grunt-humans-txt/blob/master/README.md # [NOTE] Needs “module.exports = (grunt) ->” instead of “module.exports =”, that don't get an error: # “ReferenceError: grunt is not defined” module.exports = (grunt) -> options: pkg: grunt.file.readJSON('package.json') intro: 'humans.txt file for Kristinita’s Search' commentStyle: 'c' # Indentation of nested values: # https://github.com/robinpokorny/grunt-humans-txt#tab tab: '\t' # Section, where last update date: # https://github.com/robinpokorny/grunt-humans-txt#includeupdatein includeUpdateIn: 'site' content: team: [ 'Web developer': "<%= humans_txt.options.pkg.author %>" 'Site': "<%= humans_txt.options.pkg.homepage %>" 'Contacts': 'https://vk.com/psychologist_kira_k' 'Location': 'Там, где Кира' ] thanks: [ 'Name': 'Alfy Centauri' 'Site': 'alfavika.ru' ] site: [ 'Standards': 'HTML5, CoffeeScript, Stylus' 'Components': 'Pelican, Python Markdown, Grunt and many plugins for this components' 'Software': 'Sublime Text and many plugins for Sublime Text' 'License': "<%= humans_txt.options.pkg.license %>" ] task: dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/humans.txt"
220919
###################### ## grunt-humans-txt ## ###################### # Generate humans.txt file: # https://www.npmjs.com/package/grunt-humans-txt # http://humanstxt.org/ # [WARNING] Generator outdated, you get a warning in console: # “npm WARN grunt-humans-txt@0.2.1 requires a peer of grunt@~0.4.1 but none is installed. # You must install peer dependencies yourself.” # https://github.com/roughcoder/grunt-humans-txt/pull/7 # @robinpokorny version: # https://stackoverflow.com/a/21918559/5951529 # https://github.com/roughcoder/grunt-humans-txt/issues/3#issuecomment-375207928 # I use my own fork. Reasons: # https://github.com/Kristinita/grunt-humans-txt/blob/master/README.md # [NOTE] Needs “module.exports = (grunt) ->” instead of “module.exports =”, that don't get an error: # “ReferenceError: grunt is not defined” module.exports = (grunt) -> options: pkg: grunt.file.readJSON('package.json') intro: 'humans.txt file for Kristinita’s Search' commentStyle: 'c' # Indentation of nested values: # https://github.com/robinpokorny/grunt-humans-txt#tab tab: '\t' # Section, where last update date: # https://github.com/robinpokorny/grunt-humans-txt#includeupdatein includeUpdateIn: 'site' content: team: [ 'Web developer': "<%= humans_txt.options.pkg.author %>" 'Site': "<%= humans_txt.options.pkg.homepage %>" 'Contacts': 'https://vk.com/psychologist_kira_k' 'Location': 'Там, где Кира' ] thanks: [ 'Name': '<NAME>' 'Site': 'alfavika.ru' ] site: [ 'Standards': 'HTML5, CoffeeScript, Stylus' 'Components': 'Pelican, Python Markdown, Grunt and many plugins for this components' 'Software': 'Sublime Text and many plugins for Sublime Text' 'License': "<%= humans_txt.options.pkg.license %>" ] task: dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/humans.txt"
true
###################### ## grunt-humans-txt ## ###################### # Generate humans.txt file: # https://www.npmjs.com/package/grunt-humans-txt # http://humanstxt.org/ # [WARNING] Generator outdated, you get a warning in console: # “npm WARN grunt-humans-txt@0.2.1 requires a peer of grunt@~0.4.1 but none is installed. # You must install peer dependencies yourself.” # https://github.com/roughcoder/grunt-humans-txt/pull/7 # @robinpokorny version: # https://stackoverflow.com/a/21918559/5951529 # https://github.com/roughcoder/grunt-humans-txt/issues/3#issuecomment-375207928 # I use my own fork. Reasons: # https://github.com/Kristinita/grunt-humans-txt/blob/master/README.md # [NOTE] Needs “module.exports = (grunt) ->” instead of “module.exports =”, that don't get an error: # “ReferenceError: grunt is not defined” module.exports = (grunt) -> options: pkg: grunt.file.readJSON('package.json') intro: 'humans.txt file for Kristinita’s Search' commentStyle: 'c' # Indentation of nested values: # https://github.com/robinpokorny/grunt-humans-txt#tab tab: '\t' # Section, where last update date: # https://github.com/robinpokorny/grunt-humans-txt#includeupdatein includeUpdateIn: 'site' content: team: [ 'Web developer': "<%= humans_txt.options.pkg.author %>" 'Site': "<%= humans_txt.options.pkg.homepage %>" 'Contacts': 'https://vk.com/psychologist_kira_k' 'Location': 'Там, где Кира' ] thanks: [ 'Name': 'PI:NAME:<NAME>END_PI' 'Site': 'alfavika.ru' ] site: [ 'Standards': 'HTML5, CoffeeScript, Stylus' 'Components': 'Pelican, Python Markdown, Grunt and many plugins for this components' 'Software': 'Sublime Text and many plugins for Sublime Text' 'License': "<%= humans_txt.options.pkg.license %>" ] task: dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/humans.txt"
[ { "context": "ntinue\n\n key = if key is ' ' then '' else \"#{key}=\"\n str += '; ' if str isnt '' and key isnt", "end": 565, "score": 0.8636162281036377, "start": 556, "tag": "KEY", "value": "\"#{key}=\"" } ]
src/mock-cookie.coffee
luanpotter/mock-cookie
0
# Support trim unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, "" # Support Getters/Setters Function::property = (prop, desc) -> Object.defineProperty @prototype, prop, desc # Mock the document.cookie class Document constructor: (@_cookie = {}) -> @_cookie = {} @property 'cookie', get: -> if Object.keys(@_cookie).length str = '' for key, val of @_cookie if new Date(val.expires) < new Date() delete @_cookie[key] continue key = if key is ' ' then '' else "#{key}=" str += '; ' if str isnt '' and key isnt ' ' str += key + val.value return str else return '' set: (val) -> properties = val.trim().split ';' val = (properties.shift() + '').trim().split('=') key = if val.length is 1 then ' ' else val[0].trim() value = (if val.length is 1 then val[0] else val[1]).trim() for cookie in properties cookie = cookie.trim().split '=' continue if cookie.length is 1 or cookie[0].trim() isnt 'expires' expires = new Date cookie[1] expires = '' if expires is 'Invalid Date' @_cookie[key] = value: value expires: expires ? 'Session' return value exports.Document = Document
146957
# Support trim unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, "" # Support Getters/Setters Function::property = (prop, desc) -> Object.defineProperty @prototype, prop, desc # Mock the document.cookie class Document constructor: (@_cookie = {}) -> @_cookie = {} @property 'cookie', get: -> if Object.keys(@_cookie).length str = '' for key, val of @_cookie if new Date(val.expires) < new Date() delete @_cookie[key] continue key = if key is ' ' then '' else <KEY> str += '; ' if str isnt '' and key isnt ' ' str += key + val.value return str else return '' set: (val) -> properties = val.trim().split ';' val = (properties.shift() + '').trim().split('=') key = if val.length is 1 then ' ' else val[0].trim() value = (if val.length is 1 then val[0] else val[1]).trim() for cookie in properties cookie = cookie.trim().split '=' continue if cookie.length is 1 or cookie[0].trim() isnt 'expires' expires = new Date cookie[1] expires = '' if expires is 'Invalid Date' @_cookie[key] = value: value expires: expires ? 'Session' return value exports.Document = Document
true
# Support trim unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, "" # Support Getters/Setters Function::property = (prop, desc) -> Object.defineProperty @prototype, prop, desc # Mock the document.cookie class Document constructor: (@_cookie = {}) -> @_cookie = {} @property 'cookie', get: -> if Object.keys(@_cookie).length str = '' for key, val of @_cookie if new Date(val.expires) < new Date() delete @_cookie[key] continue key = if key is ' ' then '' else PI:KEY:<KEY>END_PI str += '; ' if str isnt '' and key isnt ' ' str += key + val.value return str else return '' set: (val) -> properties = val.trim().split ';' val = (properties.shift() + '').trim().split('=') key = if val.length is 1 then ' ' else val[0].trim() value = (if val.length is 1 then val[0] else val[1]).trim() for cookie in properties cookie = cookie.trim().split '=' continue if cookie.length is 1 or cookie[0].trim() isnt 'expires' expires = new Date cookie[1] expires = '' if expires is 'Invalid Date' @_cookie[key] = value: value expires: expires ? 'Session' return value exports.Document = Document
[ { "context": "->\n beforeEach -> forgotPassword.set email: 'user@example.com'\n\n it 'is ok', -> expect(forgotPassword.isVa", "end": 479, "score": 0.9999117851257324, "start": 463, "tag": "EMAIL", "value": "user@example.com" } ]
source/NuGet/coffeescript/content/Scripts/specs/application/models/forgotpassword.coffee
kazimanzurrashid/AspNetMvcBackboneJsSpa
22
expect = @chai.expect describe 'Models.ForgotPassword', -> forgotPassword = null beforeEach -> forgotPassword = new Application.Models.ForgotPassword describe '#defaults', -> it 'has email', -> expect(forgotPassword.defaults()).to.have.property 'email' describe '#urlRoot', -> it 'is set', -> expect(forgotPassword.urlRoot()).to.exist describe 'validation', -> describe 'valid', -> beforeEach -> forgotPassword.set email: 'user@example.com' it 'is ok', -> expect(forgotPassword.isValid()).to.be.ok describe 'invalid', -> describe 'email', -> describe 'missing', -> it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email' describe 'blank', -> beforeEach -> forgotPassword.set email: '' it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email' describe 'incorrect format', -> beforeEach -> forgotPassword.set email: 'foo-bar' it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email'
7744
expect = @chai.expect describe 'Models.ForgotPassword', -> forgotPassword = null beforeEach -> forgotPassword = new Application.Models.ForgotPassword describe '#defaults', -> it 'has email', -> expect(forgotPassword.defaults()).to.have.property 'email' describe '#urlRoot', -> it 'is set', -> expect(forgotPassword.urlRoot()).to.exist describe 'validation', -> describe 'valid', -> beforeEach -> forgotPassword.set email: '<EMAIL>' it 'is ok', -> expect(forgotPassword.isValid()).to.be.ok describe 'invalid', -> describe 'email', -> describe 'missing', -> it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email' describe 'blank', -> beforeEach -> forgotPassword.set email: '' it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email' describe 'incorrect format', -> beforeEach -> forgotPassword.set email: 'foo-bar' it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email'
true
expect = @chai.expect describe 'Models.ForgotPassword', -> forgotPassword = null beforeEach -> forgotPassword = new Application.Models.ForgotPassword describe '#defaults', -> it 'has email', -> expect(forgotPassword.defaults()).to.have.property 'email' describe '#urlRoot', -> it 'is set', -> expect(forgotPassword.urlRoot()).to.exist describe 'validation', -> describe 'valid', -> beforeEach -> forgotPassword.set email: 'PI:EMAIL:<EMAIL>END_PI' it 'is ok', -> expect(forgotPassword.isValid()).to.be.ok describe 'invalid', -> describe 'email', -> describe 'missing', -> it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email' describe 'blank', -> beforeEach -> forgotPassword.set email: '' it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email' describe 'incorrect format', -> beforeEach -> forgotPassword.set email: 'foo-bar' it 'is invalid', -> expect(forgotPassword.isValid()).to.not.be.ok expect(forgotPassword.validationError).to.have.property 'email'
[ { "context": ".glog([\"Test Glog\"])\n\n\t.open(\"Level 2b\")\n\t.add \"2bshit\"\n\n_.glog(\"Test Glog\").print(0)\n\n_.glog \"Witnesses", "end": 8296, "score": 0.996222734451294, "start": 8292, "tag": "NAME", "value": "shit" } ]
utility.coffee
michael-lumley/morslamina-utility
0
_ = require("underscore") m$ = {} # Utility Functions @fold String.prototype.toDash = () -> @replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() String.prototype.frontCap = () -> @charAt(0).toUpperCase() + @slice(1); String.prototype.pluralize = (revert = false)-> plural = { '(quiz)$' : "$1zes", '^(ox)$' : "$1en", '([m|l])ouse$' : "$1ice", '(matr|vert|ind)ix|ex$' : "$1ices", '(x|ch|ss|sh)$' : "$1es", '([^aeiouy]|qu)y$' : "$1ies", '(hive)$' : "$1s", '(?:([^f])fe|([lr])f)$' : "$1$2ves", '(shea|lea|loa|thie)f$' : "$1ves", 'sis$' : "ses", '([ti])um$' : "$1a", '(tomat|potat|ech|her|vet)o$': "$1oes", '(bu)s$' : "$1ses", '(alias)$' : "$1es", '(octop)us$' : "$1i", '(ax|test)is$' : "$1es", '(us)$' : "$1es", '([^s]+)$' : "$1s" }; singular = { '(quiz)zes$' : "$1", '(matr)ices$' : "$1ix", '(vert|ind)ices$' : "$1ex", '^(ox)en$' : "$1", '(alias)es$' : "$1", '(octop|vir)i$' : "$1us", '(cris|ax|test)es$' : "$1is", '(shoe)s$' : "$1", '(o)es$' : "$1", '(bus)es$' : "$1", '([m|l])ice$' : "$1ouse", '(x|ch|ss|sh)es$' : "$1", '(m)ovies$' : "$1ovie", '(s)eries$' : "$1eries", '([^aeiouy]|qu)ies$' : "$1y", '([lr])ves$' : "$1f", '(tive)s$' : "$1", '(hive)s$' : "$1", '(li|wi|kni)ves$' : "$1fe", '(shea|loa|lea|thie)ves$': "$1f", '(^analy)ses$' : "$1sis", '((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$': "$1$2sis", '([ti])a$' : "$1um", '(n)ews$' : "$1ews", '(h|bl)ouses$' : "$1ouse", '(corpse)s$' : "$1", '(us)es$' : "$1", 's$' : "" }; irregular = { 'move' : 'moves', 'foot' : 'feet', 'goose' : 'geese', 'sex' : 'sexes', 'child' : 'children', 'man' : 'men', 'tooth' : 'teeth', 'person' : 'people' }; uncountable = [ 'sheep', 'fish', 'deer', 'series', 'species', 'money', 'rice', 'information', 'equipment' ]; # save some time in the case that singular and plural are the same if(uncountable.indexOf(this.toLowerCase()) >= 0) return this; # check for irregular forms for word of irregular if revert pattern = new RegExp(irregular[word]+'$', 'i'); replace = word; else pattern = new RegExp(word+'$', 'i'); replace = irregular[word]; if pattern.test(this) return this.replace(pattern, replace); if revert array = singular; else array = plural; # check for matches using regular expressions for reg of array pattern = new RegExp(reg, 'i'); if pattern.test(this) return this.replace(pattern, array[reg]); return this; Function.prototype.clone = ()-> that = this temp = ()-> return that.apply(this, arguments) for key in this if this.hasOwnProperty(key) temp[key] = this[key] return temp Function.prototype.then = ()-> Promise.resolve().then(this) _.deepClone = (obj)-> ret = _.clone(obj) for prop of ret if typeof ret[prop] == "object" ret[prop] = _.deepClone(obj[prop]) return ret _.deepSafeExtend = (parent, child) -> parent = _.deepClone(parent) for prop of child if typeof parent[prop] == "object" and typeof child[prop] == "object" parent[prop] = _.deepSafeExtend(parent[prop], child[prop]) #if Array.isArray(parent[prop]) and Array.isArray(child[prop]) # parent[prop] = parent[prop].concat(child[prop]) else parent[prop] = child[prop] return parent _.toClipboard = (text)-> parent = document.activeElement console.log parent textArea = document.activeElement.appendChild(document.createElement("textarea")); # # *** This styling is an extra step which is likely not required. *** # # Why is it here? To ensure: # 1. the element is able to have focus and selection. # 2. if element was to flash render it has minimal visual impact. # 3. less flakyness with selection and copying which **might** occur if # the textarea element is not visible. # # The likelihood is the element won't even render, not even a flash, # so some of these are just precautions. However in IE the element # is visible whilst the popup box asking the user for permission for # the web page to copy to the clipboard. # # Place in top-left corner of screen regardless of scroll position. textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; # Ensure it has a small width and height. Setting to 1px / 1em # doesn't work as this gives a negative w/h on some browsers. textArea.style.width = '2em'; textArea.style.height = '2em'; # We don't need padding, reducing the size if it does flash render. textArea.style.padding = 0; # Clean up any borders. textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; # Avoid flash of white box if rendered for any reason. textArea.style.background = 'transparent'; textArea.value = text; textArea.select(); console.log textArea try successful = document.execCommand('copy'); msg = successful ? 'successful' : 'unsuccessful'; parent.removeChild(textArea); console.log 'Copying text command was ' + msg catch err parent.removeChild(textArea); console.log 'Oops, unable to copy' _.forPromise = (iterable, asyncFN)-> i = 0 return new Promise((resolve, reject)-> next = ()-> if i < iterable.length asyncFN(iterable[i]).then(()-> i++ next() ) else console.log("resolving for promise") resolve() next() ) _.getStackTrace = ()-> obj = {} Error.captureStackTrace(obj) obj.stack _.objectifyArray = (array)-> obj = {} for value, key in array obj[key] = value return obj _.glog = (title, options)-> class glog constructor: (@title, @parent)-> @sublogs = [] @trace = _.getStackTrace().split(/\r?\n/); open: (title)-> newLog = new glog(title, @) @sublogs.push(newLog) _.glogs.last = newLog return newLog add: (entry)-> if _.glogs.live console.log entry @sublogs.push({entry: entry, trace: _.getStackTrace().split(/\r?\n/)}) _.glogs.last = @ return @ error: (error)-> @sublogs.push({error: error}) get: (entry)-> if Array.isArray(entry) and entry.length == 1 entry = entry[0] for log in @sublogs if log.title == entry return log return false relevantStackCall: (trace)-> for entry, key in trace if entry.indexOf("glog") == -1 and key > 1 return entry print: (trace = 1)-> console.groupCollapsed @title console.debug @relevantStackCall(@trace) if trace != 0 if @sublogs.length == 0 console.debug "No Sublogs!" console.groupEnd() return for log in @sublogs if log instanceof glog log.print(trace) else if log.entry? if trace == 0 or trace == 1 console.debug log.entry console.debug "#{@relevantStackCall(log.trace)}" if trace == 1 else if trace == 2 console.groupCollapsed log.entry for entry, key in @trace console.debug entry if key > 1 console.groupEnd() else if log.error? console.error log.error console.groupEnd() return @ if !_.glogs? _.glogs = {} if !_.glogs.root? _.glogs.root = new glog("root", null) if title == "print_all" _.glogs.root.print(options) else if title == "error" _.glogs.last.error(options) else if title == "last" ret = _.glogs.last else if Array.isArray(title) and title.length > 1 localGlog = _.glogs.root for level in title if localGlog.get(level) localGlog = localGlog.get(level) else localGlog = localGlog.open(level) ret = localGlog else if !_.glogs.root.get(title) ret = _.glogs.root.open(title) else ret = _.glogs.root.get(title) _.glogs.last = ret return ret window.onerror = (e)-> console.log "error!" console.error e _.glog("error", e) # !fold ### glog = _.glog(["Test Glog", "Level 1a"]) glog.open("Level 2a") .add("some stuff") .add("more stuff") .open("Level 3a") .add("sub child") console.log "GGGGGGGGGGEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT" _.glog(["Test Glog"]).open("Level 1b") .add("1b shit") .add("more 1b shit") console.log _.glog(["Test Glog"]) .open("Level 2b") .add "2bshit" _.glog("Test Glog").print(0) _.glog "Witnesses" .open "Merging Witness Lists for Case" _.glog "Witnesses" .add "Test Log" _.glog "Witnesses" .add "Test Log2" .add {test: "object", how: "does it work"} _.glog "Witnesses" _.glog "Witnesses" .open "A new Chain" .add "Test Log 45" _.glog "Events" .open "A test list of evevnts" .add "what happens if I add without opening?" _.glog "print_all", 0 ###
170557
_ = require("underscore") m$ = {} # Utility Functions @fold String.prototype.toDash = () -> @replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() String.prototype.frontCap = () -> @charAt(0).toUpperCase() + @slice(1); String.prototype.pluralize = (revert = false)-> plural = { '(quiz)$' : "$1zes", '^(ox)$' : "$1en", '([m|l])ouse$' : "$1ice", '(matr|vert|ind)ix|ex$' : "$1ices", '(x|ch|ss|sh)$' : "$1es", '([^aeiouy]|qu)y$' : "$1ies", '(hive)$' : "$1s", '(?:([^f])fe|([lr])f)$' : "$1$2ves", '(shea|lea|loa|thie)f$' : "$1ves", 'sis$' : "ses", '([ti])um$' : "$1a", '(tomat|potat|ech|her|vet)o$': "$1oes", '(bu)s$' : "$1ses", '(alias)$' : "$1es", '(octop)us$' : "$1i", '(ax|test)is$' : "$1es", '(us)$' : "$1es", '([^s]+)$' : "$1s" }; singular = { '(quiz)zes$' : "$1", '(matr)ices$' : "$1ix", '(vert|ind)ices$' : "$1ex", '^(ox)en$' : "$1", '(alias)es$' : "$1", '(octop|vir)i$' : "$1us", '(cris|ax|test)es$' : "$1is", '(shoe)s$' : "$1", '(o)es$' : "$1", '(bus)es$' : "$1", '([m|l])ice$' : "$1ouse", '(x|ch|ss|sh)es$' : "$1", '(m)ovies$' : "$1ovie", '(s)eries$' : "$1eries", '([^aeiouy]|qu)ies$' : "$1y", '([lr])ves$' : "$1f", '(tive)s$' : "$1", '(hive)s$' : "$1", '(li|wi|kni)ves$' : "$1fe", '(shea|loa|lea|thie)ves$': "$1f", '(^analy)ses$' : "$1sis", '((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$': "$1$2sis", '([ti])a$' : "$1um", '(n)ews$' : "$1ews", '(h|bl)ouses$' : "$1ouse", '(corpse)s$' : "$1", '(us)es$' : "$1", 's$' : "" }; irregular = { 'move' : 'moves', 'foot' : 'feet', 'goose' : 'geese', 'sex' : 'sexes', 'child' : 'children', 'man' : 'men', 'tooth' : 'teeth', 'person' : 'people' }; uncountable = [ 'sheep', 'fish', 'deer', 'series', 'species', 'money', 'rice', 'information', 'equipment' ]; # save some time in the case that singular and plural are the same if(uncountable.indexOf(this.toLowerCase()) >= 0) return this; # check for irregular forms for word of irregular if revert pattern = new RegExp(irregular[word]+'$', 'i'); replace = word; else pattern = new RegExp(word+'$', 'i'); replace = irregular[word]; if pattern.test(this) return this.replace(pattern, replace); if revert array = singular; else array = plural; # check for matches using regular expressions for reg of array pattern = new RegExp(reg, 'i'); if pattern.test(this) return this.replace(pattern, array[reg]); return this; Function.prototype.clone = ()-> that = this temp = ()-> return that.apply(this, arguments) for key in this if this.hasOwnProperty(key) temp[key] = this[key] return temp Function.prototype.then = ()-> Promise.resolve().then(this) _.deepClone = (obj)-> ret = _.clone(obj) for prop of ret if typeof ret[prop] == "object" ret[prop] = _.deepClone(obj[prop]) return ret _.deepSafeExtend = (parent, child) -> parent = _.deepClone(parent) for prop of child if typeof parent[prop] == "object" and typeof child[prop] == "object" parent[prop] = _.deepSafeExtend(parent[prop], child[prop]) #if Array.isArray(parent[prop]) and Array.isArray(child[prop]) # parent[prop] = parent[prop].concat(child[prop]) else parent[prop] = child[prop] return parent _.toClipboard = (text)-> parent = document.activeElement console.log parent textArea = document.activeElement.appendChild(document.createElement("textarea")); # # *** This styling is an extra step which is likely not required. *** # # Why is it here? To ensure: # 1. the element is able to have focus and selection. # 2. if element was to flash render it has minimal visual impact. # 3. less flakyness with selection and copying which **might** occur if # the textarea element is not visible. # # The likelihood is the element won't even render, not even a flash, # so some of these are just precautions. However in IE the element # is visible whilst the popup box asking the user for permission for # the web page to copy to the clipboard. # # Place in top-left corner of screen regardless of scroll position. textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; # Ensure it has a small width and height. Setting to 1px / 1em # doesn't work as this gives a negative w/h on some browsers. textArea.style.width = '2em'; textArea.style.height = '2em'; # We don't need padding, reducing the size if it does flash render. textArea.style.padding = 0; # Clean up any borders. textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; # Avoid flash of white box if rendered for any reason. textArea.style.background = 'transparent'; textArea.value = text; textArea.select(); console.log textArea try successful = document.execCommand('copy'); msg = successful ? 'successful' : 'unsuccessful'; parent.removeChild(textArea); console.log 'Copying text command was ' + msg catch err parent.removeChild(textArea); console.log 'Oops, unable to copy' _.forPromise = (iterable, asyncFN)-> i = 0 return new Promise((resolve, reject)-> next = ()-> if i < iterable.length asyncFN(iterable[i]).then(()-> i++ next() ) else console.log("resolving for promise") resolve() next() ) _.getStackTrace = ()-> obj = {} Error.captureStackTrace(obj) obj.stack _.objectifyArray = (array)-> obj = {} for value, key in array obj[key] = value return obj _.glog = (title, options)-> class glog constructor: (@title, @parent)-> @sublogs = [] @trace = _.getStackTrace().split(/\r?\n/); open: (title)-> newLog = new glog(title, @) @sublogs.push(newLog) _.glogs.last = newLog return newLog add: (entry)-> if _.glogs.live console.log entry @sublogs.push({entry: entry, trace: _.getStackTrace().split(/\r?\n/)}) _.glogs.last = @ return @ error: (error)-> @sublogs.push({error: error}) get: (entry)-> if Array.isArray(entry) and entry.length == 1 entry = entry[0] for log in @sublogs if log.title == entry return log return false relevantStackCall: (trace)-> for entry, key in trace if entry.indexOf("glog") == -1 and key > 1 return entry print: (trace = 1)-> console.groupCollapsed @title console.debug @relevantStackCall(@trace) if trace != 0 if @sublogs.length == 0 console.debug "No Sublogs!" console.groupEnd() return for log in @sublogs if log instanceof glog log.print(trace) else if log.entry? if trace == 0 or trace == 1 console.debug log.entry console.debug "#{@relevantStackCall(log.trace)}" if trace == 1 else if trace == 2 console.groupCollapsed log.entry for entry, key in @trace console.debug entry if key > 1 console.groupEnd() else if log.error? console.error log.error console.groupEnd() return @ if !_.glogs? _.glogs = {} if !_.glogs.root? _.glogs.root = new glog("root", null) if title == "print_all" _.glogs.root.print(options) else if title == "error" _.glogs.last.error(options) else if title == "last" ret = _.glogs.last else if Array.isArray(title) and title.length > 1 localGlog = _.glogs.root for level in title if localGlog.get(level) localGlog = localGlog.get(level) else localGlog = localGlog.open(level) ret = localGlog else if !_.glogs.root.get(title) ret = _.glogs.root.open(title) else ret = _.glogs.root.get(title) _.glogs.last = ret return ret window.onerror = (e)-> console.log "error!" console.error e _.glog("error", e) # !fold ### glog = _.glog(["Test Glog", "Level 1a"]) glog.open("Level 2a") .add("some stuff") .add("more stuff") .open("Level 3a") .add("sub child") console.log "GGGGGGGGGGEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT" _.glog(["Test Glog"]).open("Level 1b") .add("1b shit") .add("more 1b shit") console.log _.glog(["Test Glog"]) .open("Level 2b") .add "2b<NAME>" _.glog("Test Glog").print(0) _.glog "Witnesses" .open "Merging Witness Lists for Case" _.glog "Witnesses" .add "Test Log" _.glog "Witnesses" .add "Test Log2" .add {test: "object", how: "does it work"} _.glog "Witnesses" _.glog "Witnesses" .open "A new Chain" .add "Test Log 45" _.glog "Events" .open "A test list of evevnts" .add "what happens if I add without opening?" _.glog "print_all", 0 ###
true
_ = require("underscore") m$ = {} # Utility Functions @fold String.prototype.toDash = () -> @replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() String.prototype.frontCap = () -> @charAt(0).toUpperCase() + @slice(1); String.prototype.pluralize = (revert = false)-> plural = { '(quiz)$' : "$1zes", '^(ox)$' : "$1en", '([m|l])ouse$' : "$1ice", '(matr|vert|ind)ix|ex$' : "$1ices", '(x|ch|ss|sh)$' : "$1es", '([^aeiouy]|qu)y$' : "$1ies", '(hive)$' : "$1s", '(?:([^f])fe|([lr])f)$' : "$1$2ves", '(shea|lea|loa|thie)f$' : "$1ves", 'sis$' : "ses", '([ti])um$' : "$1a", '(tomat|potat|ech|her|vet)o$': "$1oes", '(bu)s$' : "$1ses", '(alias)$' : "$1es", '(octop)us$' : "$1i", '(ax|test)is$' : "$1es", '(us)$' : "$1es", '([^s]+)$' : "$1s" }; singular = { '(quiz)zes$' : "$1", '(matr)ices$' : "$1ix", '(vert|ind)ices$' : "$1ex", '^(ox)en$' : "$1", '(alias)es$' : "$1", '(octop|vir)i$' : "$1us", '(cris|ax|test)es$' : "$1is", '(shoe)s$' : "$1", '(o)es$' : "$1", '(bus)es$' : "$1", '([m|l])ice$' : "$1ouse", '(x|ch|ss|sh)es$' : "$1", '(m)ovies$' : "$1ovie", '(s)eries$' : "$1eries", '([^aeiouy]|qu)ies$' : "$1y", '([lr])ves$' : "$1f", '(tive)s$' : "$1", '(hive)s$' : "$1", '(li|wi|kni)ves$' : "$1fe", '(shea|loa|lea|thie)ves$': "$1f", '(^analy)ses$' : "$1sis", '((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$': "$1$2sis", '([ti])a$' : "$1um", '(n)ews$' : "$1ews", '(h|bl)ouses$' : "$1ouse", '(corpse)s$' : "$1", '(us)es$' : "$1", 's$' : "" }; irregular = { 'move' : 'moves', 'foot' : 'feet', 'goose' : 'geese', 'sex' : 'sexes', 'child' : 'children', 'man' : 'men', 'tooth' : 'teeth', 'person' : 'people' }; uncountable = [ 'sheep', 'fish', 'deer', 'series', 'species', 'money', 'rice', 'information', 'equipment' ]; # save some time in the case that singular and plural are the same if(uncountable.indexOf(this.toLowerCase()) >= 0) return this; # check for irregular forms for word of irregular if revert pattern = new RegExp(irregular[word]+'$', 'i'); replace = word; else pattern = new RegExp(word+'$', 'i'); replace = irregular[word]; if pattern.test(this) return this.replace(pattern, replace); if revert array = singular; else array = plural; # check for matches using regular expressions for reg of array pattern = new RegExp(reg, 'i'); if pattern.test(this) return this.replace(pattern, array[reg]); return this; Function.prototype.clone = ()-> that = this temp = ()-> return that.apply(this, arguments) for key in this if this.hasOwnProperty(key) temp[key] = this[key] return temp Function.prototype.then = ()-> Promise.resolve().then(this) _.deepClone = (obj)-> ret = _.clone(obj) for prop of ret if typeof ret[prop] == "object" ret[prop] = _.deepClone(obj[prop]) return ret _.deepSafeExtend = (parent, child) -> parent = _.deepClone(parent) for prop of child if typeof parent[prop] == "object" and typeof child[prop] == "object" parent[prop] = _.deepSafeExtend(parent[prop], child[prop]) #if Array.isArray(parent[prop]) and Array.isArray(child[prop]) # parent[prop] = parent[prop].concat(child[prop]) else parent[prop] = child[prop] return parent _.toClipboard = (text)-> parent = document.activeElement console.log parent textArea = document.activeElement.appendChild(document.createElement("textarea")); # # *** This styling is an extra step which is likely not required. *** # # Why is it here? To ensure: # 1. the element is able to have focus and selection. # 2. if element was to flash render it has minimal visual impact. # 3. less flakyness with selection and copying which **might** occur if # the textarea element is not visible. # # The likelihood is the element won't even render, not even a flash, # so some of these are just precautions. However in IE the element # is visible whilst the popup box asking the user for permission for # the web page to copy to the clipboard. # # Place in top-left corner of screen regardless of scroll position. textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; # Ensure it has a small width and height. Setting to 1px / 1em # doesn't work as this gives a negative w/h on some browsers. textArea.style.width = '2em'; textArea.style.height = '2em'; # We don't need padding, reducing the size if it does flash render. textArea.style.padding = 0; # Clean up any borders. textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; # Avoid flash of white box if rendered for any reason. textArea.style.background = 'transparent'; textArea.value = text; textArea.select(); console.log textArea try successful = document.execCommand('copy'); msg = successful ? 'successful' : 'unsuccessful'; parent.removeChild(textArea); console.log 'Copying text command was ' + msg catch err parent.removeChild(textArea); console.log 'Oops, unable to copy' _.forPromise = (iterable, asyncFN)-> i = 0 return new Promise((resolve, reject)-> next = ()-> if i < iterable.length asyncFN(iterable[i]).then(()-> i++ next() ) else console.log("resolving for promise") resolve() next() ) _.getStackTrace = ()-> obj = {} Error.captureStackTrace(obj) obj.stack _.objectifyArray = (array)-> obj = {} for value, key in array obj[key] = value return obj _.glog = (title, options)-> class glog constructor: (@title, @parent)-> @sublogs = [] @trace = _.getStackTrace().split(/\r?\n/); open: (title)-> newLog = new glog(title, @) @sublogs.push(newLog) _.glogs.last = newLog return newLog add: (entry)-> if _.glogs.live console.log entry @sublogs.push({entry: entry, trace: _.getStackTrace().split(/\r?\n/)}) _.glogs.last = @ return @ error: (error)-> @sublogs.push({error: error}) get: (entry)-> if Array.isArray(entry) and entry.length == 1 entry = entry[0] for log in @sublogs if log.title == entry return log return false relevantStackCall: (trace)-> for entry, key in trace if entry.indexOf("glog") == -1 and key > 1 return entry print: (trace = 1)-> console.groupCollapsed @title console.debug @relevantStackCall(@trace) if trace != 0 if @sublogs.length == 0 console.debug "No Sublogs!" console.groupEnd() return for log in @sublogs if log instanceof glog log.print(trace) else if log.entry? if trace == 0 or trace == 1 console.debug log.entry console.debug "#{@relevantStackCall(log.trace)}" if trace == 1 else if trace == 2 console.groupCollapsed log.entry for entry, key in @trace console.debug entry if key > 1 console.groupEnd() else if log.error? console.error log.error console.groupEnd() return @ if !_.glogs? _.glogs = {} if !_.glogs.root? _.glogs.root = new glog("root", null) if title == "print_all" _.glogs.root.print(options) else if title == "error" _.glogs.last.error(options) else if title == "last" ret = _.glogs.last else if Array.isArray(title) and title.length > 1 localGlog = _.glogs.root for level in title if localGlog.get(level) localGlog = localGlog.get(level) else localGlog = localGlog.open(level) ret = localGlog else if !_.glogs.root.get(title) ret = _.glogs.root.open(title) else ret = _.glogs.root.get(title) _.glogs.last = ret return ret window.onerror = (e)-> console.log "error!" console.error e _.glog("error", e) # !fold ### glog = _.glog(["Test Glog", "Level 1a"]) glog.open("Level 2a") .add("some stuff") .add("more stuff") .open("Level 3a") .add("sub child") console.log "GGGGGGGGGGEEEEEEEEEEEEETTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT" _.glog(["Test Glog"]).open("Level 1b") .add("1b shit") .add("more 1b shit") console.log _.glog(["Test Glog"]) .open("Level 2b") .add "2bPI:NAME:<NAME>END_PI" _.glog("Test Glog").print(0) _.glog "Witnesses" .open "Merging Witness Lists for Case" _.glog "Witnesses" .add "Test Log" _.glog "Witnesses" .add "Test Log2" .add {test: "object", how: "does it work"} _.glog "Witnesses" _.glog "Witnesses" .open "A new Chain" .add "Test Log 45" _.glog "Events" .open "A test list of evevnts" .add "what happens if I add without opening?" _.glog "print_all", 0 ###
[ { "context": "require '../lib/hmac-sha1')\n consumer_key = '10204'\n consumer_secret = 'secret-shhh'\n\n pro", "end": 290, "score": 0.9991558790206909, "start": 285, "tag": "KEY", "value": "10204" }, { "context": " consumer_key = '10204'\n consumer_secret = 'secr...
test/Provider.coffee
iturgeon/ims-lti
4
should = require 'should' lti = require '../' describe 'LTI.Provider', () -> before ()=> @lti = lti describe 'Initialization', () => it 'should accept (consumer_key, consumer_secret)', () => sig = new (require '../lib/hmac-sha1') consumer_key = '10204' consumer_secret = 'secret-shhh' provider = new @lti.Provider(consumer_key,consumer_secret) provider.should.be.an.instanceOf Object provider.consumer_key.should.equal consumer_key provider.consumer_secret.should.equal consumer_secret provider.signer.toString().should.equal sig.toString() it 'should accept (consumer_key, consumer_secret, nonceStore, sig)', () => sig = me: 3 you: 1 total: 4 provider = new @lti.Provider('10204','secret-shhh', undefined, sig) provider.signer.should.equal sig it 'should accept (consumer_key, consumer_secret, nonceStore, sig)', () => nonceStore = isNonceStore: ()->true isNew: ()->return setUsed: ()->return provider = new @lti.Provider('10204','secret-shhh',nonceStore) provider.nonceStore.should.equal nonceStore it 'should throw an error if no consumer_key or consumer_secret', () => (()=>provider = new @lti.Provider()).should.throw(lti.Errors.ConsumerError) (()=>provider = new @lti.Provider('consumer-key')).should.throw(lti.Errors.ConsumerError) describe 'Structure', () => before () => @provider = new @lti.Provider('key','secret') it 'should have valid_request method', () => should.exist @provider.valid_request @provider.valid_request.should.be.a.Function describe '.valid_request method', () => before () => @provider = new @lti.Provider('key','secret') @signer = @provider.signer it 'should return false if missing lti_message_type', (done) => req_missing_type = url: '/' body: lti_message_type: '' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' @provider.valid_request req_missing_type, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if incorrect LTI version', (done) => req_wrong_version = url: '/' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-0p0' resource_link_id: 'http://link-to-resource.com/resource' @provider.valid_request req_wrong_version, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if no resource_link_id', (done) => req_no_resource_link = url: '/' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' @provider.valid_request req_no_resource_link, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if bad oauth', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, 'secret') req.body.oauth_signature = signature # Break the signature req.body.oauth_signature += "garbage" @provider.valid_request req, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.SignatureError) valid.should.equal false done() it 'should return true if good headers and oauth', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should return true if lti_message_type is ContentItemSelectionRequest', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'ContentItemSelectionRequest' lti_version: 'LTI-1p0' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() [ 'resource_link_id', 'resource_link_title', 'resource_link_description', 'launch_presentation_return_url', 'lis_result_sourcedid' ].forEach (invalidField) => it "should return false if lti_message_type is ContentItemSelectionRequest and there is a \"#{invalidField}\" field", (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'ContentItemSelectionRequest' lti_version: 'LTI-1p0' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 req.body[invalidField] = "Invalid Field" #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.exist err valid.should.equal false done() it 'should special case and deduplicate Canvas requests', (done) => req = url: '/test?test=x&test2=y&test2=z' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 test: 'x' test2: ['y', 'z'] tool_consumer_info_product_family_code: 'canvas' query: test: 'x' test2: ['z', 'y'] signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should succeed with a hapi style req object', (done) => timestamp = Math.round(Date.now() / 1000) nonce = Date.now() + Math.random() * 100 # Compute signature from express style req expressReq = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: timestamp oauth_nonce: nonce signature = @provider.signer.build_signature(expressReq, expressReq.body, 'secret') hapiReq = raw: req: url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' payload: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: timestamp oauth_nonce: nonce oauth_signature: signature @provider.valid_request hapiReq, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should return false if nonce already seen', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) => should.not.exist err valid.should.equal true @provider.valid_request req, (err, valid) -> should.exist err err.should.be.instanceof(lti.Errors.NonceError) valid.should.equal false done() describe 'mapping', () => before () => @provider = new @lti.Provider('key','secret') req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: context_id: "4" context_label: "PHYS 2112" context_title: "Introduction To Physics" custom_param: "23" ext_lms: "moodle-2" ext_submit: "Press to launch this activity" launch_presentation_locale: "en" launch_presentation_return_url: "http://localhost:8888/moodle25/mod/lti/return.php?course=4&launch_container=4&instanceid=1" lis_outcome_service_url: "http://localhost:8888/moodle25/mod/lti/service.php" lis_person_contact_email_primary: "james@courseshark.com" lis_person_name_family: "Rundquist" lis_person_name_full: "James Rundquist" lis_person_name_given: "James" lis_result_sourcedid: "{\"data\":{\"instanceid\":\"1\",\"userid\":\"4\",\"launchid\":1480927086},\"hash\":\"03382572ba1bf35bcd99f9a9cbd44004c8f96f89c96d160a7b779a4ef89c70d5\"}" lti_message_type: "basic-lti-launch-request" lti_version: "LTI-1p0" oauth_callback: "about:blank" oauth_consumer_key: "moodle" oauth_nonce: Date.now()+Math.random()*100 oauth_signature_method: "HMAC-SHA1" oauth_timestamp: Math.round(Date.now()/1000) oauth_version: "1.0" resource_link_description: "<p>A test of the student's wits </p>" resource_link_id: "1" resource_link_title: "Fun LTI example!" roles: "Learner" role_scope_mentor: "1234,5678,12%2C34" tool_consumer_info_product_family_code: "moodle" tool_consumer_info_version: "2013051400" tool_consumer_instance_guid: "localhost" user_id: "4" #sign the request req.body.oauth_signature = @provider.signer.build_signature(req, 'secret') @provider.parse_request req it 'should create a filled @body', () => should.exist @provider.body @provider.body.should.have.property('context_id') @provider.body.should.have.property('context_label') @provider.body.should.have.property('context_title') @provider.body.should.have.property('custom_param') @provider.body.should.have.property('ext_lms') @provider.body.should.have.property('ext_submit') @provider.body.should.have.property('launch_presentation_locale') @provider.body.should.have.property('launch_presentation_return_url') @provider.body.should.have.property('lis_outcome_service_url') @provider.body.should.have.property('lis_person_contact_email_primary') @provider.body.should.have.property('lis_person_name_family') @provider.body.should.have.property('lis_person_name_full') @provider.body.should.have.property('lis_person_name_given') @provider.body.should.have.property('lis_result_sourcedid') @provider.body.should.have.property('lti_message_type') @provider.body.should.have.property('lti_version') @provider.body.should.have.property('resource_link_description') @provider.body.should.have.property('resource_link_id') @provider.body.should.have.property('resource_link_title') @provider.body.should.have.property('roles') @provider.body.should.have.property('role_scope_mentor') @provider.body.should.have.property('tool_consumer_info_product_family_code') @provider.body.should.have.property('tool_consumer_info_version') @provider.body.should.have.property('tool_consumer_instance_guid') @provider.body.should.have.property('user_id') it 'should have stripped oauth_ properties', () => @provider.body.should.not.have.property('oauth_callback') @provider.body.should.not.have.property('oauth_consumer_key') @provider.body.should.not.have.property('oauth_nonce') @provider.body.should.not.have.property('oauth_signature') @provider.body.should.not.have.property('oauth_signature_method') @provider.body.should.not.have.property('oauth_timestamp') @provider.body.should.not.have.property('oauth_version') it 'should have helper booleans for roles', () => @provider.student.should.equal true @provider.instructor.should.equal false @provider.content_developer.should.equal false @provider.member.should.equal false @provider.manager.should.equal false @provider.mentor.should.equal false @provider.admin.should.equal false @provider.ta.should.equal false it 'should have username accessor', () => @provider.username.should.equal "James" it 'should have user id accessor', () => @provider.userId.should.equal "4" it 'should handle the role_scope_mentor id array', () => @provider.mentor_user_ids.should.eql ['1234', '5678', '12,34'] it 'should have context accessors', () => @provider.context_id.should.equal "4" @provider.context_label.should.equal "PHYS 2112" @provider.context_title.should.equal "Introduction To Physics" it 'should have response outcome_service object', () => @provider.outcome_service.should.exist it 'should account for the standardized urn prefix', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti:role:ims/lis/Instructor' provider.instructor.should.equal true it 'should test for multiple roles being passed into the body', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'Instructor,Administrator' it 'should handle different role types from the specification', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti:role:ims/lis/Student,urn:lti:sysrole:ims/lis/Administrator,urn:lti:instrole:ims/lis/Alumni' provider.student.should.equal true provider.admin.should.equal true provider.alumni.should.equal true it 'should handle garbage roles that do not match the specification', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti::ims/lis/Student,urn:lti:sysrole:ims/lis/Administrator/,/Alumni' provider.student.should.equal false provider.admin.should.equal false provider.alumni.should.equal false
88640
should = require 'should' lti = require '../' describe 'LTI.Provider', () -> before ()=> @lti = lti describe 'Initialization', () => it 'should accept (consumer_key, consumer_secret)', () => sig = new (require '../lib/hmac-sha1') consumer_key = '<KEY>' consumer_secret = '<KEY>' provider = new @lti.Provider(consumer_key,consumer_secret) provider.should.be.an.instanceOf Object provider.consumer_key.should.equal consumer_key provider.consumer_secret.should.equal consumer_secret provider.signer.toString().should.equal sig.toString() it 'should accept (consumer_key, consumer_secret, nonceStore, sig)', () => sig = me: 3 you: 1 total: 4 provider = new @lti.Provider('10204','secret-shhh', undefined, sig) provider.signer.should.equal sig it 'should accept (consumer_key, consumer_secret, nonceStore, sig)', () => nonceStore = isNonceStore: ()->true isNew: ()->return setUsed: ()->return provider = new @lti.Provider('10204','secret-shhh',nonceStore) provider.nonceStore.should.equal nonceStore it 'should throw an error if no consumer_key or consumer_secret', () => (()=>provider = new @lti.Provider()).should.throw(lti.Errors.ConsumerError) (()=>provider = new @lti.Provider('consumer-key')).should.throw(lti.Errors.ConsumerError) describe 'Structure', () => before () => @provider = new @lti.Provider('key','secret') it 'should have valid_request method', () => should.exist @provider.valid_request @provider.valid_request.should.be.a.Function describe '.valid_request method', () => before () => @provider = new @lti.Provider('key','secret') @signer = @provider.signer it 'should return false if missing lti_message_type', (done) => req_missing_type = url: '/' body: lti_message_type: '' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' @provider.valid_request req_missing_type, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if incorrect LTI version', (done) => req_wrong_version = url: '/' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-0p0' resource_link_id: 'http://link-to-resource.com/resource' @provider.valid_request req_wrong_version, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if no resource_link_id', (done) => req_no_resource_link = url: '/' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' @provider.valid_request req_no_resource_link, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if bad oauth', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, 'secret') req.body.oauth_signature = signature # Break the signature req.body.oauth_signature += "garbage" @provider.valid_request req, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.SignatureError) valid.should.equal false done() it 'should return true if good headers and oauth', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should return true if lti_message_type is ContentItemSelectionRequest', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'ContentItemSelectionRequest' lti_version: 'LTI-1p0' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() [ 'resource_link_id', 'resource_link_title', 'resource_link_description', 'launch_presentation_return_url', 'lis_result_sourcedid' ].forEach (invalidField) => it "should return false if lti_message_type is ContentItemSelectionRequest and there is a \"#{invalidField}\" field", (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'ContentItemSelectionRequest' lti_version: 'LTI-1p0' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 req.body[invalidField] = "Invalid Field" #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.exist err valid.should.equal false done() it 'should special case and deduplicate Canvas requests', (done) => req = url: '/test?test=x&test2=y&test2=z' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 test: 'x' test2: ['y', 'z'] tool_consumer_info_product_family_code: 'canvas' query: test: 'x' test2: ['z', 'y'] signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should succeed with a hapi style req object', (done) => timestamp = Math.round(Date.now() / 1000) nonce = Date.now() + Math.random() * 100 # Compute signature from express style req expressReq = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: timestamp oauth_nonce: nonce signature = @provider.signer.build_signature(expressReq, expressReq.body, 'secret') hapiReq = raw: req: url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' payload: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: timestamp oauth_nonce: nonce oauth_signature: signature @provider.valid_request hapiReq, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should return false if nonce already seen', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) => should.not.exist err valid.should.equal true @provider.valid_request req, (err, valid) -> should.exist err err.should.be.instanceof(lti.Errors.NonceError) valid.should.equal false done() describe 'mapping', () => before () => @provider = new @lti.Provider('key','secret') req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: context_id: "4" context_label: "PHYS 2112" context_title: "Introduction To Physics" custom_param: "23" ext_lms: "moodle-2" ext_submit: "Press to launch this activity" launch_presentation_locale: "en" launch_presentation_return_url: "http://localhost:8888/moodle25/mod/lti/return.php?course=4&launch_container=4&instanceid=1" lis_outcome_service_url: "http://localhost:8888/moodle25/mod/lti/service.php" lis_person_contact_email_primary: "<EMAIL>" lis_person_name_family: "Rundquist" lis_person_name_full: "<NAME>undquist" lis_person_name_given: "<NAME>" lis_result_sourcedid: "{\"data\":{\"instanceid\":\"1\",\"userid\":\"4\",\"launchid\":1480927086},\"hash\":\"03382572ba1bf35bcd99f9a9cbd44004c8f96f89c96d160a7b779a4ef89c70d5\"}" lti_message_type: "basic-lti-launch-request" lti_version: "LTI-1p0" oauth_callback: "about:blank" oauth_consumer_key: "<KEY>" oauth_nonce: Date.now()+Math.random()*100 oauth_signature_method: "HMAC-SHA1" oauth_timestamp: Math.round(Date.now()/1000) oauth_version: "1.0" resource_link_description: "<p>A test of the student's wits </p>" resource_link_id: "1" resource_link_title: "Fun LTI example!" roles: "Learner" role_scope_mentor: "1234,5678,12%2C34" tool_consumer_info_product_family_code: "moodle" tool_consumer_info_version: "2013051400" tool_consumer_instance_guid: "localhost" user_id: "4" #sign the request req.body.oauth_signature = @provider.signer.build_signature(req, 'secret') @provider.parse_request req it 'should create a filled @body', () => should.exist @provider.body @provider.body.should.have.property('context_id') @provider.body.should.have.property('context_label') @provider.body.should.have.property('context_title') @provider.body.should.have.property('custom_param') @provider.body.should.have.property('ext_lms') @provider.body.should.have.property('ext_submit') @provider.body.should.have.property('launch_presentation_locale') @provider.body.should.have.property('launch_presentation_return_url') @provider.body.should.have.property('lis_outcome_service_url') @provider.body.should.have.property('lis_person_contact_email_primary') @provider.body.should.have.property('lis_person_name_family') @provider.body.should.have.property('lis_person_name_full') @provider.body.should.have.property('lis_person_name_given') @provider.body.should.have.property('lis_result_sourcedid') @provider.body.should.have.property('lti_message_type') @provider.body.should.have.property('lti_version') @provider.body.should.have.property('resource_link_description') @provider.body.should.have.property('resource_link_id') @provider.body.should.have.property('resource_link_title') @provider.body.should.have.property('roles') @provider.body.should.have.property('role_scope_mentor') @provider.body.should.have.property('tool_consumer_info_product_family_code') @provider.body.should.have.property('tool_consumer_info_version') @provider.body.should.have.property('tool_consumer_instance_guid') @provider.body.should.have.property('user_id') it 'should have stripped oauth_ properties', () => @provider.body.should.not.have.property('oauth_callback') @provider.body.should.not.have.property('oauth_consumer_key') @provider.body.should.not.have.property('oauth_nonce') @provider.body.should.not.have.property('oauth_signature') @provider.body.should.not.have.property('oauth_signature_method') @provider.body.should.not.have.property('oauth_timestamp') @provider.body.should.not.have.property('oauth_version') it 'should have helper booleans for roles', () => @provider.student.should.equal true @provider.instructor.should.equal false @provider.content_developer.should.equal false @provider.member.should.equal false @provider.manager.should.equal false @provider.mentor.should.equal false @provider.admin.should.equal false @provider.ta.should.equal false it 'should have username accessor', () => @provider.username.should.equal "James" it 'should have user id accessor', () => @provider.userId.should.equal "4" it 'should handle the role_scope_mentor id array', () => @provider.mentor_user_ids.should.eql ['1234', '5678', '12,34'] it 'should have context accessors', () => @provider.context_id.should.equal "4" @provider.context_label.should.equal "PHYS 2112" @provider.context_title.should.equal "Introduction To Physics" it 'should have response outcome_service object', () => @provider.outcome_service.should.exist it 'should account for the standardized urn prefix', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti:role:ims/lis/Instructor' provider.instructor.should.equal true it 'should test for multiple roles being passed into the body', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'Instructor,Administrator' it 'should handle different role types from the specification', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti:role:ims/lis/Student,urn:lti:sysrole:ims/lis/Administrator,urn:lti:instrole:ims/lis/Alumni' provider.student.should.equal true provider.admin.should.equal true provider.alumni.should.equal true it 'should handle garbage roles that do not match the specification', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti::ims/lis/Student,urn:lti:sysrole:ims/lis/Administrator/,/Alumni' provider.student.should.equal false provider.admin.should.equal false provider.alumni.should.equal false
true
should = require 'should' lti = require '../' describe 'LTI.Provider', () -> before ()=> @lti = lti describe 'Initialization', () => it 'should accept (consumer_key, consumer_secret)', () => sig = new (require '../lib/hmac-sha1') consumer_key = 'PI:KEY:<KEY>END_PI' consumer_secret = 'PI:KEY:<KEY>END_PI' provider = new @lti.Provider(consumer_key,consumer_secret) provider.should.be.an.instanceOf Object provider.consumer_key.should.equal consumer_key provider.consumer_secret.should.equal consumer_secret provider.signer.toString().should.equal sig.toString() it 'should accept (consumer_key, consumer_secret, nonceStore, sig)', () => sig = me: 3 you: 1 total: 4 provider = new @lti.Provider('10204','secret-shhh', undefined, sig) provider.signer.should.equal sig it 'should accept (consumer_key, consumer_secret, nonceStore, sig)', () => nonceStore = isNonceStore: ()->true isNew: ()->return setUsed: ()->return provider = new @lti.Provider('10204','secret-shhh',nonceStore) provider.nonceStore.should.equal nonceStore it 'should throw an error if no consumer_key or consumer_secret', () => (()=>provider = new @lti.Provider()).should.throw(lti.Errors.ConsumerError) (()=>provider = new @lti.Provider('consumer-key')).should.throw(lti.Errors.ConsumerError) describe 'Structure', () => before () => @provider = new @lti.Provider('key','secret') it 'should have valid_request method', () => should.exist @provider.valid_request @provider.valid_request.should.be.a.Function describe '.valid_request method', () => before () => @provider = new @lti.Provider('key','secret') @signer = @provider.signer it 'should return false if missing lti_message_type', (done) => req_missing_type = url: '/' body: lti_message_type: '' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' @provider.valid_request req_missing_type, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if incorrect LTI version', (done) => req_wrong_version = url: '/' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-0p0' resource_link_id: 'http://link-to-resource.com/resource' @provider.valid_request req_wrong_version, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if no resource_link_id', (done) => req_no_resource_link = url: '/' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' @provider.valid_request req_no_resource_link, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.ParameterError) valid.should.equal false done() it 'should return false if bad oauth', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, 'secret') req.body.oauth_signature = signature # Break the signature req.body.oauth_signature += "garbage" @provider.valid_request req, (err, valid) -> err.should.not.equal null err.should.be.instanceof(lti.Errors.SignatureError) valid.should.equal false done() it 'should return true if good headers and oauth', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should return true if lti_message_type is ContentItemSelectionRequest', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'ContentItemSelectionRequest' lti_version: 'LTI-1p0' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() [ 'resource_link_id', 'resource_link_title', 'resource_link_description', 'launch_presentation_return_url', 'lis_result_sourcedid' ].forEach (invalidField) => it "should return false if lti_message_type is ContentItemSelectionRequest and there is a \"#{invalidField}\" field", (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'ContentItemSelectionRequest' lti_version: 'LTI-1p0' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 req.body[invalidField] = "Invalid Field" #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.exist err valid.should.equal false done() it 'should special case and deduplicate Canvas requests', (done) => req = url: '/test?test=x&test2=y&test2=z' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 test: 'x' test2: ['y', 'z'] tool_consumer_info_product_family_code: 'canvas' query: test: 'x' test2: ['z', 'y'] signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should succeed with a hapi style req object', (done) => timestamp = Math.round(Date.now() / 1000) nonce = Date.now() + Math.random() * 100 # Compute signature from express style req expressReq = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: timestamp oauth_nonce: nonce signature = @provider.signer.build_signature(expressReq, expressReq.body, 'secret') hapiReq = raw: req: url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' payload: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: timestamp oauth_nonce: nonce oauth_signature: signature @provider.valid_request hapiReq, (err, valid) -> should.not.exist err valid.should.equal true done() it 'should return false if nonce already seen', (done) => req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: lti_message_type: 'basic-lti-launch-request' lti_version: 'LTI-1p0' resource_link_id: 'http://link-to-resource.com/resource' oauth_customer_key: 'key' oauth_signature_method: 'HMAC-SHA1' oauth_timestamp: Math.round(Date.now()/1000) oauth_nonce: Date.now()+Math.random()*100 #sign the fake request signature = @provider.signer.build_signature(req, req.body, 'secret') req.body.oauth_signature = signature @provider.valid_request req, (err, valid) => should.not.exist err valid.should.equal true @provider.valid_request req, (err, valid) -> should.exist err err.should.be.instanceof(lti.Errors.NonceError) valid.should.equal false done() describe 'mapping', () => before () => @provider = new @lti.Provider('key','secret') req = url: '/test' method: 'POST' connection: encrypted: undefined headers: host: 'localhost' body: context_id: "4" context_label: "PHYS 2112" context_title: "Introduction To Physics" custom_param: "23" ext_lms: "moodle-2" ext_submit: "Press to launch this activity" launch_presentation_locale: "en" launch_presentation_return_url: "http://localhost:8888/moodle25/mod/lti/return.php?course=4&launch_container=4&instanceid=1" lis_outcome_service_url: "http://localhost:8888/moodle25/mod/lti/service.php" lis_person_contact_email_primary: "PI:EMAIL:<EMAIL>END_PI" lis_person_name_family: "Rundquist" lis_person_name_full: "PI:NAME:<NAME>END_PIundquist" lis_person_name_given: "PI:NAME:<NAME>END_PI" lis_result_sourcedid: "{\"data\":{\"instanceid\":\"1\",\"userid\":\"4\",\"launchid\":1480927086},\"hash\":\"03382572ba1bf35bcd99f9a9cbd44004c8f96f89c96d160a7b779a4ef89c70d5\"}" lti_message_type: "basic-lti-launch-request" lti_version: "LTI-1p0" oauth_callback: "about:blank" oauth_consumer_key: "PI:KEY:<KEY>END_PI" oauth_nonce: Date.now()+Math.random()*100 oauth_signature_method: "HMAC-SHA1" oauth_timestamp: Math.round(Date.now()/1000) oauth_version: "1.0" resource_link_description: "<p>A test of the student's wits </p>" resource_link_id: "1" resource_link_title: "Fun LTI example!" roles: "Learner" role_scope_mentor: "1234,5678,12%2C34" tool_consumer_info_product_family_code: "moodle" tool_consumer_info_version: "2013051400" tool_consumer_instance_guid: "localhost" user_id: "4" #sign the request req.body.oauth_signature = @provider.signer.build_signature(req, 'secret') @provider.parse_request req it 'should create a filled @body', () => should.exist @provider.body @provider.body.should.have.property('context_id') @provider.body.should.have.property('context_label') @provider.body.should.have.property('context_title') @provider.body.should.have.property('custom_param') @provider.body.should.have.property('ext_lms') @provider.body.should.have.property('ext_submit') @provider.body.should.have.property('launch_presentation_locale') @provider.body.should.have.property('launch_presentation_return_url') @provider.body.should.have.property('lis_outcome_service_url') @provider.body.should.have.property('lis_person_contact_email_primary') @provider.body.should.have.property('lis_person_name_family') @provider.body.should.have.property('lis_person_name_full') @provider.body.should.have.property('lis_person_name_given') @provider.body.should.have.property('lis_result_sourcedid') @provider.body.should.have.property('lti_message_type') @provider.body.should.have.property('lti_version') @provider.body.should.have.property('resource_link_description') @provider.body.should.have.property('resource_link_id') @provider.body.should.have.property('resource_link_title') @provider.body.should.have.property('roles') @provider.body.should.have.property('role_scope_mentor') @provider.body.should.have.property('tool_consumer_info_product_family_code') @provider.body.should.have.property('tool_consumer_info_version') @provider.body.should.have.property('tool_consumer_instance_guid') @provider.body.should.have.property('user_id') it 'should have stripped oauth_ properties', () => @provider.body.should.not.have.property('oauth_callback') @provider.body.should.not.have.property('oauth_consumer_key') @provider.body.should.not.have.property('oauth_nonce') @provider.body.should.not.have.property('oauth_signature') @provider.body.should.not.have.property('oauth_signature_method') @provider.body.should.not.have.property('oauth_timestamp') @provider.body.should.not.have.property('oauth_version') it 'should have helper booleans for roles', () => @provider.student.should.equal true @provider.instructor.should.equal false @provider.content_developer.should.equal false @provider.member.should.equal false @provider.manager.should.equal false @provider.mentor.should.equal false @provider.admin.should.equal false @provider.ta.should.equal false it 'should have username accessor', () => @provider.username.should.equal "James" it 'should have user id accessor', () => @provider.userId.should.equal "4" it 'should handle the role_scope_mentor id array', () => @provider.mentor_user_ids.should.eql ['1234', '5678', '12,34'] it 'should have context accessors', () => @provider.context_id.should.equal "4" @provider.context_label.should.equal "PHYS 2112" @provider.context_title.should.equal "Introduction To Physics" it 'should have response outcome_service object', () => @provider.outcome_service.should.exist it 'should account for the standardized urn prefix', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti:role:ims/lis/Instructor' provider.instructor.should.equal true it 'should test for multiple roles being passed into the body', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'Instructor,Administrator' it 'should handle different role types from the specification', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti:role:ims/lis/Student,urn:lti:sysrole:ims/lis/Administrator,urn:lti:instrole:ims/lis/Alumni' provider.student.should.equal true provider.admin.should.equal true provider.alumni.should.equal true it 'should handle garbage roles that do not match the specification', () => provider = new @lti.Provider('key', 'secret') provider.parse_request body: roles: 'urn:lti::ims/lis/Student,urn:lti:sysrole:ims/lis/Administrator/,/Alumni' provider.student.should.equal false provider.admin.should.equal false provider.alumni.should.equal false
[ { "context": "beforeEach ->\n\t\t@user =\n\t\t\t_id: 'abcd'\n\t\t\temail: 'user@example.com'\n\t\t@UserGetter =\n\t\t\tgetUser: sinon.stub().callsAr", "end": 405, "score": 0.9999149441719055, "start": 389, "tag": "EMAIL", "value": "user@example.com" }, { "context": "oller =\n\t\t\tge...
test/unit/coffee/SudoMode/SudoModeControllerTests.coffee
shyoshyo/web-sharelatex
1
SandboxedModule = require('sandboxed-module') sinon = require 'sinon' should = require("chai").should() expect = require('chai').expect MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" modulePath = '../../../../app/js/Features/SudoMode/SudoModeController' describe 'SudoModeController', -> beforeEach -> @user = _id: 'abcd' email: 'user@example.com' @UserGetter = getUser: sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler = authenticate: sinon.stub() isSudoModeActive: sinon.stub() activateSudoMode: sinon.stub() @AuthenticationController = getLoggedInUserId: sinon.stub().returns(@user._id) _getRediretFromSession: sinon.stub() @UserGetter = getUser: sinon.stub() @SudoModeController = SandboxedModule.require modulePath, requires: 'logger-sharelatex': {log: sinon.stub(), err: sinon.stub()} './SudoModeHandler': @SudoModeHandler '../Authentication/AuthenticationController': @AuthenticationController '../../infrastructure/Mongoose': {mongo: {ObjectId: () -> 'some_object_id'}} '../User/UserGetter': @UserGetter 'settings-sharelatex': @Settings = {} describe 'sudoModePrompt', -> beforeEach -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, false) @req = {externalAuthenticationSystemUsed: sinon.stub().returns(false)} @res = {redirect: sinon.stub(), render: sinon.stub()} @next = sinon.stub() it 'should get the logged in user id', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @AuthenticationController.getLoggedInUserId.callCount.should.equal 1 @AuthenticationController.getLoggedInUserId.calledWith(@req).should.equal true it 'should check if sudo-mode is active', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @SudoModeHandler.isSudoModeActive.callCount.should.equal 1 @SudoModeHandler.isSudoModeActive.calledWith(@user._id).should.equal true it 'should redirect when sudo-mode is active', -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, true) @SudoModeController.sudoModePrompt(@req, @res, @next) @res.redirect.callCount.should.equal 1 @res.redirect.calledWith('/project').should.equal true it 'should render the sudo_mode_prompt page when sudo mode is not active', -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, false) @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 1 @res.render.calledWith('sudo_mode/sudo_mode_prompt').should.equal true describe 'when isSudoModeActive produces an error', -> beforeEach -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, new Error('woops')) @next = sinon.stub() it 'should call next with an error', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should not render page', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 0 describe 'when external auth system is used', -> beforeEach -> @req.externalAuthenticationSystemUsed = sinon.stub().returns(true) it 'should redirect', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.redirect.callCount.should.equal 1 @res.redirect.calledWith('/project').should.equal true it 'should not check if sudo mode is active', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @SudoModeHandler.isSudoModeActive.callCount.should.equal 0 it 'should not render page', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 0 describe 'submitPassword', -> beforeEach -> @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/somewhere' @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler.activateSudoMode = sinon.stub().callsArgWith(1, null) @password = 'a_terrible_secret' @req = {body: {password: @password}} @res = {json: sinon.stub()} @next = sinon.stub() describe 'when all goes well', -> beforeEach -> it 'should get the logged in user id', -> @SudoModeController.submitPassword(@req, @res, @next) @AuthenticationController.getLoggedInUserId.callCount.should.equal 1 @AuthenticationController.getLoggedInUserId.calledWith(@req).should.equal true it 'should get redirect from session', -> @SudoModeController.submitPassword(@req, @res, @next) @AuthenticationController._getRedirectFromSession.callCount.should.equal 1 @AuthenticationController._getRedirectFromSession.calledWith(@req).should.equal true it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 1 @SudoModeHandler.activateSudoMode.calledWith(@user._id).should.equal true it 'should send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 1 @res.json.calledWith({redir: '/somewhere'}).should.equal true it 'should not call next', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 0 describe 'when no password is supplied', -> beforeEach -> @req.body.password = '' @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should not get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 0 it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when getUser produces an error', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when getUser does not find a user', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when authentication fails', -> beforeEach -> @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, null, null) @res.json = sinon.stub() @req.i18n = {translate: sinon.stub()} it 'should send back a failure message', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 1 expect(@res.json.lastCall.args[0]).to.have.keys ['message'] expect(@res.json.lastCall.args[0].message).to.have.keys ['text', 'type'] @req.i18n.translate.callCount.should.equal 1 @req.i18n.translate.calledWith('invalid_password') it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 describe 'when authentication produces an error', -> beforeEach -> @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 describe 'when sudo mode activation produces an error', -> beforeEach -> @SudoModeHandler.activateSudoMode = sinon.stub().callsArgWith(1, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should have tried to activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 1 @SudoModeHandler.activateSudoMode.calledWith(@user._id).should.equal true
49625
SandboxedModule = require('sandboxed-module') sinon = require 'sinon' should = require("chai").should() expect = require('chai').expect MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" modulePath = '../../../../app/js/Features/SudoMode/SudoModeController' describe 'SudoModeController', -> beforeEach -> @user = _id: 'abcd' email: '<EMAIL>' @UserGetter = getUser: sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler = authenticate: sinon.stub() isSudoModeActive: sinon.stub() activateSudoMode: sinon.stub() @AuthenticationController = getLoggedInUserId: sinon.stub().returns(@user._id) _getRediretFromSession: sinon.stub() @UserGetter = getUser: sinon.stub() @SudoModeController = SandboxedModule.require modulePath, requires: 'logger-sharelatex': {log: sinon.stub(), err: sinon.stub()} './SudoModeHandler': @SudoModeHandler '../Authentication/AuthenticationController': @AuthenticationController '../../infrastructure/Mongoose': {mongo: {ObjectId: () -> 'some_object_id'}} '../User/UserGetter': @UserGetter 'settings-sharelatex': @Settings = {} describe 'sudoModePrompt', -> beforeEach -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, false) @req = {externalAuthenticationSystemUsed: sinon.stub().returns(false)} @res = {redirect: sinon.stub(), render: sinon.stub()} @next = sinon.stub() it 'should get the logged in user id', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @AuthenticationController.getLoggedInUserId.callCount.should.equal 1 @AuthenticationController.getLoggedInUserId.calledWith(@req).should.equal true it 'should check if sudo-mode is active', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @SudoModeHandler.isSudoModeActive.callCount.should.equal 1 @SudoModeHandler.isSudoModeActive.calledWith(@user._id).should.equal true it 'should redirect when sudo-mode is active', -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, true) @SudoModeController.sudoModePrompt(@req, @res, @next) @res.redirect.callCount.should.equal 1 @res.redirect.calledWith('/project').should.equal true it 'should render the sudo_mode_prompt page when sudo mode is not active', -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, false) @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 1 @res.render.calledWith('sudo_mode/sudo_mode_prompt').should.equal true describe 'when isSudoModeActive produces an error', -> beforeEach -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, new Error('woops')) @next = sinon.stub() it 'should call next with an error', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should not render page', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 0 describe 'when external auth system is used', -> beforeEach -> @req.externalAuthenticationSystemUsed = sinon.stub().returns(true) it 'should redirect', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.redirect.callCount.should.equal 1 @res.redirect.calledWith('/project').should.equal true it 'should not check if sudo mode is active', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @SudoModeHandler.isSudoModeActive.callCount.should.equal 0 it 'should not render page', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 0 describe 'submitPassword', -> beforeEach -> @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/somewhere' @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler.activateSudoMode = sinon.stub().callsArgWith(1, null) @password = '<PASSWORD>' @req = {body: {password: <PASSWORD>}} @res = {json: sinon.stub()} @next = sinon.stub() describe 'when all goes well', -> beforeEach -> it 'should get the logged in user id', -> @SudoModeController.submitPassword(@req, @res, @next) @AuthenticationController.getLoggedInUserId.callCount.should.equal 1 @AuthenticationController.getLoggedInUserId.calledWith(@req).should.equal true it 'should get redirect from session', -> @SudoModeController.submitPassword(@req, @res, @next) @AuthenticationController._getRedirectFromSession.callCount.should.equal 1 @AuthenticationController._getRedirectFromSession.calledWith(@req).should.equal true it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 1 @SudoModeHandler.activateSudoMode.calledWith(@user._id).should.equal true it 'should send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 1 @res.json.calledWith({redir: '/somewhere'}).should.equal true it 'should not call next', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 0 describe 'when no password is supplied', -> beforeEach -> @req.body.password =<PASSWORD> '' @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should not get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 0 it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when getUser produces an error', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when getUser does not find a user', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when authentication fails', -> beforeEach -> @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, null, null) @res.json = sinon.stub() @req.i18n = {translate: sinon.stub()} it 'should send back a failure message', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 1 expect(@res.json.lastCall.args[0]).to.have.keys ['message'] expect(@res.json.lastCall.args[0].message).to.have.keys ['text', 'type'] @req.i18n.translate.callCount.should.equal 1 @req.i18n.translate.calledWith('invalid_password') it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 describe 'when authentication produces an error', -> beforeEach -> @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 describe 'when sudo mode activation produces an error', -> beforeEach -> @SudoModeHandler.activateSudoMode = sinon.stub().callsArgWith(1, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should have tried to activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 1 @SudoModeHandler.activateSudoMode.calledWith(@user._id).should.equal true
true
SandboxedModule = require('sandboxed-module') sinon = require 'sinon' should = require("chai").should() expect = require('chai').expect MockRequest = require "../helpers/MockRequest" MockResponse = require "../helpers/MockResponse" modulePath = '../../../../app/js/Features/SudoMode/SudoModeController' describe 'SudoModeController', -> beforeEach -> @user = _id: 'abcd' email: 'PI:EMAIL:<EMAIL>END_PI' @UserGetter = getUser: sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler = authenticate: sinon.stub() isSudoModeActive: sinon.stub() activateSudoMode: sinon.stub() @AuthenticationController = getLoggedInUserId: sinon.stub().returns(@user._id) _getRediretFromSession: sinon.stub() @UserGetter = getUser: sinon.stub() @SudoModeController = SandboxedModule.require modulePath, requires: 'logger-sharelatex': {log: sinon.stub(), err: sinon.stub()} './SudoModeHandler': @SudoModeHandler '../Authentication/AuthenticationController': @AuthenticationController '../../infrastructure/Mongoose': {mongo: {ObjectId: () -> 'some_object_id'}} '../User/UserGetter': @UserGetter 'settings-sharelatex': @Settings = {} describe 'sudoModePrompt', -> beforeEach -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, false) @req = {externalAuthenticationSystemUsed: sinon.stub().returns(false)} @res = {redirect: sinon.stub(), render: sinon.stub()} @next = sinon.stub() it 'should get the logged in user id', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @AuthenticationController.getLoggedInUserId.callCount.should.equal 1 @AuthenticationController.getLoggedInUserId.calledWith(@req).should.equal true it 'should check if sudo-mode is active', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @SudoModeHandler.isSudoModeActive.callCount.should.equal 1 @SudoModeHandler.isSudoModeActive.calledWith(@user._id).should.equal true it 'should redirect when sudo-mode is active', -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, true) @SudoModeController.sudoModePrompt(@req, @res, @next) @res.redirect.callCount.should.equal 1 @res.redirect.calledWith('/project').should.equal true it 'should render the sudo_mode_prompt page when sudo mode is not active', -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, null, false) @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 1 @res.render.calledWith('sudo_mode/sudo_mode_prompt').should.equal true describe 'when isSudoModeActive produces an error', -> beforeEach -> @SudoModeHandler.isSudoModeActive = sinon.stub().callsArgWith(1, new Error('woops')) @next = sinon.stub() it 'should call next with an error', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should not render page', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 0 describe 'when external auth system is used', -> beforeEach -> @req.externalAuthenticationSystemUsed = sinon.stub().returns(true) it 'should redirect', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.redirect.callCount.should.equal 1 @res.redirect.calledWith('/project').should.equal true it 'should not check if sudo mode is active', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @SudoModeHandler.isSudoModeActive.callCount.should.equal 0 it 'should not render page', -> @SudoModeController.sudoModePrompt(@req, @res, @next) @res.render.callCount.should.equal 0 describe 'submitPassword', -> beforeEach -> @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/somewhere' @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, null, @user) @SudoModeHandler.activateSudoMode = sinon.stub().callsArgWith(1, null) @password = 'PI:PASSWORD:<PASSWORD>END_PI' @req = {body: {password: PI:PASSWORD:<PASSWORD>END_PI}} @res = {json: sinon.stub()} @next = sinon.stub() describe 'when all goes well', -> beforeEach -> it 'should get the logged in user id', -> @SudoModeController.submitPassword(@req, @res, @next) @AuthenticationController.getLoggedInUserId.callCount.should.equal 1 @AuthenticationController.getLoggedInUserId.calledWith(@req).should.equal true it 'should get redirect from session', -> @SudoModeController.submitPassword(@req, @res, @next) @AuthenticationController._getRedirectFromSession.callCount.should.equal 1 @AuthenticationController._getRedirectFromSession.calledWith(@req).should.equal true it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 1 @SudoModeHandler.activateSudoMode.calledWith(@user._id).should.equal true it 'should send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 1 @res.json.calledWith({redir: '/somewhere'}).should.equal true it 'should not call next', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 0 describe 'when no password is supplied', -> beforeEach -> @req.body.password =PI:PASSWORD:<PASSWORD>END_PI '' @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should not get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 0 it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when getUser produces an error', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when getUser does not find a user', -> beforeEach -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should not try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 0 it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 it 'should not send back a json response', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 0 describe 'when authentication fails', -> beforeEach -> @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, null, null) @res.json = sinon.stub() @req.i18n = {translate: sinon.stub()} it 'should send back a failure message', -> @SudoModeController.submitPassword(@req, @res, @next) @res.json.callCount.should.equal 1 expect(@res.json.lastCall.args[0]).to.have.keys ['message'] expect(@res.json.lastCall.args[0].message).to.have.keys ['text', 'type'] @req.i18n.translate.callCount.should.equal 1 @req.i18n.translate.calledWith('invalid_password') it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 describe 'when authentication produces an error', -> beforeEach -> @SudoModeHandler.authenticate = sinon.stub().callsArgWith(2, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should not activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 0 describe 'when sudo mode activation produces an error', -> beforeEach -> @SudoModeHandler.activateSudoMode = sinon.stub().callsArgWith(1, new Error('woops')) @next = sinon.stub() it 'should return next with an error', -> @SudoModeController.submitPassword(@req, @res, @next) @next.callCount.should.equal 1 expect(@next.lastCall.args[0]).to.be.instanceof Error it 'should get the user from storage', -> @SudoModeController.submitPassword(@req, @res, @next) @UserGetter.getUser.callCount.should.equal 1 @UserGetter.getUser.calledWith('some_object_id', {email: 1}).should.equal true it 'should try to authenticate the user with the password', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.authenticate.callCount.should.equal 1 @SudoModeHandler.authenticate.calledWith(@user.email, @password).should.equal true it 'should have tried to activate sudo mode', -> @SudoModeController.submitPassword(@req, @res, @next) @SudoModeHandler.activateSudoMode.callCount.should.equal 1 @SudoModeHandler.activateSudoMode.calledWith(@user._id).should.equal true
[ { "context": "iew Tests for max-classes-per-file rule.\n# @author James Garbutt <https://github.com/43081j>\n###\n'use strict'\n\n#--", "end": 81, "score": 0.999878466129303, "start": 68, "tag": "NAME", "value": "James Garbutt" }, { "context": "rule.\n# @author James Garbutt <https:/...
src/tests/rules/max-classes-per-file.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for max-classes-per-file rule. # @author James Garbutt <https://github.com/43081j> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-classes-per-file' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'max-classes-per-file', rule, valid: [ 'class Foo' 'x = class' 'x = 5' , code: 'class Foo' options: [1] , code: ''' class Foo class Bar ''' options: [2] ] invalid: [ code: ''' class Foo class Bar ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' x = class y = class ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo x = class ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo class Bar ''' options: [1] errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo class Bar class Baz ''' options: [2] errors: [messageId: 'maximumExceeded', type: 'Program'] ]
122328
###* # @fileoverview Tests for max-classes-per-file rule. # @author <NAME> <https://github.com/43081j> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-classes-per-file' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'max-classes-per-file', rule, valid: [ 'class Foo' 'x = class' 'x = 5' , code: 'class Foo' options: [1] , code: ''' class Foo class Bar ''' options: [2] ] invalid: [ code: ''' class Foo class Bar ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' x = class y = class ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo x = class ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo class Bar ''' options: [1] errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo class Bar class Baz ''' options: [2] errors: [messageId: 'maximumExceeded', type: 'Program'] ]
true
###* # @fileoverview Tests for max-classes-per-file rule. # @author PI:NAME:<NAME>END_PI <https://github.com/43081j> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-classes-per-file' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'max-classes-per-file', rule, valid: [ 'class Foo' 'x = class' 'x = 5' , code: 'class Foo' options: [1] , code: ''' class Foo class Bar ''' options: [2] ] invalid: [ code: ''' class Foo class Bar ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' x = class y = class ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo x = class ''' errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo class Bar ''' options: [1] errors: [messageId: 'maximumExceeded', type: 'Program'] , code: ''' class Foo class Bar class Baz ''' options: [2] errors: [messageId: 'maximumExceeded', type: 'Program'] ]
[ { "context": "stylus = require 'stylus'\nbanner = 'Copyright 2015 Thomas Yang http://thomas-yang.me/'\n\npaths =\n src: path.join", "end": 132, "score": 0.9996479749679565, "start": 121, "tag": "NAME", "value": "Thomas Yang" } ]
webpack.config.coffee
Hacker-YHJ/SingleElementForPhilographics
2
webpack = require 'webpack' path = require 'path' nib = require 'nib' stylus = require 'stylus' banner = 'Copyright 2015 Thomas Yang http://thomas-yang.me/' paths = src: path.join(__dirname, 'src') dest: path.join(__dirname, 'dist') module.exports = entry: [ 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:5000', paths.src + '/coffee/main.coffee' ] watch: true debug: true devtool: 'eval' output: path: paths.dest filename: 'main.js' resolve: # you can now require('file') instead of require('file.coffee') extensions: ['', '.js', '.json', '.coffee', '.css', '.styl'] module: loaders: [ { test: /\.coffee$/ exclude: /node_modules/ loader: 'coffee-loader' }, { test: /\.styl$/ loader: 'style-loader!css-loader!stylus-loader?resolve url' }, { test: /\.(eot|ttf|woff|svg|otf)$/ loader: 'url?limit=100000' } ], stylus: use: [nib()] define: url: stylus.url paths: [__dirname + '/src'] limit: false plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.BannerPlugin(banner) ]
159532
webpack = require 'webpack' path = require 'path' nib = require 'nib' stylus = require 'stylus' banner = 'Copyright 2015 <NAME> http://thomas-yang.me/' paths = src: path.join(__dirname, 'src') dest: path.join(__dirname, 'dist') module.exports = entry: [ 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:5000', paths.src + '/coffee/main.coffee' ] watch: true debug: true devtool: 'eval' output: path: paths.dest filename: 'main.js' resolve: # you can now require('file') instead of require('file.coffee') extensions: ['', '.js', '.json', '.coffee', '.css', '.styl'] module: loaders: [ { test: /\.coffee$/ exclude: /node_modules/ loader: 'coffee-loader' }, { test: /\.styl$/ loader: 'style-loader!css-loader!stylus-loader?resolve url' }, { test: /\.(eot|ttf|woff|svg|otf)$/ loader: 'url?limit=100000' } ], stylus: use: [nib()] define: url: stylus.url paths: [__dirname + '/src'] limit: false plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.BannerPlugin(banner) ]
true
webpack = require 'webpack' path = require 'path' nib = require 'nib' stylus = require 'stylus' banner = 'Copyright 2015 PI:NAME:<NAME>END_PI http://thomas-yang.me/' paths = src: path.join(__dirname, 'src') dest: path.join(__dirname, 'dist') module.exports = entry: [ 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:5000', paths.src + '/coffee/main.coffee' ] watch: true debug: true devtool: 'eval' output: path: paths.dest filename: 'main.js' resolve: # you can now require('file') instead of require('file.coffee') extensions: ['', '.js', '.json', '.coffee', '.css', '.styl'] module: loaders: [ { test: /\.coffee$/ exclude: /node_modules/ loader: 'coffee-loader' }, { test: /\.styl$/ loader: 'style-loader!css-loader!stylus-loader?resolve url' }, { test: /\.(eot|ttf|woff|svg|otf)$/ loader: 'url?limit=100000' } ], stylus: use: [nib()] define: url: stylus.url paths: [__dirname + '/src'] limit: false plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.BannerPlugin(banner) ]
[ { "context": "rtices.length]\n if v1 <= v2\n key = \"#{v1},#{v2}\"\n else\n key = \"#{v2},#{v1}\"\n ", "end": 7088, "score": 0.9987239837646484, "start": 7075, "tag": "KEY", "value": "\"#{v1},#{v2}\"" }, { "context": " key = \"#{v1},#{v2}\"\n ...
src/convert.coffee
pimmu1s/fold
231
### FOLD FORMAT MANIPULATORS ### geom = require './geom' filter = require './filter' convert = exports convert.edges_vertices_to_vertices_vertices_unsorted = (fold) -> ### Works for abstract structures, so NOT SORTED. Use sort_vertices_vertices to sort in counterclockwise order. ### fold.vertices_vertices = filter.edges_vertices_to_vertices_vertices fold fold convert.edges_vertices_to_vertices_vertices_sorted = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices` property (defining edge endpoints), automatically computes the `vertices_vertices` property and sorts them counterclockwise by angle in the plane. ### convert.edges_vertices_to_vertices_vertices_unsorted fold convert.sort_vertices_vertices fold convert.edges_vertices_to_vertices_edges_sorted = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices` property (defining edge endpoints), automatically computes the `vertices_edges` and `vertices_vertices` property and sorts them counterclockwise by angle in the plane. ### convert.edges_vertices_to_vertices_vertices_sorted fold convert.vertices_vertices_to_vertices_edges fold convert.sort_vertices_vertices = (fold) -> ### Sorts `fold.vertices_neighbords` in counterclockwise order using `fold.vertices_coordinates`. 2D only. Constructs `fold.vertices_neighbords` if absent, via `convert.edges_vertices_to_vertices_vertices`. ### unless fold.vertices_coords?[0]?.length == 2 throw new Error "sort_vertices_vertices: Vertex coordinates missing or not two dimensional" unless fold.vertices_vertices? convert.edges_vertices_to_vertices_vertices fold for v, neighbors of fold.vertices_vertices geom.sortByAngle neighbors, v, (x) -> fold.vertices_coords[x] fold convert.vertices_vertices_to_faces_vertices = (fold) -> ### Given a FOLD object with counterclockwise-sorted `vertices_vertices` property, constructs the implicitly defined faces, setting `faces_vertices` property. ### next = {} for neighbors, v in fold.vertices_vertices for u, i in neighbors next["#{u},#{v}"] = neighbors[(i-1) %% neighbors.length] #console.log u, v, neighbors[(i-1) %% neighbors.length] fold.faces_vertices = [] #for uv, w of next for uv in (key for key of next) w = next[uv] continue unless w? next[uv] = null [u, v] = uv.split ',' u = parseInt u v = parseInt v face = [u, v] until w == face[0] unless w? console.warn "Confusion with face #{face}" break face.push w [u, v] = [v, w] w = next["#{u},#{v}"] next["#{u},#{v}"] = null next["#{face[face.length-1]},#{face[0]}"] = null ## Outside face is clockwise; exclude it. if w? and geom.polygonOrientation(fold.vertices_coords[x] for x in face) > 0 #console.log face fold.faces_vertices.push face #else # console.log face, 'clockwise' fold convert.vertices_edges_to_faces_vertices_edges = (fold) -> ### Given a FOLD object with counterclockwise-sorted `vertices_edges` property, constructs the implicitly defined faces, setting both `faces_vertices` and `faces_edges` properties. Handles multiple edges to the same vertex (unlike `FOLD.convert.vertices_vertices_to_faces_vertices`). ### next = [] for neighbors, v in fold.vertices_edges next[v] = {} for e, i in neighbors next[v][e] = neighbors[(i-1) %% neighbors.length] #console.log e, neighbors[(i-1) %% neighbors.length] fold.faces_vertices = [] fold.faces_edges = [] for nexts, vertex in next for e1, e2 of nexts continue unless e2? e1 = parseInt e1 nexts[e1] = null edges = [e1] vertices = [filter.edges_verticesIncident fold.edges_vertices[e1], fold.edges_vertices[e2]] unless vertices[0]? throw new Error "Confusion at edges #{e1} and #{e2}" until e2 == edges[0] unless e2? console.warn "Confusion with face containing edges #{edges}" break edges.push e2 for v in fold.edges_vertices[e2] if v != vertices[vertices.length-1] vertices.push v break e1 = e2 e2 = next[v][e1] next[v][e1] = null ## Outside face is clockwise; exclude it. if e2? and geom.polygonOrientation(fold.vertices_coords[x] for x in vertices) > 0 #console.log vertices, edges fold.faces_vertices.push vertices fold.faces_edges.push edges #else # console.log face, 'clockwise' fold convert.edges_vertices_to_faces_vertices = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices`, computes a counterclockwise-sorted `vertices_vertices` property and constructs the implicitly defined faces, setting `faces_vertices` property. ### convert.edges_vertices_to_vertices_vertices_sorted fold convert.vertices_vertices_to_faces_vertices fold convert.edges_vertices_to_faces_vertices_edges = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices`, computes counterclockwise-sorted `vertices_vertices` and `vertices_edges` properties and constructs the implicitly defined faces, setting both `faces_vertices` and `faces_edges` property. ### convert.edges_vertices_to_vertices_edges_sorted fold convert.vertices_edges_to_faces_vertices_edges fold convert.vertices_vertices_to_vertices_edges = (fold) -> ### Given a FOLD object with `vertices_vertices` and `edges_vertices`, fills in the corresponding `vertices_edges` property (preserving order). ### edgeMap = {} for [v1, v2], edge in fold.edges_vertices edgeMap["#{v1},#{v2}"] = edge edgeMap["#{v2},#{v1}"] = edge fold.vertices_edges = for vertices, vertex in fold.vertices_vertices for i in [0...vertices.length] edgeMap["#{vertex},#{vertices[i]}"] convert.faces_vertices_to_faces_edges = (fold) -> ### Given a FOLD object with `faces_vertices` and `edges_vertices`, fills in the corresponding `faces_edges` property (preserving order). ### edgeMap = {} for [v1, v2], edge in fold.edges_vertices edgeMap["#{v1},#{v2}"] = edge edgeMap["#{v2},#{v1}"] = edge fold.faces_edges = for vertices, face in fold.faces_vertices for i in [0...vertices.length] edgeMap["#{vertices[i]},#{vertices[(i+1) % vertices.length]}"] convert.faces_vertices_to_edges = (mesh) -> ### Given a FOLD object with just `faces_vertices`, automatically fills in `edges_vertices`, `edges_faces`, `faces_edges`, and `edges_assignment` (indicating which edges are boundary with 'B'). ### mesh.edges_vertices = [] mesh.edges_faces = [] mesh.faces_edges = [] mesh.edges_assignment = [] edgeMap = {} for face, vertices of mesh.faces_vertices face = parseInt face mesh.faces_edges.push( for v1, i in vertices v1 = parseInt v1 v2 = vertices[(i+1) % vertices.length] if v1 <= v2 key = "#{v1},#{v2}" else key = "#{v2},#{v1}" if key of edgeMap edge = edgeMap[key] # Second instance of edge means not on boundary mesh.edges_assignment[edge] = null else edge = edgeMap[key] = mesh.edges_vertices.length if v1 <= v2 mesh.edges_vertices.push [v1, v2] else mesh.edges_vertices.push [v2, v1] mesh.edges_faces.push [null, null] # First instance of edge might be on boundary mesh.edges_assignment.push 'B' if v1 <= v2 mesh.edges_faces[edge][0] = face else mesh.edges_faces[edge][1] = face edge ) mesh convert.edges_vertices_to_edges_faces_edges = (fold) -> ### Given a `fold` object with `edges_vertices` and `faces_vertices`, fills in `faces_edges` and `edges_vertices`. ### fold.edges_faces = ([null, null] for edge in [0...fold.edges_vertices.length]) edgeMap = {} for edge, vertices of fold.edges_vertices when vertices? edge = parseInt edge edgeMap["#{vertices[0]},#{vertices[1]}"] = [edge, 0] # forward edgeMap["#{vertices[1]},#{vertices[0]}"] = [edge, 1] # backward for face, vertices of fold.faces_vertices face = parseInt face fold.faces_edges[face] = for v1, i in vertices v2 = vertices[(i+1) % vertices.length] [edge, orient] = edgeMap["#{v1},#{v2}"] fold.edges_faces[edge][orient] = face edge fold convert.flatFoldedGeometry = (fold, rootFace = 0) -> ### Assuming `fold` is a locally flat foldable crease pattern in the xy plane, sets `fold.vertices_flatFoldCoords` to give the flat-folded geometry as determined by repeated reflection relative to `rootFace`; sets `fold.faces_flatFoldTransform` transformation matrix mapping each face's unfolded --> folded geometry; and sets `fold.faces_flatFoldOrientation` to +1 or -1 to indicate whether each folded face matches its original orientation or is upside-down (so is oriented clockwise in 2D). Requires `fold` to have `vertices_coords` and `edges_vertices`; `edges_faces` and `faces_edges` will be created if they do not exist. Returns the maximum displacement error from closure constraints (multiple mappings of the same vertices, or multiple transformations of the same face). ### if fold.vertices_coords? and fold.edges_vertices? and not (fold.edges_faces? and fold.faces_edges?) convert.edges_vertices_to_edges_faces_edges fold maxError = 0 level = [rootFace] fold.faces_flatFoldTransform = (null for face in [0...fold.faces_edges.length]) fold.faces_flatFoldTransform[rootFace] = [[1,0,0],[0,1,0]] # identity fold.faces_flatFoldOrientation = (null for face in [0...fold.faces_edges.length]) fold.faces_flatFoldOrientation[rootFace] = +1 fold.vertices_flatFoldCoords = (null for vertex in [0...fold.vertices_coords.length]) # Use fold.faces_edges -> fold.edges_vertices, which are both needed below, # in case fold.faces_vertices isn't defined. for edge in fold.faces_edges[rootFace] for vertex in fold.edges_vertices[edge] fold.vertices_flatFoldCoords[vertex] ?= fold.vertices_coords[vertex][..] while level.length nextLevel = [] for face in level orientation = -fold.faces_flatFoldOrientation[face] for edge in fold.faces_edges[face] for face2 in fold.edges_faces[edge] when face2? and face2 != face transform = geom.matrixMatrix fold.faces_flatFoldTransform[face], geom.matrixReflectLine ...( for vertex in fold.edges_vertices[edge] fold.vertices_coords[vertex] ) if fold.faces_flatFoldTransform[face2]? for row, i in fold.faces_flatFoldTransform[face2] maxError = Math.max maxError, geom.dist row, transform[i] if orientation != fold.faces_flatFoldOrientation[face2] maxError = Math.max 1, maxError else fold.faces_flatFoldTransform[face2] = transform fold.faces_flatFoldOrientation[face2] = orientation for edge2 in fold.faces_edges[face2] for vertex2 in fold.edges_vertices[edge2] mapped = geom.matrixVector transform, fold.vertices_coords[vertex2] if fold.vertices_flatFoldCoords[vertex2]? maxError = Math.max maxError, geom.dist fold.vertices_flatFoldCoords[vertex2], mapped else fold.vertices_flatFoldCoords[vertex2] = mapped nextLevel.push face2 level = nextLevel maxError convert.deepCopy = (fold) -> ## Given a FOLD object, make a copy that shares no pointers with the original. if typeof fold in ['number', 'string', 'boolean'] fold else if Array.isArray fold for item in fold convert.deepCopy item else # Object copy = {} for own key, value of fold copy[key] = convert.deepCopy value copy convert.toJSON = (fold) -> ## Convert FOLD object into a nicely formatted JSON string. "{\n" + (for key, value of fold " #{JSON.stringify key}: " + if Array.isArray value "[\n" + (" #{JSON.stringify(obj)}" for obj in value).join(',\n') + "\n ]" else JSON.stringify value ).join(',\n') + "\n}\n" convert.extensions = {} convert.converters = {} convert.getConverter = (fromExt, toExt) -> if fromExt == toExt (x) -> x else convert.converters["#{fromExt}#{toExt}"] convert.setConverter = (fromExt, toExt, converter) -> convert.extensions[fromExt] = true convert.extensions[toExt] = true convert.converters["#{fromExt}#{toExt}"] = converter convert.convertFromTo = (data, fromExt, toExt) -> fromExt = ".#{fromExt}" unless fromExt[0] == '.' toExt = ".#{toExt}" unless toExt[0] == '.' converter = convert.getConverter fromExt, toExt unless converter? if fromExt == toExt return data throw new Error "No converter from #{fromExt} to #{toExt}" converter data convert.convertFrom = (data, fromExt) -> convert.convertFromTo data, fromExt, '.fold' convert.convertTo = (data, toExt) -> convert.convertFromTo data, '.fold', toExt convert.oripa = require './oripa'
122684
### FOLD FORMAT MANIPULATORS ### geom = require './geom' filter = require './filter' convert = exports convert.edges_vertices_to_vertices_vertices_unsorted = (fold) -> ### Works for abstract structures, so NOT SORTED. Use sort_vertices_vertices to sort in counterclockwise order. ### fold.vertices_vertices = filter.edges_vertices_to_vertices_vertices fold fold convert.edges_vertices_to_vertices_vertices_sorted = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices` property (defining edge endpoints), automatically computes the `vertices_vertices` property and sorts them counterclockwise by angle in the plane. ### convert.edges_vertices_to_vertices_vertices_unsorted fold convert.sort_vertices_vertices fold convert.edges_vertices_to_vertices_edges_sorted = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices` property (defining edge endpoints), automatically computes the `vertices_edges` and `vertices_vertices` property and sorts them counterclockwise by angle in the plane. ### convert.edges_vertices_to_vertices_vertices_sorted fold convert.vertices_vertices_to_vertices_edges fold convert.sort_vertices_vertices = (fold) -> ### Sorts `fold.vertices_neighbords` in counterclockwise order using `fold.vertices_coordinates`. 2D only. Constructs `fold.vertices_neighbords` if absent, via `convert.edges_vertices_to_vertices_vertices`. ### unless fold.vertices_coords?[0]?.length == 2 throw new Error "sort_vertices_vertices: Vertex coordinates missing or not two dimensional" unless fold.vertices_vertices? convert.edges_vertices_to_vertices_vertices fold for v, neighbors of fold.vertices_vertices geom.sortByAngle neighbors, v, (x) -> fold.vertices_coords[x] fold convert.vertices_vertices_to_faces_vertices = (fold) -> ### Given a FOLD object with counterclockwise-sorted `vertices_vertices` property, constructs the implicitly defined faces, setting `faces_vertices` property. ### next = {} for neighbors, v in fold.vertices_vertices for u, i in neighbors next["#{u},#{v}"] = neighbors[(i-1) %% neighbors.length] #console.log u, v, neighbors[(i-1) %% neighbors.length] fold.faces_vertices = [] #for uv, w of next for uv in (key for key of next) w = next[uv] continue unless w? next[uv] = null [u, v] = uv.split ',' u = parseInt u v = parseInt v face = [u, v] until w == face[0] unless w? console.warn "Confusion with face #{face}" break face.push w [u, v] = [v, w] w = next["#{u},#{v}"] next["#{u},#{v}"] = null next["#{face[face.length-1]},#{face[0]}"] = null ## Outside face is clockwise; exclude it. if w? and geom.polygonOrientation(fold.vertices_coords[x] for x in face) > 0 #console.log face fold.faces_vertices.push face #else # console.log face, 'clockwise' fold convert.vertices_edges_to_faces_vertices_edges = (fold) -> ### Given a FOLD object with counterclockwise-sorted `vertices_edges` property, constructs the implicitly defined faces, setting both `faces_vertices` and `faces_edges` properties. Handles multiple edges to the same vertex (unlike `FOLD.convert.vertices_vertices_to_faces_vertices`). ### next = [] for neighbors, v in fold.vertices_edges next[v] = {} for e, i in neighbors next[v][e] = neighbors[(i-1) %% neighbors.length] #console.log e, neighbors[(i-1) %% neighbors.length] fold.faces_vertices = [] fold.faces_edges = [] for nexts, vertex in next for e1, e2 of nexts continue unless e2? e1 = parseInt e1 nexts[e1] = null edges = [e1] vertices = [filter.edges_verticesIncident fold.edges_vertices[e1], fold.edges_vertices[e2]] unless vertices[0]? throw new Error "Confusion at edges #{e1} and #{e2}" until e2 == edges[0] unless e2? console.warn "Confusion with face containing edges #{edges}" break edges.push e2 for v in fold.edges_vertices[e2] if v != vertices[vertices.length-1] vertices.push v break e1 = e2 e2 = next[v][e1] next[v][e1] = null ## Outside face is clockwise; exclude it. if e2? and geom.polygonOrientation(fold.vertices_coords[x] for x in vertices) > 0 #console.log vertices, edges fold.faces_vertices.push vertices fold.faces_edges.push edges #else # console.log face, 'clockwise' fold convert.edges_vertices_to_faces_vertices = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices`, computes a counterclockwise-sorted `vertices_vertices` property and constructs the implicitly defined faces, setting `faces_vertices` property. ### convert.edges_vertices_to_vertices_vertices_sorted fold convert.vertices_vertices_to_faces_vertices fold convert.edges_vertices_to_faces_vertices_edges = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices`, computes counterclockwise-sorted `vertices_vertices` and `vertices_edges` properties and constructs the implicitly defined faces, setting both `faces_vertices` and `faces_edges` property. ### convert.edges_vertices_to_vertices_edges_sorted fold convert.vertices_edges_to_faces_vertices_edges fold convert.vertices_vertices_to_vertices_edges = (fold) -> ### Given a FOLD object with `vertices_vertices` and `edges_vertices`, fills in the corresponding `vertices_edges` property (preserving order). ### edgeMap = {} for [v1, v2], edge in fold.edges_vertices edgeMap["#{v1},#{v2}"] = edge edgeMap["#{v2},#{v1}"] = edge fold.vertices_edges = for vertices, vertex in fold.vertices_vertices for i in [0...vertices.length] edgeMap["#{vertex},#{vertices[i]}"] convert.faces_vertices_to_faces_edges = (fold) -> ### Given a FOLD object with `faces_vertices` and `edges_vertices`, fills in the corresponding `faces_edges` property (preserving order). ### edgeMap = {} for [v1, v2], edge in fold.edges_vertices edgeMap["#{v1},#{v2}"] = edge edgeMap["#{v2},#{v1}"] = edge fold.faces_edges = for vertices, face in fold.faces_vertices for i in [0...vertices.length] edgeMap["#{vertices[i]},#{vertices[(i+1) % vertices.length]}"] convert.faces_vertices_to_edges = (mesh) -> ### Given a FOLD object with just `faces_vertices`, automatically fills in `edges_vertices`, `edges_faces`, `faces_edges`, and `edges_assignment` (indicating which edges are boundary with 'B'). ### mesh.edges_vertices = [] mesh.edges_faces = [] mesh.faces_edges = [] mesh.edges_assignment = [] edgeMap = {} for face, vertices of mesh.faces_vertices face = parseInt face mesh.faces_edges.push( for v1, i in vertices v1 = parseInt v1 v2 = vertices[(i+1) % vertices.length] if v1 <= v2 key = <KEY> else key = <KEY> if key of edgeMap edge = edgeMap[key] # Second instance of edge means not on boundary mesh.edges_assignment[edge] = null else edge = edgeMap[key] = mesh.edges_vertices.length if v1 <= v2 mesh.edges_vertices.push [v1, v2] else mesh.edges_vertices.push [v2, v1] mesh.edges_faces.push [null, null] # First instance of edge might be on boundary mesh.edges_assignment.push 'B' if v1 <= v2 mesh.edges_faces[edge][0] = face else mesh.edges_faces[edge][1] = face edge ) mesh convert.edges_vertices_to_edges_faces_edges = (fold) -> ### Given a `fold` object with `edges_vertices` and `faces_vertices`, fills in `faces_edges` and `edges_vertices`. ### fold.edges_faces = ([null, null] for edge in [0...fold.edges_vertices.length]) edgeMap = {} for edge, vertices of fold.edges_vertices when vertices? edge = parseInt edge edgeMap["#{vertices[0]},#{vertices[1]}"] = [edge, 0] # forward edgeMap["#{vertices[1]},#{vertices[0]}"] = [edge, 1] # backward for face, vertices of fold.faces_vertices face = parseInt face fold.faces_edges[face] = for v1, i in vertices v2 = vertices[(i+1) % vertices.length] [edge, orient] = edgeMap["#{v1},#{v2}"] fold.edges_faces[edge][orient] = face edge fold convert.flatFoldedGeometry = (fold, rootFace = 0) -> ### Assuming `fold` is a locally flat foldable crease pattern in the xy plane, sets `fold.vertices_flatFoldCoords` to give the flat-folded geometry as determined by repeated reflection relative to `rootFace`; sets `fold.faces_flatFoldTransform` transformation matrix mapping each face's unfolded --> folded geometry; and sets `fold.faces_flatFoldOrientation` to +1 or -1 to indicate whether each folded face matches its original orientation or is upside-down (so is oriented clockwise in 2D). Requires `fold` to have `vertices_coords` and `edges_vertices`; `edges_faces` and `faces_edges` will be created if they do not exist. Returns the maximum displacement error from closure constraints (multiple mappings of the same vertices, or multiple transformations of the same face). ### if fold.vertices_coords? and fold.edges_vertices? and not (fold.edges_faces? and fold.faces_edges?) convert.edges_vertices_to_edges_faces_edges fold maxError = 0 level = [rootFace] fold.faces_flatFoldTransform = (null for face in [0...fold.faces_edges.length]) fold.faces_flatFoldTransform[rootFace] = [[1,0,0],[0,1,0]] # identity fold.faces_flatFoldOrientation = (null for face in [0...fold.faces_edges.length]) fold.faces_flatFoldOrientation[rootFace] = +1 fold.vertices_flatFoldCoords = (null for vertex in [0...fold.vertices_coords.length]) # Use fold.faces_edges -> fold.edges_vertices, which are both needed below, # in case fold.faces_vertices isn't defined. for edge in fold.faces_edges[rootFace] for vertex in fold.edges_vertices[edge] fold.vertices_flatFoldCoords[vertex] ?= fold.vertices_coords[vertex][..] while level.length nextLevel = [] for face in level orientation = -fold.faces_flatFoldOrientation[face] for edge in fold.faces_edges[face] for face2 in fold.edges_faces[edge] when face2? and face2 != face transform = geom.matrixMatrix fold.faces_flatFoldTransform[face], geom.matrixReflectLine ...( for vertex in fold.edges_vertices[edge] fold.vertices_coords[vertex] ) if fold.faces_flatFoldTransform[face2]? for row, i in fold.faces_flatFoldTransform[face2] maxError = Math.max maxError, geom.dist row, transform[i] if orientation != fold.faces_flatFoldOrientation[face2] maxError = Math.max 1, maxError else fold.faces_flatFoldTransform[face2] = transform fold.faces_flatFoldOrientation[face2] = orientation for edge2 in fold.faces_edges[face2] for vertex2 in fold.edges_vertices[edge2] mapped = geom.matrixVector transform, fold.vertices_coords[vertex2] if fold.vertices_flatFoldCoords[vertex2]? maxError = Math.max maxError, geom.dist fold.vertices_flatFoldCoords[vertex2], mapped else fold.vertices_flatFoldCoords[vertex2] = mapped nextLevel.push face2 level = nextLevel maxError convert.deepCopy = (fold) -> ## Given a FOLD object, make a copy that shares no pointers with the original. if typeof fold in ['number', 'string', 'boolean'] fold else if Array.isArray fold for item in fold convert.deepCopy item else # Object copy = {} for own key, value of fold copy[key] = convert.deepCopy value copy convert.toJSON = (fold) -> ## Convert FOLD object into a nicely formatted JSON string. "{\n" + (for key, value of fold " #{JSON.stringify key}: " + if Array.isArray value "[\n" + (" #{JSON.stringify(obj)}" for obj in value).join(',\n') + "\n ]" else JSON.stringify value ).join(',\n') + "\n}\n" convert.extensions = {} convert.converters = {} convert.getConverter = (fromExt, toExt) -> if fromExt == toExt (x) -> x else convert.converters["#{fromExt}#{toExt}"] convert.setConverter = (fromExt, toExt, converter) -> convert.extensions[fromExt] = true convert.extensions[toExt] = true convert.converters["#{fromExt}#{toExt}"] = converter convert.convertFromTo = (data, fromExt, toExt) -> fromExt = ".#{fromExt}" unless fromExt[0] == '.' toExt = ".#{toExt}" unless toExt[0] == '.' converter = convert.getConverter fromExt, toExt unless converter? if fromExt == toExt return data throw new Error "No converter from #{fromExt} to #{toExt}" converter data convert.convertFrom = (data, fromExt) -> convert.convertFromTo data, fromExt, '.fold' convert.convertTo = (data, toExt) -> convert.convertFromTo data, '.fold', toExt convert.oripa = require './oripa'
true
### FOLD FORMAT MANIPULATORS ### geom = require './geom' filter = require './filter' convert = exports convert.edges_vertices_to_vertices_vertices_unsorted = (fold) -> ### Works for abstract structures, so NOT SORTED. Use sort_vertices_vertices to sort in counterclockwise order. ### fold.vertices_vertices = filter.edges_vertices_to_vertices_vertices fold fold convert.edges_vertices_to_vertices_vertices_sorted = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices` property (defining edge endpoints), automatically computes the `vertices_vertices` property and sorts them counterclockwise by angle in the plane. ### convert.edges_vertices_to_vertices_vertices_unsorted fold convert.sort_vertices_vertices fold convert.edges_vertices_to_vertices_edges_sorted = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices` property (defining edge endpoints), automatically computes the `vertices_edges` and `vertices_vertices` property and sorts them counterclockwise by angle in the plane. ### convert.edges_vertices_to_vertices_vertices_sorted fold convert.vertices_vertices_to_vertices_edges fold convert.sort_vertices_vertices = (fold) -> ### Sorts `fold.vertices_neighbords` in counterclockwise order using `fold.vertices_coordinates`. 2D only. Constructs `fold.vertices_neighbords` if absent, via `convert.edges_vertices_to_vertices_vertices`. ### unless fold.vertices_coords?[0]?.length == 2 throw new Error "sort_vertices_vertices: Vertex coordinates missing or not two dimensional" unless fold.vertices_vertices? convert.edges_vertices_to_vertices_vertices fold for v, neighbors of fold.vertices_vertices geom.sortByAngle neighbors, v, (x) -> fold.vertices_coords[x] fold convert.vertices_vertices_to_faces_vertices = (fold) -> ### Given a FOLD object with counterclockwise-sorted `vertices_vertices` property, constructs the implicitly defined faces, setting `faces_vertices` property. ### next = {} for neighbors, v in fold.vertices_vertices for u, i in neighbors next["#{u},#{v}"] = neighbors[(i-1) %% neighbors.length] #console.log u, v, neighbors[(i-1) %% neighbors.length] fold.faces_vertices = [] #for uv, w of next for uv in (key for key of next) w = next[uv] continue unless w? next[uv] = null [u, v] = uv.split ',' u = parseInt u v = parseInt v face = [u, v] until w == face[0] unless w? console.warn "Confusion with face #{face}" break face.push w [u, v] = [v, w] w = next["#{u},#{v}"] next["#{u},#{v}"] = null next["#{face[face.length-1]},#{face[0]}"] = null ## Outside face is clockwise; exclude it. if w? and geom.polygonOrientation(fold.vertices_coords[x] for x in face) > 0 #console.log face fold.faces_vertices.push face #else # console.log face, 'clockwise' fold convert.vertices_edges_to_faces_vertices_edges = (fold) -> ### Given a FOLD object with counterclockwise-sorted `vertices_edges` property, constructs the implicitly defined faces, setting both `faces_vertices` and `faces_edges` properties. Handles multiple edges to the same vertex (unlike `FOLD.convert.vertices_vertices_to_faces_vertices`). ### next = [] for neighbors, v in fold.vertices_edges next[v] = {} for e, i in neighbors next[v][e] = neighbors[(i-1) %% neighbors.length] #console.log e, neighbors[(i-1) %% neighbors.length] fold.faces_vertices = [] fold.faces_edges = [] for nexts, vertex in next for e1, e2 of nexts continue unless e2? e1 = parseInt e1 nexts[e1] = null edges = [e1] vertices = [filter.edges_verticesIncident fold.edges_vertices[e1], fold.edges_vertices[e2]] unless vertices[0]? throw new Error "Confusion at edges #{e1} and #{e2}" until e2 == edges[0] unless e2? console.warn "Confusion with face containing edges #{edges}" break edges.push e2 for v in fold.edges_vertices[e2] if v != vertices[vertices.length-1] vertices.push v break e1 = e2 e2 = next[v][e1] next[v][e1] = null ## Outside face is clockwise; exclude it. if e2? and geom.polygonOrientation(fold.vertices_coords[x] for x in vertices) > 0 #console.log vertices, edges fold.faces_vertices.push vertices fold.faces_edges.push edges #else # console.log face, 'clockwise' fold convert.edges_vertices_to_faces_vertices = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices`, computes a counterclockwise-sorted `vertices_vertices` property and constructs the implicitly defined faces, setting `faces_vertices` property. ### convert.edges_vertices_to_vertices_vertices_sorted fold convert.vertices_vertices_to_faces_vertices fold convert.edges_vertices_to_faces_vertices_edges = (fold) -> ### Given a FOLD object with 2D `vertices_coords` and `edges_vertices`, computes counterclockwise-sorted `vertices_vertices` and `vertices_edges` properties and constructs the implicitly defined faces, setting both `faces_vertices` and `faces_edges` property. ### convert.edges_vertices_to_vertices_edges_sorted fold convert.vertices_edges_to_faces_vertices_edges fold convert.vertices_vertices_to_vertices_edges = (fold) -> ### Given a FOLD object with `vertices_vertices` and `edges_vertices`, fills in the corresponding `vertices_edges` property (preserving order). ### edgeMap = {} for [v1, v2], edge in fold.edges_vertices edgeMap["#{v1},#{v2}"] = edge edgeMap["#{v2},#{v1}"] = edge fold.vertices_edges = for vertices, vertex in fold.vertices_vertices for i in [0...vertices.length] edgeMap["#{vertex},#{vertices[i]}"] convert.faces_vertices_to_faces_edges = (fold) -> ### Given a FOLD object with `faces_vertices` and `edges_vertices`, fills in the corresponding `faces_edges` property (preserving order). ### edgeMap = {} for [v1, v2], edge in fold.edges_vertices edgeMap["#{v1},#{v2}"] = edge edgeMap["#{v2},#{v1}"] = edge fold.faces_edges = for vertices, face in fold.faces_vertices for i in [0...vertices.length] edgeMap["#{vertices[i]},#{vertices[(i+1) % vertices.length]}"] convert.faces_vertices_to_edges = (mesh) -> ### Given a FOLD object with just `faces_vertices`, automatically fills in `edges_vertices`, `edges_faces`, `faces_edges`, and `edges_assignment` (indicating which edges are boundary with 'B'). ### mesh.edges_vertices = [] mesh.edges_faces = [] mesh.faces_edges = [] mesh.edges_assignment = [] edgeMap = {} for face, vertices of mesh.faces_vertices face = parseInt face mesh.faces_edges.push( for v1, i in vertices v1 = parseInt v1 v2 = vertices[(i+1) % vertices.length] if v1 <= v2 key = PI:KEY:<KEY>END_PI else key = PI:KEY:<KEY>END_PI if key of edgeMap edge = edgeMap[key] # Second instance of edge means not on boundary mesh.edges_assignment[edge] = null else edge = edgeMap[key] = mesh.edges_vertices.length if v1 <= v2 mesh.edges_vertices.push [v1, v2] else mesh.edges_vertices.push [v2, v1] mesh.edges_faces.push [null, null] # First instance of edge might be on boundary mesh.edges_assignment.push 'B' if v1 <= v2 mesh.edges_faces[edge][0] = face else mesh.edges_faces[edge][1] = face edge ) mesh convert.edges_vertices_to_edges_faces_edges = (fold) -> ### Given a `fold` object with `edges_vertices` and `faces_vertices`, fills in `faces_edges` and `edges_vertices`. ### fold.edges_faces = ([null, null] for edge in [0...fold.edges_vertices.length]) edgeMap = {} for edge, vertices of fold.edges_vertices when vertices? edge = parseInt edge edgeMap["#{vertices[0]},#{vertices[1]}"] = [edge, 0] # forward edgeMap["#{vertices[1]},#{vertices[0]}"] = [edge, 1] # backward for face, vertices of fold.faces_vertices face = parseInt face fold.faces_edges[face] = for v1, i in vertices v2 = vertices[(i+1) % vertices.length] [edge, orient] = edgeMap["#{v1},#{v2}"] fold.edges_faces[edge][orient] = face edge fold convert.flatFoldedGeometry = (fold, rootFace = 0) -> ### Assuming `fold` is a locally flat foldable crease pattern in the xy plane, sets `fold.vertices_flatFoldCoords` to give the flat-folded geometry as determined by repeated reflection relative to `rootFace`; sets `fold.faces_flatFoldTransform` transformation matrix mapping each face's unfolded --> folded geometry; and sets `fold.faces_flatFoldOrientation` to +1 or -1 to indicate whether each folded face matches its original orientation or is upside-down (so is oriented clockwise in 2D). Requires `fold` to have `vertices_coords` and `edges_vertices`; `edges_faces` and `faces_edges` will be created if they do not exist. Returns the maximum displacement error from closure constraints (multiple mappings of the same vertices, or multiple transformations of the same face). ### if fold.vertices_coords? and fold.edges_vertices? and not (fold.edges_faces? and fold.faces_edges?) convert.edges_vertices_to_edges_faces_edges fold maxError = 0 level = [rootFace] fold.faces_flatFoldTransform = (null for face in [0...fold.faces_edges.length]) fold.faces_flatFoldTransform[rootFace] = [[1,0,0],[0,1,0]] # identity fold.faces_flatFoldOrientation = (null for face in [0...fold.faces_edges.length]) fold.faces_flatFoldOrientation[rootFace] = +1 fold.vertices_flatFoldCoords = (null for vertex in [0...fold.vertices_coords.length]) # Use fold.faces_edges -> fold.edges_vertices, which are both needed below, # in case fold.faces_vertices isn't defined. for edge in fold.faces_edges[rootFace] for vertex in fold.edges_vertices[edge] fold.vertices_flatFoldCoords[vertex] ?= fold.vertices_coords[vertex][..] while level.length nextLevel = [] for face in level orientation = -fold.faces_flatFoldOrientation[face] for edge in fold.faces_edges[face] for face2 in fold.edges_faces[edge] when face2? and face2 != face transform = geom.matrixMatrix fold.faces_flatFoldTransform[face], geom.matrixReflectLine ...( for vertex in fold.edges_vertices[edge] fold.vertices_coords[vertex] ) if fold.faces_flatFoldTransform[face2]? for row, i in fold.faces_flatFoldTransform[face2] maxError = Math.max maxError, geom.dist row, transform[i] if orientation != fold.faces_flatFoldOrientation[face2] maxError = Math.max 1, maxError else fold.faces_flatFoldTransform[face2] = transform fold.faces_flatFoldOrientation[face2] = orientation for edge2 in fold.faces_edges[face2] for vertex2 in fold.edges_vertices[edge2] mapped = geom.matrixVector transform, fold.vertices_coords[vertex2] if fold.vertices_flatFoldCoords[vertex2]? maxError = Math.max maxError, geom.dist fold.vertices_flatFoldCoords[vertex2], mapped else fold.vertices_flatFoldCoords[vertex2] = mapped nextLevel.push face2 level = nextLevel maxError convert.deepCopy = (fold) -> ## Given a FOLD object, make a copy that shares no pointers with the original. if typeof fold in ['number', 'string', 'boolean'] fold else if Array.isArray fold for item in fold convert.deepCopy item else # Object copy = {} for own key, value of fold copy[key] = convert.deepCopy value copy convert.toJSON = (fold) -> ## Convert FOLD object into a nicely formatted JSON string. "{\n" + (for key, value of fold " #{JSON.stringify key}: " + if Array.isArray value "[\n" + (" #{JSON.stringify(obj)}" for obj in value).join(',\n') + "\n ]" else JSON.stringify value ).join(',\n') + "\n}\n" convert.extensions = {} convert.converters = {} convert.getConverter = (fromExt, toExt) -> if fromExt == toExt (x) -> x else convert.converters["#{fromExt}#{toExt}"] convert.setConverter = (fromExt, toExt, converter) -> convert.extensions[fromExt] = true convert.extensions[toExt] = true convert.converters["#{fromExt}#{toExt}"] = converter convert.convertFromTo = (data, fromExt, toExt) -> fromExt = ".#{fromExt}" unless fromExt[0] == '.' toExt = ".#{toExt}" unless toExt[0] == '.' converter = convert.getConverter fromExt, toExt unless converter? if fromExt == toExt return data throw new Error "No converter from #{fromExt} to #{toExt}" converter data convert.convertFrom = (data, fromExt) -> convert.convertFromTo data, fromExt, '.fold' convert.convertTo = (data, toExt) -> convert.convertFromTo data, '.fold', toExt convert.oripa = require './oripa'
[ { "context": "OSE Integration Test Suite\", ->\n\n\trecord = name: \"Gemma\", age: 24\n\n\tinputKey = {\n\t\tkty: 'oct'\n\t\tkid: 'c93", "end": 191, "score": 0.9997566938400269, "start": 186, "tag": "NAME", "value": "Gemma" }, { "context": "d = name: \"Gemma\", age: 24\n\n\tinputKey ...
spec/joseIntegrationSpec.coffee
privatwolke/collections.coffee
0
collections = require "../src/collections" collections_jose = require "../src/collections-jose" jose = require "node-jose" describe "JOSE Integration Test Suite", -> record = name: "Gemma", age: 24 inputKey = { kty: 'oct' kid: 'c93a540b-cb2d-4ebe-b8fa-b7d63a2da4a0' k: 'TLznmW6vAmqYQPBAwYrKIg6WZyIpwMVZrMCm3Xc1m1o' } beforeEach (done) -> @keystore = jose.JWK.createKeyStore() @keystore.add(inputKey) .then (@key) => done() afterEach -> delete @key delete @keystore it "should have jose", -> expect(@keystore).toBeDefined() expect(@key).toBeDefined() it "should sign", (done) -> (new collections.Database()).initialize() .then (@database) => @database.filters.in = [collections_jose.signRecord(@key)] @database.filters.out = [collections_jose.verifyRecord(@keystore)] @database.collection("test") .then (@collection) => @collection.add(record) .then (@id) => expect(@database.data.test.records["#{@id}"].payload).toBeDefined() expect(@database.data.test.records["#{@id}"].signatures).toBeDefined() expect(@database.data.test.records["#{@id}"].name).not.toBeDefined() @collection.get(@id, false) .then (plainResult) => expect(plainResult).not.toEqual(record) @collection.get(@id) .then (result) => expect(result.record).toEqual(record) @database.drop("test") .then -> done() it "should encrypt", (done) -> (new collections.Database()).initialize() .then (@database) => @database.filters.in = [collections_jose.encryptRecord(@key)] @database.filters.out = [collections_jose.decryptRecord(@keystore)] @database.collection("test") .then (@collection) => @collection.add(record) .then (@id) => expect(@database.data.test.records["#{@id}"].ciphertext).toBeDefined() @collection.get(@id, false) .then (plainResult) => expect(plainResult).not.toEqual(record) @collection.get(@id) .then (result) => expect(result.record).toEqual(record) @database.drop("test") .then -> done()
198360
collections = require "../src/collections" collections_jose = require "../src/collections-jose" jose = require "node-jose" describe "JOSE Integration Test Suite", -> record = name: "<NAME>", age: 24 inputKey = { kty: '<KEY>' kid: '<KEY>' k: '<KEY>' } beforeEach (done) -> @keystore = jose.JWK.createKeyStore() @keystore.add(inputKey) .then (@key) => done() afterEach -> delete @key delete @keystore it "should have jose", -> expect(@keystore).toBeDefined() expect(@key).toBeDefined() it "should sign", (done) -> (new collections.Database()).initialize() .then (@database) => @database.filters.in = [collections_jose.signRecord(@key)] @database.filters.out = [collections_jose.verifyRecord(@keystore)] @database.collection("test") .then (@collection) => @collection.add(record) .then (@id) => expect(@database.data.test.records["#{@id}"].payload).toBeDefined() expect(@database.data.test.records["#{@id}"].signatures).toBeDefined() expect(@database.data.test.records["#{@id}"].name).not.toBeDefined() @collection.get(@id, false) .then (plainResult) => expect(plainResult).not.toEqual(record) @collection.get(@id) .then (result) => expect(result.record).toEqual(record) @database.drop("test") .then -> done() it "should encrypt", (done) -> (new collections.Database()).initialize() .then (@database) => @database.filters.in = [collections_jose.encryptRecord(@key)] @database.filters.out = [collections_jose.decryptRecord(@keystore)] @database.collection("test") .then (@collection) => @collection.add(record) .then (@id) => expect(@database.data.test.records["#{@id}"].ciphertext).toBeDefined() @collection.get(@id, false) .then (plainResult) => expect(plainResult).not.toEqual(record) @collection.get(@id) .then (result) => expect(result.record).toEqual(record) @database.drop("test") .then -> done()
true
collections = require "../src/collections" collections_jose = require "../src/collections-jose" jose = require "node-jose" describe "JOSE Integration Test Suite", -> record = name: "PI:NAME:<NAME>END_PI", age: 24 inputKey = { kty: 'PI:KEY:<KEY>END_PI' kid: 'PI:KEY:<KEY>END_PI' k: 'PI:KEY:<KEY>END_PI' } beforeEach (done) -> @keystore = jose.JWK.createKeyStore() @keystore.add(inputKey) .then (@key) => done() afterEach -> delete @key delete @keystore it "should have jose", -> expect(@keystore).toBeDefined() expect(@key).toBeDefined() it "should sign", (done) -> (new collections.Database()).initialize() .then (@database) => @database.filters.in = [collections_jose.signRecord(@key)] @database.filters.out = [collections_jose.verifyRecord(@keystore)] @database.collection("test") .then (@collection) => @collection.add(record) .then (@id) => expect(@database.data.test.records["#{@id}"].payload).toBeDefined() expect(@database.data.test.records["#{@id}"].signatures).toBeDefined() expect(@database.data.test.records["#{@id}"].name).not.toBeDefined() @collection.get(@id, false) .then (plainResult) => expect(plainResult).not.toEqual(record) @collection.get(@id) .then (result) => expect(result.record).toEqual(record) @database.drop("test") .then -> done() it "should encrypt", (done) -> (new collections.Database()).initialize() .then (@database) => @database.filters.in = [collections_jose.encryptRecord(@key)] @database.filters.out = [collections_jose.decryptRecord(@keystore)] @database.collection("test") .then (@collection) => @collection.add(record) .then (@id) => expect(@database.data.test.records["#{@id}"].ciphertext).toBeDefined() @collection.get(@id, false) .then (plainResult) => expect(plainResult).not.toEqual(record) @collection.get(@id) .then (result) => expect(result.record).toEqual(record) @database.drop("test") .then -> done()
[ { "context": "includedPrivates: [\"name\", \"email\", \"firstName\", \"lastName\", \"coursePrepaid\", \"coursePrepaidID\"] }) for memb", "end": 7078, "score": 0.6983206868171692, "start": 7070, "tag": "NAME", "value": "lastName" }, { "context": ")\n yield student.update({ $set: { ...
server/middleware/classrooms.coffee
johanvl/codecombat
1
_ = require 'lodash' utils = require '../lib/utils' errors = require '../commons/errors' schemas = require '../../app/schemas/schemas' wrap = require 'co-express' log = require 'winston' Promise = require 'bluebird' database = require '../commons/database' mongoose = require 'mongoose' Classroom = require '../models/Classroom' Course = require '../models/Course' Campaign = require '../models/Campaign' Level = require '../models/Level' parse = require '../commons/parse' LevelSession = require '../models/LevelSession' User = require '../models/User' CourseInstance = require '../models/CourseInstance' Prepaid = require '../models/Prepaid' TrialRequest = require '../models/TrialRequest' sendwithus = require '../sendwithus' co = require 'co' delighted = require '../delighted' subscriptions = require './subscriptions' { makeHostUrl } = require '../commons/urls' module.exports = getByCode: wrap (req, res, next) -> code = req.query.code return next() unless req.query.hasOwnProperty('code') classroom = yield Classroom.findOne({ code: code.toLowerCase().replace(RegExp(' ', 'g') , '') }).select('name ownerID aceConfig') if not classroom log.debug("classrooms.fetchByCode: Couldn't find Classroom with code: #{code}") throw new errors.NotFound('Classroom not found.') classroom = classroom.toObject() # Tack on the teacher's name for display to the user owner = (yield User.findOne({ _id: mongoose.Types.ObjectId(classroom.ownerID) }).select('name firstName lastName')).toObject() res.status(200).send({ data: classroom, owner } ) getByOwner: wrap (req, res, next) -> options = req.query ownerID = options.ownerID return next() unless ownerID throw new errors.UnprocessableEntity('Bad ownerID') unless utils.isID ownerID throw new errors.Unauthorized() unless req.user unless req.user.isAdmin() or ownerID is req.user.id log.debug("classrooms.getByOwner: Can't fetch classroom you don't own. User: #{req.user.id} Owner: #{ownerID}") throw new errors.Forbidden('"ownerID" must be yourself') sanitizedOptions = {} unless _.isUndefined(options.archived) # Handles when .archived is true, vs false-or-null sanitizedOptions.archived = { $ne: not (options.archived is 'true') } dbq = Classroom.find _.merge sanitizedOptions, { ownerID: mongoose.Types.ObjectId(ownerID) } dbq.select(parse.getProjectFromReq(req)) classrooms = yield dbq classrooms = (classroom.toObject({req: req}) for classroom in classrooms) res.status(200).send(classrooms) getByMember: wrap (req, res, next) -> { memberID } = req.query return next() unless memberID unless req.user and (req.user.isAdmin() or memberID is req.user.id) throw new errors.Forbidden() unless utils.isID memberID throw new errors.UnprocessableEntity('Bad memberID') classrooms = yield Classroom.find {members: mongoose.Types.ObjectId(memberID)} res.send((classroom.toObject({req}) for classroom in classrooms)) fetchAllLevels: wrap (req, res, next) -> classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') levelOriginals = [] for course in classroom.get('courses') or [] for level in course.levels levelOriginals.push(level.original) query = {$and: [ {original: { $in: levelOriginals }} {$or: [{primerLanguage: {$exists: false}}, {primerLanguage: { $ne: classroom.get('aceConfig')?.language }}]} {slug: { $exists: true }} ]} levels = yield Level.find(query).select(parse.getProjectFromReq(req)) levels = (level.toObject({ req: req }) for level in levels) # maintain course order levelMap = {} for level in levels levelMap[level.original] = level levels = (levelMap[levelOriginal.toString()] for levelOriginal in levelOriginals) res.status(200).send(_.filter(levels)) # for dev server where not all levels will be found fetchLevelsForCourse: wrap (req, res) -> classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') levelOriginals = [] for course in classroom.get('courses') or [] if course._id.toString() isnt req.params.courseID continue for level in course.levels levelOriginals.push(level.original) query = {$and: [ {original: { $in: levelOriginals }} {$or: [{primerLanguage: {$exists: false}}, {primerLanguage: { $ne: classroom.get('aceConfig')?.language }}]} {slug: { $exists: true }} ]} levels = yield Level.find(query).select(parse.getProjectFromReq(req)) levels = (level.toObject({ req: req }) for level in levels) # maintain course order levelMap = {} for level in levels levelMap[level.original] = level levels = (levelMap[levelOriginal.toString()] for levelOriginal in levelOriginals when levelMap[levelOriginal.toString()]) res.status(200).send(levels) fetchMemberSessions: wrap (req, res, next) -> # Return member sessions for assigned courses throw new errors.Unauthorized() unless req.user classroom = yield database.getDocFromHandle(req, Classroom) throw new errors.NotFound('Classroom not found.') if not classroom throw new errors.Forbidden('You do not own this classroom.') unless req.user.isAdmin() or classroom.get('ownerID').equals(req.user._id) memberLimit = parse.getLimitFromReq(req, {default: 10, max: 100, param: 'memberLimit'}) memberSkip = parse.getSkipFromReq(req, {param: 'memberSkip'}) members = classroom.get('members') or [] members = members.slice(memberSkip, memberSkip + memberLimit) sessions = yield classroom.fetchSessionsForMembers(members) res.status(200).send(sessions) fetchMembers: wrap (req, res, next) -> throw new errors.Unauthorized() unless req.user memberLimit = parse.getLimitFromReq(req, {default: 10, max: 100, param: 'memberLimit'}) memberSkip = parse.getSkipFromReq(req, {param: 'memberSkip'}) classroom = yield database.getDocFromHandle(req, Classroom) throw new errors.NotFound('Classroom not found.') if not classroom isOwner = classroom.get('ownerID').equals(req.user._id) isMember = req.user.id in (m.toString() for m in classroom.get('members')) unless req.user.isAdmin() or isOwner or isMember log.debug "classrooms.fetchMembers: Can't fetch members for class (#{classroom.id}) you (#{req.user.id}) don't own and aren't a member of." throw new errors.Forbidden('You do not own this classroom.') memberIDs = classroom.get('members') or [] memberIDs = memberIDs.slice(memberSkip, memberSkip + memberLimit) members = yield User.find({ _id: { $in: memberIDs }}).select(parse.getProjectFromReq(req)) # members = yield User.find({ _id: { $in: memberIDs }, deleted: { $ne: true }}).select(parse.getProjectFromReq(req)) memberObjects = (member.toObject({ req: req, includedPrivates: ["name", "email", "firstName", "lastName", "coursePrepaid", "coursePrepaidID"] }) for member in members) res.status(200).send(memberObjects) checkIsAutoRevokable: wrap (req, res, next) -> userID = req.params.memberID throw new errors.UnprocessableEntity('Member ID must be a MongoDB ID') unless utils.isID(userID) try classroom = yield Classroom.findById req.params.classroomID catch err throw new errors.InternalServerError('Error finding classroom by ID: ' + err) throw new errors.NotFound('No classroom found with that ID') if not classroom if not _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID) throw new errors.Forbidden() ownsClassroom = classroom.get('ownerID').equals(req.user.get('_id')) unless ownsClassroom throw new errors.Forbidden() try otherClassrooms = yield Classroom.find { members: mongoose.Types.ObjectId(userID), _id: {$ne: classroom.get('_id')} } catch err throw new errors.InternalServerError('Error finding other classrooms by memberID: ' + err) # If the student is being removed from their very last classroom, unenroll them user = yield User.findOne({ _id: mongoose.Types.ObjectId(userID) }) if user.isEnrolled() and otherClassrooms.length is 0 # log.debug "User removed from their last classroom; auto-revoking:", userID prepaid = yield Prepaid.findOne({ type: "course", "redeemers.userID": mongoose.Types.ObjectId(userID) }) if prepaid if not prepaid.canBeUsedBy(req.user._id) return res.status(200).send({ willRevokeLicense: false }) # This logic is slightly different than the removing endpoint, # since we don't want to tell a teacher it will be revoked unless it's *their* license return res.status(200).send({ willRevokeLicense: true }) return res.status(200).send({ willRevokeLicense: false }) deleteMember: wrap (req, res, next) -> userID = req.params.memberID throw new errors.UnprocessableEntity('Member ID must be a MongoDB ID') unless utils.isID(userID) try classroom = yield Classroom.findById req.params.classroomID catch err throw new errors.InternalServerError('Error finding classroom by ID: ' + err) throw new errors.NotFound('No classroom found with that ID') if not classroom if not _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID) throw new errors.Forbidden() ownsClassroom = classroom.get('ownerID').equals(req.user.get('_id')) unless ownsClassroom throw new errors.Forbidden() try otherClassrooms = yield Classroom.find { members: mongoose.Types.ObjectId(userID), _id: {$ne: classroom.get('_id')} } catch err throw new errors.InternalServerError('Error finding other classrooms by memberID: ' + err) # If the student is being removed from their very last classroom, unenroll them user = yield User.findOne({ _id: mongoose.Types.ObjectId(userID) }) if user.isEnrolled() and otherClassrooms.length is 0 # log.debug "User removed from their last classroom; auto-revoking:", userID prepaid = yield Prepaid.findOne({ type: "course", "redeemers.userID": mongoose.Types.ObjectId(userID) }) if prepaid yield prepaid.revoke(user) members = _.clone(classroom.get('members')) members = (m for m in members when m.toString() isnt userID) classroom.set('members', members) try classroom = yield classroom.save() catch err console.log err throw new errors.InternalServerError(err) res.status(200).send(classroom.toObject()) fetchPlaytimes: wrap (req, res, next) -> # For given courseID, returns array of course/level IDs and slugs, and an array of recent level sessions # TODO: returns on this are pretty weird, because the client calls it repeatedly for more data throw new errors.Unauthorized('You must be an administrator.') unless req.user?.isAdmin() sessionLimit = parseInt(req.query?.sessionLimit ? 1000) unless startDay = req.query?.startDay startDay = new Date() startDay.setUTCDate(startDay.getUTCDate() - 1) startDay = startDay.toISOString().substring(0, 10) endDay = req.query?.endDay # console.log "DEBUG: fetchPlaytimes courseID=#{req.query?.courseID} startDay=#{startDay} endDay=#{endDay}" query = {$and: [{releasePhase: 'released'}]} query.$and.push {_id: req.query.courseID} if req.query?.courseID? courses = yield Course.find(query, {campaignID: 1, slug: 1}).lean() campaignIDs = [] campaignCourseMap = {} for course in courses campaignIDs.push(course.campaignID) campaignCourseMap[course.campaignID] = course campaigns = yield Campaign.find({_id: {$in: campaignIDs}}, {levels: 1, slug: 1}).lean() courseLevelPlaytimes = [] levelOriginals = [] levelSlugMap = {} for campaign in campaigns for levelOriginal, level of campaign.levels levelOriginals.push(levelOriginal) levelSlugMap[levelOriginal] = level.slug unless level.campaignIndex? log.debug "NO level.campaignIndex for #{campaignCourseMap[campaign._id].slug} #{level.slug}" courseLevelPlaytimes.push courseID: campaignCourseMap[campaign._id]._id courseSlug: campaignCourseMap[campaign._id].slug levelIndex: level.campaignIndex levelSlug: level.slug levelOriginal: levelOriginal practice: level.practice ? false # console.log "DEBUG: courseID=#{req.query?.courseID} total levels=#{levelOriginals.length}" query = {$and: [ {_id: {$gte: utils.objectIdFromTimestamp(startDay + "T00:00:00.000Z")}} {'level.original': {$in: levelOriginals}} { isForClassroom: true } {'state.complete': true} ]} query.$and.push({_id: {$lt: utils.objectIdFromTimestamp(endDay + "T00:00:00.000Z")}}) if endDay project = {creator: 1, 'level.original': 1, playtime: 1} levelSessions = yield LevelSession.find(query, project).lean() # console.log "DEBUG: courseID=#{req.query?.courseID} level sessions=#{levelSessions.length}" levelCountMap = {} minimalLevelSessions = [] for levelSession in levelSessions continue if levelCountMap[levelSession.level.original] >= sessionLimit levelCountMap[levelSession.level.original] ?= 0 levelCountMap[levelSession.level.original]++ minimalLevelSessions.push(levelSession) res.status(200).send([courseLevelPlaytimes, minimalLevelSessions]) post: wrap (req, res) -> throw new errors.Unauthorized() unless req.user and not req.user.isAnonymous() unless req.user?.isTeacher() log.debug "classrooms.post: Can't create classroom if you (#{req.user?.id}) aren't a teacher." throw new errors.Forbidden() classroom = database.initDoc(req, Classroom) classroom.set 'ownerID', req.user._id classroom.set 'members', [] database.assignBody(req, classroom) owner = req.user yield classroom.setUpdatedCourses({isAdmin: req.user?.isAdmin(), addNewCoursesOnly: false, includeAssessments: owner.hasPermission('assessments')}) # finish database.validateDoc(classroom) classroom = yield classroom.save() yield delighted.checkTriggerClassroomCreated(req.user) res.status(201).send(classroom.toObject({req: req})) updateCourses: wrap (req, res) -> throw new errors.Unauthorized() unless req.user and not req.user.isAnonymous() classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') unless req.user._id.equals(classroom.get('ownerID')) or req.user.isAdmin() throw new errors.Forbidden('Only the owner may update their classroom content') addNewCoursesOnly = req.body?.addNewCoursesOnly ? false # make sure updates are based on owner, not logged in user if not req.user._id.equals(classroom.get('ownerID')) owner = yield User.findById(classroom.get('ownerID')) else owner = req.user yield classroom.setUpdatedCourses({isAdmin: owner.isAdmin(), addNewCoursesOnly, includeAssessments: owner.hasPermission('assessments')}) database.validateDoc(classroom) classroom = yield classroom.save() res.status(200).send(classroom.toObject({req: req})) join: wrap (req, res) -> unless req.body?.code throw new errors.UnprocessableEntity('Need a code') if req.user.isTeacher() log.debug("classrooms.join: Cannot join a classroom as a teacher: #{req.user.id}") throw new errors.Forbidden('Cannot join a classroom as a teacher') code = req.body.code.toLowerCase().replace(RegExp(' ', 'g'), '') classroom = yield Classroom.findOne({code: code}) if not classroom log.debug("classrooms.join: Classroom not found with code #{code}") throw new errors.NotFound("Classroom not found with code #{code}") yield classroom.addMember(req.user) # make user role student if not req.user.get('role') req.user.set('role', 'student') yield req.user.save() # join any course instances for free courses in the classroom courseIDs = (course._id for course in classroom.get('courses')) courses = yield Course.find({_id: {$in: courseIDs}, free: true}) freeCourseIDs = (course._id for course in courses) freeCourseInstances = yield CourseInstance.find({ classroomID: classroom._id, courseID: {$in: freeCourseIDs} }).select('_id') freeCourseInstanceIDs = (courseInstance._id for courseInstance in freeCourseInstances) yield CourseInstance.update({_id: {$in: freeCourseInstanceIDs}}, { $addToSet: { members: req.user._id }}) yield User.update({ _id: req.user._id }, { $addToSet: { courseInstances: { $each: freeCourseInstanceIDs } } }) yield subscriptions.unsubscribeUser(req, req.user, false) res.send(classroom.toObject({req: req})) setStudentPassword: wrap (req, res, next) -> newPassword = req.body.password { classroomID, memberID } = req.params teacherID = req.user.id return next() if teacherID is memberID or not newPassword ownedClassrooms = yield Classroom.find({ ownerID: mongoose.Types.ObjectId(teacherID) }) ownedStudentIDs = _.flatten ownedClassrooms.map (c) -> c.get('members').map (id) -> id.toString() unless memberID in ownedStudentIDs throw new errors.Forbidden("Can't reset the password of a student that's not in one of your classrooms.") student = yield User.findById(memberID) if student.get('emailVerified') log.debug "classrooms.setStudentPassword: Can't reset password for a student (#{memberID}) that has verified their email address." throw new errors.Forbidden("Can't reset password for a student that has verified their email address.") { valid, error } = tv4.validateResult(newPassword, schemas.passwordString) unless valid throw new errors.UnprocessableEntity(error.message) yield student.update({ $set: { passwordHash: User.hashPassword(newPassword) } }) res.status(200).send({}) inviteMembers: wrap (req, res) -> if not req.body.emails log.debug "classrooms.inviteMembers: No emails included in request: #{JSON.stringify(req.body)}" throw new errors.UnprocessableEntity('Emails not included') if not req.body.recaptchaResponseToken log.debug "classrooms.inviteMembers: No recaptchaResponseToken included in request: #{JSON.stringify(req.body)}" throw new errors.UnprocessableEntity('Recaptcha response token not included') unless yield utils.verifyRecaptchaToken(req.body.recaptchaResponseToken) throw new errors.UnprocessableEntity('Could not verify reCAPTCHA response token') classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') unless classroom.get('ownerID').equals(req.user?._id) log.debug "classroom_handler.inviteMembers: Can't invite to classroom (#{classroom.id}) you (#{req.user.get('_id')}) don't own" throw new errors.Forbidden('Must be owner of classroom to send invites.') for email in req.body.emails joinCode = (classroom.get('codeCamel') or classroom.get('code')) context = email_id: sendwithus.templates.course_invite_email recipient: address: email email_data: teacher_name: req.user.broadName() class_name: classroom.get('name') join_link: makeHostUrl(req, '/students?_cc=' + joinCode) join_code: joinCode sendwithus.api.send context, _.noop res.status(200).send({}) getUsers: wrap (req, res, next) -> throw new errors.Unauthorized('You must be an administrator.') unless req.user?.isAdmin() limit = parseInt(req.query.options?.limit ? 0) query = {} if req.query.options?.beforeId beforeId = mongoose.Types.ObjectId(req.query.options.beforeId) query = {$and: [{_id: {$lt: beforeId}}, query]} classrooms = yield Classroom.find(query).sort({_id: -1}).limit(limit).select('ownerID members').lean() res.status(200).send(classrooms)
154827
_ = require 'lodash' utils = require '../lib/utils' errors = require '../commons/errors' schemas = require '../../app/schemas/schemas' wrap = require 'co-express' log = require 'winston' Promise = require 'bluebird' database = require '../commons/database' mongoose = require 'mongoose' Classroom = require '../models/Classroom' Course = require '../models/Course' Campaign = require '../models/Campaign' Level = require '../models/Level' parse = require '../commons/parse' LevelSession = require '../models/LevelSession' User = require '../models/User' CourseInstance = require '../models/CourseInstance' Prepaid = require '../models/Prepaid' TrialRequest = require '../models/TrialRequest' sendwithus = require '../sendwithus' co = require 'co' delighted = require '../delighted' subscriptions = require './subscriptions' { makeHostUrl } = require '../commons/urls' module.exports = getByCode: wrap (req, res, next) -> code = req.query.code return next() unless req.query.hasOwnProperty('code') classroom = yield Classroom.findOne({ code: code.toLowerCase().replace(RegExp(' ', 'g') , '') }).select('name ownerID aceConfig') if not classroom log.debug("classrooms.fetchByCode: Couldn't find Classroom with code: #{code}") throw new errors.NotFound('Classroom not found.') classroom = classroom.toObject() # Tack on the teacher's name for display to the user owner = (yield User.findOne({ _id: mongoose.Types.ObjectId(classroom.ownerID) }).select('name firstName lastName')).toObject() res.status(200).send({ data: classroom, owner } ) getByOwner: wrap (req, res, next) -> options = req.query ownerID = options.ownerID return next() unless ownerID throw new errors.UnprocessableEntity('Bad ownerID') unless utils.isID ownerID throw new errors.Unauthorized() unless req.user unless req.user.isAdmin() or ownerID is req.user.id log.debug("classrooms.getByOwner: Can't fetch classroom you don't own. User: #{req.user.id} Owner: #{ownerID}") throw new errors.Forbidden('"ownerID" must be yourself') sanitizedOptions = {} unless _.isUndefined(options.archived) # Handles when .archived is true, vs false-or-null sanitizedOptions.archived = { $ne: not (options.archived is 'true') } dbq = Classroom.find _.merge sanitizedOptions, { ownerID: mongoose.Types.ObjectId(ownerID) } dbq.select(parse.getProjectFromReq(req)) classrooms = yield dbq classrooms = (classroom.toObject({req: req}) for classroom in classrooms) res.status(200).send(classrooms) getByMember: wrap (req, res, next) -> { memberID } = req.query return next() unless memberID unless req.user and (req.user.isAdmin() or memberID is req.user.id) throw new errors.Forbidden() unless utils.isID memberID throw new errors.UnprocessableEntity('Bad memberID') classrooms = yield Classroom.find {members: mongoose.Types.ObjectId(memberID)} res.send((classroom.toObject({req}) for classroom in classrooms)) fetchAllLevels: wrap (req, res, next) -> classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') levelOriginals = [] for course in classroom.get('courses') or [] for level in course.levels levelOriginals.push(level.original) query = {$and: [ {original: { $in: levelOriginals }} {$or: [{primerLanguage: {$exists: false}}, {primerLanguage: { $ne: classroom.get('aceConfig')?.language }}]} {slug: { $exists: true }} ]} levels = yield Level.find(query).select(parse.getProjectFromReq(req)) levels = (level.toObject({ req: req }) for level in levels) # maintain course order levelMap = {} for level in levels levelMap[level.original] = level levels = (levelMap[levelOriginal.toString()] for levelOriginal in levelOriginals) res.status(200).send(_.filter(levels)) # for dev server where not all levels will be found fetchLevelsForCourse: wrap (req, res) -> classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') levelOriginals = [] for course in classroom.get('courses') or [] if course._id.toString() isnt req.params.courseID continue for level in course.levels levelOriginals.push(level.original) query = {$and: [ {original: { $in: levelOriginals }} {$or: [{primerLanguage: {$exists: false}}, {primerLanguage: { $ne: classroom.get('aceConfig')?.language }}]} {slug: { $exists: true }} ]} levels = yield Level.find(query).select(parse.getProjectFromReq(req)) levels = (level.toObject({ req: req }) for level in levels) # maintain course order levelMap = {} for level in levels levelMap[level.original] = level levels = (levelMap[levelOriginal.toString()] for levelOriginal in levelOriginals when levelMap[levelOriginal.toString()]) res.status(200).send(levels) fetchMemberSessions: wrap (req, res, next) -> # Return member sessions for assigned courses throw new errors.Unauthorized() unless req.user classroom = yield database.getDocFromHandle(req, Classroom) throw new errors.NotFound('Classroom not found.') if not classroom throw new errors.Forbidden('You do not own this classroom.') unless req.user.isAdmin() or classroom.get('ownerID').equals(req.user._id) memberLimit = parse.getLimitFromReq(req, {default: 10, max: 100, param: 'memberLimit'}) memberSkip = parse.getSkipFromReq(req, {param: 'memberSkip'}) members = classroom.get('members') or [] members = members.slice(memberSkip, memberSkip + memberLimit) sessions = yield classroom.fetchSessionsForMembers(members) res.status(200).send(sessions) fetchMembers: wrap (req, res, next) -> throw new errors.Unauthorized() unless req.user memberLimit = parse.getLimitFromReq(req, {default: 10, max: 100, param: 'memberLimit'}) memberSkip = parse.getSkipFromReq(req, {param: 'memberSkip'}) classroom = yield database.getDocFromHandle(req, Classroom) throw new errors.NotFound('Classroom not found.') if not classroom isOwner = classroom.get('ownerID').equals(req.user._id) isMember = req.user.id in (m.toString() for m in classroom.get('members')) unless req.user.isAdmin() or isOwner or isMember log.debug "classrooms.fetchMembers: Can't fetch members for class (#{classroom.id}) you (#{req.user.id}) don't own and aren't a member of." throw new errors.Forbidden('You do not own this classroom.') memberIDs = classroom.get('members') or [] memberIDs = memberIDs.slice(memberSkip, memberSkip + memberLimit) members = yield User.find({ _id: { $in: memberIDs }}).select(parse.getProjectFromReq(req)) # members = yield User.find({ _id: { $in: memberIDs }, deleted: { $ne: true }}).select(parse.getProjectFromReq(req)) memberObjects = (member.toObject({ req: req, includedPrivates: ["name", "email", "firstName", "<NAME>", "coursePrepaid", "coursePrepaidID"] }) for member in members) res.status(200).send(memberObjects) checkIsAutoRevokable: wrap (req, res, next) -> userID = req.params.memberID throw new errors.UnprocessableEntity('Member ID must be a MongoDB ID') unless utils.isID(userID) try classroom = yield Classroom.findById req.params.classroomID catch err throw new errors.InternalServerError('Error finding classroom by ID: ' + err) throw new errors.NotFound('No classroom found with that ID') if not classroom if not _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID) throw new errors.Forbidden() ownsClassroom = classroom.get('ownerID').equals(req.user.get('_id')) unless ownsClassroom throw new errors.Forbidden() try otherClassrooms = yield Classroom.find { members: mongoose.Types.ObjectId(userID), _id: {$ne: classroom.get('_id')} } catch err throw new errors.InternalServerError('Error finding other classrooms by memberID: ' + err) # If the student is being removed from their very last classroom, unenroll them user = yield User.findOne({ _id: mongoose.Types.ObjectId(userID) }) if user.isEnrolled() and otherClassrooms.length is 0 # log.debug "User removed from their last classroom; auto-revoking:", userID prepaid = yield Prepaid.findOne({ type: "course", "redeemers.userID": mongoose.Types.ObjectId(userID) }) if prepaid if not prepaid.canBeUsedBy(req.user._id) return res.status(200).send({ willRevokeLicense: false }) # This logic is slightly different than the removing endpoint, # since we don't want to tell a teacher it will be revoked unless it's *their* license return res.status(200).send({ willRevokeLicense: true }) return res.status(200).send({ willRevokeLicense: false }) deleteMember: wrap (req, res, next) -> userID = req.params.memberID throw new errors.UnprocessableEntity('Member ID must be a MongoDB ID') unless utils.isID(userID) try classroom = yield Classroom.findById req.params.classroomID catch err throw new errors.InternalServerError('Error finding classroom by ID: ' + err) throw new errors.NotFound('No classroom found with that ID') if not classroom if not _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID) throw new errors.Forbidden() ownsClassroom = classroom.get('ownerID').equals(req.user.get('_id')) unless ownsClassroom throw new errors.Forbidden() try otherClassrooms = yield Classroom.find { members: mongoose.Types.ObjectId(userID), _id: {$ne: classroom.get('_id')} } catch err throw new errors.InternalServerError('Error finding other classrooms by memberID: ' + err) # If the student is being removed from their very last classroom, unenroll them user = yield User.findOne({ _id: mongoose.Types.ObjectId(userID) }) if user.isEnrolled() and otherClassrooms.length is 0 # log.debug "User removed from their last classroom; auto-revoking:", userID prepaid = yield Prepaid.findOne({ type: "course", "redeemers.userID": mongoose.Types.ObjectId(userID) }) if prepaid yield prepaid.revoke(user) members = _.clone(classroom.get('members')) members = (m for m in members when m.toString() isnt userID) classroom.set('members', members) try classroom = yield classroom.save() catch err console.log err throw new errors.InternalServerError(err) res.status(200).send(classroom.toObject()) fetchPlaytimes: wrap (req, res, next) -> # For given courseID, returns array of course/level IDs and slugs, and an array of recent level sessions # TODO: returns on this are pretty weird, because the client calls it repeatedly for more data throw new errors.Unauthorized('You must be an administrator.') unless req.user?.isAdmin() sessionLimit = parseInt(req.query?.sessionLimit ? 1000) unless startDay = req.query?.startDay startDay = new Date() startDay.setUTCDate(startDay.getUTCDate() - 1) startDay = startDay.toISOString().substring(0, 10) endDay = req.query?.endDay # console.log "DEBUG: fetchPlaytimes courseID=#{req.query?.courseID} startDay=#{startDay} endDay=#{endDay}" query = {$and: [{releasePhase: 'released'}]} query.$and.push {_id: req.query.courseID} if req.query?.courseID? courses = yield Course.find(query, {campaignID: 1, slug: 1}).lean() campaignIDs = [] campaignCourseMap = {} for course in courses campaignIDs.push(course.campaignID) campaignCourseMap[course.campaignID] = course campaigns = yield Campaign.find({_id: {$in: campaignIDs}}, {levels: 1, slug: 1}).lean() courseLevelPlaytimes = [] levelOriginals = [] levelSlugMap = {} for campaign in campaigns for levelOriginal, level of campaign.levels levelOriginals.push(levelOriginal) levelSlugMap[levelOriginal] = level.slug unless level.campaignIndex? log.debug "NO level.campaignIndex for #{campaignCourseMap[campaign._id].slug} #{level.slug}" courseLevelPlaytimes.push courseID: campaignCourseMap[campaign._id]._id courseSlug: campaignCourseMap[campaign._id].slug levelIndex: level.campaignIndex levelSlug: level.slug levelOriginal: levelOriginal practice: level.practice ? false # console.log "DEBUG: courseID=#{req.query?.courseID} total levels=#{levelOriginals.length}" query = {$and: [ {_id: {$gte: utils.objectIdFromTimestamp(startDay + "T00:00:00.000Z")}} {'level.original': {$in: levelOriginals}} { isForClassroom: true } {'state.complete': true} ]} query.$and.push({_id: {$lt: utils.objectIdFromTimestamp(endDay + "T00:00:00.000Z")}}) if endDay project = {creator: 1, 'level.original': 1, playtime: 1} levelSessions = yield LevelSession.find(query, project).lean() # console.log "DEBUG: courseID=#{req.query?.courseID} level sessions=#{levelSessions.length}" levelCountMap = {} minimalLevelSessions = [] for levelSession in levelSessions continue if levelCountMap[levelSession.level.original] >= sessionLimit levelCountMap[levelSession.level.original] ?= 0 levelCountMap[levelSession.level.original]++ minimalLevelSessions.push(levelSession) res.status(200).send([courseLevelPlaytimes, minimalLevelSessions]) post: wrap (req, res) -> throw new errors.Unauthorized() unless req.user and not req.user.isAnonymous() unless req.user?.isTeacher() log.debug "classrooms.post: Can't create classroom if you (#{req.user?.id}) aren't a teacher." throw new errors.Forbidden() classroom = database.initDoc(req, Classroom) classroom.set 'ownerID', req.user._id classroom.set 'members', [] database.assignBody(req, classroom) owner = req.user yield classroom.setUpdatedCourses({isAdmin: req.user?.isAdmin(), addNewCoursesOnly: false, includeAssessments: owner.hasPermission('assessments')}) # finish database.validateDoc(classroom) classroom = yield classroom.save() yield delighted.checkTriggerClassroomCreated(req.user) res.status(201).send(classroom.toObject({req: req})) updateCourses: wrap (req, res) -> throw new errors.Unauthorized() unless req.user and not req.user.isAnonymous() classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') unless req.user._id.equals(classroom.get('ownerID')) or req.user.isAdmin() throw new errors.Forbidden('Only the owner may update their classroom content') addNewCoursesOnly = req.body?.addNewCoursesOnly ? false # make sure updates are based on owner, not logged in user if not req.user._id.equals(classroom.get('ownerID')) owner = yield User.findById(classroom.get('ownerID')) else owner = req.user yield classroom.setUpdatedCourses({isAdmin: owner.isAdmin(), addNewCoursesOnly, includeAssessments: owner.hasPermission('assessments')}) database.validateDoc(classroom) classroom = yield classroom.save() res.status(200).send(classroom.toObject({req: req})) join: wrap (req, res) -> unless req.body?.code throw new errors.UnprocessableEntity('Need a code') if req.user.isTeacher() log.debug("classrooms.join: Cannot join a classroom as a teacher: #{req.user.id}") throw new errors.Forbidden('Cannot join a classroom as a teacher') code = req.body.code.toLowerCase().replace(RegExp(' ', 'g'), '') classroom = yield Classroom.findOne({code: code}) if not classroom log.debug("classrooms.join: Classroom not found with code #{code}") throw new errors.NotFound("Classroom not found with code #{code}") yield classroom.addMember(req.user) # make user role student if not req.user.get('role') req.user.set('role', 'student') yield req.user.save() # join any course instances for free courses in the classroom courseIDs = (course._id for course in classroom.get('courses')) courses = yield Course.find({_id: {$in: courseIDs}, free: true}) freeCourseIDs = (course._id for course in courses) freeCourseInstances = yield CourseInstance.find({ classroomID: classroom._id, courseID: {$in: freeCourseIDs} }).select('_id') freeCourseInstanceIDs = (courseInstance._id for courseInstance in freeCourseInstances) yield CourseInstance.update({_id: {$in: freeCourseInstanceIDs}}, { $addToSet: { members: req.user._id }}) yield User.update({ _id: req.user._id }, { $addToSet: { courseInstances: { $each: freeCourseInstanceIDs } } }) yield subscriptions.unsubscribeUser(req, req.user, false) res.send(classroom.toObject({req: req})) setStudentPassword: wrap (req, res, next) -> newPassword = req.body.password { classroomID, memberID } = req.params teacherID = req.user.id return next() if teacherID is memberID or not newPassword ownedClassrooms = yield Classroom.find({ ownerID: mongoose.Types.ObjectId(teacherID) }) ownedStudentIDs = _.flatten ownedClassrooms.map (c) -> c.get('members').map (id) -> id.toString() unless memberID in ownedStudentIDs throw new errors.Forbidden("Can't reset the password of a student that's not in one of your classrooms.") student = yield User.findById(memberID) if student.get('emailVerified') log.debug "classrooms.setStudentPassword: Can't reset password for a student (#{memberID}) that has verified their email address." throw new errors.Forbidden("Can't reset password for a student that has verified their email address.") { valid, error } = tv4.validateResult(newPassword, schemas.passwordString) unless valid throw new errors.UnprocessableEntity(error.message) yield student.update({ $set: { passwordHash: <PASSWORD>.hashPassword(<PASSWORD>Password) } }) res.status(200).send({}) inviteMembers: wrap (req, res) -> if not req.body.emails log.debug "classrooms.inviteMembers: No emails included in request: #{JSON.stringify(req.body)}" throw new errors.UnprocessableEntity('Emails not included') if not req.body.recaptchaResponseToken log.debug "classrooms.inviteMembers: No recaptchaResponseToken included in request: #{JSON.stringify(req.body)}" throw new errors.UnprocessableEntity('Recaptcha response token not included') unless yield utils.verifyRecaptchaToken(req.body.recaptchaResponseToken) throw new errors.UnprocessableEntity('Could not verify reCAPTCHA response token') classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') unless classroom.get('ownerID').equals(req.user?._id) log.debug "classroom_handler.inviteMembers: Can't invite to classroom (#{classroom.id}) you (#{req.user.get('_id')}) don't own" throw new errors.Forbidden('Must be owner of classroom to send invites.') for email in req.body.emails joinCode = (classroom.get('codeCamel') or classroom.get('code')) context = email_id: sendwithus.templates.course_invite_email recipient: address: email email_data: teacher_name: req.user.broadName() class_name: classroom.get('name') join_link: makeHostUrl(req, '/students?_cc=' + joinCode) join_code: joinCode sendwithus.api.send context, _.noop res.status(200).send({}) getUsers: wrap (req, res, next) -> throw new errors.Unauthorized('You must be an administrator.') unless req.user?.isAdmin() limit = parseInt(req.query.options?.limit ? 0) query = {} if req.query.options?.beforeId beforeId = mongoose.Types.ObjectId(req.query.options.beforeId) query = {$and: [{_id: {$lt: beforeId}}, query]} classrooms = yield Classroom.find(query).sort({_id: -1}).limit(limit).select('ownerID members').lean() res.status(200).send(classrooms)
true
_ = require 'lodash' utils = require '../lib/utils' errors = require '../commons/errors' schemas = require '../../app/schemas/schemas' wrap = require 'co-express' log = require 'winston' Promise = require 'bluebird' database = require '../commons/database' mongoose = require 'mongoose' Classroom = require '../models/Classroom' Course = require '../models/Course' Campaign = require '../models/Campaign' Level = require '../models/Level' parse = require '../commons/parse' LevelSession = require '../models/LevelSession' User = require '../models/User' CourseInstance = require '../models/CourseInstance' Prepaid = require '../models/Prepaid' TrialRequest = require '../models/TrialRequest' sendwithus = require '../sendwithus' co = require 'co' delighted = require '../delighted' subscriptions = require './subscriptions' { makeHostUrl } = require '../commons/urls' module.exports = getByCode: wrap (req, res, next) -> code = req.query.code return next() unless req.query.hasOwnProperty('code') classroom = yield Classroom.findOne({ code: code.toLowerCase().replace(RegExp(' ', 'g') , '') }).select('name ownerID aceConfig') if not classroom log.debug("classrooms.fetchByCode: Couldn't find Classroom with code: #{code}") throw new errors.NotFound('Classroom not found.') classroom = classroom.toObject() # Tack on the teacher's name for display to the user owner = (yield User.findOne({ _id: mongoose.Types.ObjectId(classroom.ownerID) }).select('name firstName lastName')).toObject() res.status(200).send({ data: classroom, owner } ) getByOwner: wrap (req, res, next) -> options = req.query ownerID = options.ownerID return next() unless ownerID throw new errors.UnprocessableEntity('Bad ownerID') unless utils.isID ownerID throw new errors.Unauthorized() unless req.user unless req.user.isAdmin() or ownerID is req.user.id log.debug("classrooms.getByOwner: Can't fetch classroom you don't own. User: #{req.user.id} Owner: #{ownerID}") throw new errors.Forbidden('"ownerID" must be yourself') sanitizedOptions = {} unless _.isUndefined(options.archived) # Handles when .archived is true, vs false-or-null sanitizedOptions.archived = { $ne: not (options.archived is 'true') } dbq = Classroom.find _.merge sanitizedOptions, { ownerID: mongoose.Types.ObjectId(ownerID) } dbq.select(parse.getProjectFromReq(req)) classrooms = yield dbq classrooms = (classroom.toObject({req: req}) for classroom in classrooms) res.status(200).send(classrooms) getByMember: wrap (req, res, next) -> { memberID } = req.query return next() unless memberID unless req.user and (req.user.isAdmin() or memberID is req.user.id) throw new errors.Forbidden() unless utils.isID memberID throw new errors.UnprocessableEntity('Bad memberID') classrooms = yield Classroom.find {members: mongoose.Types.ObjectId(memberID)} res.send((classroom.toObject({req}) for classroom in classrooms)) fetchAllLevels: wrap (req, res, next) -> classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') levelOriginals = [] for course in classroom.get('courses') or [] for level in course.levels levelOriginals.push(level.original) query = {$and: [ {original: { $in: levelOriginals }} {$or: [{primerLanguage: {$exists: false}}, {primerLanguage: { $ne: classroom.get('aceConfig')?.language }}]} {slug: { $exists: true }} ]} levels = yield Level.find(query).select(parse.getProjectFromReq(req)) levels = (level.toObject({ req: req }) for level in levels) # maintain course order levelMap = {} for level in levels levelMap[level.original] = level levels = (levelMap[levelOriginal.toString()] for levelOriginal in levelOriginals) res.status(200).send(_.filter(levels)) # for dev server where not all levels will be found fetchLevelsForCourse: wrap (req, res) -> classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') levelOriginals = [] for course in classroom.get('courses') or [] if course._id.toString() isnt req.params.courseID continue for level in course.levels levelOriginals.push(level.original) query = {$and: [ {original: { $in: levelOriginals }} {$or: [{primerLanguage: {$exists: false}}, {primerLanguage: { $ne: classroom.get('aceConfig')?.language }}]} {slug: { $exists: true }} ]} levels = yield Level.find(query).select(parse.getProjectFromReq(req)) levels = (level.toObject({ req: req }) for level in levels) # maintain course order levelMap = {} for level in levels levelMap[level.original] = level levels = (levelMap[levelOriginal.toString()] for levelOriginal in levelOriginals when levelMap[levelOriginal.toString()]) res.status(200).send(levels) fetchMemberSessions: wrap (req, res, next) -> # Return member sessions for assigned courses throw new errors.Unauthorized() unless req.user classroom = yield database.getDocFromHandle(req, Classroom) throw new errors.NotFound('Classroom not found.') if not classroom throw new errors.Forbidden('You do not own this classroom.') unless req.user.isAdmin() or classroom.get('ownerID').equals(req.user._id) memberLimit = parse.getLimitFromReq(req, {default: 10, max: 100, param: 'memberLimit'}) memberSkip = parse.getSkipFromReq(req, {param: 'memberSkip'}) members = classroom.get('members') or [] members = members.slice(memberSkip, memberSkip + memberLimit) sessions = yield classroom.fetchSessionsForMembers(members) res.status(200).send(sessions) fetchMembers: wrap (req, res, next) -> throw new errors.Unauthorized() unless req.user memberLimit = parse.getLimitFromReq(req, {default: 10, max: 100, param: 'memberLimit'}) memberSkip = parse.getSkipFromReq(req, {param: 'memberSkip'}) classroom = yield database.getDocFromHandle(req, Classroom) throw new errors.NotFound('Classroom not found.') if not classroom isOwner = classroom.get('ownerID').equals(req.user._id) isMember = req.user.id in (m.toString() for m in classroom.get('members')) unless req.user.isAdmin() or isOwner or isMember log.debug "classrooms.fetchMembers: Can't fetch members for class (#{classroom.id}) you (#{req.user.id}) don't own and aren't a member of." throw new errors.Forbidden('You do not own this classroom.') memberIDs = classroom.get('members') or [] memberIDs = memberIDs.slice(memberSkip, memberSkip + memberLimit) members = yield User.find({ _id: { $in: memberIDs }}).select(parse.getProjectFromReq(req)) # members = yield User.find({ _id: { $in: memberIDs }, deleted: { $ne: true }}).select(parse.getProjectFromReq(req)) memberObjects = (member.toObject({ req: req, includedPrivates: ["name", "email", "firstName", "PI:NAME:<NAME>END_PI", "coursePrepaid", "coursePrepaidID"] }) for member in members) res.status(200).send(memberObjects) checkIsAutoRevokable: wrap (req, res, next) -> userID = req.params.memberID throw new errors.UnprocessableEntity('Member ID must be a MongoDB ID') unless utils.isID(userID) try classroom = yield Classroom.findById req.params.classroomID catch err throw new errors.InternalServerError('Error finding classroom by ID: ' + err) throw new errors.NotFound('No classroom found with that ID') if not classroom if not _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID) throw new errors.Forbidden() ownsClassroom = classroom.get('ownerID').equals(req.user.get('_id')) unless ownsClassroom throw new errors.Forbidden() try otherClassrooms = yield Classroom.find { members: mongoose.Types.ObjectId(userID), _id: {$ne: classroom.get('_id')} } catch err throw new errors.InternalServerError('Error finding other classrooms by memberID: ' + err) # If the student is being removed from their very last classroom, unenroll them user = yield User.findOne({ _id: mongoose.Types.ObjectId(userID) }) if user.isEnrolled() and otherClassrooms.length is 0 # log.debug "User removed from their last classroom; auto-revoking:", userID prepaid = yield Prepaid.findOne({ type: "course", "redeemers.userID": mongoose.Types.ObjectId(userID) }) if prepaid if not prepaid.canBeUsedBy(req.user._id) return res.status(200).send({ willRevokeLicense: false }) # This logic is slightly different than the removing endpoint, # since we don't want to tell a teacher it will be revoked unless it's *their* license return res.status(200).send({ willRevokeLicense: true }) return res.status(200).send({ willRevokeLicense: false }) deleteMember: wrap (req, res, next) -> userID = req.params.memberID throw new errors.UnprocessableEntity('Member ID must be a MongoDB ID') unless utils.isID(userID) try classroom = yield Classroom.findById req.params.classroomID catch err throw new errors.InternalServerError('Error finding classroom by ID: ' + err) throw new errors.NotFound('No classroom found with that ID') if not classroom if not _.any(classroom.get('members'), (memberID) -> memberID.toString() is userID) throw new errors.Forbidden() ownsClassroom = classroom.get('ownerID').equals(req.user.get('_id')) unless ownsClassroom throw new errors.Forbidden() try otherClassrooms = yield Classroom.find { members: mongoose.Types.ObjectId(userID), _id: {$ne: classroom.get('_id')} } catch err throw new errors.InternalServerError('Error finding other classrooms by memberID: ' + err) # If the student is being removed from their very last classroom, unenroll them user = yield User.findOne({ _id: mongoose.Types.ObjectId(userID) }) if user.isEnrolled() and otherClassrooms.length is 0 # log.debug "User removed from their last classroom; auto-revoking:", userID prepaid = yield Prepaid.findOne({ type: "course", "redeemers.userID": mongoose.Types.ObjectId(userID) }) if prepaid yield prepaid.revoke(user) members = _.clone(classroom.get('members')) members = (m for m in members when m.toString() isnt userID) classroom.set('members', members) try classroom = yield classroom.save() catch err console.log err throw new errors.InternalServerError(err) res.status(200).send(classroom.toObject()) fetchPlaytimes: wrap (req, res, next) -> # For given courseID, returns array of course/level IDs and slugs, and an array of recent level sessions # TODO: returns on this are pretty weird, because the client calls it repeatedly for more data throw new errors.Unauthorized('You must be an administrator.') unless req.user?.isAdmin() sessionLimit = parseInt(req.query?.sessionLimit ? 1000) unless startDay = req.query?.startDay startDay = new Date() startDay.setUTCDate(startDay.getUTCDate() - 1) startDay = startDay.toISOString().substring(0, 10) endDay = req.query?.endDay # console.log "DEBUG: fetchPlaytimes courseID=#{req.query?.courseID} startDay=#{startDay} endDay=#{endDay}" query = {$and: [{releasePhase: 'released'}]} query.$and.push {_id: req.query.courseID} if req.query?.courseID? courses = yield Course.find(query, {campaignID: 1, slug: 1}).lean() campaignIDs = [] campaignCourseMap = {} for course in courses campaignIDs.push(course.campaignID) campaignCourseMap[course.campaignID] = course campaigns = yield Campaign.find({_id: {$in: campaignIDs}}, {levels: 1, slug: 1}).lean() courseLevelPlaytimes = [] levelOriginals = [] levelSlugMap = {} for campaign in campaigns for levelOriginal, level of campaign.levels levelOriginals.push(levelOriginal) levelSlugMap[levelOriginal] = level.slug unless level.campaignIndex? log.debug "NO level.campaignIndex for #{campaignCourseMap[campaign._id].slug} #{level.slug}" courseLevelPlaytimes.push courseID: campaignCourseMap[campaign._id]._id courseSlug: campaignCourseMap[campaign._id].slug levelIndex: level.campaignIndex levelSlug: level.slug levelOriginal: levelOriginal practice: level.practice ? false # console.log "DEBUG: courseID=#{req.query?.courseID} total levels=#{levelOriginals.length}" query = {$and: [ {_id: {$gte: utils.objectIdFromTimestamp(startDay + "T00:00:00.000Z")}} {'level.original': {$in: levelOriginals}} { isForClassroom: true } {'state.complete': true} ]} query.$and.push({_id: {$lt: utils.objectIdFromTimestamp(endDay + "T00:00:00.000Z")}}) if endDay project = {creator: 1, 'level.original': 1, playtime: 1} levelSessions = yield LevelSession.find(query, project).lean() # console.log "DEBUG: courseID=#{req.query?.courseID} level sessions=#{levelSessions.length}" levelCountMap = {} minimalLevelSessions = [] for levelSession in levelSessions continue if levelCountMap[levelSession.level.original] >= sessionLimit levelCountMap[levelSession.level.original] ?= 0 levelCountMap[levelSession.level.original]++ minimalLevelSessions.push(levelSession) res.status(200).send([courseLevelPlaytimes, minimalLevelSessions]) post: wrap (req, res) -> throw new errors.Unauthorized() unless req.user and not req.user.isAnonymous() unless req.user?.isTeacher() log.debug "classrooms.post: Can't create classroom if you (#{req.user?.id}) aren't a teacher." throw new errors.Forbidden() classroom = database.initDoc(req, Classroom) classroom.set 'ownerID', req.user._id classroom.set 'members', [] database.assignBody(req, classroom) owner = req.user yield classroom.setUpdatedCourses({isAdmin: req.user?.isAdmin(), addNewCoursesOnly: false, includeAssessments: owner.hasPermission('assessments')}) # finish database.validateDoc(classroom) classroom = yield classroom.save() yield delighted.checkTriggerClassroomCreated(req.user) res.status(201).send(classroom.toObject({req: req})) updateCourses: wrap (req, res) -> throw new errors.Unauthorized() unless req.user and not req.user.isAnonymous() classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') unless req.user._id.equals(classroom.get('ownerID')) or req.user.isAdmin() throw new errors.Forbidden('Only the owner may update their classroom content') addNewCoursesOnly = req.body?.addNewCoursesOnly ? false # make sure updates are based on owner, not logged in user if not req.user._id.equals(classroom.get('ownerID')) owner = yield User.findById(classroom.get('ownerID')) else owner = req.user yield classroom.setUpdatedCourses({isAdmin: owner.isAdmin(), addNewCoursesOnly, includeAssessments: owner.hasPermission('assessments')}) database.validateDoc(classroom) classroom = yield classroom.save() res.status(200).send(classroom.toObject({req: req})) join: wrap (req, res) -> unless req.body?.code throw new errors.UnprocessableEntity('Need a code') if req.user.isTeacher() log.debug("classrooms.join: Cannot join a classroom as a teacher: #{req.user.id}") throw new errors.Forbidden('Cannot join a classroom as a teacher') code = req.body.code.toLowerCase().replace(RegExp(' ', 'g'), '') classroom = yield Classroom.findOne({code: code}) if not classroom log.debug("classrooms.join: Classroom not found with code #{code}") throw new errors.NotFound("Classroom not found with code #{code}") yield classroom.addMember(req.user) # make user role student if not req.user.get('role') req.user.set('role', 'student') yield req.user.save() # join any course instances for free courses in the classroom courseIDs = (course._id for course in classroom.get('courses')) courses = yield Course.find({_id: {$in: courseIDs}, free: true}) freeCourseIDs = (course._id for course in courses) freeCourseInstances = yield CourseInstance.find({ classroomID: classroom._id, courseID: {$in: freeCourseIDs} }).select('_id') freeCourseInstanceIDs = (courseInstance._id for courseInstance in freeCourseInstances) yield CourseInstance.update({_id: {$in: freeCourseInstanceIDs}}, { $addToSet: { members: req.user._id }}) yield User.update({ _id: req.user._id }, { $addToSet: { courseInstances: { $each: freeCourseInstanceIDs } } }) yield subscriptions.unsubscribeUser(req, req.user, false) res.send(classroom.toObject({req: req})) setStudentPassword: wrap (req, res, next) -> newPassword = req.body.password { classroomID, memberID } = req.params teacherID = req.user.id return next() if teacherID is memberID or not newPassword ownedClassrooms = yield Classroom.find({ ownerID: mongoose.Types.ObjectId(teacherID) }) ownedStudentIDs = _.flatten ownedClassrooms.map (c) -> c.get('members').map (id) -> id.toString() unless memberID in ownedStudentIDs throw new errors.Forbidden("Can't reset the password of a student that's not in one of your classrooms.") student = yield User.findById(memberID) if student.get('emailVerified') log.debug "classrooms.setStudentPassword: Can't reset password for a student (#{memberID}) that has verified their email address." throw new errors.Forbidden("Can't reset password for a student that has verified their email address.") { valid, error } = tv4.validateResult(newPassword, schemas.passwordString) unless valid throw new errors.UnprocessableEntity(error.message) yield student.update({ $set: { passwordHash: PI:PASSWORD:<PASSWORD>END_PI.hashPassword(PI:PASSWORD:<PASSWORD>END_PIPassword) } }) res.status(200).send({}) inviteMembers: wrap (req, res) -> if not req.body.emails log.debug "classrooms.inviteMembers: No emails included in request: #{JSON.stringify(req.body)}" throw new errors.UnprocessableEntity('Emails not included') if not req.body.recaptchaResponseToken log.debug "classrooms.inviteMembers: No recaptchaResponseToken included in request: #{JSON.stringify(req.body)}" throw new errors.UnprocessableEntity('Recaptcha response token not included') unless yield utils.verifyRecaptchaToken(req.body.recaptchaResponseToken) throw new errors.UnprocessableEntity('Could not verify reCAPTCHA response token') classroom = yield database.getDocFromHandle(req, Classroom) if not classroom throw new errors.NotFound('Classroom not found.') unless classroom.get('ownerID').equals(req.user?._id) log.debug "classroom_handler.inviteMembers: Can't invite to classroom (#{classroom.id}) you (#{req.user.get('_id')}) don't own" throw new errors.Forbidden('Must be owner of classroom to send invites.') for email in req.body.emails joinCode = (classroom.get('codeCamel') or classroom.get('code')) context = email_id: sendwithus.templates.course_invite_email recipient: address: email email_data: teacher_name: req.user.broadName() class_name: classroom.get('name') join_link: makeHostUrl(req, '/students?_cc=' + joinCode) join_code: joinCode sendwithus.api.send context, _.noop res.status(200).send({}) getUsers: wrap (req, res, next) -> throw new errors.Unauthorized('You must be an administrator.') unless req.user?.isAdmin() limit = parseInt(req.query.options?.limit ? 0) query = {} if req.query.options?.beforeId beforeId = mongoose.Types.ObjectId(req.query.options.beforeId) query = {$and: [{_id: {$lt: beforeId}}, query]} classrooms = yield Classroom.find(query).sort({_id: -1}).limit(limit).select('ownerID members').lean() res.status(200).send(classrooms)
[ { "context": " analytics.__set__ 'opts', SEGMENT_WRITE_KEY: 'foobar'\n scope = this\n analytics.__set__ 'Analytic", "end": 194, "score": 0.7255129218101501, "start": 188, "tag": "KEY", "value": "foobar" } ]
test/app/analytics.coffee
eessex/artsy-passport
0
sinon = require 'sinon' rewire = require 'rewire' analytics = rewire '../../lib/app/analytics' describe 'analytics', -> beforeEach -> analytics.__set__ 'opts', SEGMENT_WRITE_KEY: 'foobar' scope = this analytics.__set__ 'Analytics', class Analytics constructor: -> scope.analytics = this track: sinon.stub() @req = { session: {}, body: {}, user: { get: -> 'foo' }, query: {} } @res = { locals: { sd: {} } } @next = sinon.stub() it 'tracks signup', -> analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties.signup_service.should.equal 'email' it 'tracks login', -> analytics.trackLogin @req, @res, @next @analytics.track.args[0][0].event.should.equal 'Successfully logged in' @analytics.track.args[0][0].userId.should.equal 'foo' it 'passes along modal_id and acquisition_initiative submitted fields', -> @req.body.modal_id = 'foo' @req.body.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties .modal_id.should.equal 'foo' @analytics.track.args[0][0].properties .acquisition_initiative.should.equal 'bar' it 'passes along acquisition_initiative query params for OAuth links', -> @req.query.modal_id = 'foo' @req.query.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties .modal_id.should.equal 'foo' @analytics.track.args[0][0].properties .acquisition_initiative.should.equal 'bar' it 'doesnt hold on to the temporary session variable', -> analytics.__set__ 'opts', {} @req.body.modal_id = 'foo' @req.body.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next Object.keys(@req.session).length.should.equal 0
183101
sinon = require 'sinon' rewire = require 'rewire' analytics = rewire '../../lib/app/analytics' describe 'analytics', -> beforeEach -> analytics.__set__ 'opts', SEGMENT_WRITE_KEY: '<KEY>' scope = this analytics.__set__ 'Analytics', class Analytics constructor: -> scope.analytics = this track: sinon.stub() @req = { session: {}, body: {}, user: { get: -> 'foo' }, query: {} } @res = { locals: { sd: {} } } @next = sinon.stub() it 'tracks signup', -> analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties.signup_service.should.equal 'email' it 'tracks login', -> analytics.trackLogin @req, @res, @next @analytics.track.args[0][0].event.should.equal 'Successfully logged in' @analytics.track.args[0][0].userId.should.equal 'foo' it 'passes along modal_id and acquisition_initiative submitted fields', -> @req.body.modal_id = 'foo' @req.body.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties .modal_id.should.equal 'foo' @analytics.track.args[0][0].properties .acquisition_initiative.should.equal 'bar' it 'passes along acquisition_initiative query params for OAuth links', -> @req.query.modal_id = 'foo' @req.query.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties .modal_id.should.equal 'foo' @analytics.track.args[0][0].properties .acquisition_initiative.should.equal 'bar' it 'doesnt hold on to the temporary session variable', -> analytics.__set__ 'opts', {} @req.body.modal_id = 'foo' @req.body.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next Object.keys(@req.session).length.should.equal 0
true
sinon = require 'sinon' rewire = require 'rewire' analytics = rewire '../../lib/app/analytics' describe 'analytics', -> beforeEach -> analytics.__set__ 'opts', SEGMENT_WRITE_KEY: 'PI:KEY:<KEY>END_PI' scope = this analytics.__set__ 'Analytics', class Analytics constructor: -> scope.analytics = this track: sinon.stub() @req = { session: {}, body: {}, user: { get: -> 'foo' }, query: {} } @res = { locals: { sd: {} } } @next = sinon.stub() it 'tracks signup', -> analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties.signup_service.should.equal 'email' it 'tracks login', -> analytics.trackLogin @req, @res, @next @analytics.track.args[0][0].event.should.equal 'Successfully logged in' @analytics.track.args[0][0].userId.should.equal 'foo' it 'passes along modal_id and acquisition_initiative submitted fields', -> @req.body.modal_id = 'foo' @req.body.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties .modal_id.should.equal 'foo' @analytics.track.args[0][0].properties .acquisition_initiative.should.equal 'bar' it 'passes along acquisition_initiative query params for OAuth links', -> @req.query.modal_id = 'foo' @req.query.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next @analytics.track.args[0][0].properties .modal_id.should.equal 'foo' @analytics.track.args[0][0].properties .acquisition_initiative.should.equal 'bar' it 'doesnt hold on to the temporary session variable', -> analytics.__set__ 'opts', {} @req.body.modal_id = 'foo' @req.body.acquisition_initiative = 'bar' analytics.setCampaign @req, @res, @next analytics.trackSignup('email') @req, @res, @next Object.keys(@req.session).length.should.equal 0
[ { "context": "#\n# Project's main unit\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Tabs extends Element\n include: core.Opti", "end": 64, "score": 0.999881386756897, "start": 47, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/tabs/src/tabs.coffee
lovely-io/lovely.io-stl
2
# # Project's main unit # # Copyright (C) 2012 Nikolay Nemshilov # class Tabs extends Element include: core.Options extend: Options: # default options idPrefix: '' # # Default constructor # constructor: (element, options)-> options = ext({}, options) try options = ext(options, JSON.parse(element.getAttribute('data-tabs'))) catch e @setOptions(options) for key of Tabs.Options delete(options[key]) super element, options @addClass('lui-tabs').style({visibility: 'visible'}) @nav = @first('nav,ul').on 'click', (event)=> if link = event.find('a') event.preventDefault() @select @nav.find('a').indexOf(link) @select(0) # # Selects a tab by an _integer_ index or panels _string_ ID # # @param {numeric|String} tab index or ID # @return {Tabs} this # select: (index)-> links = @nav.find('a') panels = @children() switch typeof(index) when 'number' then link = links[index] when 'string' then link = links.first (i)-> i._.getAttribute('href').substr(1) is index if link = (link || links[0]) id = @options.idPrefix + link._.getAttribute('href').substr(1) panel = panels.filter((p)-> p._.id is id)[0] if panel @current_link.removeClass('lui-tabs-current') if @current_link @current_panel.removeClass('lui-tabs-current') if @current_panel @current_link = link.addClass('lui-tabs-current') @current_panel = panel.addClass('lui-tabs-current') @emit 'select', index: links.indexOf(link), link: link, panel: panel return @
207008
# # Project's main unit # # Copyright (C) 2012 <NAME> # class Tabs extends Element include: core.Options extend: Options: # default options idPrefix: '' # # Default constructor # constructor: (element, options)-> options = ext({}, options) try options = ext(options, JSON.parse(element.getAttribute('data-tabs'))) catch e @setOptions(options) for key of Tabs.Options delete(options[key]) super element, options @addClass('lui-tabs').style({visibility: 'visible'}) @nav = @first('nav,ul').on 'click', (event)=> if link = event.find('a') event.preventDefault() @select @nav.find('a').indexOf(link) @select(0) # # Selects a tab by an _integer_ index or panels _string_ ID # # @param {numeric|String} tab index or ID # @return {Tabs} this # select: (index)-> links = @nav.find('a') panels = @children() switch typeof(index) when 'number' then link = links[index] when 'string' then link = links.first (i)-> i._.getAttribute('href').substr(1) is index if link = (link || links[0]) id = @options.idPrefix + link._.getAttribute('href').substr(1) panel = panels.filter((p)-> p._.id is id)[0] if panel @current_link.removeClass('lui-tabs-current') if @current_link @current_panel.removeClass('lui-tabs-current') if @current_panel @current_link = link.addClass('lui-tabs-current') @current_panel = panel.addClass('lui-tabs-current') @emit 'select', index: links.indexOf(link), link: link, panel: panel return @
true
# # Project's main unit # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Tabs extends Element include: core.Options extend: Options: # default options idPrefix: '' # # Default constructor # constructor: (element, options)-> options = ext({}, options) try options = ext(options, JSON.parse(element.getAttribute('data-tabs'))) catch e @setOptions(options) for key of Tabs.Options delete(options[key]) super element, options @addClass('lui-tabs').style({visibility: 'visible'}) @nav = @first('nav,ul').on 'click', (event)=> if link = event.find('a') event.preventDefault() @select @nav.find('a').indexOf(link) @select(0) # # Selects a tab by an _integer_ index or panels _string_ ID # # @param {numeric|String} tab index or ID # @return {Tabs} this # select: (index)-> links = @nav.find('a') panels = @children() switch typeof(index) when 'number' then link = links[index] when 'string' then link = links.first (i)-> i._.getAttribute('href').substr(1) is index if link = (link || links[0]) id = @options.idPrefix + link._.getAttribute('href').substr(1) panel = panels.filter((p)-> p._.id is id)[0] if panel @current_link.removeClass('lui-tabs-current') if @current_link @current_panel.removeClass('lui-tabs-current') if @current_panel @current_link = link.addClass('lui-tabs-current') @current_panel = panel.addClass('lui-tabs-current') @emit 'select', index: links.indexOf(link), link: link, panel: panel return @
[ { "context": "[\n {\n title: \"Spyns\"\n group: \"Development\"\n paths: [\n \"~/D", "end": 23, "score": 0.9994957447052002, "start": 18, "tag": "NAME", "value": "Spyns" } ]
atom/dot-atom/projects.leopard-jkg.cson
jkglasbrenner/dotfiles
0
[ { title: "Spyns" group: "Development" paths: [ "~/Development/spyns" ] }, { title: "CSI-702: Homework02 Instructor Attempt" group: "Mason Spring 2017" paths: [ "~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructor-attempt" ] }, ]
4290
[ { title: "<NAME>" group: "Development" paths: [ "~/Development/spyns" ] }, { title: "CSI-702: Homework02 Instructor Attempt" group: "Mason Spring 2017" paths: [ "~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructor-attempt" ] }, ]
true
[ { title: "PI:NAME:<NAME>END_PI" group: "Development" paths: [ "~/Development/spyns" ] }, { title: "CSI-702: Homework02 Instructor Attempt" group: "Mason Spring 2017" paths: [ "~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructor-attempt" ] }, ]
[ { "context": "ongoose.resources/users/create\",\n {email: 'jon@test.com'}, (err, result) =>\n\n # Then I should ge", "end": 2156, "score": 0.9999208450317383, "start": 2144, "tag": "EMAIL", "value": "jon@test.com" }, { "context": " 'expected user'\n user.emai...
test/run.coffee
TorchlightSoftware/axiom-mongoose
0
{join} = require 'path' rel = (args...) -> join __dirname, '..', args... should = require 'should' axiom = require 'axiom' _ = require 'lodash' db = require 'mongoose' axiomMongoose = require '..' describe 'Mongoose Run', -> before (done) -> axiom.wireUpLoggers [{writer: 'console', level: 'warning'}] axiom.init {}, {root: rel 'sample'} # Given the run command is initiated axiom.request "server.run", {}, (err, {mongoose: {db}}) => should.not.exist err @db = db axiom.request 'mongoose.linkFactory', {db}, (err, {@Factory}) => @Factory.clear(done) afterEach (done) -> @Factory.clear(done) after (done) -> axiom.reset(done) it 'models should be loaded after server.run', -> @db.models.should.have.keys ['User'] describe 'CRUD', -> it 'should respond to users/index', (done) -> # Given a user in the system @Factory.create 'user', (err, createdUser) => should.not.exist err # When I request a user listing axiom.request "mongoose.resources/users/index", {}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {users} = result should.exist users, 'expected users' users.should.have.length 1 users[0].should.eql createdUser.toJSON() done() it 'should respond to users/show', (done) -> # Given a user in the system @Factory.create 'user', (err, createdUser) => should.not.exist err # When I request a user axiom.request "mongoose.resources/users/show", {_id: createdUser._id}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done() it 'should respond to users/create', (done) -> # When I create a user axiom.request "mongoose.resources/users/create", {email: 'jon@test.com'}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.email.should.eql 'jon@test.com' done() it 'should respond to users/update', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/update", { _id: createdUser._id email: 'not-jon@test.com' }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.email.should.eql 'not-jon@test.com' done() it 'should respond to users/delete', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/delete", { _id: createdUser._id }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done() it 'should respond to users/findByEmail', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/findByEmail", { email: createdUser.email }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done()
166497
{join} = require 'path' rel = (args...) -> join __dirname, '..', args... should = require 'should' axiom = require 'axiom' _ = require 'lodash' db = require 'mongoose' axiomMongoose = require '..' describe 'Mongoose Run', -> before (done) -> axiom.wireUpLoggers [{writer: 'console', level: 'warning'}] axiom.init {}, {root: rel 'sample'} # Given the run command is initiated axiom.request "server.run", {}, (err, {mongoose: {db}}) => should.not.exist err @db = db axiom.request 'mongoose.linkFactory', {db}, (err, {@Factory}) => @Factory.clear(done) afterEach (done) -> @Factory.clear(done) after (done) -> axiom.reset(done) it 'models should be loaded after server.run', -> @db.models.should.have.keys ['User'] describe 'CRUD', -> it 'should respond to users/index', (done) -> # Given a user in the system @Factory.create 'user', (err, createdUser) => should.not.exist err # When I request a user listing axiom.request "mongoose.resources/users/index", {}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {users} = result should.exist users, 'expected users' users.should.have.length 1 users[0].should.eql createdUser.toJSON() done() it 'should respond to users/show', (done) -> # Given a user in the system @Factory.create 'user', (err, createdUser) => should.not.exist err # When I request a user axiom.request "mongoose.resources/users/show", {_id: createdUser._id}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done() it 'should respond to users/create', (done) -> # When I create a user axiom.request "mongoose.resources/users/create", {email: '<EMAIL>'}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.email.should.eql '<EMAIL>' done() it 'should respond to users/update', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/update", { _id: createdUser._id email: '<EMAIL>' }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.email.should.eql '<EMAIL>' done() it 'should respond to users/delete', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/delete", { _id: createdUser._id }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done() it 'should respond to users/findByEmail', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/findByEmail", { email: createdUser.email }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done()
true
{join} = require 'path' rel = (args...) -> join __dirname, '..', args... should = require 'should' axiom = require 'axiom' _ = require 'lodash' db = require 'mongoose' axiomMongoose = require '..' describe 'Mongoose Run', -> before (done) -> axiom.wireUpLoggers [{writer: 'console', level: 'warning'}] axiom.init {}, {root: rel 'sample'} # Given the run command is initiated axiom.request "server.run", {}, (err, {mongoose: {db}}) => should.not.exist err @db = db axiom.request 'mongoose.linkFactory', {db}, (err, {@Factory}) => @Factory.clear(done) afterEach (done) -> @Factory.clear(done) after (done) -> axiom.reset(done) it 'models should be loaded after server.run', -> @db.models.should.have.keys ['User'] describe 'CRUD', -> it 'should respond to users/index', (done) -> # Given a user in the system @Factory.create 'user', (err, createdUser) => should.not.exist err # When I request a user listing axiom.request "mongoose.resources/users/index", {}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {users} = result should.exist users, 'expected users' users.should.have.length 1 users[0].should.eql createdUser.toJSON() done() it 'should respond to users/show', (done) -> # Given a user in the system @Factory.create 'user', (err, createdUser) => should.not.exist err # When I request a user axiom.request "mongoose.resources/users/show", {_id: createdUser._id}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done() it 'should respond to users/create', (done) -> # When I create a user axiom.request "mongoose.resources/users/create", {email: 'PI:EMAIL:<EMAIL>END_PI'}, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.email.should.eql 'PI:EMAIL:<EMAIL>END_PI' done() it 'should respond to users/update', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/update", { _id: createdUser._id email: 'PI:EMAIL:<EMAIL>END_PI' }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.email.should.eql 'PI:EMAIL:<EMAIL>END_PI' done() it 'should respond to users/delete', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/delete", { _id: createdUser._id }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done() it 'should respond to users/findByEmail', (done) -> @Factory.create 'user', (err, createdUser) => should.not.exist err # When I create a user axiom.request "mongoose.resources/users/findByEmail", { email: createdUser.email }, (err, result) => # Then I should get the user I created should.not.exist err should.exist result, 'expected result' {user} = result should.exist user, 'expected user' user.should.eql createdUser.toJSON() done()