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": "local building command\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nexports.init = (args) ->\n fs = require('", "end": 81, "score": 0.9998889565467834, "start": 64, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
cli/commands/build.coffee
lovely-io/lovely.io-stl
2
# # Package, local building command # # Copyright (C) 2011-2012 Nikolay Nemshilov # exports.init = (args) -> fs = require('fs') source = require('../source') pack = require('../package') vanilla = args.indexOf('--vanilla') isnt -1 no_style = args.indexOf('--no-styles') isnt -1 || args.indexOf('--no-style') isnt -1 location = process.cwd() filename = location + "/build/" sout "» Compiling: #{pack.name || ''}".ljust(32) fs.existsSync(filename) || fs.mkdirSync(filename, 0o0755) filename += pack.name || 'result'; fs.writeFileSync(filename + "-src.js", source.compile(location, vanilla, no_style)) fs.writeFileSync(filename + ".js", source.minify(location, vanilla, no_style)) system("gzip -c #{filename}.js > #{filename}.js.gz") print " Done".green if no_style # dumping styles in a separated file sout "» Converting styles: #{pack.name || ''}".ljust(32) for format in ['css', 'sass', 'styl', 'scss'] if fs.existsSync("#{location}/main.#{format}") style = fs.readFileSync("#{location}/main.#{format}").toString() fs.writeFileSync(filename + ".css", source.style(style, format)) print " Done".green break exports.help = (args) -> """ Builds and minifies the source code in a single file Usage: lovely build Options: --vanilla vanilla (non lovely.io) module build --no-styles dump styles in a separated file """
86015
# # Package, local building command # # Copyright (C) 2011-2012 <NAME> # exports.init = (args) -> fs = require('fs') source = require('../source') pack = require('../package') vanilla = args.indexOf('--vanilla') isnt -1 no_style = args.indexOf('--no-styles') isnt -1 || args.indexOf('--no-style') isnt -1 location = process.cwd() filename = location + "/build/" sout "» Compiling: #{pack.name || ''}".ljust(32) fs.existsSync(filename) || fs.mkdirSync(filename, 0o0755) filename += pack.name || 'result'; fs.writeFileSync(filename + "-src.js", source.compile(location, vanilla, no_style)) fs.writeFileSync(filename + ".js", source.minify(location, vanilla, no_style)) system("gzip -c #{filename}.js > #{filename}.js.gz") print " Done".green if no_style # dumping styles in a separated file sout "» Converting styles: #{pack.name || ''}".ljust(32) for format in ['css', 'sass', 'styl', 'scss'] if fs.existsSync("#{location}/main.#{format}") style = fs.readFileSync("#{location}/main.#{format}").toString() fs.writeFileSync(filename + ".css", source.style(style, format)) print " Done".green break exports.help = (args) -> """ Builds and minifies the source code in a single file Usage: lovely build Options: --vanilla vanilla (non lovely.io) module build --no-styles dump styles in a separated file """
true
# # Package, local building command # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # exports.init = (args) -> fs = require('fs') source = require('../source') pack = require('../package') vanilla = args.indexOf('--vanilla') isnt -1 no_style = args.indexOf('--no-styles') isnt -1 || args.indexOf('--no-style') isnt -1 location = process.cwd() filename = location + "/build/" sout "» Compiling: #{pack.name || ''}".ljust(32) fs.existsSync(filename) || fs.mkdirSync(filename, 0o0755) filename += pack.name || 'result'; fs.writeFileSync(filename + "-src.js", source.compile(location, vanilla, no_style)) fs.writeFileSync(filename + ".js", source.minify(location, vanilla, no_style)) system("gzip -c #{filename}.js > #{filename}.js.gz") print " Done".green if no_style # dumping styles in a separated file sout "» Converting styles: #{pack.name || ''}".ljust(32) for format in ['css', 'sass', 'styl', 'scss'] if fs.existsSync("#{location}/main.#{format}") style = fs.readFileSync("#{location}/main.#{format}").toString() fs.writeFileSync(filename + ".css", source.style(style, format)) print " Done".green break exports.help = (args) -> """ Builds and minifies the source code in a single file Usage: lovely build Options: --vanilla vanilla (non lovely.io) module build --no-styles dump styles in a separated file """
[ { "context": "uld work with map', ->\n user = { firstName: 'tom' }\n expect(getFirstName user).to.deep.equal ", "end": 497, "score": 0.9268333911895752, "start": 494, "tag": "NAME", "value": "tom" }, { "context": "rstName user).to.deep.equal Maybe.Just 'my name is tom'\n\n ...
app/shared/utilities/functional-utils.spec.coffee
kasperstorgaard/chatapp
0
expect = chai.expect; F = require './functional-utils.js' Maybe = require 'pointfree-fantasy/instances/maybe' Identity = require('pointfree-fantasy/instances/identity').Identity R = require 'ramda' getFirstName = R.compose(R.map(R.add 'my name is '), F.safeGet 'firstName') describe 'functional utils', -> describe 'log', -> it 'should return value', -> expect(F.log('test')).to.equal 'test' describe 'safeGet', -> it 'should work with map', -> user = { firstName: 'tom' } expect(getFirstName user).to.deep.equal Maybe.Just 'my name is tom' it 'should work when no attr is present', -> user = {} expect(getFirstName user).to.deep.equal Maybe.Nothing()
163025
expect = chai.expect; F = require './functional-utils.js' Maybe = require 'pointfree-fantasy/instances/maybe' Identity = require('pointfree-fantasy/instances/identity').Identity R = require 'ramda' getFirstName = R.compose(R.map(R.add 'my name is '), F.safeGet 'firstName') describe 'functional utils', -> describe 'log', -> it 'should return value', -> expect(F.log('test')).to.equal 'test' describe 'safeGet', -> it 'should work with map', -> user = { firstName: '<NAME>' } expect(getFirstName user).to.deep.equal Maybe.Just 'my name is <NAME>' it 'should work when no attr is present', -> user = {} expect(getFirstName user).to.deep.equal Maybe.Nothing()
true
expect = chai.expect; F = require './functional-utils.js' Maybe = require 'pointfree-fantasy/instances/maybe' Identity = require('pointfree-fantasy/instances/identity').Identity R = require 'ramda' getFirstName = R.compose(R.map(R.add 'my name is '), F.safeGet 'firstName') describe 'functional utils', -> describe 'log', -> it 'should return value', -> expect(F.log('test')).to.equal 'test' describe 'safeGet', -> it 'should work with map', -> user = { firstName: 'PI:NAME:<NAME>END_PI' } expect(getFirstName user).to.deep.equal Maybe.Just 'my name is PI:NAME:<NAME>END_PI' it 'should work when no attr is present', -> user = {} expect(getFirstName user).to.deep.equal Maybe.Nothing()
[ { "context": "%= deploy.username %>\"\n\t\t\t\t\tpassword: \"<%= deploy.password %>\"\n\t\t\t\t\tcreateDirectories: true\n\t\n\t\t\tclientconfi", "end": 4597, "score": 0.5984742045402527, "start": 4589, "tag": "PASSWORD", "value": "password" }, { "context": "<%= deploy.username %>\"\...
Gruntfile.coffee
mpneuried/node-pi-photobooth
0
path = require( "path" ) request = require( "request" ) _ = require( "lodash" ) try _gconfig = require( "./config.json" )?.grunt if not _gconfig? console.log( "INFO: No grunt config in `config.json` found. So use default.\n" ) _gconfig = {} catch _e if _e.code is "MODULE_NOT_FOUND" console.log( "INFO: No `config.json` found. So use default.\n" ) _gconfig = {} _.defaults( _gconfig, { "gettext_path": "/usr/local/opt/gettext/bin/" }) languageCodes = [ 'de', 'en' ] module.exports = (grunt) -> deploy = grunt.file.readJSON( "deploy.json" ) # Project configuration. grunt.initConfig pkg: grunt.file.readJSON('package.json') gconfig: _gconfig deploy: deploy regarde: client: files: ["_src/*.coffee", "_src/lib/*.coffee"] tasks: [ "update-client" ] serverjs: files: ["_src/**/*.coffee"] tasks: [ "coffee:serverchanged" ] frontendjs: files: ["_src_static/js/**/*.coffee"] tasks: [ "build_staticjs" ] frontendvendorjs: files: ["_src_static/js/vendor/**/*.js"] tasks: [ "build_staticjs" ] frontendcss: files: ["_src_static/css/**/*.styl"] tasks: [ "stylus" ] static: files: ["_src_static/static/**/*.*"] tasks: [ "build_staticfiles" ] #i18nserver: # files: ["_locale/**/*.po"] # tasks: [ "build_i18n_server" ] coffee: serverchanged: expand: true cwd: '_src' src: [ '<% print( _.first( ((typeof grunt !== "undefined" && grunt !== null ? (_ref = grunt.regarde) != null ? _ref.changed : void 0 : void 0) || ["_src/nothing"]) ).slice( "_src/".length ) ) %>' ] # template to cut off `_src/` and throw on error on non-regrade call # CF: `_.first( grunt?.regarde?.changed or [ "_src/nothing" ] ).slice( "_src/".length ) dest: '' ext: '.js' frontendchanged: expand: true cwd: '_src_static/js' src: [ '<% print( _.first( ((typeof grunt !== "undefined" && grunt !== null ? (_ref = grunt.regarde) != null ? _ref.changed : void 0 : void 0) || ["_src_static/js/nothing"]) ).slice( "_src_static/js/".length ) ) %>' ] # template to cut off `_src_static/js/` and throw on error on non-regrade call # CF: `_.first( grunt?.regarde?.changed or [ "_src_static/js/nothing" ] ).slice( "_src_static/js/".length ) dest: 'static_tmp/js' ext: '.js' backend_base: expand: true cwd: '_src', src: ["**/*.coffee"] dest: '' ext: '.js' frontend_base: expand: true cwd: '_src_static/js', src: ["**/*.coffee"] dest: 'static_tmp/js' ext: '.js' clean: server: src: [ "lib", "modules", "model", "models", "*.js", "release", "test" ] frontend: src: [ "static", "static_tmp" ] mimified: src: [ "static/js/*.js", "!static/js/main.js" ] statictmp: src: [ "static_tmp" ] stylus: standard: options: "include css": true files: "static/css/style.css": ["_src_static/css/style.styl"] "static/css/login.css": ["_src_static/css/login.styl"] browserify: main: src: [ 'static_tmp/js/main.js' ] dest: 'static/js/main.js' login: src: [ 'static_tmp/js/login.js' ] dest: 'static/js/login.js' copy: static: expand: true cwd: '_src_static/static', src: [ "**" ] dest: "static/" bootstrap_fonts: expand: true cwd: 'node_modules/bootstrap/dist/fonts', src: [ "**" ] dest: "static/fonts/" uglify: options: banner: '/*!<%= pkg.name %> - v<%= pkg.version %>\n*/\n' staticjs: files: "static/js/main.js": [ "static/js/main.js" ] cssmin: options: banner: '/*! <%= pkg.name %> - v<%= pkg.version %>*/\n' staticcss: files: "static/css/external.css": [ "_src_static/css/*.css", "node_modules/bootstrap/dist/css/bootstrap.css" ] compress: main: options: archive: "release/<%= pkg.name %>_deploy_<%= pkg.version.replace( '.', '_' ) %>.zip" files: [ { src: [ "package.json", "server.js", "modules/**", "lib/**", "static/**", "views/**", "_src_static/css/**/*.styl" ], dest: "./" } ] cli: options: archive: "release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" files: [ { src: [ "package_client.json", "client.js", "lib/*", "_docs/*" ], dest: "./" } ] sftp: client: files: "./": [ "release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" ] options: path: "<%= deploy.targetServerPath %>" host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true clientconfig: files: "./": [ "<%= deploy.configfile %>" ] options: path: "<%= deploy.targetServerPath %>" host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true sshexec: preparelogfile: command: "sudo touch /home/pi/Sites/logs/photobooth-camera-client.log && sudo chmod 666 /home/pi/Sites/logs/photobooth-camera-client.log" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" movestartup: command: [ "cd <%= deploy.targetServerPath %> && sudo mv -f _docs/photobooth-client /etc/init.d/ && sudo chmod 777 /etc/init.d/photobooth-client" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true cleanup: command: "rm -rf <%= deploy.targetServerPath %>*" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" cleanup_nonpm: command: "cd <%= deploy.targetServerPath %> && sudo rm -rf $(ls | grep -v node_modules)" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" unzip: command: [ "cd <%= deploy.targetServerPath %> && unzip -u -q -o release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip", "ls" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true removezip: command: [ "cd <%= deploy.targetServerPath %> && rm -f release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true donpminstall: command: [ "cd <%= deploy.targetServerPath %> && npm install --production" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true renameconfig: command: [ "cd <%= deploy.targetServerPath %> && mv <%= deploy.configfile %> config.json" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true renamepackage: command: [ "cd <%= deploy.targetServerPath %> && mv <%= deploy.packagefile %> package.json" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true stop: command: [ "/etc/init.d/photobooth-client stop" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" start: command: [ "/etc/init.d/photobooth-client start &" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" # Load npm modules grunt.loadNpmTasks "grunt-regarde" grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-stylus" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-contrib-cssmin" grunt.loadNpmTasks "grunt-contrib-copy" grunt.loadNpmTasks "grunt-contrib-compress" grunt.loadNpmTasks "grunt-contrib-concat" grunt.loadNpmTasks "grunt-contrib-clean" grunt.loadNpmTasks "grunt-ssh" grunt.loadNpmTasks "grunt-browserify" # just a hack until this issue has been fixed: https://github.com/yeoman/grunt-regarde/issues/3 grunt.option('force', not grunt.option('force')) # ALIAS TASKS grunt.registerTask "watch", "regarde" grunt.registerTask "default", "build" grunt.registerTask "uc", "update-client" grunt.registerTask "dc", "deploy-client" grunt.registerTask "dcn", "deploy-client-npm" grunt.registerTask "clear", [ "clean:server", "clean:frontend" ] # build the project grunt.registerTask "build", [ "clean:frontend", "build_server", "build_frontend" ] grunt.registerTask "build-dev", [ "build" ] grunt.registerTask "build_server", [ "coffee:backend_base" ] grunt.registerTask "build_frontend", [ "build_staticjs", "build_vendorcss", "stylus", "build_staticfiles" ] grunt.registerTask "build_staticjs", [ "clean:statictmp", "coffee:frontend_base", "browserify:main", "clean:mimified" ] grunt.registerTask "build_vendorcss", [ "cssmin:staticcss" ] grunt.registerTask "build_staticfiles", [ "copy:static", "copy:bootstrap_fonts" ] grunt.registerTask "prepare-client", [ "sshexec:preparelogfile", "sshexec:movestartup" ] grunt.registerTask "update-client", [ "compress:cli", "sshexec:cleanup_nonpm", "sftp:client", "sftp:clientconfig", "sshexec:unzip", "sshexec:renamepackage", "sshexec:renameconfig", "sshexec:removezip", "sshexec:stop", "sshexec:start" ] grunt.registerTask "deploy-client", [ "build", "update-client" ] grunt.registerTask "deploy-client-npm", [ "build", "compress:cli", "sshexec:cleanup", "sftp:client", "sftp:clientconfig", "sshexec:unzip", "sshexec:renamepackage", "sshexec:donpminstall", "sshexec:renameconfig", "sshexec:removezip", "sshexec:stop", "sshexec:start" ] grunt.registerTask "release", [ "build", "uglify:staticjs", "compress:main" ]
70222
path = require( "path" ) request = require( "request" ) _ = require( "lodash" ) try _gconfig = require( "./config.json" )?.grunt if not _gconfig? console.log( "INFO: No grunt config in `config.json` found. So use default.\n" ) _gconfig = {} catch _e if _e.code is "MODULE_NOT_FOUND" console.log( "INFO: No `config.json` found. So use default.\n" ) _gconfig = {} _.defaults( _gconfig, { "gettext_path": "/usr/local/opt/gettext/bin/" }) languageCodes = [ 'de', 'en' ] module.exports = (grunt) -> deploy = grunt.file.readJSON( "deploy.json" ) # Project configuration. grunt.initConfig pkg: grunt.file.readJSON('package.json') gconfig: _gconfig deploy: deploy regarde: client: files: ["_src/*.coffee", "_src/lib/*.coffee"] tasks: [ "update-client" ] serverjs: files: ["_src/**/*.coffee"] tasks: [ "coffee:serverchanged" ] frontendjs: files: ["_src_static/js/**/*.coffee"] tasks: [ "build_staticjs" ] frontendvendorjs: files: ["_src_static/js/vendor/**/*.js"] tasks: [ "build_staticjs" ] frontendcss: files: ["_src_static/css/**/*.styl"] tasks: [ "stylus" ] static: files: ["_src_static/static/**/*.*"] tasks: [ "build_staticfiles" ] #i18nserver: # files: ["_locale/**/*.po"] # tasks: [ "build_i18n_server" ] coffee: serverchanged: expand: true cwd: '_src' src: [ '<% print( _.first( ((typeof grunt !== "undefined" && grunt !== null ? (_ref = grunt.regarde) != null ? _ref.changed : void 0 : void 0) || ["_src/nothing"]) ).slice( "_src/".length ) ) %>' ] # template to cut off `_src/` and throw on error on non-regrade call # CF: `_.first( grunt?.regarde?.changed or [ "_src/nothing" ] ).slice( "_src/".length ) dest: '' ext: '.js' frontendchanged: expand: true cwd: '_src_static/js' src: [ '<% print( _.first( ((typeof grunt !== "undefined" && grunt !== null ? (_ref = grunt.regarde) != null ? _ref.changed : void 0 : void 0) || ["_src_static/js/nothing"]) ).slice( "_src_static/js/".length ) ) %>' ] # template to cut off `_src_static/js/` and throw on error on non-regrade call # CF: `_.first( grunt?.regarde?.changed or [ "_src_static/js/nothing" ] ).slice( "_src_static/js/".length ) dest: 'static_tmp/js' ext: '.js' backend_base: expand: true cwd: '_src', src: ["**/*.coffee"] dest: '' ext: '.js' frontend_base: expand: true cwd: '_src_static/js', src: ["**/*.coffee"] dest: 'static_tmp/js' ext: '.js' clean: server: src: [ "lib", "modules", "model", "models", "*.js", "release", "test" ] frontend: src: [ "static", "static_tmp" ] mimified: src: [ "static/js/*.js", "!static/js/main.js" ] statictmp: src: [ "static_tmp" ] stylus: standard: options: "include css": true files: "static/css/style.css": ["_src_static/css/style.styl"] "static/css/login.css": ["_src_static/css/login.styl"] browserify: main: src: [ 'static_tmp/js/main.js' ] dest: 'static/js/main.js' login: src: [ 'static_tmp/js/login.js' ] dest: 'static/js/login.js' copy: static: expand: true cwd: '_src_static/static', src: [ "**" ] dest: "static/" bootstrap_fonts: expand: true cwd: 'node_modules/bootstrap/dist/fonts', src: [ "**" ] dest: "static/fonts/" uglify: options: banner: '/*!<%= pkg.name %> - v<%= pkg.version %>\n*/\n' staticjs: files: "static/js/main.js": [ "static/js/main.js" ] cssmin: options: banner: '/*! <%= pkg.name %> - v<%= pkg.version %>*/\n' staticcss: files: "static/css/external.css": [ "_src_static/css/*.css", "node_modules/bootstrap/dist/css/bootstrap.css" ] compress: main: options: archive: "release/<%= pkg.name %>_deploy_<%= pkg.version.replace( '.', '_' ) %>.zip" files: [ { src: [ "package.json", "server.js", "modules/**", "lib/**", "static/**", "views/**", "_src_static/css/**/*.styl" ], dest: "./" } ] cli: options: archive: "release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" files: [ { src: [ "package_client.json", "client.js", "lib/*", "_docs/*" ], dest: "./" } ] sftp: client: files: "./": [ "release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" ] options: path: "<%= deploy.targetServerPath %>" host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" createDirectories: true clientconfig: files: "./": [ "<%= deploy.configfile %>" ] options: path: "<%= deploy.targetServerPath %>" host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" createDirectories: true sshexec: preparelogfile: command: "sudo touch /home/pi/Sites/logs/photobooth-camera-client.log && sudo chmod 666 /home/pi/Sites/logs/photobooth-camera-client.log" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= <PASSWORD> %>" movestartup: command: [ "cd <%= deploy.targetServerPath %> && sudo mv -f _docs/photobooth-client /etc/init.d/ && sudo chmod 777 /etc/init.d/photobooth-client" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" createDirectories: true cleanup: command: "rm -rf <%= deploy.targetServerPath %>*" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" cleanup_nonpm: command: "cd <%= deploy.targetServerPath %> && sudo rm -rf $(ls | grep -v node_modules)" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" unzip: command: [ "cd <%= deploy.targetServerPath %> && unzip -u -q -o release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip", "ls" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true removezip: command: [ "cd <%= deploy.targetServerPath %> && rm -f release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" createDirectories: true donpminstall: command: [ "cd <%= deploy.targetServerPath %> && npm install --production" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= <PASSWORD> %>" createDirectories: true renameconfig: command: [ "cd <%= deploy.targetServerPath %> && mv <%= deploy.configfile %> config.json" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" createDirectories: true renamepackage: command: [ "cd <%= deploy.targetServerPath %> && mv <%= deploy.packagefile %> package.json" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" createDirectories: true stop: command: [ "/etc/init.d/photobooth-client stop" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.<PASSWORD> %>" start: command: [ "/etc/init.d/photobooth-client start &" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" # Load npm modules grunt.loadNpmTasks "grunt-regarde" grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-stylus" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-contrib-cssmin" grunt.loadNpmTasks "grunt-contrib-copy" grunt.loadNpmTasks "grunt-contrib-compress" grunt.loadNpmTasks "grunt-contrib-concat" grunt.loadNpmTasks "grunt-contrib-clean" grunt.loadNpmTasks "grunt-ssh" grunt.loadNpmTasks "grunt-browserify" # just a hack until this issue has been fixed: https://github.com/yeoman/grunt-regarde/issues/3 grunt.option('force', not grunt.option('force')) # ALIAS TASKS grunt.registerTask "watch", "regarde" grunt.registerTask "default", "build" grunt.registerTask "uc", "update-client" grunt.registerTask "dc", "deploy-client" grunt.registerTask "dcn", "deploy-client-npm" grunt.registerTask "clear", [ "clean:server", "clean:frontend" ] # build the project grunt.registerTask "build", [ "clean:frontend", "build_server", "build_frontend" ] grunt.registerTask "build-dev", [ "build" ] grunt.registerTask "build_server", [ "coffee:backend_base" ] grunt.registerTask "build_frontend", [ "build_staticjs", "build_vendorcss", "stylus", "build_staticfiles" ] grunt.registerTask "build_staticjs", [ "clean:statictmp", "coffee:frontend_base", "browserify:main", "clean:mimified" ] grunt.registerTask "build_vendorcss", [ "cssmin:staticcss" ] grunt.registerTask "build_staticfiles", [ "copy:static", "copy:bootstrap_fonts" ] grunt.registerTask "prepare-client", [ "sshexec:preparelogfile", "sshexec:movestartup" ] grunt.registerTask "update-client", [ "compress:cli", "sshexec:cleanup_nonpm", "sftp:client", "sftp:clientconfig", "sshexec:unzip", "sshexec:renamepackage", "sshexec:renameconfig", "sshexec:removezip", "sshexec:stop", "sshexec:start" ] grunt.registerTask "deploy-client", [ "build", "update-client" ] grunt.registerTask "deploy-client-npm", [ "build", "compress:cli", "sshexec:cleanup", "sftp:client", "sftp:clientconfig", "sshexec:unzip", "sshexec:renamepackage", "sshexec:donpminstall", "sshexec:renameconfig", "sshexec:removezip", "sshexec:stop", "sshexec:start" ] grunt.registerTask "release", [ "build", "uglify:staticjs", "compress:main" ]
true
path = require( "path" ) request = require( "request" ) _ = require( "lodash" ) try _gconfig = require( "./config.json" )?.grunt if not _gconfig? console.log( "INFO: No grunt config in `config.json` found. So use default.\n" ) _gconfig = {} catch _e if _e.code is "MODULE_NOT_FOUND" console.log( "INFO: No `config.json` found. So use default.\n" ) _gconfig = {} _.defaults( _gconfig, { "gettext_path": "/usr/local/opt/gettext/bin/" }) languageCodes = [ 'de', 'en' ] module.exports = (grunt) -> deploy = grunt.file.readJSON( "deploy.json" ) # Project configuration. grunt.initConfig pkg: grunt.file.readJSON('package.json') gconfig: _gconfig deploy: deploy regarde: client: files: ["_src/*.coffee", "_src/lib/*.coffee"] tasks: [ "update-client" ] serverjs: files: ["_src/**/*.coffee"] tasks: [ "coffee:serverchanged" ] frontendjs: files: ["_src_static/js/**/*.coffee"] tasks: [ "build_staticjs" ] frontendvendorjs: files: ["_src_static/js/vendor/**/*.js"] tasks: [ "build_staticjs" ] frontendcss: files: ["_src_static/css/**/*.styl"] tasks: [ "stylus" ] static: files: ["_src_static/static/**/*.*"] tasks: [ "build_staticfiles" ] #i18nserver: # files: ["_locale/**/*.po"] # tasks: [ "build_i18n_server" ] coffee: serverchanged: expand: true cwd: '_src' src: [ '<% print( _.first( ((typeof grunt !== "undefined" && grunt !== null ? (_ref = grunt.regarde) != null ? _ref.changed : void 0 : void 0) || ["_src/nothing"]) ).slice( "_src/".length ) ) %>' ] # template to cut off `_src/` and throw on error on non-regrade call # CF: `_.first( grunt?.regarde?.changed or [ "_src/nothing" ] ).slice( "_src/".length ) dest: '' ext: '.js' frontendchanged: expand: true cwd: '_src_static/js' src: [ '<% print( _.first( ((typeof grunt !== "undefined" && grunt !== null ? (_ref = grunt.regarde) != null ? _ref.changed : void 0 : void 0) || ["_src_static/js/nothing"]) ).slice( "_src_static/js/".length ) ) %>' ] # template to cut off `_src_static/js/` and throw on error on non-regrade call # CF: `_.first( grunt?.regarde?.changed or [ "_src_static/js/nothing" ] ).slice( "_src_static/js/".length ) dest: 'static_tmp/js' ext: '.js' backend_base: expand: true cwd: '_src', src: ["**/*.coffee"] dest: '' ext: '.js' frontend_base: expand: true cwd: '_src_static/js', src: ["**/*.coffee"] dest: 'static_tmp/js' ext: '.js' clean: server: src: [ "lib", "modules", "model", "models", "*.js", "release", "test" ] frontend: src: [ "static", "static_tmp" ] mimified: src: [ "static/js/*.js", "!static/js/main.js" ] statictmp: src: [ "static_tmp" ] stylus: standard: options: "include css": true files: "static/css/style.css": ["_src_static/css/style.styl"] "static/css/login.css": ["_src_static/css/login.styl"] browserify: main: src: [ 'static_tmp/js/main.js' ] dest: 'static/js/main.js' login: src: [ 'static_tmp/js/login.js' ] dest: 'static/js/login.js' copy: static: expand: true cwd: '_src_static/static', src: [ "**" ] dest: "static/" bootstrap_fonts: expand: true cwd: 'node_modules/bootstrap/dist/fonts', src: [ "**" ] dest: "static/fonts/" uglify: options: banner: '/*!<%= pkg.name %> - v<%= pkg.version %>\n*/\n' staticjs: files: "static/js/main.js": [ "static/js/main.js" ] cssmin: options: banner: '/*! <%= pkg.name %> - v<%= pkg.version %>*/\n' staticcss: files: "static/css/external.css": [ "_src_static/css/*.css", "node_modules/bootstrap/dist/css/bootstrap.css" ] compress: main: options: archive: "release/<%= pkg.name %>_deploy_<%= pkg.version.replace( '.', '_' ) %>.zip" files: [ { src: [ "package.json", "server.js", "modules/**", "lib/**", "static/**", "views/**", "_src_static/css/**/*.styl" ], dest: "./" } ] cli: options: archive: "release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" files: [ { src: [ "package_client.json", "client.js", "lib/*", "_docs/*" ], dest: "./" } ] sftp: client: files: "./": [ "release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" ] options: path: "<%= deploy.targetServerPath %>" host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true clientconfig: files: "./": [ "<%= deploy.configfile %>" ] options: path: "<%= deploy.targetServerPath %>" host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true sshexec: preparelogfile: command: "sudo touch /home/pi/Sites/logs/photobooth-camera-client.log && sudo chmod 666 /home/pi/Sites/logs/photobooth-camera-client.log" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= PI:PASSWORD:<PASSWORD>END_PI %>" movestartup: command: [ "cd <%= deploy.targetServerPath %> && sudo mv -f _docs/photobooth-client /etc/init.d/ && sudo chmod 777 /etc/init.d/photobooth-client" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true cleanup: command: "rm -rf <%= deploy.targetServerPath %>*" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" cleanup_nonpm: command: "cd <%= deploy.targetServerPath %> && sudo rm -rf $(ls | grep -v node_modules)" options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" unzip: command: [ "cd <%= deploy.targetServerPath %> && unzip -u -q -o release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip", "ls" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" createDirectories: true removezip: command: [ "cd <%= deploy.targetServerPath %> && rm -f release/<%= pkg.name %>_client_<%= pkg.version.replace( '.', '_' ) %>.zip" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true donpminstall: command: [ "cd <%= deploy.targetServerPath %> && npm install --production" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true renameconfig: command: [ "cd <%= deploy.targetServerPath %> && mv <%= deploy.configfile %> config.json" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true renamepackage: command: [ "cd <%= deploy.targetServerPath %> && mv <%= deploy.packagefile %> package.json" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" createDirectories: true stop: command: [ "/etc/init.d/photobooth-client stop" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.PI:PASSWORD:<PASSWORD>END_PI %>" start: command: [ "/etc/init.d/photobooth-client start &" ] options: host: "<%= deploy.host %>" username: "<%= deploy.username %>" password: "<%= deploy.password %>" # Load npm modules grunt.loadNpmTasks "grunt-regarde" grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-stylus" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-contrib-cssmin" grunt.loadNpmTasks "grunt-contrib-copy" grunt.loadNpmTasks "grunt-contrib-compress" grunt.loadNpmTasks "grunt-contrib-concat" grunt.loadNpmTasks "grunt-contrib-clean" grunt.loadNpmTasks "grunt-ssh" grunt.loadNpmTasks "grunt-browserify" # just a hack until this issue has been fixed: https://github.com/yeoman/grunt-regarde/issues/3 grunt.option('force', not grunt.option('force')) # ALIAS TASKS grunt.registerTask "watch", "regarde" grunt.registerTask "default", "build" grunt.registerTask "uc", "update-client" grunt.registerTask "dc", "deploy-client" grunt.registerTask "dcn", "deploy-client-npm" grunt.registerTask "clear", [ "clean:server", "clean:frontend" ] # build the project grunt.registerTask "build", [ "clean:frontend", "build_server", "build_frontend" ] grunt.registerTask "build-dev", [ "build" ] grunt.registerTask "build_server", [ "coffee:backend_base" ] grunt.registerTask "build_frontend", [ "build_staticjs", "build_vendorcss", "stylus", "build_staticfiles" ] grunt.registerTask "build_staticjs", [ "clean:statictmp", "coffee:frontend_base", "browserify:main", "clean:mimified" ] grunt.registerTask "build_vendorcss", [ "cssmin:staticcss" ] grunt.registerTask "build_staticfiles", [ "copy:static", "copy:bootstrap_fonts" ] grunt.registerTask "prepare-client", [ "sshexec:preparelogfile", "sshexec:movestartup" ] grunt.registerTask "update-client", [ "compress:cli", "sshexec:cleanup_nonpm", "sftp:client", "sftp:clientconfig", "sshexec:unzip", "sshexec:renamepackage", "sshexec:renameconfig", "sshexec:removezip", "sshexec:stop", "sshexec:start" ] grunt.registerTask "deploy-client", [ "build", "update-client" ] grunt.registerTask "deploy-client-npm", [ "build", "compress:cli", "sshexec:cleanup", "sftp:client", "sftp:clientconfig", "sshexec:unzip", "sshexec:renamepackage", "sshexec:donpminstall", "sshexec:renameconfig", "sshexec:removezip", "sshexec:stop", "sshexec:start" ] grunt.registerTask "release", [ "build", "uglify:staticjs", "compress:main" ]
[ { "context": "quetas\"\nPAGES: \"Páginas\"\nPOSTS: \"Posts\"\nAUTHORS: \"Autores\"\nSEARCH: \"Buscar\"\nSOCIAL_NETWORKS: \"Redes Sociais", "end": 356, "score": 0.9946791529655457, "start": 349, "tag": "NAME", "value": "Autores" }, { "context": "aring\": \n \"shared\": \"Compartilh...
src/i18n/pt.cson
Intraktio/hybrid
2
PULL_TO_REFRESH: "Puxe para atualizar" RETRY: "Tentar novamente" CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Voltar" ERROR: "Ocorreu um erro, tente novamente." ATTEMPT_TO_CONNECT: "Tentativa de conexão {{attempt}} de {{attemptMax}}." OK: "Ok" YES: "Sim" NO: "Não" MENU: "Menu" HOME: "Início" TAGS: "Etiquetas" PAGES: "Páginas" POSTS: "Posts" AUTHORS: "Autores" SEARCH: "Buscar" SOCIAL_NETWORKS: "Redes Sociais" CATEGORIES: "Categorias" SETTINGS: "Configurações" CUSTOM_POSTS: "Posts customizados" CUSTOM_TAXO: "Taxonomia customizada" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Nova publicação!" PUSH_NOTIF_TEXT: "Novo artigo: '{{postTitle}}' em {{appTitle}}, quer visualizar?" BOOKMARKS: "Favoritos" BOOKMARKS_EMPTY: "Não há nada salvo!" BOOKMARK_ADDED: "Adicionado aos favoritos!" BOOKMARK_REMOVED: "Eliminado dos favoritos!" ZOOM: "Zoom" CACHE_CLEAR: "Clear cache" CACHE_CLEARED: "Cache cleared" "tags": "title": "Etiquetas" "tag": "title": "Etiqueta: {{name}}" "categories": "title": "Categorias" "category": "title": "Categoria {{name}}" "home": "title": "Início" "search": "inputPlaceholder": "Buscar" "title": "Buscar", "titleQuery": "Buscar: {{query}}" "sharing": "shared": "Compartilhado!" AUTHORS: "Autores" AUTHOR: "Autor" AUTHOR_TITLE: "Autor: {{name}}" "pages": "title": "Páginas" "posts": "title": "Início" "empty": "Não encontrou novas publicações!" "featured": "Em destaque" "post": "comments": "Comentários" "openInBrowser": "Abrir no navegador" "about": "title": "Sobre" "languages": "en": "Inglês" "fr": "Francês" "zh": "Chinês" "es": "Espanhol" "pl": "Polaco" "de": "Alemão" "pt": "Português" "it": "Italiano" "nl": "Holandês"
31725
PULL_TO_REFRESH: "Puxe para atualizar" RETRY: "Tentar novamente" CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Voltar" ERROR: "Ocorreu um erro, tente novamente." ATTEMPT_TO_CONNECT: "Tentativa de conexão {{attempt}} de {{attemptMax}}." OK: "Ok" YES: "Sim" NO: "Não" MENU: "Menu" HOME: "Início" TAGS: "Etiquetas" PAGES: "Páginas" POSTS: "Posts" AUTHORS: "<NAME>" SEARCH: "Buscar" SOCIAL_NETWORKS: "Redes Sociais" CATEGORIES: "Categorias" SETTINGS: "Configurações" CUSTOM_POSTS: "Posts customizados" CUSTOM_TAXO: "Taxonomia customizada" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Nova publicação!" PUSH_NOTIF_TEXT: "Novo artigo: '{{postTitle}}' em {{appTitle}}, quer visualizar?" BOOKMARKS: "Favoritos" BOOKMARKS_EMPTY: "Não há nada salvo!" BOOKMARK_ADDED: "Adicionado aos favoritos!" BOOKMARK_REMOVED: "Eliminado dos favoritos!" ZOOM: "Zoom" CACHE_CLEAR: "Clear cache" CACHE_CLEARED: "Cache cleared" "tags": "title": "Etiquetas" "tag": "title": "Etiqueta: {{name}}" "categories": "title": "Categorias" "category": "title": "Categoria {{name}}" "home": "title": "Início" "search": "inputPlaceholder": "Buscar" "title": "Buscar", "titleQuery": "Buscar: {{query}}" "sharing": "shared": "Compartilhado!" AUTHORS: "<NAME>" AUTHOR: "<NAME>" AUTHOR_TITLE: "Autor: {{name}}" "pages": "title": "Páginas" "posts": "title": "Início" "empty": "Não encontrou novas publicações!" "featured": "Em destaque" "post": "comments": "Comentários" "openInBrowser": "Abrir no navegador" "about": "title": "Sobre" "languages": "en": "Inglês" "fr": "Francês" "zh": "Chinês" "es": "Espanhol" "pl": "Polaco" "de": "Alemão" "pt": "Português" "it": "Italiano" "nl": "Holandês"
true
PULL_TO_REFRESH: "Puxe para atualizar" RETRY: "Tentar novamente" CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Voltar" ERROR: "Ocorreu um erro, tente novamente." ATTEMPT_TO_CONNECT: "Tentativa de conexão {{attempt}} de {{attemptMax}}." OK: "Ok" YES: "Sim" NO: "Não" MENU: "Menu" HOME: "Início" TAGS: "Etiquetas" PAGES: "Páginas" POSTS: "Posts" AUTHORS: "PI:NAME:<NAME>END_PI" SEARCH: "Buscar" SOCIAL_NETWORKS: "Redes Sociais" CATEGORIES: "Categorias" SETTINGS: "Configurações" CUSTOM_POSTS: "Posts customizados" CUSTOM_TAXO: "Taxonomia customizada" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Nova publicação!" PUSH_NOTIF_TEXT: "Novo artigo: '{{postTitle}}' em {{appTitle}}, quer visualizar?" BOOKMARKS: "Favoritos" BOOKMARKS_EMPTY: "Não há nada salvo!" BOOKMARK_ADDED: "Adicionado aos favoritos!" BOOKMARK_REMOVED: "Eliminado dos favoritos!" ZOOM: "Zoom" CACHE_CLEAR: "Clear cache" CACHE_CLEARED: "Cache cleared" "tags": "title": "Etiquetas" "tag": "title": "Etiqueta: {{name}}" "categories": "title": "Categorias" "category": "title": "Categoria {{name}}" "home": "title": "Início" "search": "inputPlaceholder": "Buscar" "title": "Buscar", "titleQuery": "Buscar: {{query}}" "sharing": "shared": "Compartilhado!" AUTHORS: "PI:NAME:<NAME>END_PI" AUTHOR: "PI:NAME:<NAME>END_PI" AUTHOR_TITLE: "Autor: {{name}}" "pages": "title": "Páginas" "posts": "title": "Início" "empty": "Não encontrou novas publicações!" "featured": "Em destaque" "post": "comments": "Comentários" "openInBrowser": "Abrir no navegador" "about": "title": "Sobre" "languages": "en": "Inglês" "fr": "Francês" "zh": "Chinês" "es": "Espanhol" "pl": "Polaco" "de": "Alemão" "pt": "Português" "it": "Italiano" "nl": "Holandês"
[ { "context": ".MONGOLAB_URI or process.env.db or \"mongodb://bag:bag@ds047602.mongolab.com:47602/bag-dev\"\n\n\nStore = require \"../src/models/s", "end": 107, "score": 0.9971498250961304, "start": 82, "tag": "EMAIL", "value": "bag@ds047602.mongolab.com" }, { "context": "from the bag...
policeman/index.coffee
1egoman/bag-node
0
require("../src/db") process.env.MONGOLAB_URI or process.env.db or "mongodb://bag:bag@ds047602.mongolab.com:47602/bag-dev" Store = require "../src/models/store_model" Foodstuff = require "../src/models/foodstuff_model" Bag = require "../src/models/bag_model" inq = require "inquirer" async = require "async" chalk = require "chalk" _ = require "underscore" Store.find verified: false .exec (err, stores) -> return console.log err if err Foodstuff.find verified: false .exec (err, foodstuffs) -> return console.log err if err # loop through the stores, and ask if they are ok or not. async.mapSeries stores, (s, cb) -> Foodstuff.findOne _id: s.item.toString() .exec (err, f) -> return cb err if err # look at each of the stores for that item, and see if it matches what the # user inputted (we are looking for duplicates) async.mapSeries Object.keys(f.stores), (store, cb) -> Store.findOne verified: true _id: store , (err, sval) -> return cb err if err if sval # see if the store is a possible match score = _.intersection sval.name.split(' '), s.name.split(' ') if score cb null, sval else cb null else cb null , (err, matches) -> return cb err if err matches = _.compact matches # get the users opinion inq.prompt [ type: "rawlist" message: """ Store: #{chalk.red "Store Name: #{s.name}"} #{chalk.cyan "Item Name: #{f.name}"} #{chalk.green "Item Brand: #{s.item_brand}"} #{chalk.green "Item Price: #{s.item_price}"} """ name: "resp" choices: [ "Make this a new store" "A duplicate, but not listed" "Totally junk" new inq.Separator() ].concat matches.map (m) -> "|Really a duplicate of: #{chalk.red m.name}" ], (answers) -> store = s switch # the store is really new.... lets verify it! when answers.resp.indexOf('new') isnt -1 inq.prompt [ type: "input" default: s.name message: "Store Name" name: "store_name" , type: "input" message: "Store Desc" name: "store_desc" default: s.desc , type: "input" message: "Store Logo" name: "store_logo" default: s.image , type: "input" message: "Store Tags" name: "store_tags" default: s.tags.join(' ') ] , (out) -> # save the store store.verified = true store.name = out.store_name store.desc = out.store_desc store.image = out.store_logo store.image = out.store_tags.split ' ' store.save (err) -> return cb err if err console.log "Saved #{chalk.red out.store_name}" # save the foodstuff f.stores[store._id] = price: s.item_price f.markModified "stores.#{store._id}.price" # this is magic f.save (err, user) -> return cb err if err console.log "Saved #{chalk.red f.name}" cb null, answers # the store is a dupe... # we'll take all the item info from this store and use it to create # a new foodstuff attached to the specified store. Then, we'll # delete it. when answers.resp.indexOf('duplicate') isnt -1 do_store = (store_name) -> # find the store Store.findOne name: store_name, (err, store) -> return cb err if err if store # save the foodstuff f.stores[store._id] = price: s.item_price f.markModified "stores.#{store._id}.price" # this is magic f.save (err, user) -> return cb err if err console.log "Saved #{chalk.red f.name}" cb null else console.log "bad store. skipping for now..." cb null if answers.resp[0] is '|' store = answers.resp.split(': ')[1] do_store chalk.stripColor store.trim() else inq.prompt [ type: "input" message: "Enter the store name of the duplicate store" name: "store_id" ] , (out) -> do_store out.store_id # just delete the foodstuff, as it's just garbage when answers.resp.indexOf('junk') isnt -1 Store.remove _id: s._id, (err) -> return cb err if err console.log "Deleted junk: #{chalk.red s.name}" cb null , (err, all) -> console.log "Error", err if err console.log chalk.bold chalk.green "drumroll.... and, we are done with the stores!" # loop through the foodstuffs, and ask if they are ok or not. async.mapSeries foodstuffs, (f, cb) -> # try and find any duplicates query = for word in f.name.split ' ' name: new RegExp word, 'i' _id: $ne: f._id Foodstuff.find $or: query .exec (err, related) -> return cb err if err console.log related # get the users opinion inq.prompt [ type: "rawlist" message: """ Foodstuff: #{chalk.red "Item Name: #{f.name}"} #{chalk.green "Item Desc: #{f.desc}"} #{chalk.green "Item Tags: #{f.tags}"} #{chalk.green "Item Price: #{f.price}"} # """ name: "resp" choices: [ "Make this a new foodstuff" "Unlisted duplicate" "Totally junk" ].concat related.map (r) -> "|Really a duplicate of: #{chalk.red r.name}" ], (answers) -> switch # the foodstuff is really new.... lets verify it! when answers.resp.indexOf('new') isnt -1 inq.prompt [ type: "input" default: f.name message: "Foodstuff Name" name: "foodstuff_name" , type: "input" message: "Foodstuff Desc" name: "foodstuff_desc" default: f.desc , type: "input" message: "Foodstuff Price" name: "foodstuff_price" default: f.price , type: "input" message: "^^ At what store" name: "store" , type: "input" message: "Foodstuff Tags" name: "foodstuff_tags" default: f.tags.join ' ' ] , (out) -> # get store info Store.findOne name: out.store, (err, store) -> return cb err if err f.stores[store._id] = price: f.price # save the foodstuff f.verified = true f.name = out.foodstuff_name f.desc = out.foodstuff_desc f.image = out.foodstuff_logo f.image = out.foodstuff_tags.split ' ' f.price = undefined f.save (err) -> return cb err if err console.log "Saved #{chalk.red out.foodstuff_name}" cb null, answers # the store is a dupe... # we'll take all the item info from this store and use it to create # a new foodstuff attached to the specified store. Then, we'll # delete it. when answers.resp.indexOf('duplicate') isnt -1 do_fds = (fds_name) -> Foodstuff.findOne name: fds_name, (err, new_item) -> return cb err if err # update bag to reflect duplicate Bag.findOne user: f.user, (err, bag) -> return cb err if err # replace in the user's bag with the new item bag.contents = bag.contents.map (c) -> if c._id.toString() is f._id.toString() new_item = new_item.toObject() new_item.quantity or= 1 new_item else c bag.markModified "contents" bag.save (err) -> return cb err if err # delete the physical item, too Foodstuff.remove _id: f._id, (err) -> return cb err if err console.log "Fixed dupes: #{chalk.red f.name} -> #{chalk.red new_item.name}" cb null if answers.resp[0] is '|' store = answers.resp.split(': ')[1] do_fds chalk.stripColor store.trim() else inq.prompt [ type: "input" message: "Enter the name of the duplicate item" name: "store_id" ] , (out) -> do_fds out.store_id # just delete the foodstuff, as it's just garbage when answers.resp.indexOf('junk') isnt -1 console.log f # delete from the bag Bag.findOne user: f.user, (err, bag) -> return cb err if err # remove in the user's bag bag.contents = bag.contents.filter (c) -> c._id.toString() isnt f._id.toString() bag.markModified "contents" bag.save (err) -> return cb err if err # delete the physical item, too Foodstuff.remove _id: f._id, (err) -> return cb err if err console.log "Deleted junk: #{chalk.red f.name}" cb null , (err, data) -> return console.log err if err console.log chalk.bold chalk.cyan "drumroll.... and, we are done, like, completely!" process.exit 0
33005
require("../src/db") process.env.MONGOLAB_URI or process.env.db or "mongodb://bag:<EMAIL>:47602/bag-dev" Store = require "../src/models/store_model" Foodstuff = require "../src/models/foodstuff_model" Bag = require "../src/models/bag_model" inq = require "inquirer" async = require "async" chalk = require "chalk" _ = require "underscore" Store.find verified: false .exec (err, stores) -> return console.log err if err Foodstuff.find verified: false .exec (err, foodstuffs) -> return console.log err if err # loop through the stores, and ask if they are ok or not. async.mapSeries stores, (s, cb) -> Foodstuff.findOne _id: s.item.toString() .exec (err, f) -> return cb err if err # look at each of the stores for that item, and see if it matches what the # user inputted (we are looking for duplicates) async.mapSeries Object.keys(f.stores), (store, cb) -> Store.findOne verified: true _id: store , (err, sval) -> return cb err if err if sval # see if the store is a possible match score = _.intersection sval.name.split(' '), s.name.split(' ') if score cb null, sval else cb null else cb null , (err, matches) -> return cb err if err matches = _.compact matches # get the users opinion inq.prompt [ type: "rawlist" message: """ Store: #{chalk.red "Store Name: #{s.name}"} #{chalk.cyan "Item Name: #{f.name}"} #{chalk.green "Item Brand: #{s.item_brand}"} #{chalk.green "Item Price: #{s.item_price}"} """ name: "resp" choices: [ "Make this a new store" "A duplicate, but not listed" "Totally junk" new inq.Separator() ].concat matches.map (m) -> "|Really a duplicate of: #{chalk.red m.name}" ], (answers) -> store = s switch # the store is really new.... lets verify it! when answers.resp.indexOf('new') isnt -1 inq.prompt [ type: "input" default: s.name message: "Store Name" name: "store_name" , type: "input" message: "Store Desc" name: "store_desc" default: s.desc , type: "input" message: "Store Logo" name: "store_logo" default: s.image , type: "input" message: "Store Tags" name: "store_tags" default: s.tags.join(' ') ] , (out) -> # save the store store.verified = true store.name = out.store_name store.desc = out.store_desc store.image = out.store_logo store.image = out.store_tags.split ' ' store.save (err) -> return cb err if err console.log "Saved #{chalk.red out.store_name}" # save the foodstuff f.stores[store._id] = price: s.item_price f.markModified "stores.#{store._id}.price" # this is magic f.save (err, user) -> return cb err if err console.log "Saved #{chalk.red f.name}" cb null, answers # the store is a dupe... # we'll take all the item info from this store and use it to create # a new foodstuff attached to the specified store. Then, we'll # delete it. when answers.resp.indexOf('duplicate') isnt -1 do_store = (store_name) -> # find the store Store.findOne name: store_name, (err, store) -> return cb err if err if store # save the foodstuff f.stores[store._id] = price: s.item_price f.markModified "stores.#{store._id}.price" # this is magic f.save (err, user) -> return cb err if err console.log "Saved #{chalk.red f.name}" cb null else console.log "bad store. skipping for now..." cb null if answers.resp[0] is '|' store = answers.resp.split(': ')[1] do_store chalk.stripColor store.trim() else inq.prompt [ type: "input" message: "Enter the store name of the duplicate store" name: "store_id" ] , (out) -> do_store out.store_id # just delete the foodstuff, as it's just garbage when answers.resp.indexOf('junk') isnt -1 Store.remove _id: s._id, (err) -> return cb err if err console.log "Deleted junk: #{chalk.red s.name}" cb null , (err, all) -> console.log "Error", err if err console.log chalk.bold chalk.green "drumroll.... and, we are done with the stores!" # loop through the foodstuffs, and ask if they are ok or not. async.mapSeries foodstuffs, (f, cb) -> # try and find any duplicates query = for word in f.name.split ' ' name: new RegExp word, 'i' _id: $ne: f._id Foodstuff.find $or: query .exec (err, related) -> return cb err if err console.log related # get the users opinion inq.prompt [ type: "rawlist" message: """ Foodstuff: #{chalk.red "Item Name: #{f.name}"} #{chalk.green "Item Desc: #{f.desc}"} #{chalk.green "Item Tags: #{f.tags}"} #{chalk.green "Item Price: #{f.price}"} # """ name: "resp" choices: [ "Make this a new foodstuff" "Unlisted duplicate" "Totally junk" ].concat related.map (r) -> "|Really a duplicate of: #{chalk.red r.name}" ], (answers) -> switch # the foodstuff is really new.... lets verify it! when answers.resp.indexOf('new') isnt -1 inq.prompt [ type: "input" default: f.name message: "Foodstuff Name" name: "foodstuff_name" , type: "input" message: "Foodstuff Desc" name: "foodstuff_desc" default: f.desc , type: "input" message: "Foodstuff Price" name: "foodstuff_price" default: f.price , type: "input" message: "^^ At what store" name: "store" , type: "input" message: "Foodstuff Tags" name: "foodstuff_tags" default: f.tags.join ' ' ] , (out) -> # get store info Store.findOne name: out.store, (err, store) -> return cb err if err f.stores[store._id] = price: f.price # save the foodstuff f.verified = true f.name = out.foodstuff_name f.desc = out.foodstuff_desc f.image = out.foodstuff_logo f.image = out.foodstuff_tags.split ' ' f.price = undefined f.save (err) -> return cb err if err console.log "Saved #{chalk.red out.foodstuff_name}" cb null, answers # the store is a dupe... # we'll take all the item info from this store and use it to create # a new foodstuff attached to the specified store. Then, we'll # delete it. when answers.resp.indexOf('duplicate') isnt -1 do_fds = (fds_name) -> Foodstuff.findOne name: fds_name, (err, new_item) -> return cb err if err # update bag to reflect duplicate Bag.findOne user: f.user, (err, bag) -> return cb err if err # replace in the user's bag with the new item bag.contents = bag.contents.map (c) -> if c._id.toString() is f._id.toString() new_item = new_item.toObject() new_item.quantity or= 1 new_item else c bag.markModified "contents" bag.save (err) -> return cb err if err # delete the physical item, too Foodstuff.remove _id: f._id, (err) -> return cb err if err console.log "Fixed dupes: #{chalk.red f.name} -> #{chalk.red new_item.name}" cb null if answers.resp[0] is '|' store = answers.resp.split(': ')[1] do_fds chalk.stripColor store.trim() else inq.prompt [ type: "input" message: "Enter the name of the duplicate item" name: "store_id" ] , (out) -> do_fds out.store_id # just delete the foodstuff, as it's just garbage when answers.resp.indexOf('junk') isnt -1 console.log f # delete from the bag Bag.findOne user: f.user, (err, bag) -> return cb err if err # remove in the user's bag bag.contents = bag.contents.filter (c) -> c._id.toString() isnt f._id.toString() bag.markModified "contents" bag.save (err) -> return cb err if err # delete the physical item, too Foodstuff.remove _id: f._id, (err) -> return cb err if err console.log "Deleted junk: #{chalk.red f.name}" cb null , (err, data) -> return console.log err if err console.log chalk.bold chalk.cyan "drumroll.... and, we are done, like, completely!" process.exit 0
true
require("../src/db") process.env.MONGOLAB_URI or process.env.db or "mongodb://bag:PI:EMAIL:<EMAIL>END_PI:47602/bag-dev" Store = require "../src/models/store_model" Foodstuff = require "../src/models/foodstuff_model" Bag = require "../src/models/bag_model" inq = require "inquirer" async = require "async" chalk = require "chalk" _ = require "underscore" Store.find verified: false .exec (err, stores) -> return console.log err if err Foodstuff.find verified: false .exec (err, foodstuffs) -> return console.log err if err # loop through the stores, and ask if they are ok or not. async.mapSeries stores, (s, cb) -> Foodstuff.findOne _id: s.item.toString() .exec (err, f) -> return cb err if err # look at each of the stores for that item, and see if it matches what the # user inputted (we are looking for duplicates) async.mapSeries Object.keys(f.stores), (store, cb) -> Store.findOne verified: true _id: store , (err, sval) -> return cb err if err if sval # see if the store is a possible match score = _.intersection sval.name.split(' '), s.name.split(' ') if score cb null, sval else cb null else cb null , (err, matches) -> return cb err if err matches = _.compact matches # get the users opinion inq.prompt [ type: "rawlist" message: """ Store: #{chalk.red "Store Name: #{s.name}"} #{chalk.cyan "Item Name: #{f.name}"} #{chalk.green "Item Brand: #{s.item_brand}"} #{chalk.green "Item Price: #{s.item_price}"} """ name: "resp" choices: [ "Make this a new store" "A duplicate, but not listed" "Totally junk" new inq.Separator() ].concat matches.map (m) -> "|Really a duplicate of: #{chalk.red m.name}" ], (answers) -> store = s switch # the store is really new.... lets verify it! when answers.resp.indexOf('new') isnt -1 inq.prompt [ type: "input" default: s.name message: "Store Name" name: "store_name" , type: "input" message: "Store Desc" name: "store_desc" default: s.desc , type: "input" message: "Store Logo" name: "store_logo" default: s.image , type: "input" message: "Store Tags" name: "store_tags" default: s.tags.join(' ') ] , (out) -> # save the store store.verified = true store.name = out.store_name store.desc = out.store_desc store.image = out.store_logo store.image = out.store_tags.split ' ' store.save (err) -> return cb err if err console.log "Saved #{chalk.red out.store_name}" # save the foodstuff f.stores[store._id] = price: s.item_price f.markModified "stores.#{store._id}.price" # this is magic f.save (err, user) -> return cb err if err console.log "Saved #{chalk.red f.name}" cb null, answers # the store is a dupe... # we'll take all the item info from this store and use it to create # a new foodstuff attached to the specified store. Then, we'll # delete it. when answers.resp.indexOf('duplicate') isnt -1 do_store = (store_name) -> # find the store Store.findOne name: store_name, (err, store) -> return cb err if err if store # save the foodstuff f.stores[store._id] = price: s.item_price f.markModified "stores.#{store._id}.price" # this is magic f.save (err, user) -> return cb err if err console.log "Saved #{chalk.red f.name}" cb null else console.log "bad store. skipping for now..." cb null if answers.resp[0] is '|' store = answers.resp.split(': ')[1] do_store chalk.stripColor store.trim() else inq.prompt [ type: "input" message: "Enter the store name of the duplicate store" name: "store_id" ] , (out) -> do_store out.store_id # just delete the foodstuff, as it's just garbage when answers.resp.indexOf('junk') isnt -1 Store.remove _id: s._id, (err) -> return cb err if err console.log "Deleted junk: #{chalk.red s.name}" cb null , (err, all) -> console.log "Error", err if err console.log chalk.bold chalk.green "drumroll.... and, we are done with the stores!" # loop through the foodstuffs, and ask if they are ok or not. async.mapSeries foodstuffs, (f, cb) -> # try and find any duplicates query = for word in f.name.split ' ' name: new RegExp word, 'i' _id: $ne: f._id Foodstuff.find $or: query .exec (err, related) -> return cb err if err console.log related # get the users opinion inq.prompt [ type: "rawlist" message: """ Foodstuff: #{chalk.red "Item Name: #{f.name}"} #{chalk.green "Item Desc: #{f.desc}"} #{chalk.green "Item Tags: #{f.tags}"} #{chalk.green "Item Price: #{f.price}"} # """ name: "resp" choices: [ "Make this a new foodstuff" "Unlisted duplicate" "Totally junk" ].concat related.map (r) -> "|Really a duplicate of: #{chalk.red r.name}" ], (answers) -> switch # the foodstuff is really new.... lets verify it! when answers.resp.indexOf('new') isnt -1 inq.prompt [ type: "input" default: f.name message: "Foodstuff Name" name: "foodstuff_name" , type: "input" message: "Foodstuff Desc" name: "foodstuff_desc" default: f.desc , type: "input" message: "Foodstuff Price" name: "foodstuff_price" default: f.price , type: "input" message: "^^ At what store" name: "store" , type: "input" message: "Foodstuff Tags" name: "foodstuff_tags" default: f.tags.join ' ' ] , (out) -> # get store info Store.findOne name: out.store, (err, store) -> return cb err if err f.stores[store._id] = price: f.price # save the foodstuff f.verified = true f.name = out.foodstuff_name f.desc = out.foodstuff_desc f.image = out.foodstuff_logo f.image = out.foodstuff_tags.split ' ' f.price = undefined f.save (err) -> return cb err if err console.log "Saved #{chalk.red out.foodstuff_name}" cb null, answers # the store is a dupe... # we'll take all the item info from this store and use it to create # a new foodstuff attached to the specified store. Then, we'll # delete it. when answers.resp.indexOf('duplicate') isnt -1 do_fds = (fds_name) -> Foodstuff.findOne name: fds_name, (err, new_item) -> return cb err if err # update bag to reflect duplicate Bag.findOne user: f.user, (err, bag) -> return cb err if err # replace in the user's bag with the new item bag.contents = bag.contents.map (c) -> if c._id.toString() is f._id.toString() new_item = new_item.toObject() new_item.quantity or= 1 new_item else c bag.markModified "contents" bag.save (err) -> return cb err if err # delete the physical item, too Foodstuff.remove _id: f._id, (err) -> return cb err if err console.log "Fixed dupes: #{chalk.red f.name} -> #{chalk.red new_item.name}" cb null if answers.resp[0] is '|' store = answers.resp.split(': ')[1] do_fds chalk.stripColor store.trim() else inq.prompt [ type: "input" message: "Enter the name of the duplicate item" name: "store_id" ] , (out) -> do_fds out.store_id # just delete the foodstuff, as it's just garbage when answers.resp.indexOf('junk') isnt -1 console.log f # delete from the bag Bag.findOne user: f.user, (err, bag) -> return cb err if err # remove in the user's bag bag.contents = bag.contents.filter (c) -> c._id.toString() isnt f._id.toString() bag.markModified "contents" bag.save (err) -> return cb err if err # delete the physical item, too Foodstuff.remove _id: f._id, (err) -> return cb err if err console.log "Deleted junk: #{chalk.red f.name}" cb null , (err, data) -> return console.log err if err console.log chalk.bold chalk.cyan "drumroll.... and, we are done, like, completely!" process.exit 0
[ { "context": "e: #{new Date()}\n\nProject Ukko\nhttps://github.com/MoritzStefaner/project-ukko-os\nLicensed under Apache 2.0\n(c) by ", "end": 755, "score": 0.9578168988227844, "start": 741, "tag": "USERNAME", "value": "MoritzStefaner" }, { "context": "r/project-ukko-os\nLicensed und...
www/gulpfile.coffee
MoritzStefaner/project-ukko-os
2
gulp = require 'gulp' coffee = require 'gulp-coffee' concat = require 'gulp-concat' notify = require 'gulp-notify' sourcemaps = require 'gulp-sourcemaps' bower = require 'main-bower-files' sass = require 'gulp-sass' fileinclude = require 'gulp-file-include' replace = require 'gulp-replace-task' connect = require 'gulp-connect' del = require 'del' uglify = require 'gulp-uglify' # imagemin = require 'gulp-imagemin' sequence = require 'run-sequence' sftp = require 'gulp-sftp' bump = require 'gulp-bump' git = require 'gulp-git' Bust = require 'gulp-bust' bust = new Bust() pkg = require './package.json' banner = """ -- #{pkg.name} -- authors: #{pkg.authors} version: #{pkg.version} date: #{new Date()} Project Ukko https://github.com/MoritzStefaner/project-ukko-os Licensed under Apache 2.0 (c) by Moritz Stefaner and Dominikus Baur, 2015-2016 """ configDev = "mode": "dev" # dev|dist "target": "dev" # dev|dist "bowerDir": "bower_components" "variables": "SITE_NAME": "Project Ukko (v#{pkg.version})" "GA_ID": "_" "GA_URL": "_" "FB_APP_ID": "_" "BANNER": banner "VERSION": pkg.version configDist = "mode": "dist" # dev|dist "target": "dist" # dev|dist "bowerDir": "bower_components" "variables": "SITE_NAME": "Project Ukko — visualizing seasonal wind predictions" "GA_ID": "_" "GA_URL": "_" "FB_APP_ID": "_" "BANNER": banner "VERSION": pkg.version config = configDev onError = (err) -> notify().write err gulp.task 'sftp-deploy', ['minify'], -> gulp.src config.target + '/**/*!(.sass-cache)*' .pipe sftp host: 'starling.columba.uberspace.de' port: 22 authKey: 'key1' remotePath: "/var/www/virtual/starling/html/euporias/#{pkg.version}" gulp.src config.target + '/.htaccess' .pipe sftp host: 'starling.columba.uberspace.de' port: 22 authKey: 'key1' remotePath: "/var/www/virtual/starling/html/euporias" gulp.task 'sftp-deploy-public', ['minify'], -> gulp.src config.target + '/**/*!(.sass-cache|.htaccess)*' .pipe sftp host: 'projectukko.default.ukko.uk0.bigv.io' port: 22 authKey: 'key2' remotePath: "/srv/project-ukko.net/public/htdocs" gulp.task 'bower', -> gulp.src bower() .pipe connect.reload() .pipe concat "libs.js" .pipe gulp.dest config.target + '/js' gulp.task 'coffee', -> gulp.src ['src/coffee/main.coffee', 'src/coffee/**/!(main)*.coffee'] .pipe concat "main.js" .pipe connect.reload() .pipe sourcemaps.init() .pipe coffee bare:false .on "error", notify.onError "Error: <%= error.message %>" .pipe sourcemaps.write() .pipe gulp.dest config.target + '/js' #.pipe notify "coffee's ready!" gulp.task 'sass', -> sassStyle = "nested" sassStyle = "compressed" if config.mode == "dist" gulp.src('src/sass/**/*.sass') .pipe(sass outputStyle: sassStyle options: includePaths: [] ) .on "error", notify.onError "Error: <%= error.message %>" .pipe connect.reload() .pipe gulp.dest config.target + '/css' gulp.task 'copy', -> gulp.src ["src/assets/**/*.!(psd)", "src/assets/**/*"] .pipe gulp.dest config.target + '/assets' gulp.src "src/js/**/*" .pipe gulp.dest config.target + '/js' gulp.src "src/data/**/*" .pipe gulp.dest config.target + '/data' gulp.src "./" .pipe connect.reload() gulp.task 'includereplace', -> gulp.src ["src/**/!(_)*.html", "src/.htaccess"] .pipe fileinclude prefix: '@@' basepath: '@file' .pipe replace patterns: [ json: config.variables ] .pipe connect.reload() .pipe gulp.dest config.target + '/' gulp.task 'uglify', ['initial-build'], -> gulp.src config.target + '/js/**/*.js' .pipe uglify() .on "error", notify.onError "Error: <%= error.message %>" .pipe gulp.dest config.target + '/js' # gulp.task 'imagemin', ['initial-build'], -> # gulp.src config.target + '/assets/**/*.{png,jpg,gif}' # .pipe imagemin() # .on "error", notify.onError "Error: <%= error.message %>" # .pipe gulp.dest config.target + '/assets' gulp.task 'clean', (cb) -> del [ config.target ], cb gulp.task 'initial-build', ['clean'], (cb) -> sequence(['copy', 'includereplace', 'coffee', 'sass', 'bower'], cb) gulp.task 'connect', ['initial-build'], -> connect.server root: config.target + '/' port: 8000 livereload: true gulp.task 'watch', ['connect'], -> gulp.watch 'bower_components/**', ['bower'] gulp.watch 'src/coffee/**', ['coffee'] gulp.watch 'src/sass/**', ['sass'] gulp.watch 'src/assets/**', ['copy'] gulp.watch 'src/js/**/*', ['copy'] gulp.watch 'src/data/**', ['copy'] gulp.watch 'src/**/*.html', ['includereplace'] gulp.task 'minify', ['uglify'] # main tasks: gulp.task 'dev', -> config = configDev sequence 'watch' gulp.task 'dist', -> config = configDist sequence 'minify' gulp.task 'ftp', -> config = configDist sequence 'sftp-deploy' gulp.task 'deploy', -> config = configDist sequence 'sftp-deploy-public' gulp.task 'bump', () -> gulp.src ['./package.json', './bower.json'] .pipe bump() .pipe gulp.dest('./') gulp.task 'bump:major', () -> gulp.src ['./package.json', './bower.json'] .pipe bump type: 'major' .pipe gulp.dest('./') gulp.task 'bump:minor', () -> gulp.src ['./package.json', './bower.json'] .pipe bump type: 'minor' .pipe gulp.dest('./') gulp.task 'tag', () -> pkg = require './package.json' v = 'v' + pkg.version message = 'Release ' + v git.commit message git.tag v, message git.push 'origin', 'master', {args: '--tags'}
81126
gulp = require 'gulp' coffee = require 'gulp-coffee' concat = require 'gulp-concat' notify = require 'gulp-notify' sourcemaps = require 'gulp-sourcemaps' bower = require 'main-bower-files' sass = require 'gulp-sass' fileinclude = require 'gulp-file-include' replace = require 'gulp-replace-task' connect = require 'gulp-connect' del = require 'del' uglify = require 'gulp-uglify' # imagemin = require 'gulp-imagemin' sequence = require 'run-sequence' sftp = require 'gulp-sftp' bump = require 'gulp-bump' git = require 'gulp-git' Bust = require 'gulp-bust' bust = new Bust() pkg = require './package.json' banner = """ -- #{pkg.name} -- authors: #{pkg.authors} version: #{pkg.version} date: #{new Date()} Project Ukko https://github.com/MoritzStefaner/project-ukko-os Licensed under Apache 2.0 (c) by <NAME> and <NAME>, 2015-2016 """ configDev = "mode": "dev" # dev|dist "target": "dev" # dev|dist "bowerDir": "bower_components" "variables": "SITE_NAME": "Project Ukko (v#{pkg.version})" "GA_ID": "_" "GA_URL": "_" "FB_APP_ID": "_" "BANNER": banner "VERSION": pkg.version configDist = "mode": "dist" # dev|dist "target": "dist" # dev|dist "bowerDir": "bower_components" "variables": "SITE_NAME": "Project Ukko — visualizing seasonal wind predictions" "GA_ID": "_" "GA_URL": "_" "FB_APP_ID": "_" "BANNER": banner "VERSION": pkg.version config = configDev onError = (err) -> notify().write err gulp.task 'sftp-deploy', ['minify'], -> gulp.src config.target + '/**/*!(.sass-cache)*' .pipe sftp host: 'starling.columba.uberspace.de' port: 22 authKey: '<KEY>' remotePath: "/var/www/virtual/starling/html/euporias/#{pkg.version}" gulp.src config.target + '/.htaccess' .pipe sftp host: 'starling.columba.uberspace.de' port: 22 authKey: '<KEY>' remotePath: "/var/www/virtual/starling/html/euporias" gulp.task 'sftp-deploy-public', ['minify'], -> gulp.src config.target + '/**/*!(.sass-cache|.htaccess)*' .pipe sftp host: 'projectukko.default.ukko.uk0.bigv.io' port: 22 authKey: '<KEY>' remotePath: "/srv/project-ukko.net/public/htdocs" gulp.task 'bower', -> gulp.src bower() .pipe connect.reload() .pipe concat "libs.js" .pipe gulp.dest config.target + '/js' gulp.task 'coffee', -> gulp.src ['src/coffee/main.coffee', 'src/coffee/**/!(main)*.coffee'] .pipe concat "main.js" .pipe connect.reload() .pipe sourcemaps.init() .pipe coffee bare:false .on "error", notify.onError "Error: <%= error.message %>" .pipe sourcemaps.write() .pipe gulp.dest config.target + '/js' #.pipe notify "coffee's ready!" gulp.task 'sass', -> sassStyle = "nested" sassStyle = "compressed" if config.mode == "dist" gulp.src('src/sass/**/*.sass') .pipe(sass outputStyle: sassStyle options: includePaths: [] ) .on "error", notify.onError "Error: <%= error.message %>" .pipe connect.reload() .pipe gulp.dest config.target + '/css' gulp.task 'copy', -> gulp.src ["src/assets/**/*.!(psd)", "src/assets/**/*"] .pipe gulp.dest config.target + '/assets' gulp.src "src/js/**/*" .pipe gulp.dest config.target + '/js' gulp.src "src/data/**/*" .pipe gulp.dest config.target + '/data' gulp.src "./" .pipe connect.reload() gulp.task 'includereplace', -> gulp.src ["src/**/!(_)*.html", "src/.htaccess"] .pipe fileinclude prefix: '@@' basepath: '@file' .pipe replace patterns: [ json: config.variables ] .pipe connect.reload() .pipe gulp.dest config.target + '/' gulp.task 'uglify', ['initial-build'], -> gulp.src config.target + '/js/**/*.js' .pipe uglify() .on "error", notify.onError "Error: <%= error.message %>" .pipe gulp.dest config.target + '/js' # gulp.task 'imagemin', ['initial-build'], -> # gulp.src config.target + '/assets/**/*.{png,jpg,gif}' # .pipe imagemin() # .on "error", notify.onError "Error: <%= error.message %>" # .pipe gulp.dest config.target + '/assets' gulp.task 'clean', (cb) -> del [ config.target ], cb gulp.task 'initial-build', ['clean'], (cb) -> sequence(['copy', 'includereplace', 'coffee', 'sass', 'bower'], cb) gulp.task 'connect', ['initial-build'], -> connect.server root: config.target + '/' port: 8000 livereload: true gulp.task 'watch', ['connect'], -> gulp.watch 'bower_components/**', ['bower'] gulp.watch 'src/coffee/**', ['coffee'] gulp.watch 'src/sass/**', ['sass'] gulp.watch 'src/assets/**', ['copy'] gulp.watch 'src/js/**/*', ['copy'] gulp.watch 'src/data/**', ['copy'] gulp.watch 'src/**/*.html', ['includereplace'] gulp.task 'minify', ['uglify'] # main tasks: gulp.task 'dev', -> config = configDev sequence 'watch' gulp.task 'dist', -> config = configDist sequence 'minify' gulp.task 'ftp', -> config = configDist sequence 'sftp-deploy' gulp.task 'deploy', -> config = configDist sequence 'sftp-deploy-public' gulp.task 'bump', () -> gulp.src ['./package.json', './bower.json'] .pipe bump() .pipe gulp.dest('./') gulp.task 'bump:major', () -> gulp.src ['./package.json', './bower.json'] .pipe bump type: 'major' .pipe gulp.dest('./') gulp.task 'bump:minor', () -> gulp.src ['./package.json', './bower.json'] .pipe bump type: 'minor' .pipe gulp.dest('./') gulp.task 'tag', () -> pkg = require './package.json' v = 'v' + pkg.version message = 'Release ' + v git.commit message git.tag v, message git.push 'origin', 'master', {args: '--tags'}
true
gulp = require 'gulp' coffee = require 'gulp-coffee' concat = require 'gulp-concat' notify = require 'gulp-notify' sourcemaps = require 'gulp-sourcemaps' bower = require 'main-bower-files' sass = require 'gulp-sass' fileinclude = require 'gulp-file-include' replace = require 'gulp-replace-task' connect = require 'gulp-connect' del = require 'del' uglify = require 'gulp-uglify' # imagemin = require 'gulp-imagemin' sequence = require 'run-sequence' sftp = require 'gulp-sftp' bump = require 'gulp-bump' git = require 'gulp-git' Bust = require 'gulp-bust' bust = new Bust() pkg = require './package.json' banner = """ -- #{pkg.name} -- authors: #{pkg.authors} version: #{pkg.version} date: #{new Date()} Project Ukko https://github.com/MoritzStefaner/project-ukko-os Licensed under Apache 2.0 (c) by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI, 2015-2016 """ configDev = "mode": "dev" # dev|dist "target": "dev" # dev|dist "bowerDir": "bower_components" "variables": "SITE_NAME": "Project Ukko (v#{pkg.version})" "GA_ID": "_" "GA_URL": "_" "FB_APP_ID": "_" "BANNER": banner "VERSION": pkg.version configDist = "mode": "dist" # dev|dist "target": "dist" # dev|dist "bowerDir": "bower_components" "variables": "SITE_NAME": "Project Ukko — visualizing seasonal wind predictions" "GA_ID": "_" "GA_URL": "_" "FB_APP_ID": "_" "BANNER": banner "VERSION": pkg.version config = configDev onError = (err) -> notify().write err gulp.task 'sftp-deploy', ['minify'], -> gulp.src config.target + '/**/*!(.sass-cache)*' .pipe sftp host: 'starling.columba.uberspace.de' port: 22 authKey: 'PI:KEY:<KEY>END_PI' remotePath: "/var/www/virtual/starling/html/euporias/#{pkg.version}" gulp.src config.target + '/.htaccess' .pipe sftp host: 'starling.columba.uberspace.de' port: 22 authKey: 'PI:KEY:<KEY>END_PI' remotePath: "/var/www/virtual/starling/html/euporias" gulp.task 'sftp-deploy-public', ['minify'], -> gulp.src config.target + '/**/*!(.sass-cache|.htaccess)*' .pipe sftp host: 'projectukko.default.ukko.uk0.bigv.io' port: 22 authKey: 'PI:KEY:<KEY>END_PI' remotePath: "/srv/project-ukko.net/public/htdocs" gulp.task 'bower', -> gulp.src bower() .pipe connect.reload() .pipe concat "libs.js" .pipe gulp.dest config.target + '/js' gulp.task 'coffee', -> gulp.src ['src/coffee/main.coffee', 'src/coffee/**/!(main)*.coffee'] .pipe concat "main.js" .pipe connect.reload() .pipe sourcemaps.init() .pipe coffee bare:false .on "error", notify.onError "Error: <%= error.message %>" .pipe sourcemaps.write() .pipe gulp.dest config.target + '/js' #.pipe notify "coffee's ready!" gulp.task 'sass', -> sassStyle = "nested" sassStyle = "compressed" if config.mode == "dist" gulp.src('src/sass/**/*.sass') .pipe(sass outputStyle: sassStyle options: includePaths: [] ) .on "error", notify.onError "Error: <%= error.message %>" .pipe connect.reload() .pipe gulp.dest config.target + '/css' gulp.task 'copy', -> gulp.src ["src/assets/**/*.!(psd)", "src/assets/**/*"] .pipe gulp.dest config.target + '/assets' gulp.src "src/js/**/*" .pipe gulp.dest config.target + '/js' gulp.src "src/data/**/*" .pipe gulp.dest config.target + '/data' gulp.src "./" .pipe connect.reload() gulp.task 'includereplace', -> gulp.src ["src/**/!(_)*.html", "src/.htaccess"] .pipe fileinclude prefix: '@@' basepath: '@file' .pipe replace patterns: [ json: config.variables ] .pipe connect.reload() .pipe gulp.dest config.target + '/' gulp.task 'uglify', ['initial-build'], -> gulp.src config.target + '/js/**/*.js' .pipe uglify() .on "error", notify.onError "Error: <%= error.message %>" .pipe gulp.dest config.target + '/js' # gulp.task 'imagemin', ['initial-build'], -> # gulp.src config.target + '/assets/**/*.{png,jpg,gif}' # .pipe imagemin() # .on "error", notify.onError "Error: <%= error.message %>" # .pipe gulp.dest config.target + '/assets' gulp.task 'clean', (cb) -> del [ config.target ], cb gulp.task 'initial-build', ['clean'], (cb) -> sequence(['copy', 'includereplace', 'coffee', 'sass', 'bower'], cb) gulp.task 'connect', ['initial-build'], -> connect.server root: config.target + '/' port: 8000 livereload: true gulp.task 'watch', ['connect'], -> gulp.watch 'bower_components/**', ['bower'] gulp.watch 'src/coffee/**', ['coffee'] gulp.watch 'src/sass/**', ['sass'] gulp.watch 'src/assets/**', ['copy'] gulp.watch 'src/js/**/*', ['copy'] gulp.watch 'src/data/**', ['copy'] gulp.watch 'src/**/*.html', ['includereplace'] gulp.task 'minify', ['uglify'] # main tasks: gulp.task 'dev', -> config = configDev sequence 'watch' gulp.task 'dist', -> config = configDist sequence 'minify' gulp.task 'ftp', -> config = configDist sequence 'sftp-deploy' gulp.task 'deploy', -> config = configDist sequence 'sftp-deploy-public' gulp.task 'bump', () -> gulp.src ['./package.json', './bower.json'] .pipe bump() .pipe gulp.dest('./') gulp.task 'bump:major', () -> gulp.src ['./package.json', './bower.json'] .pipe bump type: 'major' .pipe gulp.dest('./') gulp.task 'bump:minor', () -> gulp.src ['./package.json', './bower.json'] .pipe bump type: 'minor' .pipe gulp.dest('./') gulp.task 'tag', () -> pkg = require './package.json' v = 'v' + pkg.version message = 'Release ' + v git.commit message git.tag v, message git.push 'origin', 'master', {args: '--tags'}
[ { "context": " TODO fix on travis\n\n###\n\nuserData = {\n email: 'teacher@example.com'\n password: 'password'\n password_confirmation: ", "end": 90, "score": 0.999911904335022, "start": 71, "tag": "EMAIL", "value": "teacher@example.com" }, { "context": "a = {\n email: 'teacher@...
test/spec/integration/profile/signup_test.coffee
JulianMiller/opened.io
1
### Sign up tests TODO fix on travis ### userData = { email: 'teacher@example.com' password: 'password' password_confirmation: 'password' first_name: 'John' last_name: 'Bull' } password = '.ts-signup-password' passwordConfirmation = '.ts-signup-password' email = '.ts-signup-email' firstName = '.ts-signup-firstName' lastName = '.ts-signup-lastName' classCode = '.ts-signup-code' button = '.ts-signup-signupButton' profileLink = '.ts-profileButton' module 'Sign up', setup: -> Em.run -> Openedui.reset() Openedui.deferReadiness() # teardown: -> # $.mockjaxClear() # localStorage.clear() # Ember.testing = false test 'We got inputs for email and password', -> expect(5) Ember.run Openedui, 'advanceReadiness' visit('/profile/signup').then(-> passwordInput = find(password) passwordConfirmationInput = find(passwordConfirmation) emailInput = find(email) firstNameInput = find(firstName) lastNameInput = find(lastName) equal(passwordInput.length, 1, 'We have password field') equal(passwordConfirmationInput.length, 1, 'We have password confirmation field') equal(emailInput.length, 1, 'We have email field') equal(firstNameInput.length, 1, 'We have last name field') equal(lastNameInput.length, 1, 'We have first name field') ) test 'Sign up with correct user info', -> expect(3) #response = {"api_key":{"id":15,"access_token":"0616cc104f34c9f4012d07abfa04a154","user_id":1, "role": "teacher"}} #stubEndpointForHttpRequest(API.url.signup(), response, 'POST') Ember.run Openedui, 'advanceReadiness' visit('/profile/signup').then( -> equal($(button).length, 1 , 'See submit button') ok(!Openedui.session.apiKey, "session not opened") equal($(profileLink).length, 0, 'Dont see profile button') #fillIn password, userData.password #fillIn passwordConfirmation, userData.password_confirmation #fillIn(email, userData.email) #fillIn firstName, userData.first_name #fillIn lastName, userData.last_name #click(button) ).then(-> # dont use 'mising' as a assertion, its kind of weird #ok(Openedui.session.apiKey, "session was opened") #equal Openedui.session.get("apiKey.user.id"), 1, "user_id is 1" #equal($(button).length, 0 , 'We moved away from sign up page') #equal($(profileLink).length, 1, 'see profile button') ) #test 'Sign in with wrong credentials', -> # expect(3) # # $.mockjax # url: API.url.signup() # dataType: 'json', # responseText: '{"errors":"Password doesn\'t match confirmation"}', # proxyType: "POST" # status: 422 # # visit('/profile/signup').then( -> # fillIn password, userData.password # fillIn passwordConfirmation, 'passwd' # fillIn(email, userData.email) # fillIn firstName, userData.first_name # fillIn lastName, userData.last_name # # click(button) # ).then(-> # # dont use 'mising' as a assertion, its kind of weird # equal($(button).length, 1 , 'We stay on sign up page') # equal($(".alert-error").text(), "Password doesn\'t match confirmation", 'See an error message') # ok(!Openedui.session.apiKey, "session not opened") # )
147621
### Sign up tests TODO fix on travis ### userData = { email: '<EMAIL>' password: '<PASSWORD>' password_confirmation: '<PASSWORD>' first_name: '<NAME>' last_name: '<NAME>' } password = <PASSWORD>' passwordConfirmation = <PASSWORD>' email = '.ts-signup-email' firstName = '.ts-signup-firstName' lastName = '.ts-signup-lastName' classCode = '.ts-signup-code' button = '.ts-signup-signupButton' profileLink = '.ts-profileButton' module 'Sign up', setup: -> Em.run -> Openedui.reset() Openedui.deferReadiness() # teardown: -> # $.mockjaxClear() # localStorage.clear() # Ember.testing = false test 'We got inputs for email and password', -> expect(5) Ember.run Openedui, 'advanceReadiness' visit('/profile/signup').then(-> passwordInput = find(password) passwordConfirmationInput = find(passwordConfirmation) emailInput = find(email) firstNameInput = find(firstName) lastNameInput = find(lastName) equal(passwordInput.length, 1, 'We have password field') equal(passwordConfirmationInput.length, 1, 'We have password confirmation field') equal(emailInput.length, 1, 'We have email field') equal(firstNameInput.length, 1, 'We have last name field') equal(lastNameInput.length, 1, 'We have first name field') ) test 'Sign up with correct user info', -> expect(3) #response = {"api_key":{"id":15,"access_token":"<KEY>","user_id":1, "role": "teacher"}} #stubEndpointForHttpRequest(API.url.signup(), response, 'POST') Ember.run Openedui, 'advanceReadiness' visit('/profile/signup').then( -> equal($(button).length, 1 , 'See submit button') ok(!Openedui.session.apiKey, "session not opened") equal($(profileLink).length, 0, 'Dont see profile button') #fillIn password, <PASSWORD> #fillIn passwordConfirmation, userData.password_confirmation #fillIn(email, userData.email) #fillIn firstName, userData.first_name #fillIn lastName, userData.last_name #click(button) ).then(-> # dont use 'mising' as a assertion, its kind of weird #ok(Openedui.session.apiKey, "session was opened") #equal Openedui.session.get("apiKey.user.id"), 1, "user_id is 1" #equal($(button).length, 0 , 'We moved away from sign up page') #equal($(profileLink).length, 1, 'see profile button') ) #test 'Sign in with wrong credentials', -> # expect(3) # # $.mockjax # url: API.url.signup() # dataType: 'json', # responseText: '{"errors":"Password doesn\'t match confirmation"}', # proxyType: "POST" # status: 422 # # visit('/profile/signup').then( -> # fillIn password, <PASSWORD> # fillIn passwordConfirmation, '<PASSWORD>' # fillIn(email, userData.email) # fillIn firstName, userData.first_name # fillIn lastName, userData.last_name # # click(button) # ).then(-> # # dont use 'mising' as a assertion, its kind of weird # equal($(button).length, 1 , 'We stay on sign up page') # equal($(".alert-error").text(), "Password doesn\'t match confirmation", 'See an error message') # ok(!Openedui.session.apiKey, "session not opened") # )
true
### Sign up tests TODO fix on travis ### userData = { email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' password_confirmation: 'PI:PASSWORD:<PASSWORD>END_PI' first_name: 'PI:NAME:<NAME>END_PI' last_name: 'PI:NAME:<NAME>END_PI' } password = PI:PASSWORD:<PASSWORD>END_PI' passwordConfirmation = PI:PASSWORD:<PASSWORD>END_PI' email = '.ts-signup-email' firstName = '.ts-signup-firstName' lastName = '.ts-signup-lastName' classCode = '.ts-signup-code' button = '.ts-signup-signupButton' profileLink = '.ts-profileButton' module 'Sign up', setup: -> Em.run -> Openedui.reset() Openedui.deferReadiness() # teardown: -> # $.mockjaxClear() # localStorage.clear() # Ember.testing = false test 'We got inputs for email and password', -> expect(5) Ember.run Openedui, 'advanceReadiness' visit('/profile/signup').then(-> passwordInput = find(password) passwordConfirmationInput = find(passwordConfirmation) emailInput = find(email) firstNameInput = find(firstName) lastNameInput = find(lastName) equal(passwordInput.length, 1, 'We have password field') equal(passwordConfirmationInput.length, 1, 'We have password confirmation field') equal(emailInput.length, 1, 'We have email field') equal(firstNameInput.length, 1, 'We have last name field') equal(lastNameInput.length, 1, 'We have first name field') ) test 'Sign up with correct user info', -> expect(3) #response = {"api_key":{"id":15,"access_token":"PI:KEY:<KEY>END_PI","user_id":1, "role": "teacher"}} #stubEndpointForHttpRequest(API.url.signup(), response, 'POST') Ember.run Openedui, 'advanceReadiness' visit('/profile/signup').then( -> equal($(button).length, 1 , 'See submit button') ok(!Openedui.session.apiKey, "session not opened") equal($(profileLink).length, 0, 'Dont see profile button') #fillIn password, PI:PASSWORD:<PASSWORD>END_PI #fillIn passwordConfirmation, userData.password_confirmation #fillIn(email, userData.email) #fillIn firstName, userData.first_name #fillIn lastName, userData.last_name #click(button) ).then(-> # dont use 'mising' as a assertion, its kind of weird #ok(Openedui.session.apiKey, "session was opened") #equal Openedui.session.get("apiKey.user.id"), 1, "user_id is 1" #equal($(button).length, 0 , 'We moved away from sign up page') #equal($(profileLink).length, 1, 'see profile button') ) #test 'Sign in with wrong credentials', -> # expect(3) # # $.mockjax # url: API.url.signup() # dataType: 'json', # responseText: '{"errors":"Password doesn\'t match confirmation"}', # proxyType: "POST" # status: 422 # # visit('/profile/signup').then( -> # fillIn password, PI:PASSWORD:<PASSWORD>END_PI # fillIn passwordConfirmation, 'PI:PASSWORD:<PASSWORD>END_PI' # fillIn(email, userData.email) # fillIn firstName, userData.first_name # fillIn lastName, userData.last_name # # click(button) # ).then(-> # # dont use 'mising' as a assertion, its kind of weird # equal($(button).length, 1 , 'We stay on sign up page') # equal($(".alert-error").text(), "Password doesn\'t match confirmation", 'See an error message') # ok(!Openedui.session.apiKey, "session not opened") # )
[ { "context": "ess.env.DB_USER ? 'postgres'\n password: process.env.DB_PASSWORD\n database: process.env.DB ? 'gc'\n\n ", "end": 1641, "score": 0.9446917772293091, "start": 1618, "tag": "PASSWORD", "value": "process.env.DB_PASSWORD" }, { "context": " type:...
storage/test/integration-geocaches.coffee
foobert/gc
1
{expect} = require 'chai' Promise = require 'bluebird' request = require 'superagent-as-promised' access = require '../lib/access' geocacheService = require '../lib/geocache' describe 'REST routes for geocaches', -> @timeout 5000 db = null token = null url = null setupTestData = Promise.coroutine (geocaches) -> geocaches = JSON.parse JSON.stringify geocaches g = geocacheService db yield g.deleteAll() for geocache in geocaches yield g.upsert geocache yield g.forceRefresh() gc = (id, options) -> defaults = Code: "GC#{id}" Name: 'geocache name' Latitude: 10 Longitude: 20 Terrain: 1 Difficulty: 1 Archived: false Available: true CacheType: GeocacheTypeId: 2 ContainerType: ContainerTypeName: 'Micro' UTCPlaceDate: "/Date(#{new Date().getTime()}-0000)/" EncodedHints: 'some hints' merge = (a, b) -> return a unless b? for k, v of b if typeof v is 'object' a[k] = {} unless a[k]? merge a[k], v else a[k] = v a merge defaults, options before Promise.coroutine -> url = "http://#{process.env.APP_PORT_8081_TCP_ADDR}:#{process.env.APP_PORT_8081_TCP_PORT}" db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: process.env.DB_PASSWORD database: process.env.DB ? 'gc' a = access db token = yield a.getToken() tries = 5 appRunning = false while tries-- > 0 try response = yield request.get url if response.status is 200 console.log "found app at #{url}" appRunning = true break yield Promise.delay 1000 catch err yield Promise.delay 1000 if not appRunning throw new Error "App is not running at #{url}" beforeEach Promise.coroutine -> yield setupTestData [] describe '/gcs', -> it 'should return a list of GC numbers on GET', Promise.coroutine -> yield setupTestData [ gc '100' gc '101' ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC101'] it 'should filter by age using "maxAge"', Promise.coroutine -> yield setupTestData [ gc '100', UTCPlaceDate: "/Date(#{new Date().getTime()}-0000)/" gc '101', UTCPlaceDate: '/Date(00946684800-0000)/' ] response = yield request .get "#{url}/gcs" .query maxAge: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should filter by coordinates using "bounds"', Promise.coroutine -> yield setupTestData [ gc '100', Latitude: 10 Longitude: 10 gc '101', Latitude: 10 Longitude: 11 gc '102', Latitude: 11 Longitude: 10 gc '103', Latitude: 11 Longitude: 11 ] response = yield request .get "#{url}/gcs" .query bounds: [9.5, 9.5, 10.5, 10.5] .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should filter by type id using "typeIds"', Promise.coroutine -> yield setupTestData [ gc '100', CacheType: GeocacheTypeId: 5 gc '101', CacheType: GeocacheTypeId: 6 gc '102', CacheType: GeocacheTypeId: 7 ] response = yield request .get "#{url}/gcs" .query typeIds: [5, 7] .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC102'] it 'should filter disabled/archived geocaches using "excludeDisabled"', Promise.coroutine -> yield setupTestData [ gc '100', Archived: false Available: false gc '101', Archived: false Available: true gc '102', Archived: true Available: false gc '103', Archived: true Available: true ] response = yield request .get "#{url}/gcs" .query excludeDisabled: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC101'] it 'should return disabled/archived geocaches by default', Promise.coroutine -> yield setupTestData [ gc '100', Archived: false Available: false gc '101', Archived: false Available: true gc '102', Archived: true Available: false gc '103', Archived: true Available: true ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 4 expect(response.body).to.include.members ['GC100', 'GC101', 'GC102', 'GC103'] it 'should filter stale geocaches by default', Promise.coroutine -> yield setupTestData [ gc '100', meta: updated: new Date().toISOString() gc '101', meta: updated: '2000-01-01 00:00:00Z' ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should return stale geocaches when "stale" is 1', Promise.coroutine -> yield setupTestData [ gc '100', meta: updated: new Date().toISOString() gc '101', meta: updated: '2000-01-01 00:00:00Z' ] response = yield request .get "#{url}/gcs" .query stale: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC101'] describe '/geocaches', -> it 'should return a list of geocaches on GET', Promise.coroutine -> a = gc '100' b = gc '101' yield setupTestData [a, b] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body.map (gc) -> gc.Code).to.deep.equal ['GC100', 'GC101'] [ name: 'Code' type: 'String' , name: 'Name' type: 'String' , name: 'Terrain' type: 'Number' , name: 'Difficulty' type: 'Number' , name: 'Archived' type: 'Boolean' , name: 'UTCPlaceDate' type: 'String' ].forEach ({name, type}) -> it "should include field #{name} of type #{type}", Promise.coroutine -> a = gc '100' yield setupTestData [a] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' [result] = response.body expect(result[name]).to.exist expect(result[name]).to.be.a type it 'should include the update timestamp', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() yield setupTestData [a] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' [result] = response.body expect(result.meta.updated).to.equal a.meta.updated it 'should create new geocaches on POST', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a getResponse = yield request .get "#{url}/geocache/GC100" .set 'Accept', 'application/json' expect(putResponse.status).to.equal 201 expect(getResponse.status).to.equal 200 it 'should should reject POSTs without a valid API key', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() try putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .set 'X-Token', 'invalid' .send a catch err # expected expect(err.status).to.equal 403 getResponse = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(getResponse.body).to.deep.equal [] it 'should should reject POSTs with a missing API key', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() try putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .send a catch err # expected expect(err.status).to.equal 403 getResponse = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(getResponse.body).to.deep.equal []
13059
{expect} = require 'chai' Promise = require 'bluebird' request = require 'superagent-as-promised' access = require '../lib/access' geocacheService = require '../lib/geocache' describe 'REST routes for geocaches', -> @timeout 5000 db = null token = null url = null setupTestData = Promise.coroutine (geocaches) -> geocaches = JSON.parse JSON.stringify geocaches g = geocacheService db yield g.deleteAll() for geocache in geocaches yield g.upsert geocache yield g.forceRefresh() gc = (id, options) -> defaults = Code: "GC#{id}" Name: 'geocache name' Latitude: 10 Longitude: 20 Terrain: 1 Difficulty: 1 Archived: false Available: true CacheType: GeocacheTypeId: 2 ContainerType: ContainerTypeName: 'Micro' UTCPlaceDate: "/Date(#{new Date().getTime()}-0000)/" EncodedHints: 'some hints' merge = (a, b) -> return a unless b? for k, v of b if typeof v is 'object' a[k] = {} unless a[k]? merge a[k], v else a[k] = v a merge defaults, options before Promise.coroutine -> url = "http://#{process.env.APP_PORT_8081_TCP_ADDR}:#{process.env.APP_PORT_8081_TCP_PORT}" db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: <PASSWORD> database: process.env.DB ? 'gc' a = access db token = yield a.getToken() tries = 5 appRunning = false while tries-- > 0 try response = yield request.get url if response.status is 200 console.log "found app at #{url}" appRunning = true break yield Promise.delay 1000 catch err yield Promise.delay 1000 if not appRunning throw new Error "App is not running at #{url}" beforeEach Promise.coroutine -> yield setupTestData [] describe '/gcs', -> it 'should return a list of GC numbers on GET', Promise.coroutine -> yield setupTestData [ gc '100' gc '101' ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC101'] it 'should filter by age using "maxAge"', Promise.coroutine -> yield setupTestData [ gc '100', UTCPlaceDate: "/Date(#{new Date().getTime()}-0000)/" gc '101', UTCPlaceDate: '/Date(00946684800-0000)/' ] response = yield request .get "#{url}/gcs" .query maxAge: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should filter by coordinates using "bounds"', Promise.coroutine -> yield setupTestData [ gc '100', Latitude: 10 Longitude: 10 gc '101', Latitude: 10 Longitude: 11 gc '102', Latitude: 11 Longitude: 10 gc '103', Latitude: 11 Longitude: 11 ] response = yield request .get "#{url}/gcs" .query bounds: [9.5, 9.5, 10.5, 10.5] .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should filter by type id using "typeIds"', Promise.coroutine -> yield setupTestData [ gc '100', CacheType: GeocacheTypeId: 5 gc '101', CacheType: GeocacheTypeId: 6 gc '102', CacheType: GeocacheTypeId: 7 ] response = yield request .get "#{url}/gcs" .query typeIds: [5, 7] .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC102'] it 'should filter disabled/archived geocaches using "excludeDisabled"', Promise.coroutine -> yield setupTestData [ gc '100', Archived: false Available: false gc '101', Archived: false Available: true gc '102', Archived: true Available: false gc '103', Archived: true Available: true ] response = yield request .get "#{url}/gcs" .query excludeDisabled: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC101'] it 'should return disabled/archived geocaches by default', Promise.coroutine -> yield setupTestData [ gc '100', Archived: false Available: false gc '101', Archived: false Available: true gc '102', Archived: true Available: false gc '103', Archived: true Available: true ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 4 expect(response.body).to.include.members ['GC100', 'GC101', 'GC102', 'GC103'] it 'should filter stale geocaches by default', Promise.coroutine -> yield setupTestData [ gc '100', meta: updated: new Date().toISOString() gc '101', meta: updated: '2000-01-01 00:00:00Z' ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should return stale geocaches when "stale" is 1', Promise.coroutine -> yield setupTestData [ gc '100', meta: updated: new Date().toISOString() gc '101', meta: updated: '2000-01-01 00:00:00Z' ] response = yield request .get "#{url}/gcs" .query stale: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC101'] describe '/geocaches', -> it 'should return a list of geocaches on GET', Promise.coroutine -> a = gc '100' b = gc '101' yield setupTestData [a, b] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body.map (gc) -> gc.Code).to.deep.equal ['GC100', 'GC101'] [ name: 'Code' type: 'String' , name: '<NAME>' type: 'String' , name: 'Terrain' type: 'Number' , name: 'Difficulty' type: 'Number' , name: 'Archived' type: 'Boolean' , name: 'UTCPlaceDate' type: 'String' ].forEach ({name, type}) -> it "should include field #{name} of type #{type}", Promise.coroutine -> a = gc '100' yield setupTestData [a] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' [result] = response.body expect(result[name]).to.exist expect(result[name]).to.be.a type it 'should include the update timestamp', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() yield setupTestData [a] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' [result] = response.body expect(result.meta.updated).to.equal a.meta.updated it 'should create new geocaches on POST', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a getResponse = yield request .get "#{url}/geocache/GC100" .set 'Accept', 'application/json' expect(putResponse.status).to.equal 201 expect(getResponse.status).to.equal 200 it 'should should reject POSTs without a valid API key', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() try putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .set 'X-Token', 'invalid' .send a catch err # expected expect(err.status).to.equal 403 getResponse = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(getResponse.body).to.deep.equal [] it 'should should reject POSTs with a missing API key', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() try putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .send a catch err # expected expect(err.status).to.equal 403 getResponse = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(getResponse.body).to.deep.equal []
true
{expect} = require 'chai' Promise = require 'bluebird' request = require 'superagent-as-promised' access = require '../lib/access' geocacheService = require '../lib/geocache' describe 'REST routes for geocaches', -> @timeout 5000 db = null token = null url = null setupTestData = Promise.coroutine (geocaches) -> geocaches = JSON.parse JSON.stringify geocaches g = geocacheService db yield g.deleteAll() for geocache in geocaches yield g.upsert geocache yield g.forceRefresh() gc = (id, options) -> defaults = Code: "GC#{id}" Name: 'geocache name' Latitude: 10 Longitude: 20 Terrain: 1 Difficulty: 1 Archived: false Available: true CacheType: GeocacheTypeId: 2 ContainerType: ContainerTypeName: 'Micro' UTCPlaceDate: "/Date(#{new Date().getTime()}-0000)/" EncodedHints: 'some hints' merge = (a, b) -> return a unless b? for k, v of b if typeof v is 'object' a[k] = {} unless a[k]? merge a[k], v else a[k] = v a merge defaults, options before Promise.coroutine -> url = "http://#{process.env.APP_PORT_8081_TCP_ADDR}:#{process.env.APP_PORT_8081_TCP_PORT}" db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: PI:PASSWORD:<PASSWORD>END_PI database: process.env.DB ? 'gc' a = access db token = yield a.getToken() tries = 5 appRunning = false while tries-- > 0 try response = yield request.get url if response.status is 200 console.log "found app at #{url}" appRunning = true break yield Promise.delay 1000 catch err yield Promise.delay 1000 if not appRunning throw new Error "App is not running at #{url}" beforeEach Promise.coroutine -> yield setupTestData [] describe '/gcs', -> it 'should return a list of GC numbers on GET', Promise.coroutine -> yield setupTestData [ gc '100' gc '101' ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC101'] it 'should filter by age using "maxAge"', Promise.coroutine -> yield setupTestData [ gc '100', UTCPlaceDate: "/Date(#{new Date().getTime()}-0000)/" gc '101', UTCPlaceDate: '/Date(00946684800-0000)/' ] response = yield request .get "#{url}/gcs" .query maxAge: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should filter by coordinates using "bounds"', Promise.coroutine -> yield setupTestData [ gc '100', Latitude: 10 Longitude: 10 gc '101', Latitude: 10 Longitude: 11 gc '102', Latitude: 11 Longitude: 10 gc '103', Latitude: 11 Longitude: 11 ] response = yield request .get "#{url}/gcs" .query bounds: [9.5, 9.5, 10.5, 10.5] .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should filter by type id using "typeIds"', Promise.coroutine -> yield setupTestData [ gc '100', CacheType: GeocacheTypeId: 5 gc '101', CacheType: GeocacheTypeId: 6 gc '102', CacheType: GeocacheTypeId: 7 ] response = yield request .get "#{url}/gcs" .query typeIds: [5, 7] .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC102'] it 'should filter disabled/archived geocaches using "excludeDisabled"', Promise.coroutine -> yield setupTestData [ gc '100', Archived: false Available: false gc '101', Archived: false Available: true gc '102', Archived: true Available: false gc '103', Archived: true Available: true ] response = yield request .get "#{url}/gcs" .query excludeDisabled: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC101'] it 'should return disabled/archived geocaches by default', Promise.coroutine -> yield setupTestData [ gc '100', Archived: false Available: false gc '101', Archived: false Available: true gc '102', Archived: true Available: false gc '103', Archived: true Available: true ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 4 expect(response.body).to.include.members ['GC100', 'GC101', 'GC102', 'GC103'] it 'should filter stale geocaches by default', Promise.coroutine -> yield setupTestData [ gc '100', meta: updated: new Date().toISOString() gc '101', meta: updated: '2000-01-01 00:00:00Z' ] response = yield request .get "#{url}/gcs" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 1 expect(response.body).to.include.members ['GC100'] it 'should return stale geocaches when "stale" is 1', Promise.coroutine -> yield setupTestData [ gc '100', meta: updated: new Date().toISOString() gc '101', meta: updated: '2000-01-01 00:00:00Z' ] response = yield request .get "#{url}/gcs" .query stale: 1 .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body).to.include.members ['GC100', 'GC101'] describe '/geocaches', -> it 'should return a list of geocaches on GET', Promise.coroutine -> a = gc '100' b = gc '101' yield setupTestData [a, b] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(response.type).to.equal 'application/json' expect(response.body.length).to.equal 2 expect(response.body.map (gc) -> gc.Code).to.deep.equal ['GC100', 'GC101'] [ name: 'Code' type: 'String' , name: 'PI:NAME:<NAME>END_PI' type: 'String' , name: 'Terrain' type: 'Number' , name: 'Difficulty' type: 'Number' , name: 'Archived' type: 'Boolean' , name: 'UTCPlaceDate' type: 'String' ].forEach ({name, type}) -> it "should include field #{name} of type #{type}", Promise.coroutine -> a = gc '100' yield setupTestData [a] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' [result] = response.body expect(result[name]).to.exist expect(result[name]).to.be.a type it 'should include the update timestamp', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() yield setupTestData [a] response = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' [result] = response.body expect(result.meta.updated).to.equal a.meta.updated it 'should create new geocaches on POST', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a getResponse = yield request .get "#{url}/geocache/GC100" .set 'Accept', 'application/json' expect(putResponse.status).to.equal 201 expect(getResponse.status).to.equal 200 it 'should should reject POSTs without a valid API key', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() try putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .set 'X-Token', 'invalid' .send a catch err # expected expect(err.status).to.equal 403 getResponse = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(getResponse.body).to.deep.equal [] it 'should should reject POSTs with a missing API key', Promise.coroutine -> a = gc '100', meta: updated: new Date().toISOString() try putResponse = yield request .post "#{url}/geocache" .set 'Content-Type', 'application/json' .send a catch err # expected expect(err.status).to.equal 403 getResponse = yield request .get "#{url}/geocaches" .set 'Accept', 'application/json' expect(getResponse.body).to.deep.equal []
[ { "context": ".1:9999/test/tests.html'\n ]\n username: 'goldinteractive-open'\n key: 'bb3f9f3e-8dac-43bd-823f-16f7d998fe16", "end": 164, "score": 0.999646008014679, "start": 144, "tag": "USERNAME", "value": "goldinteractive-open" }, { "context": " username: 'goldin...
grunt/saucelabs-mocha.coffee
hrishiranjan/Grid
0
module.exports = (grunt, options) => all: options: urls: [ 'http://127.0.0.1:9999/test/tests.html' ] username: 'goldinteractive-open' key: 'bb3f9f3e-8dac-43bd-823f-16f7d998fe16' browsers: grunt.file.readJSON('test/saucelabs-browsers.json') build: process.env.TRAVIS_JOB_ID testname: 'jQuery.GI.TheWall.js' sauceConfig: 'video-upload-on-pass': false
67232
module.exports = (grunt, options) => all: options: urls: [ 'http://127.0.0.1:9999/test/tests.html' ] username: 'goldinteractive-open' key: '<KEY>' browsers: grunt.file.readJSON('test/saucelabs-browsers.json') build: process.env.TRAVIS_JOB_ID testname: 'jQuery.GI.TheWall.js' sauceConfig: 'video-upload-on-pass': false
true
module.exports = (grunt, options) => all: options: urls: [ 'http://127.0.0.1:9999/test/tests.html' ] username: 'goldinteractive-open' key: 'PI:KEY:<KEY>END_PI' browsers: grunt.file.readJSON('test/saucelabs-browsers.json') build: process.env.TRAVIS_JOB_ID testname: 'jQuery.GI.TheWall.js' sauceConfig: 'video-upload-on-pass': false
[ { "context": "/register\"\n\t\t\tjson:\n\t\t\t\temail: email\n\t\t\t\tpassword: password\n\t\t}, callback\n\n\ndescribe \"LoginRateLimit\", ->\n\n\tb", "end": 1074, "score": 0.9952285885810852, "start": 1066, "tag": "PASSWORD", "value": "password" }, { "context": ">\n\n\tbefore ->\n\...
test/acceptance/coffee/RegistrationTests.coffee
shyoshyo/web-sharelatex
1
expect = require("chai").expect assert = require("chai").assert async = require("async") User = require "./helpers/User" request = require "./helpers/request" settings = require "settings-sharelatex" redis = require "./helpers/redis" _ = require 'lodash' # Currently this is testing registration via the 'public-registration' module, # whereas in production we're using the 'overleaf-integration' module. # Expectations expectProjectAccess = (user, projectId, callback=(err,result)->) -> # should have access to project user.openProject projectId, (err) => expect(err).to.be.oneOf [null, undefined] callback() expectNoProjectAccess = (user, projectId, callback=(err,result)->) -> # should not have access to project page user.openProject projectId, (err) => expect(err).to.be.instanceof Error callback() # Actions tryLoginThroughRegistrationForm = (user, email, password, callback=(err, response, body)->) -> user.getCsrfToken (err) -> return callback(err) if err? user.request.post { url: "/register" json: email: email password: password }, callback describe "LoginRateLimit", -> before -> @user = new User() @badEmail = 'bademail@example.com' @badPassword = 'badpassword' it 'should rate limit login attempts after 10 within two minutes', (done) -> @user.request.get '/login', (err, res, body) => async.timesSeries( 15 , (n, cb) => @user.getCsrfToken (error) => return cb(error) if error? @user.request.post { url: "/login" json: email: @badEmail password: @badPassword }, (err, response, body) => cb(null, body?.message?.text) , (err, results) => # ten incorrect-credentials messages, then five rate-limit messages expect(results.length).to.equal 15 assert.deepEqual( results, _.concat( _.fill([1..10], 'Your email or password is incorrect. Please try again'), _.fill([1..5], 'This account has had too many login requests. Please wait 2 minutes before trying to log in again') ) ) done() ) describe "CSRF protection", -> beforeEach -> @user = new User() @email = "test+#{Math.random()}@example.com" @password = "password11" afterEach -> @user.full_delete_user(@email) it 'should register with the csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => @user.request.post { url: "/register" json: email: @email password: @password headers:{ "x-csrf-token": @user.csrfToken } }, (error, response, body) => expect(err?).to.equal false expect(response.statusCode).to.equal 200 done() it 'should fail with no csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => @user.request.post { url: "/register" json: email: @email password: @password headers:{ "x-csrf-token": "" } }, (error, response, body) => expect(response.statusCode).to.equal 403 done() it 'should fail with a stale csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => oldCsrfToken = @user.csrfToken @user.logout (err) => @user.request.post { url: "/register" json: email: @email password: @password headers:{ "x-csrf-token": oldCsrfToken } }, (error, response, body) => expect(response.statusCode).to.equal 403 done() describe "Register", -> before -> @user = new User() it 'Set emails attribute', (done) -> @user.register (error, user) => expect(error).to.not.exist user.email.should.equal @user.email user.emails.should.exist user.emails.should.be.a 'array' user.emails.length.should.equal 1 user.emails[0].email.should.equal @user.email done() describe "Register with bonus referal id", -> before (done) -> @user1 = new User() @user2 = new User() async.series [ (cb) => @user1.register cb (cb) => @user2.registerWithQuery '?r=' + @user1.referal_id + '&rm=d&rs=b', cb ], done it 'Adds a referal when an id is supplied and the referal source is "bonus"', (done) -> @user1.get (error, user) => expect(error).to.not.exist user.refered_user_count.should.eql 1 done() describe "LoginViaRegistration", -> before (done) -> @timeout(60000) @user1 = new User() @user2 = new User() async.series [ (cb) => @user1.login cb (cb) => @user1.logout cb (cb) => redis.clearUserSessions @user1, cb (cb) => @user2.login cb (cb) => @user2.logout cb (cb) => redis.clearUserSessions @user2, cb ], done @project_id = null describe "[Security] Trying to register/login as another user", -> it 'should not allow sign in with secondary email', (done) -> secondaryEmail = "acceptance-test-secondary@example.com" @user1.addEmail secondaryEmail, (err) => @user1.loginWith secondaryEmail, (err) => expect(err?).to.equal false @user1.isLoggedIn (err, isLoggedIn) -> expect(isLoggedIn).to.equal false done() it 'should have user1 login', (done) -> @user1.login (err) -> expect(err?).to.equal false done() it 'should have user1 create a project', (done) -> @user1.createProject 'Private Project', (err, project_id) => expect(err?).to.equal false @project_id = project_id done() it 'should ensure user1 can access their project', (done) -> expectProjectAccess @user1, @project_id, done it 'should ensure user2 cannot access the project', (done) -> expectNoProjectAccess @user2, @project_id, done it 'should prevent user2 from login/register with user1 email address', (done) -> tryLoginThroughRegistrationForm @user2, @user1.email, 'totally_not_the_right_password', (err, response, body) => expect(body.redir?).to.equal false expect(body.message?).to.equal true expect(body.message).to.have.all.keys('type', 'text') expect(body.message.type).to.equal 'error' done() it 'should still ensure user2 cannot access the project', (done) -> expectNoProjectAccess @user2, @project_id, done
119947
expect = require("chai").expect assert = require("chai").assert async = require("async") User = require "./helpers/User" request = require "./helpers/request" settings = require "settings-sharelatex" redis = require "./helpers/redis" _ = require 'lodash' # Currently this is testing registration via the 'public-registration' module, # whereas in production we're using the 'overleaf-integration' module. # Expectations expectProjectAccess = (user, projectId, callback=(err,result)->) -> # should have access to project user.openProject projectId, (err) => expect(err).to.be.oneOf [null, undefined] callback() expectNoProjectAccess = (user, projectId, callback=(err,result)->) -> # should not have access to project page user.openProject projectId, (err) => expect(err).to.be.instanceof Error callback() # Actions tryLoginThroughRegistrationForm = (user, email, password, callback=(err, response, body)->) -> user.getCsrfToken (err) -> return callback(err) if err? user.request.post { url: "/register" json: email: email password: <PASSWORD> }, callback describe "LoginRateLimit", -> before -> @user = new User() @badEmail = '<EMAIL>' @badPassword = '<PASSWORD>' it 'should rate limit login attempts after 10 within two minutes', (done) -> @user.request.get '/login', (err, res, body) => async.timesSeries( 15 , (n, cb) => @user.getCsrfToken (error) => return cb(error) if error? @user.request.post { url: "/login" json: email: @badEmail password: <PASSWORD> }, (err, response, body) => cb(null, body?.message?.text) , (err, results) => # ten incorrect-credentials messages, then five rate-limit messages expect(results.length).to.equal 15 assert.deepEqual( results, _.concat( _.fill([1..10], 'Your email or password is incorrect. Please try again'), _.fill([1..5], 'This account has had too many login requests. Please wait 2 minutes before trying to log in again') ) ) done() ) describe "CSRF protection", -> beforeEach -> @user = new User() @email = "<EMAIL>" @password = "<PASSWORD>" afterEach -> @user.full_delete_user(@email) it 'should register with the csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => @user.request.post { url: "/register" json: email: @email password: <PASSWORD> headers:{ "x-csrf-token": @user.csrfToken } }, (error, response, body) => expect(err?).to.equal false expect(response.statusCode).to.equal 200 done() it 'should fail with no csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => @user.request.post { url: "/register" json: email: @email password: <PASSWORD> headers:{ "x-csrf-token": "" } }, (error, response, body) => expect(response.statusCode).to.equal 403 done() it 'should fail with a stale csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => oldCsrfToken = @user.csrfToken @user.logout (err) => @user.request.post { url: "/register" json: email: @email password: <PASSWORD> headers:{ "x-csrf-token": oldCsrfToken } }, (error, response, body) => expect(response.statusCode).to.equal 403 done() describe "Register", -> before -> @user = new User() it 'Set emails attribute', (done) -> @user.register (error, user) => expect(error).to.not.exist user.email.should.equal @user.email user.emails.should.exist user.emails.should.be.a 'array' user.emails.length.should.equal 1 user.emails[0].email.should.equal @user.email done() describe "Register with bonus referal id", -> before (done) -> @user1 = new User() @user2 = new User() async.series [ (cb) => @user1.register cb (cb) => @user2.registerWithQuery '?r=' + @user1.referal_id + '&rm=d&rs=b', cb ], done it 'Adds a referal when an id is supplied and the referal source is "bonus"', (done) -> @user1.get (error, user) => expect(error).to.not.exist user.refered_user_count.should.eql 1 done() describe "LoginViaRegistration", -> before (done) -> @timeout(60000) @user1 = new User() @user2 = new User() async.series [ (cb) => @user1.login cb (cb) => @user1.logout cb (cb) => redis.clearUserSessions @user1, cb (cb) => @user2.login cb (cb) => @user2.logout cb (cb) => redis.clearUserSessions @user2, cb ], done @project_id = null describe "[Security] Trying to register/login as another user", -> it 'should not allow sign in with secondary email', (done) -> secondaryEmail = "<EMAIL>" @user1.addEmail secondaryEmail, (err) => @user1.loginWith secondaryEmail, (err) => expect(err?).to.equal false @user1.isLoggedIn (err, isLoggedIn) -> expect(isLoggedIn).to.equal false done() it 'should have user1 login', (done) -> @user1.login (err) -> expect(err?).to.equal false done() it 'should have user1 create a project', (done) -> @user1.createProject 'Private Project', (err, project_id) => expect(err?).to.equal false @project_id = project_id done() it 'should ensure user1 can access their project', (done) -> expectProjectAccess @user1, @project_id, done it 'should ensure user2 cannot access the project', (done) -> expectNoProjectAccess @user2, @project_id, done it 'should prevent user2 from login/register with user1 email address', (done) -> tryLoginThroughRegistrationForm @user2, @user1.email, '<PASSWORD>', (err, response, body) => expect(body.redir?).to.equal false expect(body.message?).to.equal true expect(body.message).to.have.all.keys('type', 'text') expect(body.message.type).to.equal 'error' done() it 'should still ensure user2 cannot access the project', (done) -> expectNoProjectAccess @user2, @project_id, done
true
expect = require("chai").expect assert = require("chai").assert async = require("async") User = require "./helpers/User" request = require "./helpers/request" settings = require "settings-sharelatex" redis = require "./helpers/redis" _ = require 'lodash' # Currently this is testing registration via the 'public-registration' module, # whereas in production we're using the 'overleaf-integration' module. # Expectations expectProjectAccess = (user, projectId, callback=(err,result)->) -> # should have access to project user.openProject projectId, (err) => expect(err).to.be.oneOf [null, undefined] callback() expectNoProjectAccess = (user, projectId, callback=(err,result)->) -> # should not have access to project page user.openProject projectId, (err) => expect(err).to.be.instanceof Error callback() # Actions tryLoginThroughRegistrationForm = (user, email, password, callback=(err, response, body)->) -> user.getCsrfToken (err) -> return callback(err) if err? user.request.post { url: "/register" json: email: email password: PI:PASSWORD:<PASSWORD>END_PI }, callback describe "LoginRateLimit", -> before -> @user = new User() @badEmail = 'PI:EMAIL:<EMAIL>END_PI' @badPassword = 'PI:PASSWORD:<PASSWORD>END_PI' it 'should rate limit login attempts after 10 within two minutes', (done) -> @user.request.get '/login', (err, res, body) => async.timesSeries( 15 , (n, cb) => @user.getCsrfToken (error) => return cb(error) if error? @user.request.post { url: "/login" json: email: @badEmail password: PI:PASSWORD:<PASSWORD>END_PI }, (err, response, body) => cb(null, body?.message?.text) , (err, results) => # ten incorrect-credentials messages, then five rate-limit messages expect(results.length).to.equal 15 assert.deepEqual( results, _.concat( _.fill([1..10], 'Your email or password is incorrect. Please try again'), _.fill([1..5], 'This account has had too many login requests. Please wait 2 minutes before trying to log in again') ) ) done() ) describe "CSRF protection", -> beforeEach -> @user = new User() @email = "PI:EMAIL:<EMAIL>END_PI" @password = "PI:PASSWORD:<PASSWORD>END_PI" afterEach -> @user.full_delete_user(@email) it 'should register with the csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => @user.request.post { url: "/register" json: email: @email password: PI:PASSWORD:<PASSWORD>END_PI headers:{ "x-csrf-token": @user.csrfToken } }, (error, response, body) => expect(err?).to.equal false expect(response.statusCode).to.equal 200 done() it 'should fail with no csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => @user.request.post { url: "/register" json: email: @email password: PI:PASSWORD:<PASSWORD>END_PI headers:{ "x-csrf-token": "" } }, (error, response, body) => expect(response.statusCode).to.equal 403 done() it 'should fail with a stale csrf token', (done) -> @user.request.get '/login', (err, res, body) => @user.getCsrfToken (error) => oldCsrfToken = @user.csrfToken @user.logout (err) => @user.request.post { url: "/register" json: email: @email password: PI:PASSWORD:<PASSWORD>END_PI headers:{ "x-csrf-token": oldCsrfToken } }, (error, response, body) => expect(response.statusCode).to.equal 403 done() describe "Register", -> before -> @user = new User() it 'Set emails attribute', (done) -> @user.register (error, user) => expect(error).to.not.exist user.email.should.equal @user.email user.emails.should.exist user.emails.should.be.a 'array' user.emails.length.should.equal 1 user.emails[0].email.should.equal @user.email done() describe "Register with bonus referal id", -> before (done) -> @user1 = new User() @user2 = new User() async.series [ (cb) => @user1.register cb (cb) => @user2.registerWithQuery '?r=' + @user1.referal_id + '&rm=d&rs=b', cb ], done it 'Adds a referal when an id is supplied and the referal source is "bonus"', (done) -> @user1.get (error, user) => expect(error).to.not.exist user.refered_user_count.should.eql 1 done() describe "LoginViaRegistration", -> before (done) -> @timeout(60000) @user1 = new User() @user2 = new User() async.series [ (cb) => @user1.login cb (cb) => @user1.logout cb (cb) => redis.clearUserSessions @user1, cb (cb) => @user2.login cb (cb) => @user2.logout cb (cb) => redis.clearUserSessions @user2, cb ], done @project_id = null describe "[Security] Trying to register/login as another user", -> it 'should not allow sign in with secondary email', (done) -> secondaryEmail = "PI:EMAIL:<EMAIL>END_PI" @user1.addEmail secondaryEmail, (err) => @user1.loginWith secondaryEmail, (err) => expect(err?).to.equal false @user1.isLoggedIn (err, isLoggedIn) -> expect(isLoggedIn).to.equal false done() it 'should have user1 login', (done) -> @user1.login (err) -> expect(err?).to.equal false done() it 'should have user1 create a project', (done) -> @user1.createProject 'Private Project', (err, project_id) => expect(err?).to.equal false @project_id = project_id done() it 'should ensure user1 can access their project', (done) -> expectProjectAccess @user1, @project_id, done it 'should ensure user2 cannot access the project', (done) -> expectNoProjectAccess @user2, @project_id, done it 'should prevent user2 from login/register with user1 email address', (done) -> tryLoginThroughRegistrationForm @user2, @user1.email, 'PI:PASSWORD:<PASSWORD>END_PI', (err, response, body) => expect(body.redir?).to.equal false expect(body.message?).to.equal true expect(body.message).to.have.all.keys('type', 'text') expect(body.message.type).to.equal 'error' done() it 'should still ensure user2 cannot access the project', (done) -> expectNoProjectAccess @user2, @project_id, done
[ { "context": "# mologie:autoform-selectize\n# Copyright 2014 Oliver Kuckertz <oliver.kuckertz@mologie.de>\n# See COPYING for li", "end": 61, "score": 0.9990830421447754, "start": 46, "tag": "NAME", "value": "Oliver Kuckertz" }, { "context": "oform-selectize\n# Copyright 2014 Oliver K...
autoform-selectize.coffee
mologie/meteor-autoform-selectize
0
# mologie:autoform-selectize # Copyright 2014 Oliver Kuckertz <oliver.kuckertz@mologie.de> # See COPYING for license information. # Support for dynamically evaluating default values (non-standard) evaluateArray = (values) -> _.map values, (value) -> if typeof value is "function" Tracker.nonreactive -> value() else value AutoForm.addInputType "selectize", template: "afSelectize" valueIsArray: true valueOut: -> # Selectize.js will return a string for single-value fields, and an # array of strings for multi-select fields this[0].selectize.getValue() contextAdjust: (context) -> # Build configuration defaults = valueField: "_id" placeholder: context.atts.placeholder options: context.selectOptions selected: evaluateArray _.compact context.value config = _.extend defaults, context.atts.selectize # Adjust context delete context.atts.selectize # Create controller context.controller = new ReactiveSelectizeController config context Template.afSelectize.rendered = -> controller = @data.controller controller.attach @$('select') Template.afSelectize.destroyed = -> controller = @data.controller controller.stop()
188863
# mologie:autoform-selectize # Copyright 2014 <NAME> <<EMAIL>> # See COPYING for license information. # Support for dynamically evaluating default values (non-standard) evaluateArray = (values) -> _.map values, (value) -> if typeof value is "function" Tracker.nonreactive -> value() else value AutoForm.addInputType "selectize", template: "afSelectize" valueIsArray: true valueOut: -> # Selectize.js will return a string for single-value fields, and an # array of strings for multi-select fields this[0].selectize.getValue() contextAdjust: (context) -> # Build configuration defaults = valueField: "_id" placeholder: context.atts.placeholder options: context.selectOptions selected: evaluateArray _.compact context.value config = _.extend defaults, context.atts.selectize # Adjust context delete context.atts.selectize # Create controller context.controller = new ReactiveSelectizeController config context Template.afSelectize.rendered = -> controller = @data.controller controller.attach @$('select') Template.afSelectize.destroyed = -> controller = @data.controller controller.stop()
true
# mologie:autoform-selectize # Copyright 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # See COPYING for license information. # Support for dynamically evaluating default values (non-standard) evaluateArray = (values) -> _.map values, (value) -> if typeof value is "function" Tracker.nonreactive -> value() else value AutoForm.addInputType "selectize", template: "afSelectize" valueIsArray: true valueOut: -> # Selectize.js will return a string for single-value fields, and an # array of strings for multi-select fields this[0].selectize.getValue() contextAdjust: (context) -> # Build configuration defaults = valueField: "_id" placeholder: context.atts.placeholder options: context.selectOptions selected: evaluateArray _.compact context.value config = _.extend defaults, context.atts.selectize # Adjust context delete context.atts.selectize # Create controller context.controller = new ReactiveSelectizeController config context Template.afSelectize.rendered = -> controller = @data.controller controller.attach @$('select') Template.afSelectize.destroyed = -> controller = @data.controller controller.stop()
[ { "context": "ebook\n phonebook = [\n { name: \"Jurg\", surname: \"Billeter\", phone: \"555-0123\", descrip", "end": 1475, "score": 0.9997649788856506, "start": 1471, "tag": "NAME", "value": "Jurg" }, { "context": "nebook = [\n { name: \"Jurg\", surname...
example/liststore.coffee
darkoverlordofdata/gir2scala
0
#!/usr/bin/gjs GObject = imports.gi.GObject Gtk = imports.gi.Gtk Pango = imports.gi.Pango class TreeViewExample Name: 'TreeView Example with Simple ListStore' # Create the application itself constructor:() -> @application = new Gtk.Application( application_id: 'org.example.jstreeviewsimpleliststore' ) # Connect 'activate' and 'startup' signals to the callback s @application.connect('activate', => @_onActivate()) @application.connect('startup', => @_onStartup()) # Callback for 'activate' signal presents window when active _onActivate:() -> @_window.present() # Callback for 'startup' signal builds the UI _onStartup:() -> @_buildUI() # Build the application's UI _buildUI:() -> # Create the application window @_window = new Gtk.ApplicationWindow( application: @application, window_position: Gtk.WindowPosition.CENTER, default_height: 250, default_width: 100, border_width: 20, title: "My Phone Book") # Create the underlying liststore for the phonebook @_listStore = new Gtk.ListStore() @_listStore.set_column_types([ GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING]) # Data to go in the phonebook phonebook = [ { name: "Jurg", surname: "Billeter", phone: "555-0123", description: "A friendly person." }, { name: "Johannes", surname: "Schmid", phone: "555-1234", description: "Easy phone number to remember." }, { name: "Julita", surname: "Inca", phone: "555-2345", description: "Another friendly person." }, { name: "Javier", surname: "Jardon", phone: "555-3456", description: "Bring fish for his penguins." }, { name: "Jason", surname: "Clinton", phone: "555-4567", description: "His cake's not a lie." }, { name: "Random J.", surname: "Hacker", phone: "555-5678", description: "Very random!" } ] # Put the data in the phonebook for contact in phonebook @_listStore.set(@_listStore.append(), [0, 1, 2, 3], [contact.name, contact.surname, contact.phone, contact.description]) # Create the treeview @_treeView = new Gtk.TreeView( expand: true, model: @_listStore) # Create the columns for the address book firstName = new Gtk.TreeViewColumn(title: "First Name") lastName = new Gtk.TreeViewColumn(title: "Last Name") phone = new Gtk.TreeViewColumn(title: "Phone Number") # Create a cell renderer for when bold text is needed bold = new Gtk.CellRendererText(weight: Pango.Weight.BOLD) # Create a cell renderer for normal text normal = new Gtk.CellRendererText() # Pack the cell renderers into the columns firstName.pack_start(bold, true) lastName.pack_start(normal, true) phone.pack_start(normal, true) # Set each column to pull text from the TreeView's model firstName.add_attribute(bold, "text", 0) lastName.add_attribute(normal, "text", 1) phone.add_attribute(normal, "text", 2) # Insert the columns into the treeview @_treeView.insert_column(firstName, 0) @_treeView.insert_column(lastName, 1) @_treeView.insert_column(phone, 2) # Create the label that shows details for the name you select @_label = new Gtk.Label(label: "") # Get which item is selected @selection = @_treeView.get_selection() # When something new is selected, call _on_changed @selection.connect('changed', => @_onSelectionChanged()) # Create a grid to organize everything in @_grid = new Gtk.Grid # Attach the treeview and label to the grid @_grid.attach(@_treeView, 0, 0, 1, 1) @_grid.attach(@_label, 0, 1, 1, 1) # Add the grid to the window @_window.add(@_grid) # Show the window and all child widgets @_window.show_all() _onSelectionChanged: () -> # Grab a treeiter pointing to the current selection [ isSelected, model, iter ] = @selection.get_selected() # Set the label to read off the values stored in the current selection @_label.set_label("\n" + @_listStore.get_value(iter, 0) + " " + @_listStore.get_value(iter, 1) + " " + @_listStore.get_value(iter, 2) + "\n" + @_listStore.get_value(iter, 3)) # Run the application app = new TreeViewExample() app.application.run(ARGV)
173298
#!/usr/bin/gjs GObject = imports.gi.GObject Gtk = imports.gi.Gtk Pango = imports.gi.Pango class TreeViewExample Name: 'TreeView Example with Simple ListStore' # Create the application itself constructor:() -> @application = new Gtk.Application( application_id: 'org.example.jstreeviewsimpleliststore' ) # Connect 'activate' and 'startup' signals to the callback s @application.connect('activate', => @_onActivate()) @application.connect('startup', => @_onStartup()) # Callback for 'activate' signal presents window when active _onActivate:() -> @_window.present() # Callback for 'startup' signal builds the UI _onStartup:() -> @_buildUI() # Build the application's UI _buildUI:() -> # Create the application window @_window = new Gtk.ApplicationWindow( application: @application, window_position: Gtk.WindowPosition.CENTER, default_height: 250, default_width: 100, border_width: 20, title: "My Phone Book") # Create the underlying liststore for the phonebook @_listStore = new Gtk.ListStore() @_listStore.set_column_types([ GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING]) # Data to go in the phonebook phonebook = [ { name: "<NAME>", surname: "<NAME>", phone: "555-0123", description: "A friendly person." }, { name: "<NAME>", surname: "<NAME>", phone: "555-1234", description: "Easy phone number to remember." }, { name: "<NAME>", surname: "<NAME>", phone: "555-2345", description: "Another friendly person." }, { name: "<NAME>", surname: "<NAME>", phone: "555-3456", description: "Bring fish for his penguins." }, { name: "<NAME>", surname: "<NAME>", phone: "555-4567", description: "His cake's not a lie." }, { name: "<NAME>.", surname: "<NAME>", phone: "555-5678", description: "Very random!" } ] # Put the data in the phonebook for contact in phonebook @_listStore.set(@_listStore.append(), [0, 1, 2, 3], [contact.name, contact.surname, contact.phone, contact.description]) # Create the treeview @_treeView = new Gtk.TreeView( expand: true, model: @_listStore) # Create the columns for the address book firstName = new Gtk.TreeViewColumn(title: "First Name") lastName = new Gtk.TreeViewColumn(title: "Last Name") phone = new Gtk.TreeViewColumn(title: "Phone Number") # Create a cell renderer for when bold text is needed bold = new Gtk.CellRendererText(weight: Pango.Weight.BOLD) # Create a cell renderer for normal text normal = new Gtk.CellRendererText() # Pack the cell renderers into the columns firstName.pack_start(bold, true) lastName.pack_start(normal, true) phone.pack_start(normal, true) # Set each column to pull text from the TreeView's model firstName.add_attribute(bold, "text", 0) lastName.add_attribute(normal, "text", 1) phone.add_attribute(normal, "text", 2) # Insert the columns into the treeview @_treeView.insert_column(firstName, 0) @_treeView.insert_column(lastName, 1) @_treeView.insert_column(phone, 2) # Create the label that shows details for the name you select @_label = new Gtk.Label(label: "") # Get which item is selected @selection = @_treeView.get_selection() # When something new is selected, call _on_changed @selection.connect('changed', => @_onSelectionChanged()) # Create a grid to organize everything in @_grid = new Gtk.Grid # Attach the treeview and label to the grid @_grid.attach(@_treeView, 0, 0, 1, 1) @_grid.attach(@_label, 0, 1, 1, 1) # Add the grid to the window @_window.add(@_grid) # Show the window and all child widgets @_window.show_all() _onSelectionChanged: () -> # Grab a treeiter pointing to the current selection [ isSelected, model, iter ] = @selection.get_selected() # Set the label to read off the values stored in the current selection @_label.set_label("\n" + @_listStore.get_value(iter, 0) + " " + @_listStore.get_value(iter, 1) + " " + @_listStore.get_value(iter, 2) + "\n" + @_listStore.get_value(iter, 3)) # Run the application app = new TreeViewExample() app.application.run(ARGV)
true
#!/usr/bin/gjs GObject = imports.gi.GObject Gtk = imports.gi.Gtk Pango = imports.gi.Pango class TreeViewExample Name: 'TreeView Example with Simple ListStore' # Create the application itself constructor:() -> @application = new Gtk.Application( application_id: 'org.example.jstreeviewsimpleliststore' ) # Connect 'activate' and 'startup' signals to the callback s @application.connect('activate', => @_onActivate()) @application.connect('startup', => @_onStartup()) # Callback for 'activate' signal presents window when active _onActivate:() -> @_window.present() # Callback for 'startup' signal builds the UI _onStartup:() -> @_buildUI() # Build the application's UI _buildUI:() -> # Create the application window @_window = new Gtk.ApplicationWindow( application: @application, window_position: Gtk.WindowPosition.CENTER, default_height: 250, default_width: 100, border_width: 20, title: "My Phone Book") # Create the underlying liststore for the phonebook @_listStore = new Gtk.ListStore() @_listStore.set_column_types([ GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING]) # Data to go in the phonebook phonebook = [ { name: "PI:NAME:<NAME>END_PI", surname: "PI:NAME:<NAME>END_PI", phone: "555-0123", description: "A friendly person." }, { name: "PI:NAME:<NAME>END_PI", surname: "PI:NAME:<NAME>END_PI", phone: "555-1234", description: "Easy phone number to remember." }, { name: "PI:NAME:<NAME>END_PI", surname: "PI:NAME:<NAME>END_PI", phone: "555-2345", description: "Another friendly person." }, { name: "PI:NAME:<NAME>END_PI", surname: "PI:NAME:<NAME>END_PI", phone: "555-3456", description: "Bring fish for his penguins." }, { name: "PI:NAME:<NAME>END_PI", surname: "PI:NAME:<NAME>END_PI", phone: "555-4567", description: "His cake's not a lie." }, { name: "PI:NAME:<NAME>END_PI.", surname: "PI:NAME:<NAME>END_PI", phone: "555-5678", description: "Very random!" } ] # Put the data in the phonebook for contact in phonebook @_listStore.set(@_listStore.append(), [0, 1, 2, 3], [contact.name, contact.surname, contact.phone, contact.description]) # Create the treeview @_treeView = new Gtk.TreeView( expand: true, model: @_listStore) # Create the columns for the address book firstName = new Gtk.TreeViewColumn(title: "First Name") lastName = new Gtk.TreeViewColumn(title: "Last Name") phone = new Gtk.TreeViewColumn(title: "Phone Number") # Create a cell renderer for when bold text is needed bold = new Gtk.CellRendererText(weight: Pango.Weight.BOLD) # Create a cell renderer for normal text normal = new Gtk.CellRendererText() # Pack the cell renderers into the columns firstName.pack_start(bold, true) lastName.pack_start(normal, true) phone.pack_start(normal, true) # Set each column to pull text from the TreeView's model firstName.add_attribute(bold, "text", 0) lastName.add_attribute(normal, "text", 1) phone.add_attribute(normal, "text", 2) # Insert the columns into the treeview @_treeView.insert_column(firstName, 0) @_treeView.insert_column(lastName, 1) @_treeView.insert_column(phone, 2) # Create the label that shows details for the name you select @_label = new Gtk.Label(label: "") # Get which item is selected @selection = @_treeView.get_selection() # When something new is selected, call _on_changed @selection.connect('changed', => @_onSelectionChanged()) # Create a grid to organize everything in @_grid = new Gtk.Grid # Attach the treeview and label to the grid @_grid.attach(@_treeView, 0, 0, 1, 1) @_grid.attach(@_label, 0, 1, 1, 1) # Add the grid to the window @_window.add(@_grid) # Show the window and all child widgets @_window.show_all() _onSelectionChanged: () -> # Grab a treeiter pointing to the current selection [ isSelected, model, iter ] = @selection.get_selected() # Set the label to read off the values stored in the current selection @_label.set_label("\n" + @_listStore.get_value(iter, 0) + " " + @_listStore.get_value(iter, 1) + " " + @_listStore.get_value(iter, 2) + "\n" + @_listStore.get_value(iter, 3)) # Run the application app = new TreeViewExample() app.application.run(ARGV)
[ { "context": "ffort\n\n# Based on juration \n\n# https://github.com/domchristie/juration\n# \n# Copyright 2011, Dom Christie\n# Lice", "end": 72, "score": 0.9982743263244629, "start": 61, "tag": "USERNAME", "value": "domchristie" }, { "context": "thub.com/domchristie/juration\n# \n# ...
src/assets/coffee/angular/factories/effort.coffee
assignittous/aitui
0
# # PersonEffort # Based on juration # https://github.com/domchristie/juration # # Copyright 2011, Dom Christie # Licenced under the MIT licence # Converts human readable effort amounts into minutes, and vice versa. # ## Dependencies # * Angular # * Sugar.js # Parse Example: # "1 h" -> 60 # Humanize Example: # 90 -> "1.5 h" App .factory "PersonEffort", (current)-> return { hours_per_day: 7.5 days_per_week: 5 weeks_per_month: 4 weeks_per_year: 52 day: ()-> @hours_per_day * 60 week: ()-> @days_per_week * @day() month: ()-> @weeks_per_month * @week() year: ()-> @weeks_per_year * @week() units: minutes: patterns: ["minute", "min", "m(?!s)"] formats: chrono: ":" micro: "m" short: "min" long: "minute" hours: patterns: ["hour", "hr", "h",":"] formats: chrono: ":" micro: "h" short: "hr" long: "hour" days: patterns: ["day", "dy", "d"] formats: chrono: ":" micro: "d" short: "day" long: "day" weeks: patterns: ["week", "wk", "w"] formats: chrono: ":" micro: "w" short: "wk" long: "week" months: patterns: ["month", "mon", "mo", "mth"] formats: chrono: ":" micro: "mo" short: "mth" long: "month" years: patterns: ["year", "yr", "y"] formats: chrono: ":" micro: "y" short: "yr" long: "year" parse: (string)-> options = minutes: 1 hours: 60 days: @day() weeks: @week() months: @month() years: @year() # error trap items not passed in by an input field if angular.isNumber(string) string = "#{string}" if string? for unit of @units i = 0 mLen = @units[unit].patterns.length while i < mLen regex = new RegExp("((?:\\d+\\.\\d+)|\\d+)\\s?(" + @units[unit].patterns[i] + "s?(?=\\s|\\d|\\b))", "gi") string = string.replace(regex, (str, p1, p2) -> " " + (p1 * options[unit]).toString() + " " ) i++ sum = 0 # replaces non-word chars (excluding '.') with whitespace # trim L/R whitespace, replace known join words with '' numbers = string.replace(/(?!\.)\W+/g, " ").replace(/^\s+|\s+$|(?:and|plus|with)\s?/g, "").split(" ") j = 0 nLen = numbers.length while j < nLen if numbers[j] and isFinite(numbers[j]) sum += parseFloat(numbers[j]) else unless numbers[j] # Unable to parse: a falsey value 0 else 0 j++ return sum else return 0 # ## Humanize # Humanize returns effort in person days and hours only. # start_at_hours sets the output to use hours instead of days humanize: (minutes, start_at_hours)-> humanized_effort = "" start_at_hours = start_at_hours || false if minutes? minutes = parseInt(minutes) if !isNaN(minutes) # days if !start_at_hours if minutes >= @day() unit = "day" days = Math.floor(minutes / @day()) minutes = minutes - (days * @day()) if days > 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{days} #{unit} " # hours if minutes >= 60 unit = "hour" hours = Math.floor(minutes / 60) minutes = minutes - (hours * 60) if hours > 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{hours} #{unit} " # minutes if minutes >= 0 unit = "minute" if minutes != 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{minutes} #{unit}" return humanized_effort else return "0 minutes" else return "0 minutes" }
200974
# # PersonEffort # Based on juration # https://github.com/domchristie/juration # # Copyright 2011, <NAME> # Licenced under the MIT licence # Converts human readable effort amounts into minutes, and vice versa. # ## Dependencies # * Angular # * Sugar.js # Parse Example: # "1 h" -> 60 # Humanize Example: # 90 -> "1.5 h" App .factory "PersonEffort", (current)-> return { hours_per_day: 7.5 days_per_week: 5 weeks_per_month: 4 weeks_per_year: 52 day: ()-> @hours_per_day * 60 week: ()-> @days_per_week * @day() month: ()-> @weeks_per_month * @week() year: ()-> @weeks_per_year * @week() units: minutes: patterns: ["minute", "min", "m(?!s)"] formats: chrono: ":" micro: "m" short: "min" long: "minute" hours: patterns: ["hour", "hr", "h",":"] formats: chrono: ":" micro: "h" short: "hr" long: "hour" days: patterns: ["day", "dy", "d"] formats: chrono: ":" micro: "d" short: "day" long: "day" weeks: patterns: ["week", "wk", "w"] formats: chrono: ":" micro: "w" short: "wk" long: "week" months: patterns: ["month", "mon", "mo", "mth"] formats: chrono: ":" micro: "mo" short: "mth" long: "month" years: patterns: ["year", "yr", "y"] formats: chrono: ":" micro: "y" short: "yr" long: "year" parse: (string)-> options = minutes: 1 hours: 60 days: @day() weeks: @week() months: @month() years: @year() # error trap items not passed in by an input field if angular.isNumber(string) string = "#{string}" if string? for unit of @units i = 0 mLen = @units[unit].patterns.length while i < mLen regex = new RegExp("((?:\\d+\\.\\d+)|\\d+)\\s?(" + @units[unit].patterns[i] + "s?(?=\\s|\\d|\\b))", "gi") string = string.replace(regex, (str, p1, p2) -> " " + (p1 * options[unit]).toString() + " " ) i++ sum = 0 # replaces non-word chars (excluding '.') with whitespace # trim L/R whitespace, replace known join words with '' numbers = string.replace(/(?!\.)\W+/g, " ").replace(/^\s+|\s+$|(?:and|plus|with)\s?/g, "").split(" ") j = 0 nLen = numbers.length while j < nLen if numbers[j] and isFinite(numbers[j]) sum += parseFloat(numbers[j]) else unless numbers[j] # Unable to parse: a falsey value 0 else 0 j++ return sum else return 0 # ## Humanize # Humanize returns effort in person days and hours only. # start_at_hours sets the output to use hours instead of days humanize: (minutes, start_at_hours)-> humanized_effort = "" start_at_hours = start_at_hours || false if minutes? minutes = parseInt(minutes) if !isNaN(minutes) # days if !start_at_hours if minutes >= @day() unit = "day" days = Math.floor(minutes / @day()) minutes = minutes - (days * @day()) if days > 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{days} #{unit} " # hours if minutes >= 60 unit = "hour" hours = Math.floor(minutes / 60) minutes = minutes - (hours * 60) if hours > 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{hours} #{unit} " # minutes if minutes >= 0 unit = "minute" if minutes != 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{minutes} #{unit}" return humanized_effort else return "0 minutes" else return "0 minutes" }
true
# # PersonEffort # Based on juration # https://github.com/domchristie/juration # # Copyright 2011, PI:NAME:<NAME>END_PI # Licenced under the MIT licence # Converts human readable effort amounts into minutes, and vice versa. # ## Dependencies # * Angular # * Sugar.js # Parse Example: # "1 h" -> 60 # Humanize Example: # 90 -> "1.5 h" App .factory "PersonEffort", (current)-> return { hours_per_day: 7.5 days_per_week: 5 weeks_per_month: 4 weeks_per_year: 52 day: ()-> @hours_per_day * 60 week: ()-> @days_per_week * @day() month: ()-> @weeks_per_month * @week() year: ()-> @weeks_per_year * @week() units: minutes: patterns: ["minute", "min", "m(?!s)"] formats: chrono: ":" micro: "m" short: "min" long: "minute" hours: patterns: ["hour", "hr", "h",":"] formats: chrono: ":" micro: "h" short: "hr" long: "hour" days: patterns: ["day", "dy", "d"] formats: chrono: ":" micro: "d" short: "day" long: "day" weeks: patterns: ["week", "wk", "w"] formats: chrono: ":" micro: "w" short: "wk" long: "week" months: patterns: ["month", "mon", "mo", "mth"] formats: chrono: ":" micro: "mo" short: "mth" long: "month" years: patterns: ["year", "yr", "y"] formats: chrono: ":" micro: "y" short: "yr" long: "year" parse: (string)-> options = minutes: 1 hours: 60 days: @day() weeks: @week() months: @month() years: @year() # error trap items not passed in by an input field if angular.isNumber(string) string = "#{string}" if string? for unit of @units i = 0 mLen = @units[unit].patterns.length while i < mLen regex = new RegExp("((?:\\d+\\.\\d+)|\\d+)\\s?(" + @units[unit].patterns[i] + "s?(?=\\s|\\d|\\b))", "gi") string = string.replace(regex, (str, p1, p2) -> " " + (p1 * options[unit]).toString() + " " ) i++ sum = 0 # replaces non-word chars (excluding '.') with whitespace # trim L/R whitespace, replace known join words with '' numbers = string.replace(/(?!\.)\W+/g, " ").replace(/^\s+|\s+$|(?:and|plus|with)\s?/g, "").split(" ") j = 0 nLen = numbers.length while j < nLen if numbers[j] and isFinite(numbers[j]) sum += parseFloat(numbers[j]) else unless numbers[j] # Unable to parse: a falsey value 0 else 0 j++ return sum else return 0 # ## Humanize # Humanize returns effort in person days and hours only. # start_at_hours sets the output to use hours instead of days humanize: (minutes, start_at_hours)-> humanized_effort = "" start_at_hours = start_at_hours || false if minutes? minutes = parseInt(minutes) if !isNaN(minutes) # days if !start_at_hours if minutes >= @day() unit = "day" days = Math.floor(minutes / @day()) minutes = minutes - (days * @day()) if days > 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{days} #{unit} " # hours if minutes >= 60 unit = "hour" hours = Math.floor(minutes / 60) minutes = minutes - (hours * 60) if hours > 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{hours} #{unit} " # minutes if minutes >= 0 unit = "minute" if minutes != 1 unit = unit.pluralize() humanized_effort = humanized_effort + "#{minutes} #{unit}" return humanized_effort else return "0 minutes" else return "0 minutes" }
[ { "context": " pushToken = {type: user.type, token: user.token}\n if pushToken.type is 'iOS'\n ", "end": 559, "score": 0.48955628275871277, "start": 559, "tag": "PASSWORD", "value": "" }, { "context": " pushToken = {type: user.type, token: user.token}\n ...
PushServer/server/start_push.coffee
Ritesh1991/mobile_app_server
0
if Meteor.isServer Meteor.startup ()-> pushToAllJPushUsers = (content)-> extras = { type: "Notify" } client.push().setPlatform 'ios', 'android' .setAudience JPush.ALL .setNotification '回复通知',JPush.ios(content,null,null,null,extras),JPush.android(content, null, 1,extras) .setOptions null, 60 .send (err, res)-> if err console.log('send error') pushToIOSUser = (user,content)-> pushToken = {type: user.type, token: user.token} if pushToken.type is 'iOS' token = pushToken.token waitReadCount = 1 pushServer.sendIOS 'me', token , '', content, waitReadCount pushToUser = (user,content)-> pushToken = {type: user.type, token: user.token} if pushToken.type is 'JPush' token = pushToken.token extras = { type: "Notify" } #console.log 'JPUSH to ' + pushToken.token client.push().setPlatform 'ios', 'android' .setAudience JPush.registration_id(token) .setNotification '回复通知',JPush.ios(content,null,null,null,extras),JPush.android(content, null, 1,extras) .setOptions null, 60 .send (err, res)-> if err console.log('send error') else if pushToken.type is 'iOS' token = pushToken.token waitReadCount = 1 pushServer.sendIOS 'me', token , '', content, waitReadCount content = '谢谢使用故事帖!根据阿里云的通知(“违规类型:涉政类->政治人物“),故事帖暂停使用,接受处罚及整改(大约一周)。”每个人都是故事的主角“,无论如何,故事帖将会继续服务。敬请关注最新进展: 1)故事帖公共号;或 2)微信群;或 3)QQq群;或 4)Email' #pushToAllJPushUsers(content) allIOSUsers = Meteor.users.find({"token":{$exists:true}, "type":"iOS"}).fetch() userIndex = 0 pushToIOSUserByIndex = (index)-> pushToIOSUser(allIOSUsers[index], content) userIndex = userIndex + 1 if (userIndex < allIOSUsers.length) setTimeout(()-> pushToIOSUserByIndex(userIndex) , 500) console.log '##RDBG allIOSUsers: ' + allIOSUsers if allIOSUsers and allIOSUsers.length > 0 userIndex = 0 pushToIOSUserByIndex(userIndex, content)
122445
if Meteor.isServer Meteor.startup ()-> pushToAllJPushUsers = (content)-> extras = { type: "Notify" } client.push().setPlatform 'ios', 'android' .setAudience JPush.ALL .setNotification '回复通知',JPush.ios(content,null,null,null,extras),JPush.android(content, null, 1,extras) .setOptions null, 60 .send (err, res)-> if err console.log('send error') pushToIOSUser = (user,content)-> pushToken = {type: user.type, token: user<PASSWORD>.token} if pushToken.type is 'iOS' token = pushToken.token waitReadCount = 1 pushServer.sendIOS 'me', token , '', content, waitReadCount pushToUser = (user,content)-> pushToken = {type: user.type, token: user<PASSWORD>.token} if pushToken.type is 'JPush' token = pushToken.token extras = { type: "Notify" } #console.log 'JPUSH to ' + pushToken.token client.push().setPlatform 'ios', 'android' .setAudience JPush.registration_id(token) .setNotification '回复通知',JPush.ios(content,null,null,null,extras),JPush.android(content, null, 1,extras) .setOptions null, 60 .send (err, res)-> if err console.log('send error') else if pushToken.type is 'iOS' token = pushToken.token waitReadCount = 1 pushServer.sendIOS 'me', token , '', content, waitReadCount content = '谢谢使用故事帖!根据阿里云的通知(“违规类型:涉政类->政治人物“),故事帖暂停使用,接受处罚及整改(大约一周)。”每个人都是故事的主角“,无论如何,故事帖将会继续服务。敬请关注最新进展: 1)故事帖公共号;或 2)微信群;或 3)QQq群;或 4)Email' #pushToAllJPushUsers(content) allIOSUsers = Meteor.users.find({"token":{$exists:true}, "type":"iOS"}).fetch() userIndex = 0 pushToIOSUserByIndex = (index)-> pushToIOSUser(allIOSUsers[index], content) userIndex = userIndex + 1 if (userIndex < allIOSUsers.length) setTimeout(()-> pushToIOSUserByIndex(userIndex) , 500) console.log '##RDBG allIOSUsers: ' + allIOSUsers if allIOSUsers and allIOSUsers.length > 0 userIndex = 0 pushToIOSUserByIndex(userIndex, content)
true
if Meteor.isServer Meteor.startup ()-> pushToAllJPushUsers = (content)-> extras = { type: "Notify" } client.push().setPlatform 'ios', 'android' .setAudience JPush.ALL .setNotification '回复通知',JPush.ios(content,null,null,null,extras),JPush.android(content, null, 1,extras) .setOptions null, 60 .send (err, res)-> if err console.log('send error') pushToIOSUser = (user,content)-> pushToken = {type: user.type, token: userPI:PASSWORD:<PASSWORD>END_PI.token} if pushToken.type is 'iOS' token = pushToken.token waitReadCount = 1 pushServer.sendIOS 'me', token , '', content, waitReadCount pushToUser = (user,content)-> pushToken = {type: user.type, token: userPI:PASSWORD:<PASSWORD>END_PI.token} if pushToken.type is 'JPush' token = pushToken.token extras = { type: "Notify" } #console.log 'JPUSH to ' + pushToken.token client.push().setPlatform 'ios', 'android' .setAudience JPush.registration_id(token) .setNotification '回复通知',JPush.ios(content,null,null,null,extras),JPush.android(content, null, 1,extras) .setOptions null, 60 .send (err, res)-> if err console.log('send error') else if pushToken.type is 'iOS' token = pushToken.token waitReadCount = 1 pushServer.sendIOS 'me', token , '', content, waitReadCount content = '谢谢使用故事帖!根据阿里云的通知(“违规类型:涉政类->政治人物“),故事帖暂停使用,接受处罚及整改(大约一周)。”每个人都是故事的主角“,无论如何,故事帖将会继续服务。敬请关注最新进展: 1)故事帖公共号;或 2)微信群;或 3)QQq群;或 4)Email' #pushToAllJPushUsers(content) allIOSUsers = Meteor.users.find({"token":{$exists:true}, "type":"iOS"}).fetch() userIndex = 0 pushToIOSUserByIndex = (index)-> pushToIOSUser(allIOSUsers[index], content) userIndex = userIndex + 1 if (userIndex < allIOSUsers.length) setTimeout(()-> pushToIOSUserByIndex(userIndex) , 500) console.log '##RDBG allIOSUsers: ' + allIOSUsers if allIOSUsers and allIOSUsers.length > 0 userIndex = 0 pushToIOSUserByIndex(userIndex, content)
[ { "context": " ['test.xml',\n '<person>\\n <name>Kenji Doi</name>\\n <age>31</age>\\n</person>\\n'\n ]", "end": 345, "score": 0.9995271563529968, "start": 336, "tag": "NAME", "value": "Kenji Doi" }, { "context": "est-2sheets-1.xml',\n '<person>\\n...
test/generate-test.coffee
knjcode/autometa
0
chai = require 'chai' chai.should() autometa = require '../src/autometa.coffee' describe 'autometa generate function should return', -> it '1 sheet data if input Excel spreadsheet with 1 sheet', -> autometa.generate('./test/test.xlsx').should.deep.equal( [1, [ ['test.xml', '<person>\n <name>Kenji Doi</name>\n <age>31</age>\n</person>\n' ] ] ] ) it '2 sheets data if input Excel spreadsheet with 2 sheets', -> autometa.generate('./test/test-2sheets.xlsx').should.deep.equal( [2, [ ['test-2sheets-1.xml', '<person>\n <name>Kenji Doi 1</name>\n <age>31</age>\n</person>\n' ], ['test-2sheets-2.xml', '<person>\n <name>Kenji Doi 2</name>\n <age>31</age>\n</person>\n' ] ] ] ) it 'repeat data if elements repeated only horizontally', -> string = autometa.generate('./test/test-repeat.xlsx')[1][0][1] string.should.have.contain('Bob Dylan') string.should.have.contain('Bonnie Tyler') string.should.have.contain('Dolly Parton') string.should.have.contain('Gary Moore') string.should.have.contain('Eros Ramazzotti') it 'repeat data if elements repeated only vertically', -> string = autometa.generate('./test/test-repeat2.xlsx')[1][0][1] string.should.have.contain('Bob Dylan') string.should.have.contain('Bonnie Tyler') string.should.have.contain('Dolly Parton') string.should.have.contain('Gary Moore') string.should.have.contain('Eros Ramazzotti') it 'false if invalid filename specified', -> autometa.generate('not-exist-file').should.to.be.false it 'false if no filename specified', -> autometa.generate('').should.to.be.false it 'false if invalid template ID specified in Excel spreadsheet', -> autometa.generate('./test/test-invalid-templateid.xlsx').should.to.be.false
178949
chai = require 'chai' chai.should() autometa = require '../src/autometa.coffee' describe 'autometa generate function should return', -> it '1 sheet data if input Excel spreadsheet with 1 sheet', -> autometa.generate('./test/test.xlsx').should.deep.equal( [1, [ ['test.xml', '<person>\n <name><NAME></name>\n <age>31</age>\n</person>\n' ] ] ] ) it '2 sheets data if input Excel spreadsheet with 2 sheets', -> autometa.generate('./test/test-2sheets.xlsx').should.deep.equal( [2, [ ['test-2sheets-1.xml', '<person>\n <name><NAME> 1</name>\n <age>31</age>\n</person>\n' ], ['test-2sheets-2.xml', '<person>\n <name><NAME> 2</name>\n <age>31</age>\n</person>\n' ] ] ] ) it 'repeat data if elements repeated only horizontally', -> string = autometa.generate('./test/test-repeat.xlsx')[1][0][1] string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') it 'repeat data if elements repeated only vertically', -> string = autometa.generate('./test/test-repeat2.xlsx')[1][0][1] string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') string.should.have.contain('<NAME>') it 'false if invalid filename specified', -> autometa.generate('not-exist-file').should.to.be.false it 'false if no filename specified', -> autometa.generate('').should.to.be.false it 'false if invalid template ID specified in Excel spreadsheet', -> autometa.generate('./test/test-invalid-templateid.xlsx').should.to.be.false
true
chai = require 'chai' chai.should() autometa = require '../src/autometa.coffee' describe 'autometa generate function should return', -> it '1 sheet data if input Excel spreadsheet with 1 sheet', -> autometa.generate('./test/test.xlsx').should.deep.equal( [1, [ ['test.xml', '<person>\n <name>PI:NAME:<NAME>END_PI</name>\n <age>31</age>\n</person>\n' ] ] ] ) it '2 sheets data if input Excel spreadsheet with 2 sheets', -> autometa.generate('./test/test-2sheets.xlsx').should.deep.equal( [2, [ ['test-2sheets-1.xml', '<person>\n <name>PI:NAME:<NAME>END_PI 1</name>\n <age>31</age>\n</person>\n' ], ['test-2sheets-2.xml', '<person>\n <name>PI:NAME:<NAME>END_PI 2</name>\n <age>31</age>\n</person>\n' ] ] ] ) it 'repeat data if elements repeated only horizontally', -> string = autometa.generate('./test/test-repeat.xlsx')[1][0][1] string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') it 'repeat data if elements repeated only vertically', -> string = autometa.generate('./test/test-repeat2.xlsx')[1][0][1] string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') string.should.have.contain('PI:NAME:<NAME>END_PI') it 'false if invalid filename specified', -> autometa.generate('not-exist-file').should.to.be.false it 'false if no filename specified', -> autometa.generate('').should.to.be.false it 'false if invalid template ID specified in Excel spreadsheet', -> autometa.generate('./test/test-invalid-templateid.xlsx').should.to.be.false
[ { "context": "aStore.size--\n\treturn value\n\nON_NODE_DISPOSE_KEY = \"__onNodeDispose\"\nON_NODE_REMOVE_KEY = \"__onNodeRemove\"\nON_NODE_IN", "end": 2880, "score": 0.8893271684646606, "start": 2864, "tag": "KEY", "value": "\"__onNodeDispose" }, { "context": "SPOSE_KEY = \"__onNodeD...
src/core/dom-util.coffee
homeant/cola-ui
90
_$ = $() _$.length = 1 this.$fly = (dom)-> _$[0] = dom return _$ cola.util.isVisible = (dom)-> return !!(dom.offsetWidth or dom.offsetHeight) cola.util.setText = (dom, text = "")-> if cola.browser.mozilla if typeof text is "string" text = text.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/\n/g, "<br>") dom.innerHTML = text else dom.innerText = text return cola.util.cacheDom = (ele)-> cola._ignoreNodeRemoved = true hiddenDiv = cola.util.cacheDom.hiddenDiv if not hiddenDiv cola.util.cacheDom.hiddenDiv = hiddenDiv = $.xCreate( tagName: "div" id: "_hidden_div" style: display: "none" ) cola.util._freezeDom(hiddenDiv) hiddenDiv.setAttribute(cola.constants.IGNORE_DIRECTIVE, "") document.body.appendChild(hiddenDiv) hiddenDiv.appendChild(ele) cola._ignoreNodeRemoved = false return cola.util.userDataStore = size: 0 cola.util.userData = (node, key, data)-> return if node.nodeType is 3 userData = cola.util.userDataStore if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) if arguments.length is 3 if not id id = cola.uniqueId() if node.nodeType is 8 if i > -1 node.nodeValue = text.substring(0, i + 1) + id else node.nodeValue = if text then text + "|" + id else "|" + id else if node.getAttribute node.setAttribute(cola.constants.DOM_USER_DATA_KEY, id) userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ else store = userData[id] if not store userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ store[key] = data else if arguments.length is 2 if typeof key is "string" if id store = userData[id] return store?[key] else if key and typeof key is "object" id = cola.uniqueId() if node.nodeType is 8 if i > -1 node.nodeValue = text.substring(0, i + 1) + id else node.nodeValue = if text then text + "|" + id else "|" + id else if node.getAttribute node.setAttribute(cola.constants.DOM_USER_DATA_KEY, id) userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ for k, v of key store[k] = v else if arguments.length is 1 if id return userData[id] return cola.util.removeUserData = (node, key)-> if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) if id store = cola.util.userDataStore[id] if store if key value = store[key] delete store[key] else value = store delete cola.util.userDataStore[id] cola.util.userDataStore.size-- return value ON_NODE_DISPOSE_KEY = "__onNodeDispose" ON_NODE_REMOVE_KEY = "__onNodeRemove" ON_NODE_INSERT_KEY = "__onNodeInsert" cleanStamp = 1 cola.detachNode = (node)-> return unless node.parentNode cola._ignoreNodeRemoved = true node.parentNode.removeChild(node) cola._ignoreNodeRemoved = false return cola.util.onNodeRemove = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_REMOVE_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_REMOVE_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_REMOVE_KEY, listener) return cola.util.onNodeDispose = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_DISPOSE_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_DISPOSE_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_DISPOSE_KEY, listener) return cola.util.onNodeInsert = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_INSERT_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_INSERT_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_INSERT_KEY, listener) return cola.util._nodesToBeRemove = {} cola.util._getNodeDataId = (node)-> return if node.nodeType is 3 if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) return id _doNodeInserted = (node)-> id = cola.util._getNodeDataId(node) if id delete cola.util._nodesToBeRemove[id] store = cola.util.userDataStore[id] if store listeners = store[ON_NODE_INSERT_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) child = node.firstChild while child _doNodeInserted(child) child = child.nextSibling return _doNodeRemoved = (node)-> id = cola.util._getNodeDataId(node) if id cola.util._nodesToBeRemove[id] = node store = cola.util.userDataStore[id] if store listeners = store[ON_NODE_REMOVE_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) child = node.firstChild while child _doNodeRemoved(child) child = child.nextSibling return _DOMNodeInsertedListener = (evt)-> node = evt.target if node _doNodeInserted(node) if node.parentNode._freezedCount > 0 cola.util._freezeDom(node) return _DOMNodeRemovedListener = (evt)-> return if cola._ignoreNodeRemoved or window.closed node = evt.target if node _doNodeRemoved(node) if node.parentNode._freezedCount > 0 cola.util._unfreezeDom(node) return jQuery.event.special.domFreezed = setup: ()-> @_hasFreezedListener = true return teardown: ()-> delete @_hasFreezedListener return jQuery.event.special.domUnfreezed = setup: ()-> @_hasUnfreezedListener = true return teardown: ()-> delete @_hasUnfreezedListener return cola.util._freezeDom = (dom)-> oldFreezedCount = dom._freezedCount dom._freezedCount = (dom._freezedCount || 0) + 1 if oldFreezedCount is 0 if dom._hasFreezedListener $fly(dom).trigger("domFreezed") child = dom.firstChild while child cola.util._freezeDom(child) child = child.nextSibling return return cola.util._unfreezeDom = (dom)-> if dom._freezedCount > 0 dom._freezedCount-- if dom._freezedCount is 0 if dom._hasUnfreezedListener $fly(dom).trigger("domUnfreezed") child = dom.firstChild while child cola.util._unfreezeDom(child) child = child.nextSibling return return cola.util.getGlobalTemplate = (name)-> template = document.getElementById(name) if template html = template.innerHTML if not template.hasAttribute("shared") then $fly(template).remove() return html do ()-> document.addEventListener("DOMNodeInserted", _DOMNodeInsertedListener) document.addEventListener("DOMNodeRemoved", _DOMNodeRemovedListener) $fly(window).on("unload", ()-> document.removeEventListener("DOMNodeInserted", _DOMNodeInsertedListener) document.removeEventListener("DOMNodeRemoved", _DOMNodeRemovedListener) return ) setInterval(()-> userDataStore = cola.util.userDataStore nodesToBeRemove = cola.util._nodesToBeRemove for id, node of nodesToBeRemove store = userDataStore[id] if store changed = true listeners = store[ON_NODE_DISPOSE_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) delete userDataStore[id] userDataStore.size-- if changed then cola.util._nodesToBeRemove = {} return , 300) #if cola.device.mobile # $fly(window).on("load", ()-> # FastClick.attach(document.body) # return # ) if cola.browser.webkit browser = "webkit" if cola.browser.chrome browser += " chrome" else if cola.browser.safari browser += " safari" # else if cola.browser.qqbrowser # browser += " qqbrowser" else if cola.browser.ie browser = "ie" else if cola.browser.mozilla browser = "mozilla" else browser = "" if cola.os.android os = " android" else if cola.os.ios os = " ios" else if cola.os.windows os = " windows" else os = "" if cola.device.mobile os += " mobile" else if cola.device.desktop os += " desktop" if browser or os $fly(document.documentElement).addClass(browser + os)
148575
_$ = $() _$.length = 1 this.$fly = (dom)-> _$[0] = dom return _$ cola.util.isVisible = (dom)-> return !!(dom.offsetWidth or dom.offsetHeight) cola.util.setText = (dom, text = "")-> if cola.browser.mozilla if typeof text is "string" text = text.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/\n/g, "<br>") dom.innerHTML = text else dom.innerText = text return cola.util.cacheDom = (ele)-> cola._ignoreNodeRemoved = true hiddenDiv = cola.util.cacheDom.hiddenDiv if not hiddenDiv cola.util.cacheDom.hiddenDiv = hiddenDiv = $.xCreate( tagName: "div" id: "_hidden_div" style: display: "none" ) cola.util._freezeDom(hiddenDiv) hiddenDiv.setAttribute(cola.constants.IGNORE_DIRECTIVE, "") document.body.appendChild(hiddenDiv) hiddenDiv.appendChild(ele) cola._ignoreNodeRemoved = false return cola.util.userDataStore = size: 0 cola.util.userData = (node, key, data)-> return if node.nodeType is 3 userData = cola.util.userDataStore if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) if arguments.length is 3 if not id id = cola.uniqueId() if node.nodeType is 8 if i > -1 node.nodeValue = text.substring(0, i + 1) + id else node.nodeValue = if text then text + "|" + id else "|" + id else if node.getAttribute node.setAttribute(cola.constants.DOM_USER_DATA_KEY, id) userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ else store = userData[id] if not store userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ store[key] = data else if arguments.length is 2 if typeof key is "string" if id store = userData[id] return store?[key] else if key and typeof key is "object" id = cola.uniqueId() if node.nodeType is 8 if i > -1 node.nodeValue = text.substring(0, i + 1) + id else node.nodeValue = if text then text + "|" + id else "|" + id else if node.getAttribute node.setAttribute(cola.constants.DOM_USER_DATA_KEY, id) userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ for k, v of key store[k] = v else if arguments.length is 1 if id return userData[id] return cola.util.removeUserData = (node, key)-> if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) if id store = cola.util.userDataStore[id] if store if key value = store[key] delete store[key] else value = store delete cola.util.userDataStore[id] cola.util.userDataStore.size-- return value ON_NODE_DISPOSE_KEY = <KEY>" ON_NODE_REMOVE_KEY = <KEY>" ON_NODE_INSERT_KEY = <KEY>Insert" cleanStamp = 1 cola.detachNode = (node)-> return unless node.parentNode cola._ignoreNodeRemoved = true node.parentNode.removeChild(node) cola._ignoreNodeRemoved = false return cola.util.onNodeRemove = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_REMOVE_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_REMOVE_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_REMOVE_KEY, listener) return cola.util.onNodeDispose = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_DISPOSE_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_DISPOSE_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_DISPOSE_KEY, listener) return cola.util.onNodeInsert = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_INSERT_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_INSERT_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_INSERT_KEY, listener) return cola.util._nodesToBeRemove = {} cola.util._getNodeDataId = (node)-> return if node.nodeType is 3 if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) return id _doNodeInserted = (node)-> id = cola.util._getNodeDataId(node) if id delete cola.util._nodesToBeRemove[id] store = cola.util.userDataStore[id] if store listeners = store[ON_NODE_INSERT_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) child = node.firstChild while child _doNodeInserted(child) child = child.nextSibling return _doNodeRemoved = (node)-> id = cola.util._getNodeDataId(node) if id cola.util._nodesToBeRemove[id] = node store = cola.util.userDataStore[id] if store listeners = store[ON_NODE_REMOVE_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) child = node.firstChild while child _doNodeRemoved(child) child = child.nextSibling return _DOMNodeInsertedListener = (evt)-> node = evt.target if node _doNodeInserted(node) if node.parentNode._freezedCount > 0 cola.util._freezeDom(node) return _DOMNodeRemovedListener = (evt)-> return if cola._ignoreNodeRemoved or window.closed node = evt.target if node _doNodeRemoved(node) if node.parentNode._freezedCount > 0 cola.util._unfreezeDom(node) return jQuery.event.special.domFreezed = setup: ()-> @_hasFreezedListener = true return teardown: ()-> delete @_hasFreezedListener return jQuery.event.special.domUnfreezed = setup: ()-> @_hasUnfreezedListener = true return teardown: ()-> delete @_hasUnfreezedListener return cola.util._freezeDom = (dom)-> oldFreezedCount = dom._freezedCount dom._freezedCount = (dom._freezedCount || 0) + 1 if oldFreezedCount is 0 if dom._hasFreezedListener $fly(dom).trigger("domFreezed") child = dom.firstChild while child cola.util._freezeDom(child) child = child.nextSibling return return cola.util._unfreezeDom = (dom)-> if dom._freezedCount > 0 dom._freezedCount-- if dom._freezedCount is 0 if dom._hasUnfreezedListener $fly(dom).trigger("domUnfreezed") child = dom.firstChild while child cola.util._unfreezeDom(child) child = child.nextSibling return return cola.util.getGlobalTemplate = (name)-> template = document.getElementById(name) if template html = template.innerHTML if not template.hasAttribute("shared") then $fly(template).remove() return html do ()-> document.addEventListener("DOMNodeInserted", _DOMNodeInsertedListener) document.addEventListener("DOMNodeRemoved", _DOMNodeRemovedListener) $fly(window).on("unload", ()-> document.removeEventListener("DOMNodeInserted", _DOMNodeInsertedListener) document.removeEventListener("DOMNodeRemoved", _DOMNodeRemovedListener) return ) setInterval(()-> userDataStore = cola.util.userDataStore nodesToBeRemove = cola.util._nodesToBeRemove for id, node of nodesToBeRemove store = userDataStore[id] if store changed = true listeners = store[ON_NODE_DISPOSE_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) delete userDataStore[id] userDataStore.size-- if changed then cola.util._nodesToBeRemove = {} return , 300) #if cola.device.mobile # $fly(window).on("load", ()-> # FastClick.attach(document.body) # return # ) if cola.browser.webkit browser = "webkit" if cola.browser.chrome browser += " chrome" else if cola.browser.safari browser += " safari" # else if cola.browser.qqbrowser # browser += " qqbrowser" else if cola.browser.ie browser = "ie" else if cola.browser.mozilla browser = "mozilla" else browser = "" if cola.os.android os = " android" else if cola.os.ios os = " ios" else if cola.os.windows os = " windows" else os = "" if cola.device.mobile os += " mobile" else if cola.device.desktop os += " desktop" if browser or os $fly(document.documentElement).addClass(browser + os)
true
_$ = $() _$.length = 1 this.$fly = (dom)-> _$[0] = dom return _$ cola.util.isVisible = (dom)-> return !!(dom.offsetWidth or dom.offsetHeight) cola.util.setText = (dom, text = "")-> if cola.browser.mozilla if typeof text is "string" text = text.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/\n/g, "<br>") dom.innerHTML = text else dom.innerText = text return cola.util.cacheDom = (ele)-> cola._ignoreNodeRemoved = true hiddenDiv = cola.util.cacheDom.hiddenDiv if not hiddenDiv cola.util.cacheDom.hiddenDiv = hiddenDiv = $.xCreate( tagName: "div" id: "_hidden_div" style: display: "none" ) cola.util._freezeDom(hiddenDiv) hiddenDiv.setAttribute(cola.constants.IGNORE_DIRECTIVE, "") document.body.appendChild(hiddenDiv) hiddenDiv.appendChild(ele) cola._ignoreNodeRemoved = false return cola.util.userDataStore = size: 0 cola.util.userData = (node, key, data)-> return if node.nodeType is 3 userData = cola.util.userDataStore if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) if arguments.length is 3 if not id id = cola.uniqueId() if node.nodeType is 8 if i > -1 node.nodeValue = text.substring(0, i + 1) + id else node.nodeValue = if text then text + "|" + id else "|" + id else if node.getAttribute node.setAttribute(cola.constants.DOM_USER_DATA_KEY, id) userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ else store = userData[id] if not store userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ store[key] = data else if arguments.length is 2 if typeof key is "string" if id store = userData[id] return store?[key] else if key and typeof key is "object" id = cola.uniqueId() if node.nodeType is 8 if i > -1 node.nodeValue = text.substring(0, i + 1) + id else node.nodeValue = if text then text + "|" + id else "|" + id else if node.getAttribute node.setAttribute(cola.constants.DOM_USER_DATA_KEY, id) userData[id] = store = { __cleanStamp: cleanStamp } userData.size++ for k, v of key store[k] = v else if arguments.length is 1 if id return userData[id] return cola.util.removeUserData = (node, key)-> if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) if id store = cola.util.userDataStore[id] if store if key value = store[key] delete store[key] else value = store delete cola.util.userDataStore[id] cola.util.userDataStore.size-- return value ON_NODE_DISPOSE_KEY = PI:KEY:<KEY>END_PI" ON_NODE_REMOVE_KEY = PI:KEY:<KEY>END_PI" ON_NODE_INSERT_KEY = PI:KEY:<KEY>END_PIInsert" cleanStamp = 1 cola.detachNode = (node)-> return unless node.parentNode cola._ignoreNodeRemoved = true node.parentNode.removeChild(node) cola._ignoreNodeRemoved = false return cola.util.onNodeRemove = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_REMOVE_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_REMOVE_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_REMOVE_KEY, listener) return cola.util.onNodeDispose = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_DISPOSE_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_DISPOSE_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_DISPOSE_KEY, listener) return cola.util.onNodeInsert = (node, listener)-> oldListener = cola.util.userData(node, ON_NODE_INSERT_KEY) if oldListener if oldListener instanceof Array oldListener.push(listener) else cola.util.userData(node, ON_NODE_INSERT_KEY, [ oldListener, listener ]) else cola.util.userData(node, ON_NODE_INSERT_KEY, listener) return cola.util._nodesToBeRemove = {} cola.util._getNodeDataId = (node)-> return if node.nodeType is 3 if node.nodeType is 8 text = node.nodeValue i = text.indexOf("|") id = text.substring(i + 1) if i > -1 else if node.getAttribute id = node.getAttribute(cola.constants.DOM_USER_DATA_KEY) return id _doNodeInserted = (node)-> id = cola.util._getNodeDataId(node) if id delete cola.util._nodesToBeRemove[id] store = cola.util.userDataStore[id] if store listeners = store[ON_NODE_INSERT_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) child = node.firstChild while child _doNodeInserted(child) child = child.nextSibling return _doNodeRemoved = (node)-> id = cola.util._getNodeDataId(node) if id cola.util._nodesToBeRemove[id] = node store = cola.util.userDataStore[id] if store listeners = store[ON_NODE_REMOVE_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) child = node.firstChild while child _doNodeRemoved(child) child = child.nextSibling return _DOMNodeInsertedListener = (evt)-> node = evt.target if node _doNodeInserted(node) if node.parentNode._freezedCount > 0 cola.util._freezeDom(node) return _DOMNodeRemovedListener = (evt)-> return if cola._ignoreNodeRemoved or window.closed node = evt.target if node _doNodeRemoved(node) if node.parentNode._freezedCount > 0 cola.util._unfreezeDom(node) return jQuery.event.special.domFreezed = setup: ()-> @_hasFreezedListener = true return teardown: ()-> delete @_hasFreezedListener return jQuery.event.special.domUnfreezed = setup: ()-> @_hasUnfreezedListener = true return teardown: ()-> delete @_hasUnfreezedListener return cola.util._freezeDom = (dom)-> oldFreezedCount = dom._freezedCount dom._freezedCount = (dom._freezedCount || 0) + 1 if oldFreezedCount is 0 if dom._hasFreezedListener $fly(dom).trigger("domFreezed") child = dom.firstChild while child cola.util._freezeDom(child) child = child.nextSibling return return cola.util._unfreezeDom = (dom)-> if dom._freezedCount > 0 dom._freezedCount-- if dom._freezedCount is 0 if dom._hasUnfreezedListener $fly(dom).trigger("domUnfreezed") child = dom.firstChild while child cola.util._unfreezeDom(child) child = child.nextSibling return return cola.util.getGlobalTemplate = (name)-> template = document.getElementById(name) if template html = template.innerHTML if not template.hasAttribute("shared") then $fly(template).remove() return html do ()-> document.addEventListener("DOMNodeInserted", _DOMNodeInsertedListener) document.addEventListener("DOMNodeRemoved", _DOMNodeRemovedListener) $fly(window).on("unload", ()-> document.removeEventListener("DOMNodeInserted", _DOMNodeInsertedListener) document.removeEventListener("DOMNodeRemoved", _DOMNodeRemovedListener) return ) setInterval(()-> userDataStore = cola.util.userDataStore nodesToBeRemove = cola.util._nodesToBeRemove for id, node of nodesToBeRemove store = userDataStore[id] if store changed = true listeners = store[ON_NODE_DISPOSE_KEY] if listeners if listeners instanceof Array for listener in listeners listener(node, store) else listeners(node, store) delete userDataStore[id] userDataStore.size-- if changed then cola.util._nodesToBeRemove = {} return , 300) #if cola.device.mobile # $fly(window).on("load", ()-> # FastClick.attach(document.body) # return # ) if cola.browser.webkit browser = "webkit" if cola.browser.chrome browser += " chrome" else if cola.browser.safari browser += " safari" # else if cola.browser.qqbrowser # browser += " qqbrowser" else if cola.browser.ie browser = "ie" else if cola.browser.mozilla browser = "mozilla" else browser = "" if cola.os.android os = " android" else if cola.os.ios os = " ios" else if cola.os.windows os = " windows" else os = "" if cola.device.mobile os += " mobile" else if cola.device.desktop os += " desktop" if browser or os $fly(document.documentElement).addClass(browser + os)
[ { "context": "is file is part of the ChinesePuzzle package.\n\n(c) Mathieu Ledru\n\nFor the full copyright and license information, ", "end": 70, "score": 0.9998525977134705, "start": 57, "tag": "NAME", "value": "Mathieu Ledru" } ]
Common/Bin/Data/coffee/Background/Background.coffee
matyo91/ChinesePuzzle
1
### This file is part of the ChinesePuzzle package. (c) Mathieu Ledru For the full copyright and license information, please view the LICENSE file that was distributed with this source code. ### cpz.Background = cc.Layer.extend( _bgPattern: null _gs: null initWithGameScene: (gs) -> return false unless @init() @_bgPattern = cc.Sprite.create cpz.GameConfig.getRootPath('bgPattern.png') texture = @_bgPattern.getTexture() if cc._renderContext isnt undefined texParams = minFilter: cc._renderContext.LINEAR magFilter: cc._renderContext.LINEAR wrapS: cc._renderContext.REPEAT wrapT: cc._renderContext.REPEAT #texture.setTexParameters(texParams) texture.setTexParameters(texParams['minFilter'], texParams['magFilter'], texParams['wrapS'], texParams['wrapT']) else texParams = minFilter: gl.LINEAR magFilter: gl.LINEAR wrapS: gl.REPEAT wrapT: gl.REPEAT texture.setTexParameters(texParams['minFilter'], texParams['magFilter'], texParams['wrapS'], texParams['wrapT']) @_bgPattern.setAnchorPoint cc.p(0.5, 0.5) @addChild @_bgPattern, cpz.GameSceneZOrder.BG @_gs = gs @setContentSize @_gs.getConf().getResolutionSize() true setContentSize: (size) -> @_super size if @_bgPattern rect = cc.rect 0, 0, size.width, size.height @_bgPattern.setTextureRect rect getGameScene: -> @_gs ) cpz.Background.create = (gs) -> obj = new cpz.Background() return obj if obj and obj.initWithGameScene(gs) null
136917
### This file is part of the ChinesePuzzle package. (c) <NAME> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. ### cpz.Background = cc.Layer.extend( _bgPattern: null _gs: null initWithGameScene: (gs) -> return false unless @init() @_bgPattern = cc.Sprite.create cpz.GameConfig.getRootPath('bgPattern.png') texture = @_bgPattern.getTexture() if cc._renderContext isnt undefined texParams = minFilter: cc._renderContext.LINEAR magFilter: cc._renderContext.LINEAR wrapS: cc._renderContext.REPEAT wrapT: cc._renderContext.REPEAT #texture.setTexParameters(texParams) texture.setTexParameters(texParams['minFilter'], texParams['magFilter'], texParams['wrapS'], texParams['wrapT']) else texParams = minFilter: gl.LINEAR magFilter: gl.LINEAR wrapS: gl.REPEAT wrapT: gl.REPEAT texture.setTexParameters(texParams['minFilter'], texParams['magFilter'], texParams['wrapS'], texParams['wrapT']) @_bgPattern.setAnchorPoint cc.p(0.5, 0.5) @addChild @_bgPattern, cpz.GameSceneZOrder.BG @_gs = gs @setContentSize @_gs.getConf().getResolutionSize() true setContentSize: (size) -> @_super size if @_bgPattern rect = cc.rect 0, 0, size.width, size.height @_bgPattern.setTextureRect rect getGameScene: -> @_gs ) cpz.Background.create = (gs) -> obj = new cpz.Background() return obj if obj and obj.initWithGameScene(gs) null
true
### This file is part of the ChinesePuzzle package. (c) PI:NAME:<NAME>END_PI For the full copyright and license information, please view the LICENSE file that was distributed with this source code. ### cpz.Background = cc.Layer.extend( _bgPattern: null _gs: null initWithGameScene: (gs) -> return false unless @init() @_bgPattern = cc.Sprite.create cpz.GameConfig.getRootPath('bgPattern.png') texture = @_bgPattern.getTexture() if cc._renderContext isnt undefined texParams = minFilter: cc._renderContext.LINEAR magFilter: cc._renderContext.LINEAR wrapS: cc._renderContext.REPEAT wrapT: cc._renderContext.REPEAT #texture.setTexParameters(texParams) texture.setTexParameters(texParams['minFilter'], texParams['magFilter'], texParams['wrapS'], texParams['wrapT']) else texParams = minFilter: gl.LINEAR magFilter: gl.LINEAR wrapS: gl.REPEAT wrapT: gl.REPEAT texture.setTexParameters(texParams['minFilter'], texParams['magFilter'], texParams['wrapS'], texParams['wrapT']) @_bgPattern.setAnchorPoint cc.p(0.5, 0.5) @addChild @_bgPattern, cpz.GameSceneZOrder.BG @_gs = gs @setContentSize @_gs.getConf().getResolutionSize() true setContentSize: (size) -> @_super size if @_bgPattern rect = cc.rect 0, 0, size.width, size.height @_bgPattern.setTextureRect rect getGameScene: -> @_gs ) cpz.Background.create = (gs) -> obj = new cpz.Background() return obj if obj and obj.initWithGameScene(gs) null
[ { "context": "(legend.coffee)\n#\n# Air Sciences Inc. - 2017\n# Jacob Fielding\n#\n\nwindow.Plotter ||= {}\n\nwindow.Plotter.Legend =", "end": 91, "score": 0.9998445510864258, "start": 77, "tag": "NAME", "value": "Jacob Fielding" } ]
coffee/legend.coffee
airsciences/metplotter
0
# # D3 V4 Legend Method (legend.coffee) # # Air Sciences Inc. - 2017 # Jacob Fielding # window.Plotter ||= {} window.Plotter.Legend = class Legend constructor: (plotter, plotId) -> @preError = "Plotter.Legend." preError = "#{@preError}.constructor(...)" @plotter = plotter @svg = @plotter.plots[plotId].proto.svg @plotId = @plotter.plots[plotId].proto.options.plotId @dimensions = @plotter.plots[plotId].proto.definition.dimensions @legend = @svg.append("g") .attr("class", "legend") set: -> @data = [] _options = @plotter.plots[@plotId].proto.options _count = 0 for key, row of _options.y _datalogger = @plotter.i.controls.getLoggerName(@plotId, row.dataLoggerId) _count++ _result = offset: _count title: "#{_datalogger}" color: row.color @data.push(_result) return @data draw: -> # Append the Legend the SVG @set() _rect = @legend.selectAll("rect") .data(@data) _rect.attr("y", (d) -> d.offset * 12) .style("fill", (d) -> d.color) _rect.enter() .append("rect") .attr("rx", 1) .attr("ry", 1) .attr("width", 6) .attr("height", 6) .attr("x", @dimensions.margin.left + 20) .attr("y", (d) -> d.offset * 12) .style("fill", (d) -> d.color) _rect.exit() .remove() _text = @legend.selectAll("text") .data(@data) _text.attr("y", (d) -> d.offset * 12 + 6) .text((d) -> d.title) _text.enter() .append("text") .attr("x", @dimensions.margin.left + 30) .attr("y", (d) -> d.offset * 12 + 6) .text((d) -> d.title) .style("font-size", "12px") .style("font-weight", 500) _text.exit() .remove() remove: -> # Remove the Legend @legend.selectAll(".legend") .remove()
17909
# # D3 V4 Legend Method (legend.coffee) # # Air Sciences Inc. - 2017 # <NAME> # window.Plotter ||= {} window.Plotter.Legend = class Legend constructor: (plotter, plotId) -> @preError = "Plotter.Legend." preError = "#{@preError}.constructor(...)" @plotter = plotter @svg = @plotter.plots[plotId].proto.svg @plotId = @plotter.plots[plotId].proto.options.plotId @dimensions = @plotter.plots[plotId].proto.definition.dimensions @legend = @svg.append("g") .attr("class", "legend") set: -> @data = [] _options = @plotter.plots[@plotId].proto.options _count = 0 for key, row of _options.y _datalogger = @plotter.i.controls.getLoggerName(@plotId, row.dataLoggerId) _count++ _result = offset: _count title: "#{_datalogger}" color: row.color @data.push(_result) return @data draw: -> # Append the Legend the SVG @set() _rect = @legend.selectAll("rect") .data(@data) _rect.attr("y", (d) -> d.offset * 12) .style("fill", (d) -> d.color) _rect.enter() .append("rect") .attr("rx", 1) .attr("ry", 1) .attr("width", 6) .attr("height", 6) .attr("x", @dimensions.margin.left + 20) .attr("y", (d) -> d.offset * 12) .style("fill", (d) -> d.color) _rect.exit() .remove() _text = @legend.selectAll("text") .data(@data) _text.attr("y", (d) -> d.offset * 12 + 6) .text((d) -> d.title) _text.enter() .append("text") .attr("x", @dimensions.margin.left + 30) .attr("y", (d) -> d.offset * 12 + 6) .text((d) -> d.title) .style("font-size", "12px") .style("font-weight", 500) _text.exit() .remove() remove: -> # Remove the Legend @legend.selectAll(".legend") .remove()
true
# # D3 V4 Legend Method (legend.coffee) # # Air Sciences Inc. - 2017 # PI:NAME:<NAME>END_PI # window.Plotter ||= {} window.Plotter.Legend = class Legend constructor: (plotter, plotId) -> @preError = "Plotter.Legend." preError = "#{@preError}.constructor(...)" @plotter = plotter @svg = @plotter.plots[plotId].proto.svg @plotId = @plotter.plots[plotId].proto.options.plotId @dimensions = @plotter.plots[plotId].proto.definition.dimensions @legend = @svg.append("g") .attr("class", "legend") set: -> @data = [] _options = @plotter.plots[@plotId].proto.options _count = 0 for key, row of _options.y _datalogger = @plotter.i.controls.getLoggerName(@plotId, row.dataLoggerId) _count++ _result = offset: _count title: "#{_datalogger}" color: row.color @data.push(_result) return @data draw: -> # Append the Legend the SVG @set() _rect = @legend.selectAll("rect") .data(@data) _rect.attr("y", (d) -> d.offset * 12) .style("fill", (d) -> d.color) _rect.enter() .append("rect") .attr("rx", 1) .attr("ry", 1) .attr("width", 6) .attr("height", 6) .attr("x", @dimensions.margin.left + 20) .attr("y", (d) -> d.offset * 12) .style("fill", (d) -> d.color) _rect.exit() .remove() _text = @legend.selectAll("text") .data(@data) _text.attr("y", (d) -> d.offset * 12 + 6) .text((d) -> d.title) _text.enter() .append("text") .attr("x", @dimensions.margin.left + 30) .attr("y", (d) -> d.offset * 12 + 6) .text((d) -> d.title) .style("font-size", "12px") .style("font-weight", 500) _text.exit() .remove() remove: -> # Remove the Legend @legend.selectAll(".legend") .remove()
[ { "context": "tory.createClient(key, null, url)\n key = utl.add0x(currentClient.secretKeyHex)\n id = utl.add0", "end": 1712, "score": 0.875525951385498, "start": 1705, "tag": "KEY", "value": "l.add0x" } ]
source/floatinginputpagemodule/floatinginputpagemodule.coffee
JhonnyJason/secret-cockpit-sources
0
floatinginputpagemodule = {name: "floatinginputpagemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["floatinginputpagemodule"]? then console.log "[floatinginputpagemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localMOdules clientFactory = require("secret-manager-client") ############################################################ utl = null state = null clientStore = null autoDetect = null slideinModule = null #endregion ############################################################ currentClient = null ############################################################ floatinginputpagemodule.initialize = () -> log "floatinginputpagemodule.initialize" utl = allModules.utilmodule state = allModules.statemodule autoDetect = allModules.autodetectkeysmodule clientStore = allModules.clientstoremodule slideinModule = allModules.slideinframemodule # floatinginputpageContent. slideinModule.wireUp(floatinginputpageContent, clearContent, applyContent) floatingKeyInput.addEventListener("change", secretInputChanged) return ############################################################ #region internalFunctions secretInputChanged = -> log "secretInputChanged" url = state.get("secretManagerURL") seed = floatingKeyInput.value key = await utl.seedToKey(seed) try currentClient = await clientFactory.createClient(key, null, url) key = utl.add0x(currentClient.secretKeyHex) id = utl.add0x(currentClient.publicKeyHex) floatingIdLine.textContent = id catch err then log err return ############################################################ clearContent = -> log "clearContent" floatingKeyInput.value = "" floatingIdLine.textContent = "" currentClient = null return applyContent = -> log "applyContent" clientStore.storeNewClient(currentClient, "floating") autoDetect.detectFor(currentClient) clearContent() return #endregion ############################################################ #region exposedFunctions floatinginputpagemodule.slideOut = -> log "floatinginputpagemodule.slideOut" slideinModule.slideoutForContentElement(floatinginputpageContent) return floatinginputpagemodule.slideIn = -> log "floatinginputpagemodule.slideIn" slideinModule.slideinForContentElement(floatinginputpageContent) return #endregion module.exports = floatinginputpagemodule
153550
floatinginputpagemodule = {name: "floatinginputpagemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["floatinginputpagemodule"]? then console.log "[floatinginputpagemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localMOdules clientFactory = require("secret-manager-client") ############################################################ utl = null state = null clientStore = null autoDetect = null slideinModule = null #endregion ############################################################ currentClient = null ############################################################ floatinginputpagemodule.initialize = () -> log "floatinginputpagemodule.initialize" utl = allModules.utilmodule state = allModules.statemodule autoDetect = allModules.autodetectkeysmodule clientStore = allModules.clientstoremodule slideinModule = allModules.slideinframemodule # floatinginputpageContent. slideinModule.wireUp(floatinginputpageContent, clearContent, applyContent) floatingKeyInput.addEventListener("change", secretInputChanged) return ############################################################ #region internalFunctions secretInputChanged = -> log "secretInputChanged" url = state.get("secretManagerURL") seed = floatingKeyInput.value key = await utl.seedToKey(seed) try currentClient = await clientFactory.createClient(key, null, url) key = ut<KEY>(currentClient.secretKeyHex) id = utl.add0x(currentClient.publicKeyHex) floatingIdLine.textContent = id catch err then log err return ############################################################ clearContent = -> log "clearContent" floatingKeyInput.value = "" floatingIdLine.textContent = "" currentClient = null return applyContent = -> log "applyContent" clientStore.storeNewClient(currentClient, "floating") autoDetect.detectFor(currentClient) clearContent() return #endregion ############################################################ #region exposedFunctions floatinginputpagemodule.slideOut = -> log "floatinginputpagemodule.slideOut" slideinModule.slideoutForContentElement(floatinginputpageContent) return floatinginputpagemodule.slideIn = -> log "floatinginputpagemodule.slideIn" slideinModule.slideinForContentElement(floatinginputpageContent) return #endregion module.exports = floatinginputpagemodule
true
floatinginputpagemodule = {name: "floatinginputpagemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["floatinginputpagemodule"]? then console.log "[floatinginputpagemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localMOdules clientFactory = require("secret-manager-client") ############################################################ utl = null state = null clientStore = null autoDetect = null slideinModule = null #endregion ############################################################ currentClient = null ############################################################ floatinginputpagemodule.initialize = () -> log "floatinginputpagemodule.initialize" utl = allModules.utilmodule state = allModules.statemodule autoDetect = allModules.autodetectkeysmodule clientStore = allModules.clientstoremodule slideinModule = allModules.slideinframemodule # floatinginputpageContent. slideinModule.wireUp(floatinginputpageContent, clearContent, applyContent) floatingKeyInput.addEventListener("change", secretInputChanged) return ############################################################ #region internalFunctions secretInputChanged = -> log "secretInputChanged" url = state.get("secretManagerURL") seed = floatingKeyInput.value key = await utl.seedToKey(seed) try currentClient = await clientFactory.createClient(key, null, url) key = utPI:KEY:<KEY>END_PI(currentClient.secretKeyHex) id = utl.add0x(currentClient.publicKeyHex) floatingIdLine.textContent = id catch err then log err return ############################################################ clearContent = -> log "clearContent" floatingKeyInput.value = "" floatingIdLine.textContent = "" currentClient = null return applyContent = -> log "applyContent" clientStore.storeNewClient(currentClient, "floating") autoDetect.detectFor(currentClient) clearContent() return #endregion ############################################################ #region exposedFunctions floatinginputpagemodule.slideOut = -> log "floatinginputpagemodule.slideOut" slideinModule.slideoutForContentElement(floatinginputpageContent) return floatinginputpagemodule.slideIn = -> log "floatinginputpagemodule.slideIn" slideinModule.slideinForContentElement(floatinginputpageContent) return #endregion module.exports = floatinginputpagemodule
[ { "context": ".equal(transaction.request.uri, '/honey?beekeeper=Adam')\n )\n )\n )\n\n describe('with parameter h", "end": 10357, "score": 0.7962073087692261, "start": 10353, "tag": "NAME", "value": "Adam" }, { "context": ".equal(transaction.request.uri, '/honey?beekeeper=H...
test/integration/compile-test.coffee
cranieri/dredd-transactions-extended
0
fixtures = require('../fixtures') createCompilationResultSchema = require('../schemas/compilation-result') createLocationSchema = require('../schemas/location') createOriginSchema = require('../schemas/origin') {assert, compileFixture} = require('../utils') describe('compile() · all API description formats', -> locationSchema = createLocationSchema() originSchema = createOriginSchema() describe('ordinary, valid API description', -> compilationResult = undefined filename = 'apiDescription.ext' compilationResultSchema = createCompilationResultSchema({ filename transactions: true paths: false mediaType: false }) fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {filename}, (args...) -> [err, compilationResult] = args done(err) ) ) it('is compiled into a compilation result of expected structure', -> assert.jsonSchema(compilationResult, compilationResultSchema) ) ) ) describe('causing an error in the parser', -> fixtures.parserError.forEachDescribe(({source}) -> errors = undefined transactions = undefined beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with an error', -> assert.ok(errors.length) ) context('the error', -> it('comes from parser', -> assert.equal(errors[0].component, 'apiDescriptionParser') ) it('has code', -> assert.isNumber(errors[0].code) ) it('has message', -> assert.isString(errors[0].message) ) it('has location', -> assert.jsonSchema(errors[0].location, locationSchema) ) it('has no origin', -> assert.isUndefined(errors[0].origin) ) ) ) ) describe('causing an error in URI expansion', -> # Parsers may provide warning in similar situations, however, we do not # rely on it in any way in behaviour tested here. This error is thrown # in case Dredd Transactions are not able to parse the URI template. # Mind that situations when parser gives the warning and when this error # is thrown can differ and also the severity is different. errors = undefined transactions = undefined fixtures.uriExpansionAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one error', -> assert.equal(errors.length, 1) ) context('the error', -> it('comes from compiler', -> assert.equal(errors[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(errors[0].code) ) it('has message', -> assert.include(errors[0].message.toLowerCase(), 'failed to parse uri template') ) it('has no location', -> assert.isUndefined(errors[0].location) ) it('has origin', -> assert.jsonSchema(errors[0].origin, originSchema) ) ) ) ) describe('causing an error in URI validation', -> errors = undefined transactions = undefined fixtures.uriValidationAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one error', -> assert.equal(errors.length, 1) ) context('the error', -> it('comes from compiler', -> assert.equal(errors[0].component, 'parametersValidation') ) it('has no code', -> assert.isUndefined(errors[0].code) ) it('has message', -> assert.include(errors[0].message.toLowerCase(), 'no example') ) it('has no location', -> assert.isUndefined(errors[0].location) ) it('has origin', -> assert.jsonSchema(errors[0].origin, originSchema) ) ) ) ) describe('causing a warning in the parser', -> fixtures.parserWarning.forEachDescribe(({source}) -> warnings = undefined transactions = undefined beforeEach((done) -> compileFixture(source, (args...) -> [err, {warnings, transactions}] = args done(err) ) ) it('is compiled into expected number of transactions', -> assert.equal(transactions.length, 1) ) it('is compiled with a warning', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from parser', -> assert.equal(warnings[0].component, 'apiDescriptionParser') ) it('has code', -> assert.isNumber(warnings[0].code) ) it('has message', -> assert.isString(warnings[0].message) ) it('has location', -> assert.jsonSchema(warnings[0].location, locationSchema) ) it('has no origin', -> assert.isUndefined(warnings[0].origin) ) ) ) ) describe('causing a warning in URI expansion', -> # This is a test for an arbitrary warning coming from URI expansion, which # doesn't have any other special side effect. Since there are no such # warnings as of now (but were in the past and could be in the future), # we need to pretend it's possible in this test. warnings = undefined transactions = undefined message = '... dummy warning message ...' stubs = './expand-uri-template-with-parameters': (args...) -> {uri: '/honey?beekeeper=Honza', errors: [], warnings: [message]} fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {stubs}, (err, compilationResult) -> return done(err) if err {warnings, transactions} = compilationResult done() ) ) it('is compiled into some transactions', -> assert.ok(transactions.length) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message, message) ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('causing an \'ambiguous parameters\' warning in URI expansion', -> # Special side effect of the warning is that affected transactions # should be skipped (shouldn't appear in output of the compilation). warnings = undefined transactions = undefined fixtures.ambiguousParametersAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {warnings, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one warning', -> assert.equal(warnings.length, 1) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message.toLowerCase(), 'ambiguous') ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('causing a warning in URI validation', -> # Since 'validateParameters' doesn't actually return any warnings # (but could in the future), we need to pretend it's possible for this # test. warnings = undefined transactions = undefined message = '... dummy warning message ...' stubs = './validate-parameters': (args...) -> {errors: [], warnings: [message]} fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {stubs}, (err, compilationResult) -> return done(err) if err {warnings, transactions} = compilationResult done() ) ) it('is compiled into some transactions', -> assert.ok(transactions.length) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'parametersValidation') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message, message) ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('with enum parameter', -> transaction = undefined fixtures.enumParameter.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI with the first enum value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Adam') ) ) ) describe('with parameter having an example value', -> transaction = undefined fixtures.exampleParameter.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI with the example value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Honza') ) ) ) describe('with response schema', -> transaction = undefined fixtures.responseSchema.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('provides the body in response data', -> assert.ok(transaction.response.body) assert.doesNotThrow( -> JSON.parse(transaction.response.body)) ) it('provides the schema in response data', -> assert.ok(transaction.response.schema) assert.doesNotThrow( -> JSON.parse(transaction.response.schema)) ) ) ) describe('with inheritance of URI parameters', -> transaction = undefined fixtures.parametersInheritance.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI using correct inheritance cascade', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Honza&amount=42') ) ) ) describe('with different default value and first enum value of URI parameter', -> transaction = undefined fixtures.preferDefault.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI using the default value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Adam') ) ) ) describe('with default value for a required URI parameter', -> errors = undefined warnings = undefined warning = undefined transactions = undefined fixtures.defaultRequired.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args {errors, warnings, transactions} = compilationResult [warning] = warnings[-1..] # the last warning done(err) ) ) it('expands the request URI using the default value', -> assert.equal(transactions[0].request.uri, '/honey?beekeeper=Honza') ) it('is compiled with no errors', -> assert.equal(errors.length, 0) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) it('there are no other warnings than from parser or URI expansion', -> assert.equal(warnings.filter((w) -> w.component isnt 'uriTemplateExpansion' and w.component isnt 'apiDescriptionParser' ).length, 0) ) context('the last warning', -> it('comes from URI expansion', -> assert.equal(warning.component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warning.code) ) it('has message', -> assert.include(warning.message.toLowerCase(), 'default value for a required parameter') ) it('has no location', -> assert.isUndefined(warning.location) ) it('has origin', -> assert.jsonSchema(warning.origin, originSchema) ) ) ) ) describe('with HTTP headers', -> transaction = undefined fixtures.httpHeaders.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) context('compiles a transaction', -> it('with expected request headers', -> assert.deepEqual(transaction.request.headers, { 'Content-Type': {value: 'application/json'} 'Accept': {value: 'application/json'} }) ) it('with expected response headers', -> assert.deepEqual(transaction.response.headers, { 'Content-Type': {value: 'application/json'} 'X-Test': {value: 'Adam'} }) ) ) ) ) )
67908
fixtures = require('../fixtures') createCompilationResultSchema = require('../schemas/compilation-result') createLocationSchema = require('../schemas/location') createOriginSchema = require('../schemas/origin') {assert, compileFixture} = require('../utils') describe('compile() · all API description formats', -> locationSchema = createLocationSchema() originSchema = createOriginSchema() describe('ordinary, valid API description', -> compilationResult = undefined filename = 'apiDescription.ext' compilationResultSchema = createCompilationResultSchema({ filename transactions: true paths: false mediaType: false }) fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {filename}, (args...) -> [err, compilationResult] = args done(err) ) ) it('is compiled into a compilation result of expected structure', -> assert.jsonSchema(compilationResult, compilationResultSchema) ) ) ) describe('causing an error in the parser', -> fixtures.parserError.forEachDescribe(({source}) -> errors = undefined transactions = undefined beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with an error', -> assert.ok(errors.length) ) context('the error', -> it('comes from parser', -> assert.equal(errors[0].component, 'apiDescriptionParser') ) it('has code', -> assert.isNumber(errors[0].code) ) it('has message', -> assert.isString(errors[0].message) ) it('has location', -> assert.jsonSchema(errors[0].location, locationSchema) ) it('has no origin', -> assert.isUndefined(errors[0].origin) ) ) ) ) describe('causing an error in URI expansion', -> # Parsers may provide warning in similar situations, however, we do not # rely on it in any way in behaviour tested here. This error is thrown # in case Dredd Transactions are not able to parse the URI template. # Mind that situations when parser gives the warning and when this error # is thrown can differ and also the severity is different. errors = undefined transactions = undefined fixtures.uriExpansionAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one error', -> assert.equal(errors.length, 1) ) context('the error', -> it('comes from compiler', -> assert.equal(errors[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(errors[0].code) ) it('has message', -> assert.include(errors[0].message.toLowerCase(), 'failed to parse uri template') ) it('has no location', -> assert.isUndefined(errors[0].location) ) it('has origin', -> assert.jsonSchema(errors[0].origin, originSchema) ) ) ) ) describe('causing an error in URI validation', -> errors = undefined transactions = undefined fixtures.uriValidationAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one error', -> assert.equal(errors.length, 1) ) context('the error', -> it('comes from compiler', -> assert.equal(errors[0].component, 'parametersValidation') ) it('has no code', -> assert.isUndefined(errors[0].code) ) it('has message', -> assert.include(errors[0].message.toLowerCase(), 'no example') ) it('has no location', -> assert.isUndefined(errors[0].location) ) it('has origin', -> assert.jsonSchema(errors[0].origin, originSchema) ) ) ) ) describe('causing a warning in the parser', -> fixtures.parserWarning.forEachDescribe(({source}) -> warnings = undefined transactions = undefined beforeEach((done) -> compileFixture(source, (args...) -> [err, {warnings, transactions}] = args done(err) ) ) it('is compiled into expected number of transactions', -> assert.equal(transactions.length, 1) ) it('is compiled with a warning', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from parser', -> assert.equal(warnings[0].component, 'apiDescriptionParser') ) it('has code', -> assert.isNumber(warnings[0].code) ) it('has message', -> assert.isString(warnings[0].message) ) it('has location', -> assert.jsonSchema(warnings[0].location, locationSchema) ) it('has no origin', -> assert.isUndefined(warnings[0].origin) ) ) ) ) describe('causing a warning in URI expansion', -> # This is a test for an arbitrary warning coming from URI expansion, which # doesn't have any other special side effect. Since there are no such # warnings as of now (but were in the past and could be in the future), # we need to pretend it's possible in this test. warnings = undefined transactions = undefined message = '... dummy warning message ...' stubs = './expand-uri-template-with-parameters': (args...) -> {uri: '/honey?beekeeper=Honza', errors: [], warnings: [message]} fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {stubs}, (err, compilationResult) -> return done(err) if err {warnings, transactions} = compilationResult done() ) ) it('is compiled into some transactions', -> assert.ok(transactions.length) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message, message) ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('causing an \'ambiguous parameters\' warning in URI expansion', -> # Special side effect of the warning is that affected transactions # should be skipped (shouldn't appear in output of the compilation). warnings = undefined transactions = undefined fixtures.ambiguousParametersAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {warnings, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one warning', -> assert.equal(warnings.length, 1) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message.toLowerCase(), 'ambiguous') ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('causing a warning in URI validation', -> # Since 'validateParameters' doesn't actually return any warnings # (but could in the future), we need to pretend it's possible for this # test. warnings = undefined transactions = undefined message = '... dummy warning message ...' stubs = './validate-parameters': (args...) -> {errors: [], warnings: [message]} fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {stubs}, (err, compilationResult) -> return done(err) if err {warnings, transactions} = compilationResult done() ) ) it('is compiled into some transactions', -> assert.ok(transactions.length) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'parametersValidation') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message, message) ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('with enum parameter', -> transaction = undefined fixtures.enumParameter.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI with the first enum value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=<NAME>') ) ) ) describe('with parameter having an example value', -> transaction = undefined fixtures.exampleParameter.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI with the example value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=<NAME>') ) ) ) describe('with response schema', -> transaction = undefined fixtures.responseSchema.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('provides the body in response data', -> assert.ok(transaction.response.body) assert.doesNotThrow( -> JSON.parse(transaction.response.body)) ) it('provides the schema in response data', -> assert.ok(transaction.response.schema) assert.doesNotThrow( -> JSON.parse(transaction.response.schema)) ) ) ) describe('with inheritance of URI parameters', -> transaction = undefined fixtures.parametersInheritance.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI using correct inheritance cascade', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Honza&amount=42') ) ) ) describe('with different default value and first enum value of URI parameter', -> transaction = undefined fixtures.preferDefault.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI using the default value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Adam') ) ) ) describe('with default value for a required URI parameter', -> errors = undefined warnings = undefined warning = undefined transactions = undefined fixtures.defaultRequired.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args {errors, warnings, transactions} = compilationResult [warning] = warnings[-1..] # the last warning done(err) ) ) it('expands the request URI using the default value', -> assert.equal(transactions[0].request.uri, '/honey?beekeeper=Honza') ) it('is compiled with no errors', -> assert.equal(errors.length, 0) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) it('there are no other warnings than from parser or URI expansion', -> assert.equal(warnings.filter((w) -> w.component isnt 'uriTemplateExpansion' and w.component isnt 'apiDescriptionParser' ).length, 0) ) context('the last warning', -> it('comes from URI expansion', -> assert.equal(warning.component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warning.code) ) it('has message', -> assert.include(warning.message.toLowerCase(), 'default value for a required parameter') ) it('has no location', -> assert.isUndefined(warning.location) ) it('has origin', -> assert.jsonSchema(warning.origin, originSchema) ) ) ) ) describe('with HTTP headers', -> transaction = undefined fixtures.httpHeaders.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) context('compiles a transaction', -> it('with expected request headers', -> assert.deepEqual(transaction.request.headers, { 'Content-Type': {value: 'application/json'} 'Accept': {value: 'application/json'} }) ) it('with expected response headers', -> assert.deepEqual(transaction.response.headers, { 'Content-Type': {value: 'application/json'} 'X-Test': {value: '<NAME>'} }) ) ) ) ) )
true
fixtures = require('../fixtures') createCompilationResultSchema = require('../schemas/compilation-result') createLocationSchema = require('../schemas/location') createOriginSchema = require('../schemas/origin') {assert, compileFixture} = require('../utils') describe('compile() · all API description formats', -> locationSchema = createLocationSchema() originSchema = createOriginSchema() describe('ordinary, valid API description', -> compilationResult = undefined filename = 'apiDescription.ext' compilationResultSchema = createCompilationResultSchema({ filename transactions: true paths: false mediaType: false }) fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {filename}, (args...) -> [err, compilationResult] = args done(err) ) ) it('is compiled into a compilation result of expected structure', -> assert.jsonSchema(compilationResult, compilationResultSchema) ) ) ) describe('causing an error in the parser', -> fixtures.parserError.forEachDescribe(({source}) -> errors = undefined transactions = undefined beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with an error', -> assert.ok(errors.length) ) context('the error', -> it('comes from parser', -> assert.equal(errors[0].component, 'apiDescriptionParser') ) it('has code', -> assert.isNumber(errors[0].code) ) it('has message', -> assert.isString(errors[0].message) ) it('has location', -> assert.jsonSchema(errors[0].location, locationSchema) ) it('has no origin', -> assert.isUndefined(errors[0].origin) ) ) ) ) describe('causing an error in URI expansion', -> # Parsers may provide warning in similar situations, however, we do not # rely on it in any way in behaviour tested here. This error is thrown # in case Dredd Transactions are not able to parse the URI template. # Mind that situations when parser gives the warning and when this error # is thrown can differ and also the severity is different. errors = undefined transactions = undefined fixtures.uriExpansionAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one error', -> assert.equal(errors.length, 1) ) context('the error', -> it('comes from compiler', -> assert.equal(errors[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(errors[0].code) ) it('has message', -> assert.include(errors[0].message.toLowerCase(), 'failed to parse uri template') ) it('has no location', -> assert.isUndefined(errors[0].location) ) it('has origin', -> assert.jsonSchema(errors[0].origin, originSchema) ) ) ) ) describe('causing an error in URI validation', -> errors = undefined transactions = undefined fixtures.uriValidationAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {errors, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one error', -> assert.equal(errors.length, 1) ) context('the error', -> it('comes from compiler', -> assert.equal(errors[0].component, 'parametersValidation') ) it('has no code', -> assert.isUndefined(errors[0].code) ) it('has message', -> assert.include(errors[0].message.toLowerCase(), 'no example') ) it('has no location', -> assert.isUndefined(errors[0].location) ) it('has origin', -> assert.jsonSchema(errors[0].origin, originSchema) ) ) ) ) describe('causing a warning in the parser', -> fixtures.parserWarning.forEachDescribe(({source}) -> warnings = undefined transactions = undefined beforeEach((done) -> compileFixture(source, (args...) -> [err, {warnings, transactions}] = args done(err) ) ) it('is compiled into expected number of transactions', -> assert.equal(transactions.length, 1) ) it('is compiled with a warning', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from parser', -> assert.equal(warnings[0].component, 'apiDescriptionParser') ) it('has code', -> assert.isNumber(warnings[0].code) ) it('has message', -> assert.isString(warnings[0].message) ) it('has location', -> assert.jsonSchema(warnings[0].location, locationSchema) ) it('has no origin', -> assert.isUndefined(warnings[0].origin) ) ) ) ) describe('causing a warning in URI expansion', -> # This is a test for an arbitrary warning coming from URI expansion, which # doesn't have any other special side effect. Since there are no such # warnings as of now (but were in the past and could be in the future), # we need to pretend it's possible in this test. warnings = undefined transactions = undefined message = '... dummy warning message ...' stubs = './expand-uri-template-with-parameters': (args...) -> {uri: '/honey?beekeeper=Honza', errors: [], warnings: [message]} fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {stubs}, (err, compilationResult) -> return done(err) if err {warnings, transactions} = compilationResult done() ) ) it('is compiled into some transactions', -> assert.ok(transactions.length) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message, message) ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('causing an \'ambiguous parameters\' warning in URI expansion', -> # Special side effect of the warning is that affected transactions # should be skipped (shouldn't appear in output of the compilation). warnings = undefined transactions = undefined fixtures.ambiguousParametersAnnotation.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, {warnings, transactions}] = args done(err) ) ) it('is compiled into zero transactions', -> assert.equal(transactions.length, 0) ) it('is compiled with one warning', -> assert.equal(warnings.length, 1) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message.toLowerCase(), 'ambiguous') ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('causing a warning in URI validation', -> # Since 'validateParameters' doesn't actually return any warnings # (but could in the future), we need to pretend it's possible for this # test. warnings = undefined transactions = undefined message = '... dummy warning message ...' stubs = './validate-parameters': (args...) -> {errors: [], warnings: [message]} fixtures.ordinary.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, {stubs}, (err, compilationResult) -> return done(err) if err {warnings, transactions} = compilationResult done() ) ) it('is compiled into some transactions', -> assert.ok(transactions.length) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) context('the warning', -> it('comes from compiler', -> assert.equal(warnings[0].component, 'parametersValidation') ) it('has no code', -> assert.isUndefined(warnings[0].code) ) it('has message', -> assert.include(warnings[0].message, message) ) it('has no location', -> assert.isUndefined(warnings[0].location) ) it('has origin', -> assert.jsonSchema(warnings[0].origin, originSchema) ) ) ) ) describe('with enum parameter', -> transaction = undefined fixtures.enumParameter.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI with the first enum value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=PI:NAME:<NAME>END_PI') ) ) ) describe('with parameter having an example value', -> transaction = undefined fixtures.exampleParameter.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI with the example value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=PI:NAME:<NAME>END_PI') ) ) ) describe('with response schema', -> transaction = undefined fixtures.responseSchema.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('provides the body in response data', -> assert.ok(transaction.response.body) assert.doesNotThrow( -> JSON.parse(transaction.response.body)) ) it('provides the schema in response data', -> assert.ok(transaction.response.schema) assert.doesNotThrow( -> JSON.parse(transaction.response.schema)) ) ) ) describe('with inheritance of URI parameters', -> transaction = undefined fixtures.parametersInheritance.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI using correct inheritance cascade', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Honza&amount=42') ) ) ) describe('with different default value and first enum value of URI parameter', -> transaction = undefined fixtures.preferDefault.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) it('expands the request URI using the default value', -> assert.equal(transaction.request.uri, '/honey?beekeeper=Adam') ) ) ) describe('with default value for a required URI parameter', -> errors = undefined warnings = undefined warning = undefined transactions = undefined fixtures.defaultRequired.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args {errors, warnings, transactions} = compilationResult [warning] = warnings[-1..] # the last warning done(err) ) ) it('expands the request URI using the default value', -> assert.equal(transactions[0].request.uri, '/honey?beekeeper=Honza') ) it('is compiled with no errors', -> assert.equal(errors.length, 0) ) it('is compiled with warnings', -> assert.ok(warnings.length) ) it('there are no other warnings than from parser or URI expansion', -> assert.equal(warnings.filter((w) -> w.component isnt 'uriTemplateExpansion' and w.component isnt 'apiDescriptionParser' ).length, 0) ) context('the last warning', -> it('comes from URI expansion', -> assert.equal(warning.component, 'uriTemplateExpansion') ) it('has no code', -> assert.isUndefined(warning.code) ) it('has message', -> assert.include(warning.message.toLowerCase(), 'default value for a required parameter') ) it('has no location', -> assert.isUndefined(warning.location) ) it('has origin', -> assert.jsonSchema(warning.origin, originSchema) ) ) ) ) describe('with HTTP headers', -> transaction = undefined fixtures.httpHeaders.forEachDescribe(({source}) -> beforeEach((done) -> compileFixture(source, (args...) -> [err, compilationResult] = args transaction = compilationResult.transactions[0] done(err) ) ) context('compiles a transaction', -> it('with expected request headers', -> assert.deepEqual(transaction.request.headers, { 'Content-Type': {value: 'application/json'} 'Accept': {value: 'application/json'} }) ) it('with expected response headers', -> assert.deepEqual(transaction.response.headers, { 'Content-Type': {value: 'application/json'} 'X-Test': {value: 'PI:NAME:<NAME>END_PI'} }) ) ) ) ) )
[ { "context": "use database and create schema\n password: 'dev.psql'\n database: 'postgres'\n schema: 'DB", "end": 167, "score": 0.9992668628692627, "start": 159, "tag": "PASSWORD", "value": "dev.psql" }, { "context": "es'\n schema: 'DBLAYER_TEST'\n ...
test/config.coffee
smbape/node-dblayer
0
_ = require 'lodash' _.extend exports, postgres: root: 'postgres' # a user who can create/use database and create schema password: 'dev.psql' database: 'postgres' schema: 'DBLAYER_TEST' host: '127.0.0.1' port: 5432 cmd: 'psql' create: database: false schema: true users: true model: false drop: database: false schema: true users: true mysql: root: 'root' password: 'dev.mysql' host: '127.0.0.1' port: 3306 cmd: 'mysql' database: 'DBLAYER_TEST' create: database: true users: true model: false drop: database: true users: true mssql: root: 'sa' password: 'dev.mssql' host: '127.0.0.1' port: 1433 database: 'DBLAYER_TEST' create: database: true users: true model: false drop: database: true users: true for dialect, config of exports _.extend config, users: admin: adapter: dialect name: 'bcms_admin' password: 'bcms_admin' writer: adapter: dialect name: 'bcms_writer' password: 'bcms_writer' reader: adapter: dialect name: 'bcms_reader' password: 'bcms_reader' stdout: null # 1, process.stdout stderr: null # 2, process.stderr keep: false for key in Object.keys(exports) newConfig = exports['new_' + key] = _.cloneDeep exports[key] newConfig.create.model = true for name, user of newConfig.users user.name = 'new_' + user.name user.password = 'new_' + user.password if newConfig.schema newConfig.schema = 'NEW_' + newConfig.schema else newConfig.database = 'NEW_' + newConfig.database for dialect, config of exports for name, user of config.users _.defaults user, {user: user.name}, _.pick config, ['host', 'port', 'database', 'schema'] # console.log require('util').inspect exports, {colors: true, depth: null}
54423
_ = require 'lodash' _.extend exports, postgres: root: 'postgres' # a user who can create/use database and create schema password: '<PASSWORD>' database: 'postgres' schema: 'DBLAYER_TEST' host: '127.0.0.1' port: 5432 cmd: 'psql' create: database: false schema: true users: true model: false drop: database: false schema: true users: true mysql: root: 'root' password: '<PASSWORD>' host: '127.0.0.1' port: 3306 cmd: 'mysql' database: 'DBLAYER_TEST' create: database: true users: true model: false drop: database: true users: true mssql: root: 'sa' password: '<PASSWORD>' host: '127.0.0.1' port: 1433 database: 'DBLAYER_TEST' create: database: true users: true model: false drop: database: true users: true for dialect, config of exports _.extend config, users: admin: adapter: dialect name: 'bcms_admin' password: '<PASSWORD>' writer: adapter: dialect name: 'bcms_writer' password: '<PASSWORD>' reader: adapter: dialect name: 'bcms_reader' password: '<PASSWORD>' stdout: null # 1, process.stdout stderr: null # 2, process.stderr keep: false for key in Object.keys(exports) newConfig = exports['new_' + key] = _.cloneDeep exports[key] newConfig.create.model = true for name, user of newConfig.users user.name = 'new_' + user.name user.password = '<PASSWORD>' + user.password if newConfig.schema newConfig.schema = 'NEW_' + newConfig.schema else newConfig.database = 'NEW_' + newConfig.database for dialect, config of exports for name, user of config.users _.defaults user, {user: user.name}, _.pick config, ['host', 'port', 'database', 'schema'] # console.log require('util').inspect exports, {colors: true, depth: null}
true
_ = require 'lodash' _.extend exports, postgres: root: 'postgres' # a user who can create/use database and create schema password: 'PI:PASSWORD:<PASSWORD>END_PI' database: 'postgres' schema: 'DBLAYER_TEST' host: '127.0.0.1' port: 5432 cmd: 'psql' create: database: false schema: true users: true model: false drop: database: false schema: true users: true mysql: root: 'root' password: 'PI:PASSWORD:<PASSWORD>END_PI' host: '127.0.0.1' port: 3306 cmd: 'mysql' database: 'DBLAYER_TEST' create: database: true users: true model: false drop: database: true users: true mssql: root: 'sa' password: 'PI:PASSWORD:<PASSWORD>END_PI' host: '127.0.0.1' port: 1433 database: 'DBLAYER_TEST' create: database: true users: true model: false drop: database: true users: true for dialect, config of exports _.extend config, users: admin: adapter: dialect name: 'bcms_admin' password: 'PI:PASSWORD:<PASSWORD>END_PI' writer: adapter: dialect name: 'bcms_writer' password: 'PI:PASSWORD:<PASSWORD>END_PI' reader: adapter: dialect name: 'bcms_reader' password: 'PI:PASSWORD:<PASSWORD>END_PI' stdout: null # 1, process.stdout stderr: null # 2, process.stderr keep: false for key in Object.keys(exports) newConfig = exports['new_' + key] = _.cloneDeep exports[key] newConfig.create.model = true for name, user of newConfig.users user.name = 'new_' + user.name user.password = 'PI:PASSWORD:<PASSWORD>END_PI' + user.password if newConfig.schema newConfig.schema = 'NEW_' + newConfig.schema else newConfig.database = 'NEW_' + newConfig.database for dialect, config of exports for name, user of config.users _.defaults user, {user: user.name}, _.pick config, ['host', 'port', 'database', 'schema'] # console.log require('util').inspect exports, {colors: true, depth: null}
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http", "end": 63, "score": 0.5220626592636108, "start": 62, "tag": "NAME", "value": "H" } ]
src/handle/HandleRect.coffee
heartyoh/infopik
0
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' 'KineticJS' ], ( dou kin ) -> "use strict" LEFT = -1 CENTER = 0 RIGHT = 1 TOP = -1 MIDDLE = 0 BOTTOM = 1 # Handler class. # # This class extends the Kinetic.Circle class. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, # right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, # bottom: 1) # @param {Number} radius Handler radius # @param {String} fill Fill color # @param {String} stroke Stroke color # @param {Number} strokeWidth Stroke width # # @return {Void} class Handler extends kin.Circle constructor: (hAlign, vAlign, radius, fill, stroke, strokeWidth) -> @_align = [hAlign, vAlign] kin.Circle.call @, radius: radius fill: fill stroke: stroke strokeWidth: strokeWidth draggable: true # Gets handler alignment. # # Returns an array of two numbers. The first number is the horizontal alignment # and the second number is the vertical alignment. # # @return {Array} getAlign: -> @_align # RotateHandler class. # # This class extends the Kinetic.Circle class. # # @param {Number} radius Handler radius # @param {String} fill Fill color # @param {String} stroke Stroke color # @param {Number} strokeWidth Stroke width # # @return {Void} class RotateHandler extends kin.Circle constructor: (radius, fill, stroke, strokeWidth) -> kin.Circle.call @, radius: radius fill: fill stroke: stroke strokeWidth: strokeWidth draggable: true # RectHandle class. # # This class extends the Kinetic.Group class. # # @param {Object} options Custom options # # @return {Void} class RectHandle extends kin.Group constructor: (options) -> @_options = options @_handlers = [] @_rotateHandler = null @_border = null kin.Group.call @, width: options.width height: options.height fill: options.fill stroke: options.stroke strokeWidth: options.strokeWidth draggable: true @createBorder() @addHandler TOP, LEFT @addHandler TOP, CENTER @addHandler TOP, RIGHT @addHandler MIDDLE, LEFT @addHandler MIDDLE, RIGHT @addHandler BOTTOM, LEFT @addHandler BOTTOM, CENTER @addHandler BOTTOM, RIGHT @addRotateHandler() # Creates the border. # # @return {Void} createBorder: -> @_border = new kin.Line points: [0, 0] stroke: @_options['border-stroke'] strokeWidth: @_options['border-stroke-width'] @add(@_border) # Creates the rotate handler. # # @return {Kinetic.Circle} addRotateHandler: -> self = this @_rotateHandler = new RotateHandler radius: @_options['handler-radius'] fill: @_options['handler-fill'] stroke: @_options['handler-stroke'] strokeWidth: @_options['handler-stroke-width'] @_rotateHandler.setDragBoundFunc (pos) -> if @isDragging() # rotateGroup = self.getParent() p = rotateGroup.getAbsolutePosition() v = x: p.x - pos.x y: p.y - pos.y angle = self.getAngle(v) rotateGroup.setRotation(angle) return pos @_rotateHandler.on 'dragmove', -> self.update() @add @_rotateHandler return @_rotateHandler # Adds a handler. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, bottom: 1) # @param {Boolean} visible Is the handler visible? # # @return {Handler} addHandler: (hAlign, vAlign) -> handler = new Handler( hAlign vAlign @_options['handler-radius'] @_options['handler-fill'] @_options['handler-stroke'] @_options['handler-strokeWidth'] ) @add handler @_handlers.push handler # Gets a handler by alignment. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, bottom: 1) # # @return {Handler} getHandlerByAlign: (hAlign, vAlign) -> for handler in @_handlers align = handler.getAlign() return handler if (align[0] is hAlign) and (align[1] is vAlign) return null # Gets the opposite handler. # # @return {Handler} getOppositeHandler: (handler) -> align = handler.getAlign() return @getHandlerByAlign -align[0], -align[1] # Set target node for handle # # @param {Kinetic.Node} # # @return {Void} setTarget: (target) -> @_target = target @update() # Set handle to visible # # @return {Void} showHandle: -> @visible true # Set handle to invisible # # @return {Void} hideHandle: -> @visible false # Updates handler positions. # # @return {Void} update: -> # target properties targetX = @_target.getX() - @_target.getOffsetX() targetY = @_target.getY() - @_target.getOffsetY() targetWidth = @_target.getWidth() targetHeight = @_target.getHeight() # positions rotate = x: targetX + targetWidth / 2 y: targetY - @_options['rotate-distance'] leftTop = {x: targetX, y: targetY} rightTop = {x: targetX + targetWidth, y: targetY} leftBottom = {x: targetX, y: targetY + targetHeight} rightBottom = {x: targetX + targetWidth, y: targetY + targetHeight} centerTop = {x: targetX + targetWidth / 2, y: targetY} leftMiddle = {x: targetX, y: targetY + targetHeight / 2} rightMiddle = {x: targetX + targetWidth, y: targetY + targetHeight / 2} centerBottom = {x: targetX + targetWidth / 2, y: targetY + targetHeight} # adds points to the border points = [ centerTop leftTop leftBottom rightBottom rightTop centerTop ] if (@_options['allow-rotate']) points.unshift(rotate) @_border.setPoints(points) # sets rotate handler position @_rotateHandler.setPosition(rotate) # sets left-top handler position @getHandlerByAlign( LEFT, TOP ).setPosition(leftTop) # sets right-top handler position @getHandlerByAlign( RIGHT, TOP ).setPosition(rightTop) # sets left-bottom handler position @getHandlerByAlign( LEFT, BOTTOM ).setPosition(leftBottom) # sets right-bottom handler position @getHandlerByAlign( RIGHT, BOTTOM ).setPosition(rightBottom) # sets center-top handler position @getHandlerByAlign( CENTER, TOP ).setPosition(centerTop) # sets left-middle handler position @getHandlerByAlign( LEFT, MIDDLE ).setPosition(leftMiddle) # sets right-middle handler position @getHandlerByAlign( RIGHT, MIDDLE ).setPosition(rightMiddle) # sets center-bottom handler position @getHandlerByAlign( CENTER, BOTTOM ).setPosition(centerBottom) view_factory = (attributes) -> handle = new RectHandle attributes handle { type: 'handle-rect' name: 'handle-rect' description: 'Rectangle Handle Specification' defaults: { width: 10 height: 10 fill: 'red' stroke: 'black' strokeWidth: 2 'handler-radius': 10 'handler-fill': 'gray' 'handler-stroke': 'black' 'handler-strokeWidth': 2 'rotate-distance': 10 'border-stroke': 'black' 'border-stroke-width': 2 } view_factory_fn: view_factory toolbox_image: 'images/toolbox_handle_rect.png' }
200919
# ========================================== # Copyright 2014 <NAME>atio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' 'KineticJS' ], ( dou kin ) -> "use strict" LEFT = -1 CENTER = 0 RIGHT = 1 TOP = -1 MIDDLE = 0 BOTTOM = 1 # Handler class. # # This class extends the Kinetic.Circle class. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, # right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, # bottom: 1) # @param {Number} radius Handler radius # @param {String} fill Fill color # @param {String} stroke Stroke color # @param {Number} strokeWidth Stroke width # # @return {Void} class Handler extends kin.Circle constructor: (hAlign, vAlign, radius, fill, stroke, strokeWidth) -> @_align = [hAlign, vAlign] kin.Circle.call @, radius: radius fill: fill stroke: stroke strokeWidth: strokeWidth draggable: true # Gets handler alignment. # # Returns an array of two numbers. The first number is the horizontal alignment # and the second number is the vertical alignment. # # @return {Array} getAlign: -> @_align # RotateHandler class. # # This class extends the Kinetic.Circle class. # # @param {Number} radius Handler radius # @param {String} fill Fill color # @param {String} stroke Stroke color # @param {Number} strokeWidth Stroke width # # @return {Void} class RotateHandler extends kin.Circle constructor: (radius, fill, stroke, strokeWidth) -> kin.Circle.call @, radius: radius fill: fill stroke: stroke strokeWidth: strokeWidth draggable: true # RectHandle class. # # This class extends the Kinetic.Group class. # # @param {Object} options Custom options # # @return {Void} class RectHandle extends kin.Group constructor: (options) -> @_options = options @_handlers = [] @_rotateHandler = null @_border = null kin.Group.call @, width: options.width height: options.height fill: options.fill stroke: options.stroke strokeWidth: options.strokeWidth draggable: true @createBorder() @addHandler TOP, LEFT @addHandler TOP, CENTER @addHandler TOP, RIGHT @addHandler MIDDLE, LEFT @addHandler MIDDLE, RIGHT @addHandler BOTTOM, LEFT @addHandler BOTTOM, CENTER @addHandler BOTTOM, RIGHT @addRotateHandler() # Creates the border. # # @return {Void} createBorder: -> @_border = new kin.Line points: [0, 0] stroke: @_options['border-stroke'] strokeWidth: @_options['border-stroke-width'] @add(@_border) # Creates the rotate handler. # # @return {Kinetic.Circle} addRotateHandler: -> self = this @_rotateHandler = new RotateHandler radius: @_options['handler-radius'] fill: @_options['handler-fill'] stroke: @_options['handler-stroke'] strokeWidth: @_options['handler-stroke-width'] @_rotateHandler.setDragBoundFunc (pos) -> if @isDragging() # rotateGroup = self.getParent() p = rotateGroup.getAbsolutePosition() v = x: p.x - pos.x y: p.y - pos.y angle = self.getAngle(v) rotateGroup.setRotation(angle) return pos @_rotateHandler.on 'dragmove', -> self.update() @add @_rotateHandler return @_rotateHandler # Adds a handler. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, bottom: 1) # @param {Boolean} visible Is the handler visible? # # @return {Handler} addHandler: (hAlign, vAlign) -> handler = new Handler( hAlign vAlign @_options['handler-radius'] @_options['handler-fill'] @_options['handler-stroke'] @_options['handler-strokeWidth'] ) @add handler @_handlers.push handler # Gets a handler by alignment. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, bottom: 1) # # @return {Handler} getHandlerByAlign: (hAlign, vAlign) -> for handler in @_handlers align = handler.getAlign() return handler if (align[0] is hAlign) and (align[1] is vAlign) return null # Gets the opposite handler. # # @return {Handler} getOppositeHandler: (handler) -> align = handler.getAlign() return @getHandlerByAlign -align[0], -align[1] # Set target node for handle # # @param {Kinetic.Node} # # @return {Void} setTarget: (target) -> @_target = target @update() # Set handle to visible # # @return {Void} showHandle: -> @visible true # Set handle to invisible # # @return {Void} hideHandle: -> @visible false # Updates handler positions. # # @return {Void} update: -> # target properties targetX = @_target.getX() - @_target.getOffsetX() targetY = @_target.getY() - @_target.getOffsetY() targetWidth = @_target.getWidth() targetHeight = @_target.getHeight() # positions rotate = x: targetX + targetWidth / 2 y: targetY - @_options['rotate-distance'] leftTop = {x: targetX, y: targetY} rightTop = {x: targetX + targetWidth, y: targetY} leftBottom = {x: targetX, y: targetY + targetHeight} rightBottom = {x: targetX + targetWidth, y: targetY + targetHeight} centerTop = {x: targetX + targetWidth / 2, y: targetY} leftMiddle = {x: targetX, y: targetY + targetHeight / 2} rightMiddle = {x: targetX + targetWidth, y: targetY + targetHeight / 2} centerBottom = {x: targetX + targetWidth / 2, y: targetY + targetHeight} # adds points to the border points = [ centerTop leftTop leftBottom rightBottom rightTop centerTop ] if (@_options['allow-rotate']) points.unshift(rotate) @_border.setPoints(points) # sets rotate handler position @_rotateHandler.setPosition(rotate) # sets left-top handler position @getHandlerByAlign( LEFT, TOP ).setPosition(leftTop) # sets right-top handler position @getHandlerByAlign( RIGHT, TOP ).setPosition(rightTop) # sets left-bottom handler position @getHandlerByAlign( LEFT, BOTTOM ).setPosition(leftBottom) # sets right-bottom handler position @getHandlerByAlign( RIGHT, BOTTOM ).setPosition(rightBottom) # sets center-top handler position @getHandlerByAlign( CENTER, TOP ).setPosition(centerTop) # sets left-middle handler position @getHandlerByAlign( LEFT, MIDDLE ).setPosition(leftMiddle) # sets right-middle handler position @getHandlerByAlign( RIGHT, MIDDLE ).setPosition(rightMiddle) # sets center-bottom handler position @getHandlerByAlign( CENTER, BOTTOM ).setPosition(centerBottom) view_factory = (attributes) -> handle = new RectHandle attributes handle { type: 'handle-rect' name: 'handle-rect' description: 'Rectangle Handle Specification' defaults: { width: 10 height: 10 fill: 'red' stroke: 'black' strokeWidth: 2 'handler-radius': 10 'handler-fill': 'gray' 'handler-stroke': 'black' 'handler-strokeWidth': 2 'rotate-distance': 10 'border-stroke': 'black' 'border-stroke-width': 2 } view_factory_fn: view_factory toolbox_image: 'images/toolbox_handle_rect.png' }
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PIatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ 'dou' 'KineticJS' ], ( dou kin ) -> "use strict" LEFT = -1 CENTER = 0 RIGHT = 1 TOP = -1 MIDDLE = 0 BOTTOM = 1 # Handler class. # # This class extends the Kinetic.Circle class. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, # right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, # bottom: 1) # @param {Number} radius Handler radius # @param {String} fill Fill color # @param {String} stroke Stroke color # @param {Number} strokeWidth Stroke width # # @return {Void} class Handler extends kin.Circle constructor: (hAlign, vAlign, radius, fill, stroke, strokeWidth) -> @_align = [hAlign, vAlign] kin.Circle.call @, radius: radius fill: fill stroke: stroke strokeWidth: strokeWidth draggable: true # Gets handler alignment. # # Returns an array of two numbers. The first number is the horizontal alignment # and the second number is the vertical alignment. # # @return {Array} getAlign: -> @_align # RotateHandler class. # # This class extends the Kinetic.Circle class. # # @param {Number} radius Handler radius # @param {String} fill Fill color # @param {String} stroke Stroke color # @param {Number} strokeWidth Stroke width # # @return {Void} class RotateHandler extends kin.Circle constructor: (radius, fill, stroke, strokeWidth) -> kin.Circle.call @, radius: radius fill: fill stroke: stroke strokeWidth: strokeWidth draggable: true # RectHandle class. # # This class extends the Kinetic.Group class. # # @param {Object} options Custom options # # @return {Void} class RectHandle extends kin.Group constructor: (options) -> @_options = options @_handlers = [] @_rotateHandler = null @_border = null kin.Group.call @, width: options.width height: options.height fill: options.fill stroke: options.stroke strokeWidth: options.strokeWidth draggable: true @createBorder() @addHandler TOP, LEFT @addHandler TOP, CENTER @addHandler TOP, RIGHT @addHandler MIDDLE, LEFT @addHandler MIDDLE, RIGHT @addHandler BOTTOM, LEFT @addHandler BOTTOM, CENTER @addHandler BOTTOM, RIGHT @addRotateHandler() # Creates the border. # # @return {Void} createBorder: -> @_border = new kin.Line points: [0, 0] stroke: @_options['border-stroke'] strokeWidth: @_options['border-stroke-width'] @add(@_border) # Creates the rotate handler. # # @return {Kinetic.Circle} addRotateHandler: -> self = this @_rotateHandler = new RotateHandler radius: @_options['handler-radius'] fill: @_options['handler-fill'] stroke: @_options['handler-stroke'] strokeWidth: @_options['handler-stroke-width'] @_rotateHandler.setDragBoundFunc (pos) -> if @isDragging() # rotateGroup = self.getParent() p = rotateGroup.getAbsolutePosition() v = x: p.x - pos.x y: p.y - pos.y angle = self.getAngle(v) rotateGroup.setRotation(angle) return pos @_rotateHandler.on 'dragmove', -> self.update() @add @_rotateHandler return @_rotateHandler # Adds a handler. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, bottom: 1) # @param {Boolean} visible Is the handler visible? # # @return {Handler} addHandler: (hAlign, vAlign) -> handler = new Handler( hAlign vAlign @_options['handler-radius'] @_options['handler-fill'] @_options['handler-stroke'] @_options['handler-strokeWidth'] ) @add handler @_handlers.push handler # Gets a handler by alignment. # # @param {Number} hAlign Horizontal alignment (left: -1, center: 0, right: 1) # @param {Number} vAlign Vertical alignment (top: -1, middle: 0, bottom: 1) # # @return {Handler} getHandlerByAlign: (hAlign, vAlign) -> for handler in @_handlers align = handler.getAlign() return handler if (align[0] is hAlign) and (align[1] is vAlign) return null # Gets the opposite handler. # # @return {Handler} getOppositeHandler: (handler) -> align = handler.getAlign() return @getHandlerByAlign -align[0], -align[1] # Set target node for handle # # @param {Kinetic.Node} # # @return {Void} setTarget: (target) -> @_target = target @update() # Set handle to visible # # @return {Void} showHandle: -> @visible true # Set handle to invisible # # @return {Void} hideHandle: -> @visible false # Updates handler positions. # # @return {Void} update: -> # target properties targetX = @_target.getX() - @_target.getOffsetX() targetY = @_target.getY() - @_target.getOffsetY() targetWidth = @_target.getWidth() targetHeight = @_target.getHeight() # positions rotate = x: targetX + targetWidth / 2 y: targetY - @_options['rotate-distance'] leftTop = {x: targetX, y: targetY} rightTop = {x: targetX + targetWidth, y: targetY} leftBottom = {x: targetX, y: targetY + targetHeight} rightBottom = {x: targetX + targetWidth, y: targetY + targetHeight} centerTop = {x: targetX + targetWidth / 2, y: targetY} leftMiddle = {x: targetX, y: targetY + targetHeight / 2} rightMiddle = {x: targetX + targetWidth, y: targetY + targetHeight / 2} centerBottom = {x: targetX + targetWidth / 2, y: targetY + targetHeight} # adds points to the border points = [ centerTop leftTop leftBottom rightBottom rightTop centerTop ] if (@_options['allow-rotate']) points.unshift(rotate) @_border.setPoints(points) # sets rotate handler position @_rotateHandler.setPosition(rotate) # sets left-top handler position @getHandlerByAlign( LEFT, TOP ).setPosition(leftTop) # sets right-top handler position @getHandlerByAlign( RIGHT, TOP ).setPosition(rightTop) # sets left-bottom handler position @getHandlerByAlign( LEFT, BOTTOM ).setPosition(leftBottom) # sets right-bottom handler position @getHandlerByAlign( RIGHT, BOTTOM ).setPosition(rightBottom) # sets center-top handler position @getHandlerByAlign( CENTER, TOP ).setPosition(centerTop) # sets left-middle handler position @getHandlerByAlign( LEFT, MIDDLE ).setPosition(leftMiddle) # sets right-middle handler position @getHandlerByAlign( RIGHT, MIDDLE ).setPosition(rightMiddle) # sets center-bottom handler position @getHandlerByAlign( CENTER, BOTTOM ).setPosition(centerBottom) view_factory = (attributes) -> handle = new RectHandle attributes handle { type: 'handle-rect' name: 'handle-rect' description: 'Rectangle Handle Specification' defaults: { width: 10 height: 10 fill: 'red' stroke: 'black' strokeWidth: 2 'handler-radius': 10 'handler-fill': 'gray' 'handler-stroke': 'black' 'handler-strokeWidth': 2 'rotate-distance': 10 'border-stroke': 'black' 'border-stroke-width': 2 } view_factory_fn: view_factory toolbox_image: 'images/toolbox_handle_rect.png' }
[ { "context": "ype: \"object\"\nproperties:\n username:\n title: \"Username\"\n type: \"string\"\n minLength: 1\n password:\n", "end": 59, "score": 0.9966257810592651, "start": 51, "tag": "USERNAME", "value": "Username" }, { "context": "\"string\"\n minLength: 1\n passw...
public/schemas/message-schema.cson
octoblu/meshblu-authenticator-local-exchange
0
type: "object" properties: username: title: "Username" type: "string" minLength: 1 password: title: "Password" type: "string" minLength: 1
175571
type: "object" properties: username: title: "Username" type: "string" minLength: 1 password: title: "<PASSWORD>" type: "string" minLength: 1
true
type: "object" properties: username: title: "Username" type: "string" minLength: 1 password: title: "PI:PASSWORD:<PASSWORD>END_PI" type: "string" minLength: 1
[ { "context": " value: @doc.name.toString()}\n {key: 'age_bin', value: @doc.age.toString()}\n ]\n\n sc", "end": 443, "score": 0.7970759272575378, "start": 440, "tag": "KEY", "value": "bin" }, { "context": "= IndexedModel.create 'indexed-key-thing', name: 'zack', a...
ExampleZukaiRestApi/node_modules/zukai/test/indexes.coffee
radjivC/interaction-node-riak
0
assert = require 'assert' {createClient} = require 'riakpbc' {createModel} = require '../src' Model = IndexedModel = null describe 'Indexes', -> before (done)-> Model = createModel 'foo', connection: createClient() indexes: -> null IndexedModel = createModel 'bar', connection: createClient() indexes: -> [ {key: 'name_bin', value: @doc.name.toString()} {key: 'age_bin', value: @doc.age.toString()} ] schema: properties: name: type: 'string' age: type: 'number' done() describe 'index function', -> it 'should be present on Models and objects', (done)-> assert Model.indexes? assert Model.create().indexes? assert typeof Model.indexes == 'function' assert typeof Model.create().indexes == 'function' done() it 'should produce arrays when called', (done)-> i = IndexedModel.create 'indexed-key-thing', name: 'zack', age:88 indexes = i.indexes() assert indexes.length == 2 for idx in indexes assert idx.key assert idx.value done() describe 'put operations with indexes', -> it 'should send indexes when called', (done)-> k = 'other-key-thing' i = IndexedModel.create k, name: 'xerxes', age:2531 i.put(return_body:true).then (doc)-> assert doc assert i.reply.content[0].indexes.length == 2 i.indexSearch qtype:1, index:'name_bin', range_min:'a', range_max:'z', (err, keys)-> assert k in keys i.del().then done()
30
assert = require 'assert' {createClient} = require 'riakpbc' {createModel} = require '../src' Model = IndexedModel = null describe 'Indexes', -> before (done)-> Model = createModel 'foo', connection: createClient() indexes: -> null IndexedModel = createModel 'bar', connection: createClient() indexes: -> [ {key: 'name_bin', value: @doc.name.toString()} {key: 'age_<KEY>', value: @doc.age.toString()} ] schema: properties: name: type: 'string' age: type: 'number' done() describe 'index function', -> it 'should be present on Models and objects', (done)-> assert Model.indexes? assert Model.create().indexes? assert typeof Model.indexes == 'function' assert typeof Model.create().indexes == 'function' done() it 'should produce arrays when called', (done)-> i = IndexedModel.create 'indexed-key-thing', name: '<NAME>', age:88 indexes = i.indexes() assert indexes.length == 2 for idx in indexes assert idx.key assert idx.value done() describe 'put operations with indexes', -> it 'should send indexes when called', (done)-> k = 'other-key-thing' i = IndexedModel.create k, name: '<NAME>', age:2531 i.put(return_body:true).then (doc)-> assert doc assert i.reply.content[0].indexes.length == 2 i.indexSearch qtype:1, index:'name_bin', range_min:'a', range_max:'z', (err, keys)-> assert k in keys i.del().then done()
true
assert = require 'assert' {createClient} = require 'riakpbc' {createModel} = require '../src' Model = IndexedModel = null describe 'Indexes', -> before (done)-> Model = createModel 'foo', connection: createClient() indexes: -> null IndexedModel = createModel 'bar', connection: createClient() indexes: -> [ {key: 'name_bin', value: @doc.name.toString()} {key: 'age_PI:KEY:<KEY>END_PI', value: @doc.age.toString()} ] schema: properties: name: type: 'string' age: type: 'number' done() describe 'index function', -> it 'should be present on Models and objects', (done)-> assert Model.indexes? assert Model.create().indexes? assert typeof Model.indexes == 'function' assert typeof Model.create().indexes == 'function' done() it 'should produce arrays when called', (done)-> i = IndexedModel.create 'indexed-key-thing', name: 'PI:NAME:<NAME>END_PI', age:88 indexes = i.indexes() assert indexes.length == 2 for idx in indexes assert idx.key assert idx.value done() describe 'put operations with indexes', -> it 'should send indexes when called', (done)-> k = 'other-key-thing' i = IndexedModel.create k, name: 'PI:NAME:<NAME>END_PI', age:2531 i.put(return_body:true).then (doc)-> assert doc assert i.reply.content[0].indexes.length == 2 i.indexSearch qtype:1, index:'name_bin', range_min:'a', range_max:'z', (err, keys)-> assert k in keys i.del().then done()
[ { "context": " new FactoryBase class: User, ->\n @name = 'john'\n @email = 'john@example.com'\n @seq", "end": 283, "score": 0.8789591193199158, "start": 279, "tag": "NAME", "value": "john" }, { "context": "User, ->\n @name = 'john'\n @email = 'john@...
test/factory_base_test.coffee
JackDanger/factory-boy
2
require('./test_helper') FactoryBase = require('../src/factory_base') class User extends Object describe 'FactoryBase', -> describe '#attributes', -> it 'should return only factory defined attributes', -> factory = new FactoryBase class: User, -> @name = 'john' @email = 'john@example.com' @sequence 'login', (n, callback) -> callback(null, "admin#{n}") @association 'profile' @initializeWith = (klass, attributes, callback) -> callback(null, new klass(attributes)) @createWith = (klass, attributes, callback) -> klass.create(attributes, callback) factory.attributes().should.eql(name: 'john', email: 'john@example.com')
168927
require('./test_helper') FactoryBase = require('../src/factory_base') class User extends Object describe 'FactoryBase', -> describe '#attributes', -> it 'should return only factory defined attributes', -> factory = new FactoryBase class: User, -> @name = '<NAME>' @email = '<EMAIL>' @sequence 'login', (n, callback) -> callback(null, "admin#{n}") @association 'profile' @initializeWith = (klass, attributes, callback) -> callback(null, new klass(attributes)) @createWith = (klass, attributes, callback) -> klass.create(attributes, callback) factory.attributes().should.eql(name: '<NAME>', email: '<EMAIL>')
true
require('./test_helper') FactoryBase = require('../src/factory_base') class User extends Object describe 'FactoryBase', -> describe '#attributes', -> it 'should return only factory defined attributes', -> factory = new FactoryBase class: User, -> @name = 'PI:NAME:<NAME>END_PI' @email = 'PI:EMAIL:<EMAIL>END_PI' @sequence 'login', (n, callback) -> callback(null, "admin#{n}") @association 'profile' @initializeWith = (klass, attributes, callback) -> callback(null, new klass(attributes)) @createWith = (klass, attributes, callback) -> klass.create(attributes, callback) factory.attributes().should.eql(name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI')
[ { "context": "lass Hobbit extends Race\n key: 'hobbit'\n name: 'hobbit'\n\n alignments: ['good']\n rarity: ['trash']", "end": 52, "score": 0.5361436009407043, "start": 51, "tag": "NAME", "value": "h" } ]
js/races/hobbit.coffee
ktchernov/7drl-lion.github.io
27
class Hobbit extends Race key: 'hobbit' name: 'hobbit' alignments: ['good'] rarity: ['trash'] base_hp: 10 base_mp: 20 base_speed: 90 base_attack: 10 base_sight_range: 8 for_player: false skills: [] register_race Hobbit
5352
class Hobbit extends Race key: 'hobbit' name: '<NAME>obbit' alignments: ['good'] rarity: ['trash'] base_hp: 10 base_mp: 20 base_speed: 90 base_attack: 10 base_sight_range: 8 for_player: false skills: [] register_race Hobbit
true
class Hobbit extends Race key: 'hobbit' name: 'PI:NAME:<NAME>END_PIobbit' alignments: ['good'] rarity: ['trash'] base_hp: 10 base_mp: 20 base_speed: 90 base_attack: 10 base_sight_range: 8 for_player: false skills: [] register_race Hobbit
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.987066924571991, "start": 16, "tag": "NAME", "value": "Konode" } ]
src/timeoutDialog.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 # Load in Timeout listeners and trigger warning dialogs _ = require 'underscore' Config = require './config' Persist = require './persist' load = (win) -> $ = win.jQuery React = win.React ReactDOM = win.ReactDOM R = React.DOM Bootbox = win.bootbox nwWin = nw.Window.get(win) Dialog = require('./dialog').load(win) CrashHandler = require('./crashHandler').load(win) Moment = require('moment') TimeoutDialog = React.createFactory React.createClass displayName: 'TimeoutDialog' getInitialState: -> return { countSeconds: null expiration: null isOpen: false password: '' isFinalWarning: false isTimedOut: false } _recalculateSeconds: -> @setState { countSeconds: Moment(@state.expiration).diff(Moment(), 'seconds') } show: -> @setState { password: '' isOpen: true expiration: Moment().add(Config.timeout.warnings.initial, 'minutes') } @_recalculateSeconds() @counter = setInterval(=> @_recalculateSeconds() , 1000) showFinalWarning: -> @setState {isFinalWarning: true} reset: -> clearInterval @counter return unless @state.isOpen or @state.isFinalWarning or @state.isTimedOut @setState { isOpen: false isTimedOut: false } _focusPasswordField: -> @refs.passwordField.focus() if @refs.passwordField? showTimeoutMessage: -> @setState { isTimedOut: true isOpen: true password: '' }, @_focusPasswordField _confirmPassword: (event) -> event.preventDefault() @refs.dialog.setIsLoading true global.ActiveSession.confirmPassword @state.password, (err, result) => @refs.dialog.setIsLoading(false) if @refs.dialog? if err if err instanceof Persist.Session.IncorrectPasswordError Bootbox.alert "Incorrect password for user \'#{global.ActiveSession.userName}\', please try again.", => @setState => password: '' @_focusPasswordField() return if err instanceof Persist.Session.DeactivatedAccountError Bootbox.alert "This user account has been deactivated." return if err instanceof Persist.IOError Bootbox.alert "An error occurred. Please check your network connection and try again.", => @_focusPasswordField() return console.error "Timeout Login Error:", err CrashHandler.handle err return global.ActiveSession.persist.eventBus.trigger 'timeout:reactivateWindows' _updatePassword: (event) -> @setState {password: event.target.value} render: -> unless @state.isOpen return R.div({}) countMoment = Moment.utc(@state.countSeconds * 1000) return Dialog({ ref: 'dialog' title: if @state.isTimedOut then "Your Session Has Timed Out" else "Inactivity Warning" disableBackgroundClick: true containerClasses: [ 'timedOut' if @state.isTimedOut 'warning' if @state.isFinalWarning ] }, R.div({className: 'timeoutDialog'}, (if @state.isTimedOut R.div({className: 'message'}, "Please confirm your password for user \"#{global.ActiveSession.userName}\" to restore all windows." R.form({className: 'form-group'}, R.input({ value: @state.password onChange: @_updatePassword placeholder: "● ● ● ● ●" type: 'password' ref: 'passwordField' }) R.div({className: 'btn-toolbar'}, R.button({ className: 'btn btn-primary btn-lg btn-block' disabled: not @state.password type: 'submit' onClick: @_confirmPassword }, "Confirm Password") ) ) ) else R.div({className: 'message'}, "Your #{Config.productName} session will shut down in " R.span({className: 'timeRemaining'}, if @state.countSeconds >= 60 "#{countMoment.format('mm:ss')} minutes" else "#{countMoment.format('ss')} seconds" ) "due to inactivity" R.br({}) R.br({}) "Any unsaved work will be lost!" ) ) ) ) getTimeoutListeners = -> # TODO: Make sure this doesn't execute again after HCR (#611) # This might be causing all the perf problems after too many HCR's timeoutContainer = win.document.createElement('div') timeoutContainer.id = 'timeoutContainer' win.document.body.appendChild timeoutContainer timeoutComponent = ReactDOM.render TimeoutDialog({}), timeoutContainer # Fires 'resetTimeout' event upon any user interaction (move, click, typing, scroll) resetTimeout = _.throttle(-> global.ActiveSession.persist.eventBus.trigger 'timeout:reset' , 350) $('body').on "mousemove mousedown keypress scroll", resetTimeout return { 'timeout:reset': => # Reset both timeout component and session timeoutComponent.reset() global.ActiveSession.resetTimeout() # Reset knowledge of warnings been delivered delete global.ActiveSession.initialWarningDelivered 'timeout:finalWarning': => timeoutComponent.showFinalWarning() 'timeout:timedOut': => # Remove all timeout-resetting listeners $('body').off "mousemove mousedown keypress scroll" timeoutComponent.showTimeoutMessage() # Ensure only 1 instance of notifications across multiple windows unless global.ActiveSession.timeoutMessage console.log "TIMEOUT: Session timed out, disabling windows..." global.ActiveSession.timeoutMessage = new Notification "Session Timed Out", { body: "Enter your password to continue the #{Config.productName} session." icon: Config.iconNotification } nwWin.requestAttention(1) # Close and remove notification instance after 5s setTimeout(-> global.ActiveSession.timeoutMessage.close() delete global.ActiveSession.timeoutMessage , 6000) 'timeout:reactivateWindows': => console.log "TIMEOUT: Confirmed password, reactivating windows" global.ActiveSession.persist.eventBus.trigger 'timeout:reset' $('body').on "mousemove mousedown keypress scroll", resetTimeout } return {getTimeoutListeners} module.exports = {load}
209201
# 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 # Load in Timeout listeners and trigger warning dialogs _ = require 'underscore' Config = require './config' Persist = require './persist' load = (win) -> $ = win.jQuery React = win.React ReactDOM = win.ReactDOM R = React.DOM Bootbox = win.bootbox nwWin = nw.Window.get(win) Dialog = require('./dialog').load(win) CrashHandler = require('./crashHandler').load(win) Moment = require('moment') TimeoutDialog = React.createFactory React.createClass displayName: 'TimeoutDialog' getInitialState: -> return { countSeconds: null expiration: null isOpen: false password: '' isFinalWarning: false isTimedOut: false } _recalculateSeconds: -> @setState { countSeconds: Moment(@state.expiration).diff(Moment(), 'seconds') } show: -> @setState { password: '' isOpen: true expiration: Moment().add(Config.timeout.warnings.initial, 'minutes') } @_recalculateSeconds() @counter = setInterval(=> @_recalculateSeconds() , 1000) showFinalWarning: -> @setState {isFinalWarning: true} reset: -> clearInterval @counter return unless @state.isOpen or @state.isFinalWarning or @state.isTimedOut @setState { isOpen: false isTimedOut: false } _focusPasswordField: -> @refs.passwordField.focus() if @refs.passwordField? showTimeoutMessage: -> @setState { isTimedOut: true isOpen: true password: '' }, @_focusPasswordField _confirmPassword: (event) -> event.preventDefault() @refs.dialog.setIsLoading true global.ActiveSession.confirmPassword @state.password, (err, result) => @refs.dialog.setIsLoading(false) if @refs.dialog? if err if err instanceof Persist.Session.IncorrectPasswordError Bootbox.alert "Incorrect password for user \'#{global.ActiveSession.userName}\', please try again.", => @setState => password: '' @_focusPasswordField() return if err instanceof Persist.Session.DeactivatedAccountError Bootbox.alert "This user account has been deactivated." return if err instanceof Persist.IOError Bootbox.alert "An error occurred. Please check your network connection and try again.", => @_focusPasswordField() return console.error "Timeout Login Error:", err CrashHandler.handle err return global.ActiveSession.persist.eventBus.trigger 'timeout:reactivateWindows' _updatePassword: (event) -> @setState {password: event.target.value} render: -> unless @state.isOpen return R.div({}) countMoment = Moment.utc(@state.countSeconds * 1000) return Dialog({ ref: 'dialog' title: if @state.isTimedOut then "Your Session Has Timed Out" else "Inactivity Warning" disableBackgroundClick: true containerClasses: [ 'timedOut' if @state.isTimedOut 'warning' if @state.isFinalWarning ] }, R.div({className: 'timeoutDialog'}, (if @state.isTimedOut R.div({className: 'message'}, "Please confirm your password for user \"#{global.ActiveSession.userName}\" to restore all windows." R.form({className: 'form-group'}, R.input({ value: @state.password onChange: @_updatePassword placeholder: "● ● ● ● ●" type: 'password' ref: 'passwordField' }) R.div({className: 'btn-toolbar'}, R.button({ className: 'btn btn-primary btn-lg btn-block' disabled: not @state.password type: 'submit' onClick: @_confirmPassword }, "Confirm Password") ) ) ) else R.div({className: 'message'}, "Your #{Config.productName} session will shut down in " R.span({className: 'timeRemaining'}, if @state.countSeconds >= 60 "#{countMoment.format('mm:ss')} minutes" else "#{countMoment.format('ss')} seconds" ) "due to inactivity" R.br({}) R.br({}) "Any unsaved work will be lost!" ) ) ) ) getTimeoutListeners = -> # TODO: Make sure this doesn't execute again after HCR (#611) # This might be causing all the perf problems after too many HCR's timeoutContainer = win.document.createElement('div') timeoutContainer.id = 'timeoutContainer' win.document.body.appendChild timeoutContainer timeoutComponent = ReactDOM.render TimeoutDialog({}), timeoutContainer # Fires 'resetTimeout' event upon any user interaction (move, click, typing, scroll) resetTimeout = _.throttle(-> global.ActiveSession.persist.eventBus.trigger 'timeout:reset' , 350) $('body').on "mousemove mousedown keypress scroll", resetTimeout return { 'timeout:reset': => # Reset both timeout component and session timeoutComponent.reset() global.ActiveSession.resetTimeout() # Reset knowledge of warnings been delivered delete global.ActiveSession.initialWarningDelivered 'timeout:finalWarning': => timeoutComponent.showFinalWarning() 'timeout:timedOut': => # Remove all timeout-resetting listeners $('body').off "mousemove mousedown keypress scroll" timeoutComponent.showTimeoutMessage() # Ensure only 1 instance of notifications across multiple windows unless global.ActiveSession.timeoutMessage console.log "TIMEOUT: Session timed out, disabling windows..." global.ActiveSession.timeoutMessage = new Notification "Session Timed Out", { body: "Enter your password to continue the #{Config.productName} session." icon: Config.iconNotification } nwWin.requestAttention(1) # Close and remove notification instance after 5s setTimeout(-> global.ActiveSession.timeoutMessage.close() delete global.ActiveSession.timeoutMessage , 6000) 'timeout:reactivateWindows': => console.log "TIMEOUT: Confirmed password, reactivating windows" global.ActiveSession.persist.eventBus.trigger 'timeout:reset' $('body').on "mousemove mousedown keypress scroll", resetTimeout } return {getTimeoutListeners} 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 # Load in Timeout listeners and trigger warning dialogs _ = require 'underscore' Config = require './config' Persist = require './persist' load = (win) -> $ = win.jQuery React = win.React ReactDOM = win.ReactDOM R = React.DOM Bootbox = win.bootbox nwWin = nw.Window.get(win) Dialog = require('./dialog').load(win) CrashHandler = require('./crashHandler').load(win) Moment = require('moment') TimeoutDialog = React.createFactory React.createClass displayName: 'TimeoutDialog' getInitialState: -> return { countSeconds: null expiration: null isOpen: false password: '' isFinalWarning: false isTimedOut: false } _recalculateSeconds: -> @setState { countSeconds: Moment(@state.expiration).diff(Moment(), 'seconds') } show: -> @setState { password: '' isOpen: true expiration: Moment().add(Config.timeout.warnings.initial, 'minutes') } @_recalculateSeconds() @counter = setInterval(=> @_recalculateSeconds() , 1000) showFinalWarning: -> @setState {isFinalWarning: true} reset: -> clearInterval @counter return unless @state.isOpen or @state.isFinalWarning or @state.isTimedOut @setState { isOpen: false isTimedOut: false } _focusPasswordField: -> @refs.passwordField.focus() if @refs.passwordField? showTimeoutMessage: -> @setState { isTimedOut: true isOpen: true password: '' }, @_focusPasswordField _confirmPassword: (event) -> event.preventDefault() @refs.dialog.setIsLoading true global.ActiveSession.confirmPassword @state.password, (err, result) => @refs.dialog.setIsLoading(false) if @refs.dialog? if err if err instanceof Persist.Session.IncorrectPasswordError Bootbox.alert "Incorrect password for user \'#{global.ActiveSession.userName}\', please try again.", => @setState => password: '' @_focusPasswordField() return if err instanceof Persist.Session.DeactivatedAccountError Bootbox.alert "This user account has been deactivated." return if err instanceof Persist.IOError Bootbox.alert "An error occurred. Please check your network connection and try again.", => @_focusPasswordField() return console.error "Timeout Login Error:", err CrashHandler.handle err return global.ActiveSession.persist.eventBus.trigger 'timeout:reactivateWindows' _updatePassword: (event) -> @setState {password: event.target.value} render: -> unless @state.isOpen return R.div({}) countMoment = Moment.utc(@state.countSeconds * 1000) return Dialog({ ref: 'dialog' title: if @state.isTimedOut then "Your Session Has Timed Out" else "Inactivity Warning" disableBackgroundClick: true containerClasses: [ 'timedOut' if @state.isTimedOut 'warning' if @state.isFinalWarning ] }, R.div({className: 'timeoutDialog'}, (if @state.isTimedOut R.div({className: 'message'}, "Please confirm your password for user \"#{global.ActiveSession.userName}\" to restore all windows." R.form({className: 'form-group'}, R.input({ value: @state.password onChange: @_updatePassword placeholder: "● ● ● ● ●" type: 'password' ref: 'passwordField' }) R.div({className: 'btn-toolbar'}, R.button({ className: 'btn btn-primary btn-lg btn-block' disabled: not @state.password type: 'submit' onClick: @_confirmPassword }, "Confirm Password") ) ) ) else R.div({className: 'message'}, "Your #{Config.productName} session will shut down in " R.span({className: 'timeRemaining'}, if @state.countSeconds >= 60 "#{countMoment.format('mm:ss')} minutes" else "#{countMoment.format('ss')} seconds" ) "due to inactivity" R.br({}) R.br({}) "Any unsaved work will be lost!" ) ) ) ) getTimeoutListeners = -> # TODO: Make sure this doesn't execute again after HCR (#611) # This might be causing all the perf problems after too many HCR's timeoutContainer = win.document.createElement('div') timeoutContainer.id = 'timeoutContainer' win.document.body.appendChild timeoutContainer timeoutComponent = ReactDOM.render TimeoutDialog({}), timeoutContainer # Fires 'resetTimeout' event upon any user interaction (move, click, typing, scroll) resetTimeout = _.throttle(-> global.ActiveSession.persist.eventBus.trigger 'timeout:reset' , 350) $('body').on "mousemove mousedown keypress scroll", resetTimeout return { 'timeout:reset': => # Reset both timeout component and session timeoutComponent.reset() global.ActiveSession.resetTimeout() # Reset knowledge of warnings been delivered delete global.ActiveSession.initialWarningDelivered 'timeout:finalWarning': => timeoutComponent.showFinalWarning() 'timeout:timedOut': => # Remove all timeout-resetting listeners $('body').off "mousemove mousedown keypress scroll" timeoutComponent.showTimeoutMessage() # Ensure only 1 instance of notifications across multiple windows unless global.ActiveSession.timeoutMessage console.log "TIMEOUT: Session timed out, disabling windows..." global.ActiveSession.timeoutMessage = new Notification "Session Timed Out", { body: "Enter your password to continue the #{Config.productName} session." icon: Config.iconNotification } nwWin.requestAttention(1) # Close and remove notification instance after 5s setTimeout(-> global.ActiveSession.timeoutMessage.close() delete global.ActiveSession.timeoutMessage , 6000) 'timeout:reactivateWindows': => console.log "TIMEOUT: Confirmed password, reactivating windows" global.ActiveSession.persist.eventBus.trigger 'timeout:reset' $('body').on "mousemove mousedown keypress scroll", resetTimeout } return {getTimeoutListeners} module.exports = {load}
[ { "context": "me format, format should be in the form of email : user@sample.com'\n\n\n LANG.title='Manage Profile Setting", "end": 1605, "score": 0.9999145269393921, "start": 1590, "tag": "EMAIL", "value": "user@sample.com" } ]
modules/profile_settings/profile_settings.coffee
signonsridhar/sridhar_hbs
0
define(['bases/control', 'models/user/user', 'css!modules/profile_settings/profile_settings' ], (BaseControl, User)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'must be between 2-40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.SIZE] = 'must be between 2-40 characters' LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : user@sample.com' LANG.title='Manage Profile Settings' LANG.profile_changed= 'Profile changed' LANG.errors[VALID.ERROR.INVALID] = 'Failed to update profile' LANG },{ init: (elem, options)-> this.prev_email_upper = this.options.prof_user.attr('email').toUpperCase() this.prev_first_name_upper = this.options.prof_user.attr('first_name').toUpperCase() this.prev_last_name_upper = this.options.prof_user.attr('last_name').toUpperCase() this.setup_viewmodel({ is_profile_changed: false }) this.render('profile_settings/profile_settings', {prof_user: this.options.prof_user}) this.bind_view(this.options.prof_user) this.set_validity(false) set_email:()-> this.options.prof_user.set_email() 'form submit': ()-> promise1 = this.options.prof_user.set_name() if (this.prev_email_upper != this.options.prof_user.email.toUpperCase) promise1.then(this.set_email).then(()=> this.viewmodel.attr('is_profile_changed', true) ).fail(()=> this.viewmodel.attr('is_profile_changed', false) this.viewmodel.attr('errors.display', "invalid") ).always(()=> this.options.prof_user.valid(false) ) else promise1.done(()=> this.viewmodel.attr('is_profile_changed', true) ).fail(()=> this.viewmodel.attr('is_profile_changed', false) this.viewmodel.attr('errors.display', "invalid") ).always(()=> this.options.prof_user.valid(false) ) return false '{user.valid} change': ()-> this.set_validity(this.options.prof_user.valid()) validate: ()-> this.options.prof_user.validate() }) )
97767
define(['bases/control', 'models/user/user', 'css!modules/profile_settings/profile_settings' ], (BaseControl, User)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'must be between 2-40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.SIZE] = 'must be between 2-40 characters' LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : <EMAIL>' LANG.title='Manage Profile Settings' LANG.profile_changed= 'Profile changed' LANG.errors[VALID.ERROR.INVALID] = 'Failed to update profile' LANG },{ init: (elem, options)-> this.prev_email_upper = this.options.prof_user.attr('email').toUpperCase() this.prev_first_name_upper = this.options.prof_user.attr('first_name').toUpperCase() this.prev_last_name_upper = this.options.prof_user.attr('last_name').toUpperCase() this.setup_viewmodel({ is_profile_changed: false }) this.render('profile_settings/profile_settings', {prof_user: this.options.prof_user}) this.bind_view(this.options.prof_user) this.set_validity(false) set_email:()-> this.options.prof_user.set_email() 'form submit': ()-> promise1 = this.options.prof_user.set_name() if (this.prev_email_upper != this.options.prof_user.email.toUpperCase) promise1.then(this.set_email).then(()=> this.viewmodel.attr('is_profile_changed', true) ).fail(()=> this.viewmodel.attr('is_profile_changed', false) this.viewmodel.attr('errors.display', "invalid") ).always(()=> this.options.prof_user.valid(false) ) else promise1.done(()=> this.viewmodel.attr('is_profile_changed', true) ).fail(()=> this.viewmodel.attr('is_profile_changed', false) this.viewmodel.attr('errors.display', "invalid") ).always(()=> this.options.prof_user.valid(false) ) return false '{user.valid} change': ()-> this.set_validity(this.options.prof_user.valid()) validate: ()-> this.options.prof_user.validate() }) )
true
define(['bases/control', 'models/user/user', 'css!modules/profile_settings/profile_settings' ], (BaseControl, User)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'must be between 2-40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.SIZE] = 'must be between 2-40 characters' LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : PI:EMAIL:<EMAIL>END_PI' LANG.title='Manage Profile Settings' LANG.profile_changed= 'Profile changed' LANG.errors[VALID.ERROR.INVALID] = 'Failed to update profile' LANG },{ init: (elem, options)-> this.prev_email_upper = this.options.prof_user.attr('email').toUpperCase() this.prev_first_name_upper = this.options.prof_user.attr('first_name').toUpperCase() this.prev_last_name_upper = this.options.prof_user.attr('last_name').toUpperCase() this.setup_viewmodel({ is_profile_changed: false }) this.render('profile_settings/profile_settings', {prof_user: this.options.prof_user}) this.bind_view(this.options.prof_user) this.set_validity(false) set_email:()-> this.options.prof_user.set_email() 'form submit': ()-> promise1 = this.options.prof_user.set_name() if (this.prev_email_upper != this.options.prof_user.email.toUpperCase) promise1.then(this.set_email).then(()=> this.viewmodel.attr('is_profile_changed', true) ).fail(()=> this.viewmodel.attr('is_profile_changed', false) this.viewmodel.attr('errors.display', "invalid") ).always(()=> this.options.prof_user.valid(false) ) else promise1.done(()=> this.viewmodel.attr('is_profile_changed', true) ).fail(()=> this.viewmodel.attr('is_profile_changed', false) this.viewmodel.attr('errors.display', "invalid") ).always(()=> this.options.prof_user.valid(false) ) return false '{user.valid} change': ()-> this.set_validity(this.options.prof_user.valid()) validate: ()-> this.options.prof_user.validate() }) )
[ { "context": "##\n * Federated Wiki : Node Server\n *\n * Copyright Ward Cunningham and other contributors\n * Licensed under the MIT ", "end": 67, "score": 0.9998761415481567, "start": 52, "tag": "NAME", "value": "Ward Cunningham" }, { "context": "nsed under the MIT license.\n * htt...
cli.coffee
RalfBarkow/wiki
0
### * Federated Wiki : Node Server * * Copyright Ward Cunningham and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki/blob/master/LICENSE.txt ### # **cli.coffee** command line interface for the # Smallest-Federated-Wiki express server http = require('http') # socketio = require('socket.io') path = require 'path' cluster = require 'cluster' parseArgs = require 'minimist' cc = require 'config-chain' glob = require 'glob' server = require 'wiki-server' farm = require './farm' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE # Handle command line options opts = { alias: { u: 'url' p: 'port' d: 'data' r: 'root' f: 'farm' o: 'host' h: 'help' conf: 'config' v: 'version' } } argv = parseArgs(process.argv.slice(2), opts) config = cc(argv, argv.config, 'config.json', path.join(__dirname, '..', 'config.json'), path.join(getUserHome(), '.wiki', 'config.json'), cc.env('wiki_'), port: 3000 root: path.dirname(require.resolve('wiki-server')) home: 'welcome-visitors' security_type: './security' data: path.join(getUserHome(), '.wiki') # see also defaultargs packageDir: path.resolve(path.join(__dirname, 'node_modules')) cookieSecret: require('crypto').randomBytes(64).toString('hex') ).store # If h/help is set print the help message and exit. if argv.help console.log(""" Usage: wiki Options: --help, -h Show this help info and exit --config, --conf Optional config file. --version, -v Show version number and exit """) return # If v/version is set print the version of the wiki components and exit. if argv.version console.log('wiki: ' + require('./package').version) console.log('wiki-server: ' + require('wiki-server/package').version) console.log('wiki-client: ' + require('wiki-client/package').version) glob 'wiki-security-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ": " + require(plugin + "/package").version) glob 'wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ': ' + require(plugin + '/package').version) return if argv.test console.log "WARNING: Server started in testing mode, other options ignored" server({port: 33333, data: path.join(argv.root, 'spec', 'data')}) return if cluster.isMaster cluster.on 'exit', (worker, code, signal) -> if code is 0 console.log 'restarting wiki server' cluster.fork() else console.error 'server unexpectly exitted, %d (%s)', worker.process.pid, signal || code cluster.fork() else if config.farm console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n') if !argv.wikiDomains and !argv.allowed console.log 'WARNING : Starting Wiki Farm in promiscous mode\n' if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki Farm will be read-only\n' unless (argv.security_legacy) farm(config) else app = server(config) app.on 'owner-set', (e) -> server = http.Server(app) # app.io = socketio(server) serv = server.listen app.startOpts.port, app.startOpts.host console.log "Federated Wiki server listening on", app.startOpts.port, "in mode:", app.settings.env if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki will be read-only\n' unless (argv.security_legacy) app.emit 'running-serv', serv
218421
### * Federated Wiki : Node Server * * Copyright <NAME> and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki/blob/master/LICENSE.txt ### # **cli.coffee** command line interface for the # Smallest-Federated-Wiki express server http = require('http') # socketio = require('socket.io') path = require 'path' cluster = require 'cluster' parseArgs = require 'minimist' cc = require 'config-chain' glob = require 'glob' server = require 'wiki-server' farm = require './farm' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE # Handle command line options opts = { alias: { u: 'url' p: 'port' d: 'data' r: 'root' f: 'farm' o: 'host' h: 'help' conf: 'config' v: 'version' } } argv = parseArgs(process.argv.slice(2), opts) config = cc(argv, argv.config, 'config.json', path.join(__dirname, '..', 'config.json'), path.join(getUserHome(), '.wiki', 'config.json'), cc.env('wiki_'), port: 3000 root: path.dirname(require.resolve('wiki-server')) home: 'welcome-visitors' security_type: './security' data: path.join(getUserHome(), '.wiki') # see also defaultargs packageDir: path.resolve(path.join(__dirname, 'node_modules')) cookieSecret: require('crypto').randomBytes(64).toString('hex') ).store # If h/help is set print the help message and exit. if argv.help console.log(""" Usage: wiki Options: --help, -h Show this help info and exit --config, --conf Optional config file. --version, -v Show version number and exit """) return # If v/version is set print the version of the wiki components and exit. if argv.version console.log('wiki: ' + require('./package').version) console.log('wiki-server: ' + require('wiki-server/package').version) console.log('wiki-client: ' + require('wiki-client/package').version) glob 'wiki-security-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ": " + require(plugin + "/package").version) glob 'wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ': ' + require(plugin + '/package').version) return if argv.test console.log "WARNING: Server started in testing mode, other options ignored" server({port: 33333, data: path.join(argv.root, 'spec', 'data')}) return if cluster.isMaster cluster.on 'exit', (worker, code, signal) -> if code is 0 console.log 'restarting wiki server' cluster.fork() else console.error 'server unexpectly exitted, %d (%s)', worker.process.pid, signal || code cluster.fork() else if config.farm console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n') if !argv.wikiDomains and !argv.allowed console.log 'WARNING : Starting Wiki Farm in promiscous mode\n' if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki Farm will be read-only\n' unless (argv.security_legacy) farm(config) else app = server(config) app.on 'owner-set', (e) -> server = http.Server(app) # app.io = socketio(server) serv = server.listen app.startOpts.port, app.startOpts.host console.log "Federated Wiki server listening on", app.startOpts.port, "in mode:", app.settings.env if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki will be read-only\n' unless (argv.security_legacy) app.emit 'running-serv', serv
true
### * Federated Wiki : Node Server * * Copyright PI:NAME:<NAME>END_PI and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki/blob/master/LICENSE.txt ### # **cli.coffee** command line interface for the # Smallest-Federated-Wiki express server http = require('http') # socketio = require('socket.io') path = require 'path' cluster = require 'cluster' parseArgs = require 'minimist' cc = require 'config-chain' glob = require 'glob' server = require 'wiki-server' farm = require './farm' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE # Handle command line options opts = { alias: { u: 'url' p: 'port' d: 'data' r: 'root' f: 'farm' o: 'host' h: 'help' conf: 'config' v: 'version' } } argv = parseArgs(process.argv.slice(2), opts) config = cc(argv, argv.config, 'config.json', path.join(__dirname, '..', 'config.json'), path.join(getUserHome(), '.wiki', 'config.json'), cc.env('wiki_'), port: 3000 root: path.dirname(require.resolve('wiki-server')) home: 'welcome-visitors' security_type: './security' data: path.join(getUserHome(), '.wiki') # see also defaultargs packageDir: path.resolve(path.join(__dirname, 'node_modules')) cookieSecret: require('crypto').randomBytes(64).toString('hex') ).store # If h/help is set print the help message and exit. if argv.help console.log(""" Usage: wiki Options: --help, -h Show this help info and exit --config, --conf Optional config file. --version, -v Show version number and exit """) return # If v/version is set print the version of the wiki components and exit. if argv.version console.log('wiki: ' + require('./package').version) console.log('wiki-server: ' + require('wiki-server/package').version) console.log('wiki-client: ' + require('wiki-client/package').version) glob 'wiki-security-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ": " + require(plugin + "/package").version) glob 'wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ': ' + require(plugin + '/package').version) return if argv.test console.log "WARNING: Server started in testing mode, other options ignored" server({port: 33333, data: path.join(argv.root, 'spec', 'data')}) return if cluster.isMaster cluster.on 'exit', (worker, code, signal) -> if code is 0 console.log 'restarting wiki server' cluster.fork() else console.error 'server unexpectly exitted, %d (%s)', worker.process.pid, signal || code cluster.fork() else if config.farm console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n') if !argv.wikiDomains and !argv.allowed console.log 'WARNING : Starting Wiki Farm in promiscous mode\n' if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki Farm will be read-only\n' unless (argv.security_legacy) farm(config) else app = server(config) app.on 'owner-set', (e) -> server = http.Server(app) # app.io = socketio(server) serv = server.listen app.startOpts.port, app.startOpts.host console.log "Federated Wiki server listening on", app.startOpts.port, "in mode:", app.settings.env if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki will be read-only\n' unless (argv.security_legacy) app.emit 'running-serv', serv
[ { "context": "er for the `STYLE` elements\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\n\nclass Style extends Element\n\n #\n # Basic con", "end": 84, "score": 0.9998900294303894, "start": 67, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/dom/src/style.coffee
lovely-io/lovely.io-stl
2
# # Custom wrapper for the `STYLE` elements # # Copyright (C) 2012 Nikolay Nemshilov # class Style extends Element # # Basic constructor # # @param {Object} options # @return {Style} this # constructor: (options)-> super 'style', type: 'text/css' options or= {} if typeof(options.html) is 'string' @_.appendChild document.createTextNode(options.html) return @ Style.include = Element.include
73899
# # Custom wrapper for the `STYLE` elements # # Copyright (C) 2012 <NAME> # class Style extends Element # # Basic constructor # # @param {Object} options # @return {Style} this # constructor: (options)-> super 'style', type: 'text/css' options or= {} if typeof(options.html) is 'string' @_.appendChild document.createTextNode(options.html) return @ Style.include = Element.include
true
# # Custom wrapper for the `STYLE` elements # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Style extends Element # # Basic constructor # # @param {Object} options # @return {Style} this # constructor: (options)-> super 'style', type: 'text/css' options or= {} if typeof(options.html) is 'string' @_.appendChild document.createTextNode(options.html) return @ Style.include = Element.include
[ { "context": "lly installed packages\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\n\nexports.init = (args) ->\n fs = require", "end": 92, "score": 0.9998892545700073, "start": 75, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
cli/commands/update.coffee
lovely-io/lovely.io-stl
2
# # Updates all the locally installed packages # # Copyright (C) 2011-2012 Nikolay Nemshilov # exports.init = (args) -> fs = require('fs') hosting = require('../hosting') repo = require('../repository') lovelyrc = require('../lovelyrc') location = lovelyrc.base installed = [] for name, versions of repo.list() installed.push(name: name, version: versions[0]) print "» Updating installed packages" update_next = -> return if installed.length is 0 entry = installed.shift() sout " ∙ ".grey + entry.name.ljust(16) + entry.version.grey + " " hosting.get_package entry.name, null, (pack, build)-> if entry.version < pack.version repo.save(pack, build) sout "→".yellow + " #{pack.version}\n" else sout "✓ ".grey + "Ok\n".green update_next() update_next() exports.help = (args) -> """ Updates all the locally installed packages from the server Usage: lovely update """
85694
# # Updates all the locally installed packages # # Copyright (C) 2011-2012 <NAME> # exports.init = (args) -> fs = require('fs') hosting = require('../hosting') repo = require('../repository') lovelyrc = require('../lovelyrc') location = lovelyrc.base installed = [] for name, versions of repo.list() installed.push(name: name, version: versions[0]) print "» Updating installed packages" update_next = -> return if installed.length is 0 entry = installed.shift() sout " ∙ ".grey + entry.name.ljust(16) + entry.version.grey + " " hosting.get_package entry.name, null, (pack, build)-> if entry.version < pack.version repo.save(pack, build) sout "→".yellow + " #{pack.version}\n" else sout "✓ ".grey + "Ok\n".green update_next() update_next() exports.help = (args) -> """ Updates all the locally installed packages from the server Usage: lovely update """
true
# # Updates all the locally installed packages # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # exports.init = (args) -> fs = require('fs') hosting = require('../hosting') repo = require('../repository') lovelyrc = require('../lovelyrc') location = lovelyrc.base installed = [] for name, versions of repo.list() installed.push(name: name, version: versions[0]) print "» Updating installed packages" update_next = -> return if installed.length is 0 entry = installed.shift() sout " ∙ ".grey + entry.name.ljust(16) + entry.version.grey + " " hosting.get_package entry.name, null, (pack, build)-> if entry.version < pack.version repo.save(pack, build) sout "→".yellow + " #{pack.version}\n" else sout "✓ ".grey + "Ok\n".green update_next() update_next() exports.help = (args) -> """ Updates all the locally installed packages from the server Usage: lovely update """
[ { "context": "5 * 24 * 60 * 60)\n app.use json()\n app.keys = ['gdaf987G**(*^%', '&*YUG^RTFUF^GYU']\n app.use session(\n store: ", "end": 823, "score": 0.9992183446884155, "start": 807, "tag": "KEY", "value": "gdaf987G**(*^%'," }, { "context": ")\n app.use json()\n app.keys =...
coffee/index.coffee
touka0/snaply
0
module.exports = (root) -> # Core dependency koa = require 'koa' app = koa() Router = require 'koa-router' json = require 'koa-json' path = require 'path' session = require 'koa-generic-session' staticCache = require 'koa-static-cache' redisStore = require 'koa-redis' cors = require 'koa-cors' logger = require 'koa-logger' # Load configs config = require './config' helpers = require './helpers' # Global variables global.C = config global.C.env = process.env.SNAP_ENV || C.env console.log C.env global.C.root = root global.H = helpers passport = require './passport' routes = require './routes' app.use logger() app.use cors() # App configs app.use staticCache(path.join(root, 'assets'), maxAge: 365 * 24 * 60 * 60) app.use json() app.keys = ['gdaf987G**(*^%', '&*YUG^RTFUF^GYU'] app.use session( store: new redisStore(), prefix: 'snaply-'+C.env+':sess', key: 'snaply-'+C.env, cookie: path: '/', httpOnly: false, maxage: 86400 * 1000 * 365, rewrite: true, signed: true ) app.use Router(app) app.use passport.initialize() app.use passport.session() authed = (next) -> if this.req.isAuthenticated() yield next; else this.session.returnTo = this.session.returnTo || this.req.url; this.redirect '/' # Routes configs router = new Router() router.get '/', routes.index router.get '/p/:id', routes.p router.get '/p/:id/raw', routes.p_raw router.get '/p/:id/html', routes.p_html router.get '/p/:id/edit', authed, routes.edit router.post '/api/markdown', routes.markdown router.post '/save/remove', authed, routes.remove router.post '/save/new', routes.create router.post '/save/update', routes.update router.get '/auth/github', passport.authenticate('github', scope: ['user:email'] ) router.get '/auth/github/callback', passport.authenticate 'github', successRedirect: '/', failureRedirect: '/' router.get '/app', authed, -> this.body = yield this.req.user router.post '/settings/password', authed, routes.password router.get '/logout', (next) -> this.logout() this.redirect '/' yield next app.use router.middleware() # Listen on port app.listen config.port console.log config.site.name + ' is singing at http://localhost:' + config.port
130252
module.exports = (root) -> # Core dependency koa = require 'koa' app = koa() Router = require 'koa-router' json = require 'koa-json' path = require 'path' session = require 'koa-generic-session' staticCache = require 'koa-static-cache' redisStore = require 'koa-redis' cors = require 'koa-cors' logger = require 'koa-logger' # Load configs config = require './config' helpers = require './helpers' # Global variables global.C = config global.C.env = process.env.SNAP_ENV || C.env console.log C.env global.C.root = root global.H = helpers passport = require './passport' routes = require './routes' app.use logger() app.use cors() # App configs app.use staticCache(path.join(root, 'assets'), maxAge: 365 * 24 * 60 * 60) app.use json() app.keys = ['<KEY> <KEY>'] app.use session( store: new redisStore(), prefix: 'snaply-'+C.env+':sess', key: '<KEY>, cookie: path: '/', httpOnly: false, maxage: 86400 * 1000 * 365, rewrite: true, signed: true ) app.use Router(app) app.use passport.initialize() app.use passport.session() authed = (next) -> if this.req.isAuthenticated() yield next; else this.session.returnTo = this.session.returnTo || this.req.url; this.redirect '/' # Routes configs router = new Router() router.get '/', routes.index router.get '/p/:id', routes.p router.get '/p/:id/raw', routes.p_raw router.get '/p/:id/html', routes.p_html router.get '/p/:id/edit', authed, routes.edit router.post '/api/markdown', routes.markdown router.post '/save/remove', authed, routes.remove router.post '/save/new', routes.create router.post '/save/update', routes.update router.get '/auth/github', passport.authenticate('github', scope: ['user:email'] ) router.get '/auth/github/callback', passport.authenticate 'github', successRedirect: '/', failureRedirect: '/' router.get '/app', authed, -> this.body = yield this.req.user router.post '/settings/password', authed, routes.password router.get '/logout', (next) -> this.logout() this.redirect '/' yield next app.use router.middleware() # Listen on port app.listen config.port console.log config.site.name + ' is singing at http://localhost:' + config.port
true
module.exports = (root) -> # Core dependency koa = require 'koa' app = koa() Router = require 'koa-router' json = require 'koa-json' path = require 'path' session = require 'koa-generic-session' staticCache = require 'koa-static-cache' redisStore = require 'koa-redis' cors = require 'koa-cors' logger = require 'koa-logger' # Load configs config = require './config' helpers = require './helpers' # Global variables global.C = config global.C.env = process.env.SNAP_ENV || C.env console.log C.env global.C.root = root global.H = helpers passport = require './passport' routes = require './routes' app.use logger() app.use cors() # App configs app.use staticCache(path.join(root, 'assets'), maxAge: 365 * 24 * 60 * 60) app.use json() app.keys = ['PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI'] app.use session( store: new redisStore(), prefix: 'snaply-'+C.env+':sess', key: 'PI:KEY:<KEY>END_PI, cookie: path: '/', httpOnly: false, maxage: 86400 * 1000 * 365, rewrite: true, signed: true ) app.use Router(app) app.use passport.initialize() app.use passport.session() authed = (next) -> if this.req.isAuthenticated() yield next; else this.session.returnTo = this.session.returnTo || this.req.url; this.redirect '/' # Routes configs router = new Router() router.get '/', routes.index router.get '/p/:id', routes.p router.get '/p/:id/raw', routes.p_raw router.get '/p/:id/html', routes.p_html router.get '/p/:id/edit', authed, routes.edit router.post '/api/markdown', routes.markdown router.post '/save/remove', authed, routes.remove router.post '/save/new', routes.create router.post '/save/update', routes.update router.get '/auth/github', passport.authenticate('github', scope: ['user:email'] ) router.get '/auth/github/callback', passport.authenticate 'github', successRedirect: '/', failureRedirect: '/' router.get '/app', authed, -> this.body = yield this.req.user router.post '/settings/password', authed, routes.password router.get '/logout', (next) -> this.logout() this.redirect '/' yield next app.use router.middleware() # Listen on port app.listen config.port console.log config.site.name + ' is singing at http://localhost:' + config.port
[ { "context": " array for list of trigger phrases\n#\n# Author:\n# Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize)\n\n", "end": 424, "score": 0.9998934268951416, "start": 408, "tag": "NAME", "value": "Morgan Wigmanich" }, { "context": "trigger phrases\n#\n# Author:\...
src/businesscat.coffee
thomasward1212/hubot-business-cat
0
# Description: # Business cat is summoned when business jargon is used # # Dependencies: # None # # Configuration: # HUBOT_BUSINESS_CAT_JARGON comma-separated list of additional "tiggers" # HUBOT_BUSINESS_CAT_OMITTED_JARGON comma-separated list of triggers to ignore # # Commands: # Business jargon - summons business cat # # Notes: # See jargon array for list of trigger phrases # # Author: # Morgan Wigmanich <okize123@gmail.com> (https://github.com/okize) images = require './data/images.json' jargon = require './data/triggers.json' removeTerm = (term, arrayToDeleteFrom) -> index = arrayToDeleteFrom.indexOf term if index > -1 arrayToDeleteFrom.splice index, 1 return arrayToDeleteFrom if process.env.HUBOT_BUSINESS_CAT_JARGON? additionalJargon = (process.env.HUBOT_BUSINESS_CAT_JARGON).split(',') jargon = jargon.concat(additionalJargon) if process.env.HUBOT_BUSINESS_CAT_OMITTED_JARGON? omittedJargon = (process.env.HUBOT_BUSINESS_CAT_OMITTED_JARGON).split(',') jargon = removeTerm(term, jargon) for term in omittedJargon regex = new RegExp jargon.join('|'), 'gi' module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images
219885
# Description: # Business cat is summoned when business jargon is used # # Dependencies: # None # # Configuration: # HUBOT_BUSINESS_CAT_JARGON comma-separated list of additional "tiggers" # HUBOT_BUSINESS_CAT_OMITTED_JARGON comma-separated list of triggers to ignore # # Commands: # Business jargon - summons business cat # # Notes: # See jargon array for list of trigger phrases # # Author: # <NAME> <<EMAIL>> (https://github.com/okize) images = require './data/images.json' jargon = require './data/triggers.json' removeTerm = (term, arrayToDeleteFrom) -> index = arrayToDeleteFrom.indexOf term if index > -1 arrayToDeleteFrom.splice index, 1 return arrayToDeleteFrom if process.env.HUBOT_BUSINESS_CAT_JARGON? additionalJargon = (process.env.HUBOT_BUSINESS_CAT_JARGON).split(',') jargon = jargon.concat(additionalJargon) if process.env.HUBOT_BUSINESS_CAT_OMITTED_JARGON? omittedJargon = (process.env.HUBOT_BUSINESS_CAT_OMITTED_JARGON).split(',') jargon = removeTerm(term, jargon) for term in omittedJargon regex = new RegExp jargon.join('|'), 'gi' module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images
true
# Description: # Business cat is summoned when business jargon is used # # Dependencies: # None # # Configuration: # HUBOT_BUSINESS_CAT_JARGON comma-separated list of additional "tiggers" # HUBOT_BUSINESS_CAT_OMITTED_JARGON comma-separated list of triggers to ignore # # Commands: # Business jargon - summons business cat # # Notes: # See jargon array for list of trigger phrases # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/okize) images = require './data/images.json' jargon = require './data/triggers.json' removeTerm = (term, arrayToDeleteFrom) -> index = arrayToDeleteFrom.indexOf term if index > -1 arrayToDeleteFrom.splice index, 1 return arrayToDeleteFrom if process.env.HUBOT_BUSINESS_CAT_JARGON? additionalJargon = (process.env.HUBOT_BUSINESS_CAT_JARGON).split(',') jargon = jargon.concat(additionalJargon) if process.env.HUBOT_BUSINESS_CAT_OMITTED_JARGON? omittedJargon = (process.env.HUBOT_BUSINESS_CAT_OMITTED_JARGON).split(',') jargon = removeTerm(term, jargon) for term in omittedJargon regex = new RegExp jargon.join('|'), 'gi' module.exports = (robot) -> robot.hear regex, (msg) -> msg.send msg.random images
[ { "context": "egex from various stack overflow blogs\n#\n# @author Christopher Kelley\n# @author Eric Fitzpatrick\n\nASCII = { }\nfor a in ", "end": 243, "score": 0.9998721480369568, "start": 225, "tag": "NAME", "value": "Christopher Kelley" }, { "context": "low blogs\n#\n# @author C...
src/parser.coffee
efitzpa1/tasty
0
# chunk statemachine inspired by jsep # operator precedence from # https://developer.mozilla.org/en-US/docs/Web/JavaScript/ # Reference/Operators/Operator_Precedence # regex from various stack overflow blogs # # @author Christopher Kelley # @author Eric Fitzpatrick ASCII = { } for a in [0...128] by 1 ASCII[String.fromCharCode a] = a module.exports = __module__ = # This class' main functionality is to take a string and return # an object with type, operator, left hand side, and right hand side. # # @example How to parse an expression. # Parser.parse("1 + 2") # # @class Parser class Parser # Returns the longest key in the provided object. # # @memberof Parser # @private # @param [Object] obj given object # @return [Number] max longest key length max_key_length = ( obj ) -> max = 0 for own key of obj max = key.length if key.length > max return max # Returns an error object and prints an error message based on input. # # @memberof Parser # @private # @param [String] msg error message you want to print # @param [Number] index line of error message occurance # @return [Object] err object that was created error = ( msg, index ) -> err = new Error "tasty: at #{index}: #{msg}" err.index = index err.description = msg return err # coffeelint: disable=colon_assignment_spacing # reason: code readability via alignment # Unary object containing known unary operators and their precedence. # @private UNARY = "-" : 15 "!" : 15 "~" : 15 "+" : 15 # Binary object containing known binary operators and their precedence. # @memberof Parser # @private BINARY = # symbol: precedence "=" : 3 "||" : 5 "&&" : 6 "|" : 7 "^" : 8 "&" : 9 "==" : 10 "!=" : 10 "===" : 10 "!==" : 10 "<" : 11 ">" : 11 "<=" : 11 ">=" : 11 "<<" : 12 ">>" : 12 ">>>" : 12 "+" : 13 "-" : 13 "*" : 14 "/" : 14 "%" : 14 MAX_UNARY = max_key_length UNARY MAX_BINARY = max_key_length BINARY # Literal object to convert strings to values. # @memberof Parser # @private LITERAL = "true" : true "false" : false "null" : null "undefined": undefined # coffeelint: enable=colon_assignment_spacing # @memberof Parser _start = decimal: ( c ) -> c in [ ASCII["+"], ASCII["-"], ASCII["."] ] or ASCII["0"] <= c <= ASCII["9"] string: ( c ) -> c in [ ASCII["\""], ASCII["\'"] ] identifier: ( c ) -> c in [ ASCII["$"], ASCII["_"] ] or ASCII["A"] <= c <= ASCII["Z"] or ASCII["a"] <= c <= ASCII["z"] # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_BINARY = 0 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_UNARY = 1 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_LITERAL = 2 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_IDENTIFIER = 3 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_CONTEXT = 4 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_ARRAY = 5 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_CALL = 6 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_MEMBER = 7 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_COMPOUND = 8 # Constructors for expression objects. # # @memberof Parser # @private _make = # constructor for binary object # # @memberof Parser # @private # @param [String] op binary operator # @param [Object] lhs left hand side of binary operation # @param [Object] rhs right hand side of binary operation binary: ( op, lhs, rhs ) -> type: Parser.TYPE_BINARY op: op lhs: lhs rhs: rhs # constructor for unary object # # @memberof Parser # @private # @param [String] op unary operator # @param [Object] rhs right hand side of unary operation unary: ( op, rhs ) -> type: Parser.TYPE_UNARY op: op rhs: rhs lhs: null # constructor for literal object # # @memberof Parser # @private # @param [String] literal value literal: ( value ) -> type: Parser.TYPE_LITERAL val: value # constructor for identifier object # # @memberof Parser # @private # @param [String] value identifier name identifier: ( value ) -> type: Parser.TYPE_IDENTIFIER val: value # constructor for context object # # @memberof Parser # @private context: ( ) -> type: Parser.TYPE_CONTEXT # constructor for array object # # @memberof Parser # @private # @param [Array] value array object to wrap array: ( value ) -> type: Parser.TYPE_ARRAY val: value # constructor for member object # # @memberof Parser # @private # @param [String] value member name to wrap # @param [Object] callee context calling this member # @param [Boolean] computed if value is accessed with dot or compute member: ( value, callee, computed ) -> type: Parser.TYPE_MEMBER val: value callee: callee computed: computed # constructor for call object # # @memberof Parser # @private # @param # @param call: ( callee, args ) -> type: Parser.TYPE_CALL callee: callee args: args # Parses the given expression. # @memberof Parser # @function parse # @param [String] expr the expression you want to parse # @return { type, operator, lhs, rhs } # @static constructor: ( expr ) -> index = 0 if "string" isnt typeof expr throw new TypeError "tasty: invalid argument, expected string, got #{typeof expr} " icode = expr.charCodeAt.bind expr consume = # Moves the index to the first non-space/tab character. spaces: ( ) -> c = icode index while c in [ ASCII["\t"], ASCII[" "] ] # tab, space c = icode ++index return false binary: # Tries to return the binary operator at the current index. # # @return [String] lookat the binary operator op: ( ) -> consume.spaces() # start from the longest string and work to nothing # if match exists in expressions return it and move index lookat = expr.substr index, MAX_BINARY while lookat.length if BINARY[lookat] index += lookat.length return lookat lookat = lookat.substr 0, lookat.length - 1 return false # Tries to return a binary expression object # at the current index. # # @return [Object] rhs the binary exp object expr: ( ) -> consume.spaces() # obtain the left token lhs = consume.token() biop = consume.binary.op() # maybe guessed wrong, return just lhs # lets me be lazy (good lazy) in outer while loop return lhs unless biop # obtain the right token rhs = consume.token() throw error "expected token", index unless rhs # start an infix stack stack = [ lhs, biop, rhs ] # continue looking for operators while biop = consume.binary.op() break unless prec = BINARY[biop] # figure out where in the stack the operator should go # compress stack forward while stack.length > 2 and prec <= BINARY[stack[stack.length - 2]] rhs = stack.pop() stack.push _make.binary stack.pop(), stack.pop(), rhs rhs = consume.token() throw error "expected token", index unless rhs stack.push biop, rhs # compress stack backward rhs = stack[stack.length - 1] for i in [stack.length - 1..1] by -2 rhs = _make.binary stack[i - 1], stack[i - 2], rhs return rhs unary: # Tries to return the unary operator at the current index. # # @return [String] lookat the unary operator op: ( ) -> consume.spaces() # start from the longest string and work to nothing # if match exists in expressions return it and move index lookat = expr.substr index, MAX_UNARY while lookat.length if UNARY[lookat] index += lookat.length return lookat lookat = lookat.substr 0, lookat.length - 1 return false # Tries to return the unary expression object # at the current index. expr: ( ) -> consume.spaces() unop = consume.unary.op() throw error "expected token", index unless unop _make.unary unop, consume.token() literal: # Returns the literal object of the number at the current index. # # @return [Object] literal object number: ( ) -> consume.spaces() number = expr.substr index .match(/[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/)[0] index += number.length return _make.literal Number(number) # Returns the literal object of the string at the current index. # # @return [Object] literal object string: ( ) -> consume.spaces() # store first quote and move forward pls = expr.substr index .match /["]((?:[^\\"]|\\.)*)["]|[']((?:[^\\']|\\.)*)[']/ throw error "unclosed string", index unless pls? if pls[1]? pls = pls[1] else if pls[2]? pls = pls[2] throw error "unclosed string", index unless pls? index += pls.length + 2 # to account quotes pls = pls .replace("\\r", "\r") .replace("\\n", "\n") .replace("\\t", "\t") .replace("\\b", "\b") .replace("\\f", "\f") .replace("\\\"", "\"") .replace("\\\\", "\\") .replace("\\\'", "\'") # its a little gross - should come up with something better return _make.literal pls # Either returns a literal or identifier object # based on what is at the current index. # # @return [Object] literal/identifier object identifier: ( ) -> consume.spaces() id = expr.substr(index).match(/^[$A-Za-z_][$0-9a-z_]*/) throw error "invalid identifier", index unless id id = id[0] index += id.length # identifier may be this type, literal or actual identifier switch when LITERAL[id] then _make.literal LITERAL[id] when "this" is id then _make.context() else _make.identifier id # Returns an array of all that is inside the list at # the current index. # # @return [Object] array list: ( ) -> termination = switch icode index++ when ASCII["("] then ASCII[")"] when ASCII["["] then ASCII["]"] else throw error "invalid list", index array = [ ] while index < expr.length consume.spaces() c = icode index if c is termination index++ break else if c is ASCII[","] index++ else unless node = consume.binary.expr() throw error "unexpected comma", index array.push node return array group: ( ) -> # move after opening paren index += 1 # get generic expression within group e = consume.binary.expr() # remove trailing spaces ( 5+5 ) consume.spaces() # die if not properly closed if ASCII[")"] isnt icode index++ throw error "unclosed group", index - 1 return e # Makes an array. array: ( ) -> _make.array consume.list() # in actuality we only have tokens # binary expressions are special and handled externally # esentially token is all but binary expressions # # @return [Object] token: ( ) -> consume.spaces() c = icode index # NO INCR switch when _start.decimal c consume.literal.number() when _start.string c consume.literal.string() when _start.identifier(c) or c is ASCII["("] consume.object() when c is ASCII["["] consume.array() else consume.unary.expr() # object is like a continuation of token # which looks for members and calls object: ( ) -> c = icode index if c is ASCII["("] node = consume.group() else # assert from token this must be identifier node = consume.identifier() consume.spaces() # dear coffee, why you no have do-while c = icode index # index changed by consumes while c in [ ASCII["."], ASCII["["], ASCII["("] ] switch c when ASCII["."] # member index += 1 #c = icode index #if c is ASCII["."] # throw error "unexpected member access", index node = _make.member consume.identifier(), node, false when ASCII["["] # computed member (not array!) index += 1 node = _make.member consume.binary.expr(), node, true # check for closing unless icode(index++) is ASCII["]"] throw error "unclosed computed member", index when ASCII["("] # function node = _make.call node, consume.list() consume.spaces() c = icode index return node nodes = [ ] while index < expr.length c = icode index # semicolon and comma insertion, ignore if c in [ ASCII[";"], ASCII[","] ] index++ else unless node = consume.binary.expr() throw error "unexpected expression", index nodes.push node if 1 is nodes.length return nodes[0] type: Parser.COMPOUND val: nodes
131910
# chunk statemachine inspired by jsep # operator precedence from # https://developer.mozilla.org/en-US/docs/Web/JavaScript/ # Reference/Operators/Operator_Precedence # regex from various stack overflow blogs # # @author <NAME> # @author <NAME> ASCII = { } for a in [0...128] by 1 ASCII[String.fromCharCode a] = a module.exports = __module__ = # This class' main functionality is to take a string and return # an object with type, operator, left hand side, and right hand side. # # @example How to parse an expression. # Parser.parse("1 + 2") # # @class Parser class Parser # Returns the longest key in the provided object. # # @memberof Parser # @private # @param [Object] obj given object # @return [Number] max longest key length max_key_length = ( obj ) -> max = 0 for own key of obj max = key.length if key.length > max return max # Returns an error object and prints an error message based on input. # # @memberof Parser # @private # @param [String] msg error message you want to print # @param [Number] index line of error message occurance # @return [Object] err object that was created error = ( msg, index ) -> err = new Error "tasty: at #{index}: #{msg}" err.index = index err.description = msg return err # coffeelint: disable=colon_assignment_spacing # reason: code readability via alignment # Unary object containing known unary operators and their precedence. # @private UNARY = "-" : 15 "!" : 15 "~" : 15 "+" : 15 # Binary object containing known binary operators and their precedence. # @memberof Parser # @private BINARY = # symbol: precedence "=" : 3 "||" : 5 "&&" : 6 "|" : 7 "^" : 8 "&" : 9 "==" : 10 "!=" : 10 "===" : 10 "!==" : 10 "<" : 11 ">" : 11 "<=" : 11 ">=" : 11 "<<" : 12 ">>" : 12 ">>>" : 12 "+" : 13 "-" : 13 "*" : 14 "/" : 14 "%" : 14 MAX_UNARY = max_key_length UNARY MAX_BINARY = max_key_length BINARY # Literal object to convert strings to values. # @memberof Parser # @private LITERAL = "true" : true "false" : false "null" : null "undefined": undefined # coffeelint: enable=colon_assignment_spacing # @memberof Parser _start = decimal: ( c ) -> c in [ ASCII["+"], ASCII["-"], ASCII["."] ] or ASCII["0"] <= c <= ASCII["9"] string: ( c ) -> c in [ ASCII["\""], ASCII["\'"] ] identifier: ( c ) -> c in [ ASCII["$"], ASCII["_"] ] or ASCII["A"] <= c <= ASCII["Z"] or ASCII["a"] <= c <= ASCII["z"] # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_BINARY = 0 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_UNARY = 1 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_LITERAL = 2 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_IDENTIFIER = 3 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_CONTEXT = 4 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_ARRAY = 5 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_CALL = 6 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_MEMBER = 7 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_COMPOUND = 8 # Constructors for expression objects. # # @memberof Parser # @private _make = # constructor for binary object # # @memberof Parser # @private # @param [String] op binary operator # @param [Object] lhs left hand side of binary operation # @param [Object] rhs right hand side of binary operation binary: ( op, lhs, rhs ) -> type: Parser.TYPE_BINARY op: op lhs: lhs rhs: rhs # constructor for unary object # # @memberof Parser # @private # @param [String] op unary operator # @param [Object] rhs right hand side of unary operation unary: ( op, rhs ) -> type: Parser.TYPE_UNARY op: op rhs: rhs lhs: null # constructor for literal object # # @memberof Parser # @private # @param [String] literal value literal: ( value ) -> type: Parser.TYPE_LITERAL val: value # constructor for identifier object # # @memberof Parser # @private # @param [String] value identifier name identifier: ( value ) -> type: Parser.TYPE_IDENTIFIER val: value # constructor for context object # # @memberof Parser # @private context: ( ) -> type: Parser.TYPE_CONTEXT # constructor for array object # # @memberof Parser # @private # @param [Array] value array object to wrap array: ( value ) -> type: Parser.TYPE_ARRAY val: value # constructor for member object # # @memberof Parser # @private # @param [String] value member name to wrap # @param [Object] callee context calling this member # @param [Boolean] computed if value is accessed with dot or compute member: ( value, callee, computed ) -> type: Parser.TYPE_MEMBER val: value callee: callee computed: computed # constructor for call object # # @memberof Parser # @private # @param # @param call: ( callee, args ) -> type: Parser.TYPE_CALL callee: callee args: args # Parses the given expression. # @memberof Parser # @function parse # @param [String] expr the expression you want to parse # @return { type, operator, lhs, rhs } # @static constructor: ( expr ) -> index = 0 if "string" isnt typeof expr throw new TypeError "tasty: invalid argument, expected string, got #{typeof expr} " icode = expr.charCodeAt.bind expr consume = # Moves the index to the first non-space/tab character. spaces: ( ) -> c = icode index while c in [ ASCII["\t"], ASCII[" "] ] # tab, space c = icode ++index return false binary: # Tries to return the binary operator at the current index. # # @return [String] lookat the binary operator op: ( ) -> consume.spaces() # start from the longest string and work to nothing # if match exists in expressions return it and move index lookat = expr.substr index, MAX_BINARY while lookat.length if BINARY[lookat] index += lookat.length return lookat lookat = lookat.substr 0, lookat.length - 1 return false # Tries to return a binary expression object # at the current index. # # @return [Object] rhs the binary exp object expr: ( ) -> consume.spaces() # obtain the left token lhs = consume.token() biop = consume.binary.op() # maybe guessed wrong, return just lhs # lets me be lazy (good lazy) in outer while loop return lhs unless biop # obtain the right token rhs = consume.token() throw error "expected token", index unless rhs # start an infix stack stack = [ lhs, biop, rhs ] # continue looking for operators while biop = consume.binary.op() break unless prec = BINARY[biop] # figure out where in the stack the operator should go # compress stack forward while stack.length > 2 and prec <= BINARY[stack[stack.length - 2]] rhs = stack.pop() stack.push _make.binary stack.pop(), stack.pop(), rhs rhs = consume.token() throw error "expected token", index unless rhs stack.push biop, rhs # compress stack backward rhs = stack[stack.length - 1] for i in [stack.length - 1..1] by -2 rhs = _make.binary stack[i - 1], stack[i - 2], rhs return rhs unary: # Tries to return the unary operator at the current index. # # @return [String] lookat the unary operator op: ( ) -> consume.spaces() # start from the longest string and work to nothing # if match exists in expressions return it and move index lookat = expr.substr index, MAX_UNARY while lookat.length if UNARY[lookat] index += lookat.length return lookat lookat = lookat.substr 0, lookat.length - 1 return false # Tries to return the unary expression object # at the current index. expr: ( ) -> consume.spaces() unop = consume.unary.op() throw error "expected token", index unless unop _make.unary unop, consume.token() literal: # Returns the literal object of the number at the current index. # # @return [Object] literal object number: ( ) -> consume.spaces() number = expr.substr index .match(/[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/)[0] index += number.length return _make.literal Number(number) # Returns the literal object of the string at the current index. # # @return [Object] literal object string: ( ) -> consume.spaces() # store first quote and move forward pls = expr.substr index .match /["]((?:[^\\"]|\\.)*)["]|[']((?:[^\\']|\\.)*)[']/ throw error "unclosed string", index unless pls? if pls[1]? pls = pls[1] else if pls[2]? pls = pls[2] throw error "unclosed string", index unless pls? index += pls.length + 2 # to account quotes pls = pls .replace("\\r", "\r") .replace("\\n", "\n") .replace("\\t", "\t") .replace("\\b", "\b") .replace("\\f", "\f") .replace("\\\"", "\"") .replace("\\\\", "\\") .replace("\\\'", "\'") # its a little gross - should come up with something better return _make.literal pls # Either returns a literal or identifier object # based on what is at the current index. # # @return [Object] literal/identifier object identifier: ( ) -> consume.spaces() id = expr.substr(index).match(/^[$A-Za-z_][$0-9a-z_]*/) throw error "invalid identifier", index unless id id = id[0] index += id.length # identifier may be this type, literal or actual identifier switch when LITERAL[id] then _make.literal LITERAL[id] when "this" is id then _make.context() else _make.identifier id # Returns an array of all that is inside the list at # the current index. # # @return [Object] array list: ( ) -> termination = switch icode index++ when ASCII["("] then ASCII[")"] when ASCII["["] then ASCII["]"] else throw error "invalid list", index array = [ ] while index < expr.length consume.spaces() c = icode index if c is termination index++ break else if c is ASCII[","] index++ else unless node = consume.binary.expr() throw error "unexpected comma", index array.push node return array group: ( ) -> # move after opening paren index += 1 # get generic expression within group e = consume.binary.expr() # remove trailing spaces ( 5+5 ) consume.spaces() # die if not properly closed if ASCII[")"] isnt icode index++ throw error "unclosed group", index - 1 return e # Makes an array. array: ( ) -> _make.array consume.list() # in actuality we only have tokens # binary expressions are special and handled externally # esentially token is all but binary expressions # # @return [Object] token: ( ) -> consume.spaces() c = icode index # NO INCR switch when _start.decimal c consume.literal.number() when _start.string c consume.literal.string() when _start.identifier(c) or c is ASCII["("] consume.object() when c is ASCII["["] consume.array() else consume.unary.expr() # object is like a continuation of token # which looks for members and calls object: ( ) -> c = icode index if c is ASCII["("] node = consume.group() else # assert from token this must be identifier node = consume.identifier() consume.spaces() # dear coffee, why you no have do-while c = icode index # index changed by consumes while c in [ ASCII["."], ASCII["["], ASCII["("] ] switch c when ASCII["."] # member index += 1 #c = icode index #if c is ASCII["."] # throw error "unexpected member access", index node = _make.member consume.identifier(), node, false when ASCII["["] # computed member (not array!) index += 1 node = _make.member consume.binary.expr(), node, true # check for closing unless icode(index++) is ASCII["]"] throw error "unclosed computed member", index when ASCII["("] # function node = _make.call node, consume.list() consume.spaces() c = icode index return node nodes = [ ] while index < expr.length c = icode index # semicolon and comma insertion, ignore if c in [ ASCII[";"], ASCII[","] ] index++ else unless node = consume.binary.expr() throw error "unexpected expression", index nodes.push node if 1 is nodes.length return nodes[0] type: Parser.COMPOUND val: nodes
true
# chunk statemachine inspired by jsep # operator precedence from # https://developer.mozilla.org/en-US/docs/Web/JavaScript/ # Reference/Operators/Operator_Precedence # regex from various stack overflow blogs # # @author PI:NAME:<NAME>END_PI # @author PI:NAME:<NAME>END_PI ASCII = { } for a in [0...128] by 1 ASCII[String.fromCharCode a] = a module.exports = __module__ = # This class' main functionality is to take a string and return # an object with type, operator, left hand side, and right hand side. # # @example How to parse an expression. # Parser.parse("1 + 2") # # @class Parser class Parser # Returns the longest key in the provided object. # # @memberof Parser # @private # @param [Object] obj given object # @return [Number] max longest key length max_key_length = ( obj ) -> max = 0 for own key of obj max = key.length if key.length > max return max # Returns an error object and prints an error message based on input. # # @memberof Parser # @private # @param [String] msg error message you want to print # @param [Number] index line of error message occurance # @return [Object] err object that was created error = ( msg, index ) -> err = new Error "tasty: at #{index}: #{msg}" err.index = index err.description = msg return err # coffeelint: disable=colon_assignment_spacing # reason: code readability via alignment # Unary object containing known unary operators and their precedence. # @private UNARY = "-" : 15 "!" : 15 "~" : 15 "+" : 15 # Binary object containing known binary operators and their precedence. # @memberof Parser # @private BINARY = # symbol: precedence "=" : 3 "||" : 5 "&&" : 6 "|" : 7 "^" : 8 "&" : 9 "==" : 10 "!=" : 10 "===" : 10 "!==" : 10 "<" : 11 ">" : 11 "<=" : 11 ">=" : 11 "<<" : 12 ">>" : 12 ">>>" : 12 "+" : 13 "-" : 13 "*" : 14 "/" : 14 "%" : 14 MAX_UNARY = max_key_length UNARY MAX_BINARY = max_key_length BINARY # Literal object to convert strings to values. # @memberof Parser # @private LITERAL = "true" : true "false" : false "null" : null "undefined": undefined # coffeelint: enable=colon_assignment_spacing # @memberof Parser _start = decimal: ( c ) -> c in [ ASCII["+"], ASCII["-"], ASCII["."] ] or ASCII["0"] <= c <= ASCII["9"] string: ( c ) -> c in [ ASCII["\""], ASCII["\'"] ] identifier: ( c ) -> c in [ ASCII["$"], ASCII["_"] ] or ASCII["A"] <= c <= ASCII["Z"] or ASCII["a"] <= c <= ASCII["z"] # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_BINARY = 0 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_UNARY = 1 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_LITERAL = 2 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_IDENTIFIER = 3 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_CONTEXT = 4 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_ARRAY = 5 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_CALL = 6 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_MEMBER = 7 # specifies type of current operator or symbol # # @memberof Parser # @static # @private @TYPE_COMPOUND = 8 # Constructors for expression objects. # # @memberof Parser # @private _make = # constructor for binary object # # @memberof Parser # @private # @param [String] op binary operator # @param [Object] lhs left hand side of binary operation # @param [Object] rhs right hand side of binary operation binary: ( op, lhs, rhs ) -> type: Parser.TYPE_BINARY op: op lhs: lhs rhs: rhs # constructor for unary object # # @memberof Parser # @private # @param [String] op unary operator # @param [Object] rhs right hand side of unary operation unary: ( op, rhs ) -> type: Parser.TYPE_UNARY op: op rhs: rhs lhs: null # constructor for literal object # # @memberof Parser # @private # @param [String] literal value literal: ( value ) -> type: Parser.TYPE_LITERAL val: value # constructor for identifier object # # @memberof Parser # @private # @param [String] value identifier name identifier: ( value ) -> type: Parser.TYPE_IDENTIFIER val: value # constructor for context object # # @memberof Parser # @private context: ( ) -> type: Parser.TYPE_CONTEXT # constructor for array object # # @memberof Parser # @private # @param [Array] value array object to wrap array: ( value ) -> type: Parser.TYPE_ARRAY val: value # constructor for member object # # @memberof Parser # @private # @param [String] value member name to wrap # @param [Object] callee context calling this member # @param [Boolean] computed if value is accessed with dot or compute member: ( value, callee, computed ) -> type: Parser.TYPE_MEMBER val: value callee: callee computed: computed # constructor for call object # # @memberof Parser # @private # @param # @param call: ( callee, args ) -> type: Parser.TYPE_CALL callee: callee args: args # Parses the given expression. # @memberof Parser # @function parse # @param [String] expr the expression you want to parse # @return { type, operator, lhs, rhs } # @static constructor: ( expr ) -> index = 0 if "string" isnt typeof expr throw new TypeError "tasty: invalid argument, expected string, got #{typeof expr} " icode = expr.charCodeAt.bind expr consume = # Moves the index to the first non-space/tab character. spaces: ( ) -> c = icode index while c in [ ASCII["\t"], ASCII[" "] ] # tab, space c = icode ++index return false binary: # Tries to return the binary operator at the current index. # # @return [String] lookat the binary operator op: ( ) -> consume.spaces() # start from the longest string and work to nothing # if match exists in expressions return it and move index lookat = expr.substr index, MAX_BINARY while lookat.length if BINARY[lookat] index += lookat.length return lookat lookat = lookat.substr 0, lookat.length - 1 return false # Tries to return a binary expression object # at the current index. # # @return [Object] rhs the binary exp object expr: ( ) -> consume.spaces() # obtain the left token lhs = consume.token() biop = consume.binary.op() # maybe guessed wrong, return just lhs # lets me be lazy (good lazy) in outer while loop return lhs unless biop # obtain the right token rhs = consume.token() throw error "expected token", index unless rhs # start an infix stack stack = [ lhs, biop, rhs ] # continue looking for operators while biop = consume.binary.op() break unless prec = BINARY[biop] # figure out where in the stack the operator should go # compress stack forward while stack.length > 2 and prec <= BINARY[stack[stack.length - 2]] rhs = stack.pop() stack.push _make.binary stack.pop(), stack.pop(), rhs rhs = consume.token() throw error "expected token", index unless rhs stack.push biop, rhs # compress stack backward rhs = stack[stack.length - 1] for i in [stack.length - 1..1] by -2 rhs = _make.binary stack[i - 1], stack[i - 2], rhs return rhs unary: # Tries to return the unary operator at the current index. # # @return [String] lookat the unary operator op: ( ) -> consume.spaces() # start from the longest string and work to nothing # if match exists in expressions return it and move index lookat = expr.substr index, MAX_UNARY while lookat.length if UNARY[lookat] index += lookat.length return lookat lookat = lookat.substr 0, lookat.length - 1 return false # Tries to return the unary expression object # at the current index. expr: ( ) -> consume.spaces() unop = consume.unary.op() throw error "expected token", index unless unop _make.unary unop, consume.token() literal: # Returns the literal object of the number at the current index. # # @return [Object] literal object number: ( ) -> consume.spaces() number = expr.substr index .match(/[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?/)[0] index += number.length return _make.literal Number(number) # Returns the literal object of the string at the current index. # # @return [Object] literal object string: ( ) -> consume.spaces() # store first quote and move forward pls = expr.substr index .match /["]((?:[^\\"]|\\.)*)["]|[']((?:[^\\']|\\.)*)[']/ throw error "unclosed string", index unless pls? if pls[1]? pls = pls[1] else if pls[2]? pls = pls[2] throw error "unclosed string", index unless pls? index += pls.length + 2 # to account quotes pls = pls .replace("\\r", "\r") .replace("\\n", "\n") .replace("\\t", "\t") .replace("\\b", "\b") .replace("\\f", "\f") .replace("\\\"", "\"") .replace("\\\\", "\\") .replace("\\\'", "\'") # its a little gross - should come up with something better return _make.literal pls # Either returns a literal or identifier object # based on what is at the current index. # # @return [Object] literal/identifier object identifier: ( ) -> consume.spaces() id = expr.substr(index).match(/^[$A-Za-z_][$0-9a-z_]*/) throw error "invalid identifier", index unless id id = id[0] index += id.length # identifier may be this type, literal or actual identifier switch when LITERAL[id] then _make.literal LITERAL[id] when "this" is id then _make.context() else _make.identifier id # Returns an array of all that is inside the list at # the current index. # # @return [Object] array list: ( ) -> termination = switch icode index++ when ASCII["("] then ASCII[")"] when ASCII["["] then ASCII["]"] else throw error "invalid list", index array = [ ] while index < expr.length consume.spaces() c = icode index if c is termination index++ break else if c is ASCII[","] index++ else unless node = consume.binary.expr() throw error "unexpected comma", index array.push node return array group: ( ) -> # move after opening paren index += 1 # get generic expression within group e = consume.binary.expr() # remove trailing spaces ( 5+5 ) consume.spaces() # die if not properly closed if ASCII[")"] isnt icode index++ throw error "unclosed group", index - 1 return e # Makes an array. array: ( ) -> _make.array consume.list() # in actuality we only have tokens # binary expressions are special and handled externally # esentially token is all but binary expressions # # @return [Object] token: ( ) -> consume.spaces() c = icode index # NO INCR switch when _start.decimal c consume.literal.number() when _start.string c consume.literal.string() when _start.identifier(c) or c is ASCII["("] consume.object() when c is ASCII["["] consume.array() else consume.unary.expr() # object is like a continuation of token # which looks for members and calls object: ( ) -> c = icode index if c is ASCII["("] node = consume.group() else # assert from token this must be identifier node = consume.identifier() consume.spaces() # dear coffee, why you no have do-while c = icode index # index changed by consumes while c in [ ASCII["."], ASCII["["], ASCII["("] ] switch c when ASCII["."] # member index += 1 #c = icode index #if c is ASCII["."] # throw error "unexpected member access", index node = _make.member consume.identifier(), node, false when ASCII["["] # computed member (not array!) index += 1 node = _make.member consume.binary.expr(), node, true # check for closing unless icode(index++) is ASCII["]"] throw error "unclosed computed member", index when ASCII["("] # function node = _make.call node, consume.list() consume.spaces() c = icode index return node nodes = [ ] while index < expr.length c = icode index # semicolon and comma insertion, ignore if c in [ ASCII[";"], ASCII[","] ] index++ else unless node = consume.binary.expr() throw error "unexpected expression", index nodes.push node if 1 is nodes.length return nodes[0] type: Parser.COMPOUND val: nodes
[ { "context": "angular: [\n { key: \"data.name\" }\n { key: \"data.uuid\" }\n { key: \"data.operation\" }\n { key: \"data.des", "end": 53, "score": 0.8463597893714905, "start": 44, "tag": "KEY", "value": "data.uuid" }, { "context": "data.name\" }\n { key: \"data.uuid\" }\n { key...
jobs/vm-lifecycle/form.cson
ratokeshi/meshblu-connector-xenserver
0
angular: [ { key: "data.name" } { key: "data.uuid" } { key: "data.operation" } { key: "data.destination" } ]
19692
angular: [ { key: "data.name" } { key: "<KEY>" } { key: "data<KEY>.operation" } { key: "data<KEY>.destination" } ]
true
angular: [ { key: "data.name" } { key: "PI:KEY:<KEY>END_PI" } { key: "dataPI:KEY:<KEY>END_PI.operation" } { key: "dataPI:KEY:<KEY>END_PI.destination" } ]
[ { "context": "******\n# JSLabel - One line text object\n# Coded by Hajime Oh-yake 2013.03.25\n#*************************************", "end": 101, "score": 0.9998908638954163, "start": 87, "tag": "NAME", "value": "Hajime Oh-yake" }, { "context": ".css(\"font-weight\", @_textWeight)\n...
JSKit/03_JSLabel.coffee
digitarhythm/codeJS
0
#***************************************** # JSLabel - One line text object # Coded by Hajime Oh-yake 2013.03.25 #***************************************** class JSLabel extends JSView constructor: (frame = JSRectMake(0, 0, 120, 24)) -> super(frame) @_textSize = 10 @_textColor = JSColor("black") @_textWeight = "normal" @_bgColor = JSColor("#f0f0f0") @_textAlignment = "JSTextAlignmentCenter" @_text = "Label" setText: (@_text) -> if ($(@_viewSelector).length) $(@_viewSelector).css("text-indent", "4px") $(@_viewSelector).html(@_text) setTextSize: (@_textSize) -> if ($(@_viewSelector).length) $(@_viewSelector).css("font-size", @_textSize+"pt") setTextWeight:(@_textWeight)-> $(@_viewSelector).css("font-weight", @_textWeight) setTextColor: (@_textColor) -> if ($(@_viewSelector).length) $(@_viewSelector).css("color", @_textColor) setTextAlignment: (@_textAlignment) -> switch @_textAlignment when "JSTextAlignmentCenter" $(@_viewSelector).css("text-align", "center") when "JSTextAlignmentLeft" $(@_viewSelector).css("text-align", "left") when "JSTextAlignmentRight" $(@_viewSelector).css("text-align", "right") else $(@_viewSelector).css("text-align", "center") setFrame:(frame)-> super(frame) $(@_viewSelector).width(frame.size.width) $(@_viewSelector).height(frame.size.height) viewDidAppear: -> super() $(@_viewSelector).width(@_frame.size.width) $(@_viewSelector).css("vertical-align", "middle") $(@_viewSelector).css("line-height",@_frame.size.height+"px") $(@_viewSelector).css("font-weight", @_textWeight) @setText(@_text) @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment)
180785
#***************************************** # JSLabel - One line text object # Coded by <NAME> 2013.03.25 #***************************************** class JSLabel extends JSView constructor: (frame = JSRectMake(0, 0, 120, 24)) -> super(frame) @_textSize = 10 @_textColor = JSColor("black") @_textWeight = "normal" @_bgColor = JSColor("#f0f0f0") @_textAlignment = "JSTextAlignmentCenter" @_text = "Label" setText: (@_text) -> if ($(@_viewSelector).length) $(@_viewSelector).css("text-indent", "4px") $(@_viewSelector).html(@_text) setTextSize: (@_textSize) -> if ($(@_viewSelector).length) $(@_viewSelector).css("font-size", @_textSize+"pt") setTextWeight:(@_textWeight)-> $(@_viewSelector).css("font-weight", @_textWeight) setTextColor: (@_textColor) -> if ($(@_viewSelector).length) $(@_viewSelector).css("color", @_textColor) setTextAlignment: (@_textAlignment) -> switch @_textAlignment when "JSTextAlignmentCenter" $(@_viewSelector).css("text-align", "center") when "JSTextAlignmentLeft" $(@_viewSelector).css("text-align", "left") when "JSTextAlignmentRight" $(@_viewSelector).css("text-align", "right") else $(@_viewSelector).css("text-align", "center") setFrame:(frame)-> super(frame) $(@_viewSelector).width(frame.size.width) $(@_viewSelector).height(frame.size.height) viewDidAppear: -> super() $(@_viewSelector).width(@_frame.size.width) $(@_viewSelector).css("vertical-align", "middle") $(@_viewSelector).css("line-height",@_frame.size.height+"px") $(@_viewSelector).css("font-weight", @_textWeight) @setText(@_text) @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment)
true
#***************************************** # JSLabel - One line text object # Coded by PI:NAME:<NAME>END_PI 2013.03.25 #***************************************** class JSLabel extends JSView constructor: (frame = JSRectMake(0, 0, 120, 24)) -> super(frame) @_textSize = 10 @_textColor = JSColor("black") @_textWeight = "normal" @_bgColor = JSColor("#f0f0f0") @_textAlignment = "JSTextAlignmentCenter" @_text = "Label" setText: (@_text) -> if ($(@_viewSelector).length) $(@_viewSelector).css("text-indent", "4px") $(@_viewSelector).html(@_text) setTextSize: (@_textSize) -> if ($(@_viewSelector).length) $(@_viewSelector).css("font-size", @_textSize+"pt") setTextWeight:(@_textWeight)-> $(@_viewSelector).css("font-weight", @_textWeight) setTextColor: (@_textColor) -> if ($(@_viewSelector).length) $(@_viewSelector).css("color", @_textColor) setTextAlignment: (@_textAlignment) -> switch @_textAlignment when "JSTextAlignmentCenter" $(@_viewSelector).css("text-align", "center") when "JSTextAlignmentLeft" $(@_viewSelector).css("text-align", "left") when "JSTextAlignmentRight" $(@_viewSelector).css("text-align", "right") else $(@_viewSelector).css("text-align", "center") setFrame:(frame)-> super(frame) $(@_viewSelector).width(frame.size.width) $(@_viewSelector).height(frame.size.height) viewDidAppear: -> super() $(@_viewSelector).width(@_frame.size.width) $(@_viewSelector).css("vertical-align", "middle") $(@_viewSelector).css("line-height",@_frame.size.height+"px") $(@_viewSelector).css("font-weight", @_textWeight) @setText(@_text) @setTextSize(@_textSize) @setTextColor(@_textColor) @setTextAlignment(@_textAlignment)
[ { "context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nVelocity = require 'veloci", "end": 35, "score": 0.9996998906135559, "start": 21, "tag": "NAME", "value": "Jesse Grosjean" } ]
atom/packages/foldingtext-for-atom/lib/editor/animations/remove-animation.coffee
prookie/dotfiles-1
0
# Copyright (c) 2015 Jesse Grosjean. All rights reserved. Velocity = require 'velocity-animate' module.exports = class RemoveAnimation @id = 'RemoveAnimation' constructor: (id, item, itemRenderer) -> @itemRenderer = itemRenderer @_id = id @_item = item @_removingLI = null @_targetHeight = 0 fastForward: -> @_removingLI?.style.height = @_targetHeight + 'px' complete: -> @itemRenderer.completedAnimation @_id if @_removingLI Velocity @_removingLI, 'stop', true @_removingLI.parentElement.removeChild @_removingLI remove: (LI, context) -> startHeight = LI.clientHeight targetHeight = 0 if @_removingLI Velocity @_removingLI, 'stop', true @_removingLI.parentElement.removeChild @_removingLI @_removingLI = LI @_targetHeight = targetHeight Velocity LI, 'stop', true Velocity e: LI p: tween: [targetHeight, startHeight] height: targetHeight o: easing: context.easing duration: context.duration begin: (elements) -> LI.style.overflowY = 'hidden' LI.style.height = startHeight LI.style.visibility = 'hidden' LI.style.pointerEvents = 'none' progress: (elements, percentComplete, timeRemaining, timeStart, tweenLIHeight) -> if tweenLIHeight < 0 LI.style.height = '0px' LI.style.marginBottom = tweenLIHeight + 'px' else LI.style.marginBottom = null complete: (elements) => @complete()
113187
# Copyright (c) 2015 <NAME>. All rights reserved. Velocity = require 'velocity-animate' module.exports = class RemoveAnimation @id = 'RemoveAnimation' constructor: (id, item, itemRenderer) -> @itemRenderer = itemRenderer @_id = id @_item = item @_removingLI = null @_targetHeight = 0 fastForward: -> @_removingLI?.style.height = @_targetHeight + 'px' complete: -> @itemRenderer.completedAnimation @_id if @_removingLI Velocity @_removingLI, 'stop', true @_removingLI.parentElement.removeChild @_removingLI remove: (LI, context) -> startHeight = LI.clientHeight targetHeight = 0 if @_removingLI Velocity @_removingLI, 'stop', true @_removingLI.parentElement.removeChild @_removingLI @_removingLI = LI @_targetHeight = targetHeight Velocity LI, 'stop', true Velocity e: LI p: tween: [targetHeight, startHeight] height: targetHeight o: easing: context.easing duration: context.duration begin: (elements) -> LI.style.overflowY = 'hidden' LI.style.height = startHeight LI.style.visibility = 'hidden' LI.style.pointerEvents = 'none' progress: (elements, percentComplete, timeRemaining, timeStart, tweenLIHeight) -> if tweenLIHeight < 0 LI.style.height = '0px' LI.style.marginBottom = tweenLIHeight + 'px' else LI.style.marginBottom = null complete: (elements) => @complete()
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. Velocity = require 'velocity-animate' module.exports = class RemoveAnimation @id = 'RemoveAnimation' constructor: (id, item, itemRenderer) -> @itemRenderer = itemRenderer @_id = id @_item = item @_removingLI = null @_targetHeight = 0 fastForward: -> @_removingLI?.style.height = @_targetHeight + 'px' complete: -> @itemRenderer.completedAnimation @_id if @_removingLI Velocity @_removingLI, 'stop', true @_removingLI.parentElement.removeChild @_removingLI remove: (LI, context) -> startHeight = LI.clientHeight targetHeight = 0 if @_removingLI Velocity @_removingLI, 'stop', true @_removingLI.parentElement.removeChild @_removingLI @_removingLI = LI @_targetHeight = targetHeight Velocity LI, 'stop', true Velocity e: LI p: tween: [targetHeight, startHeight] height: targetHeight o: easing: context.easing duration: context.duration begin: (elements) -> LI.style.overflowY = 'hidden' LI.style.height = startHeight LI.style.visibility = 'hidden' LI.style.pointerEvents = 'none' progress: (elements, percentComplete, timeRemaining, timeStart, tweenLIHeight) -> if tweenLIHeight < 0 LI.style.height = '0px' LI.style.marginBottom = tweenLIHeight + 'px' else LI.style.marginBottom = null complete: (elements) => @complete()
[ { "context": "eEach (done) ->\n App.User.insert firstName: \"Lance\", (error, record) =>\n user = record\n ", "end": 191, "score": 0.999688982963562, "start": 186, "tag": "NAME", "value": "Lance" }, { "context": "r-first-name-input\" name=\"user[firstName]\" value=\"...
test/cases/view/shared/formTest.coffee
jivagoalves/tower
1
view = null user = null describe "Tower.ViewForm", -> beforeEach -> view = Tower.View.create() describe 'form', -> beforeEach (done) -> App.User.insert firstName: "Lance", (error, record) => user = record done() test '#formFor()', -> template = -> formFor() view.render template: template, (error, result) -> assert.equal result, """ <form action="/" id="model-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> </form> """ test '#formFor(user)', -> template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users/#{user.get('id')}" id="user-form" role="form" novalidate="true" data-method="put" method="post"> <input type="hidden" name="_method" value="put" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" value="Lance" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test '#formFor(user) with errors', -> user.set "firstName", null user.validate() assert.deepEqual user.errors, { firstName: [ 'firstName can\'t be blank' ] } template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users/#{user.get('id')}" id="user-form" role="form" novalidate="true" data-method="put" method="post"> <input type="hidden" name="_method" value="put" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test '#formFor(camelCasedModel)', -> model = App.CamelCasedModel.build(name: "something") template = -> formFor @model, (form) -> form.fieldset (fields) -> fields.field "name" view.render template: template, locals: model: model, (error, result) -> assert.equal result, """ <form action="/camel-cased-models" id="camel-cased-model-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="camel-cased-model-name-field"> <label for="camel-cased-model-name-input" class="control-label"> <span>Name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="camel-cased-model-name-input" name="camelCasedModel[name]" value="something" class="string name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### describe 'ember', -> test 'string input', -> post = App.Post.build(title: 'A Post!', tags: ["ruby", "javascript"]) template = -> formFor 'post', live: true, (form) -> form.fieldset (fields) -> fields.field 'title', as: 'string' view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ <form action="/posts" id="post-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="post-title-field"> <label for="post-title-input" class="control-label"> <span>Title</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="post-title-input" name="post[title]" class="string title optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### describe 'fields', -> test 'string', -> user = App.User.build(firstName: "Lance") template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName", as: "string" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users" id="user-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" value="Lance" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test 'text', -> user = App.User.build(firstName: "Lance") template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName", as: "text" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users" id="user-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group text optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <textarea id="user-first-name-input" name="user[firstName]" class="text first-name optional input" aria-required="false">Lance</textarea> </div> </li> </ol> </fieldset> </form> """ test 'array', -> post = App.Post.build(tags: ["ruby", "javascript"]) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "tags", as: "array" view.render template: template, locals: post: post, (error, result) -> throw error if error assert.equal result, """ <form action="/posts" id="post-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group array optional" id="post-tags-field"> <label for="post-tags-input" class="control-label"> <span>Tags</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input data-type="array" id="post-tags-input" name="post[tags]" value="ruby, javascript" class="array tags optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### test 'date', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "date" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ test 'time', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "time" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ test 'datetime', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "datetime" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ ###
214625
view = null user = null describe "Tower.ViewForm", -> beforeEach -> view = Tower.View.create() describe 'form', -> beforeEach (done) -> App.User.insert firstName: "<NAME>", (error, record) => user = record done() test '#formFor()', -> template = -> formFor() view.render template: template, (error, result) -> assert.equal result, """ <form action="/" id="model-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> </form> """ test '#formFor(user)', -> template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users/#{user.get('id')}" id="user-form" role="form" novalidate="true" data-method="put" method="post"> <input type="hidden" name="_method" value="put" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" value="<NAME>" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test '#formFor(user) with errors', -> user.set "firstName", null user.validate() assert.deepEqual user.errors, { firstName: [ 'firstName can\'t be blank' ] } template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users/#{user.get('id')}" id="user-form" role="form" novalidate="true" data-method="put" method="post"> <input type="hidden" name="_method" value="put" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test '#formFor(camelCasedModel)', -> model = App.CamelCasedModel.build(name: "something") template = -> formFor @model, (form) -> form.fieldset (fields) -> fields.field "name" view.render template: template, locals: model: model, (error, result) -> assert.equal result, """ <form action="/camel-cased-models" id="camel-cased-model-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="camel-cased-model-name-field"> <label for="camel-cased-model-name-input" class="control-label"> <span>Name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="camel-cased-model-name-input" name="camelCasedModel[name]" value="something" class="string name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### describe 'ember', -> test 'string input', -> post = App.Post.build(title: 'A Post!', tags: ["ruby", "javascript"]) template = -> formFor 'post', live: true, (form) -> form.fieldset (fields) -> fields.field 'title', as: 'string' view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ <form action="/posts" id="post-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="post-title-field"> <label for="post-title-input" class="control-label"> <span>Title</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="post-title-input" name="post[title]" class="string title optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### describe 'fields', -> test 'string', -> user = App.User.build(firstName: "<NAME>") template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName", as: "string" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users" id="user-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" value="<NAME>" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test 'text', -> user = App.User.build(firstName: "<NAME>") template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName", as: "text" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users" id="user-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group text optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <textarea id="user-first-name-input" name="user[firstName]" class="text first-name optional input" aria-required="false">L<NAME></textarea> </div> </li> </ol> </fieldset> </form> """ test 'array', -> post = App.Post.build(tags: ["ruby", "javascript"]) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "tags", as: "array" view.render template: template, locals: post: post, (error, result) -> throw error if error assert.equal result, """ <form action="/posts" id="post-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group array optional" id="post-tags-field"> <label for="post-tags-input" class="control-label"> <span>Tags</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input data-type="array" id="post-tags-input" name="post[tags]" value="ruby, javascript" class="array tags optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### test 'date', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "date" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ test 'time', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "time" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ test 'datetime', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "datetime" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ ###
true
view = null user = null describe "Tower.ViewForm", -> beforeEach -> view = Tower.View.create() describe 'form', -> beforeEach (done) -> App.User.insert firstName: "PI:NAME:<NAME>END_PI", (error, record) => user = record done() test '#formFor()', -> template = -> formFor() view.render template: template, (error, result) -> assert.equal result, """ <form action="/" id="model-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> </form> """ test '#formFor(user)', -> template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users/#{user.get('id')}" id="user-form" role="form" novalidate="true" data-method="put" method="post"> <input type="hidden" name="_method" value="put" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" value="PI:NAME:<NAME>END_PI" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test '#formFor(user) with errors', -> user.set "firstName", null user.validate() assert.deepEqual user.errors, { firstName: [ 'firstName can\'t be blank' ] } template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users/#{user.get('id')}" id="user-form" role="form" novalidate="true" data-method="put" method="post"> <input type="hidden" name="_method" value="put" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test '#formFor(camelCasedModel)', -> model = App.CamelCasedModel.build(name: "something") template = -> formFor @model, (form) -> form.fieldset (fields) -> fields.field "name" view.render template: template, locals: model: model, (error, result) -> assert.equal result, """ <form action="/camel-cased-models" id="camel-cased-model-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="camel-cased-model-name-field"> <label for="camel-cased-model-name-input" class="control-label"> <span>Name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="camel-cased-model-name-input" name="camelCasedModel[name]" value="something" class="string name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### describe 'ember', -> test 'string input', -> post = App.Post.build(title: 'A Post!', tags: ["ruby", "javascript"]) template = -> formFor 'post', live: true, (form) -> form.fieldset (fields) -> fields.field 'title', as: 'string' view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ <form action="/posts" id="post-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="post-title-field"> <label for="post-title-input" class="control-label"> <span>Title</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="post-title-input" name="post[title]" class="string title optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### describe 'fields', -> test 'string', -> user = App.User.build(firstName: "PI:NAME:<NAME>END_PI") template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName", as: "string" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users" id="user-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group string optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input type="text" id="user-first-name-input" name="user[firstName]" value="PI:NAME:<NAME>END_PI" class="string first-name optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ test 'text', -> user = App.User.build(firstName: "PI:NAME:<NAME>END_PI") template = -> formFor @user, (form) -> form.fieldset (fields) -> fields.field "firstName", as: "text" view.render template: template, locals: user: user, (error, result) -> throw error if error assert.equal result, """ <form action="/users" id="user-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group text optional" id="user-first-name-field"> <label for="user-first-name-input" class="control-label"> <span>First name</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <textarea id="user-first-name-input" name="user[firstName]" class="text first-name optional input" aria-required="false">LPI:NAME:<NAME>END_PI</textarea> </div> </li> </ol> </fieldset> </form> """ test 'array', -> post = App.Post.build(tags: ["ruby", "javascript"]) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "tags", as: "array" view.render template: template, locals: post: post, (error, result) -> throw error if error assert.equal result, """ <form action="/posts" id="post-form" role="form" novalidate="true" data-method="post" method="post"> <input type="hidden" name="_method" value="post" /> <fieldset> <ol class="fields"> <li class="field control-group array optional" id="post-tags-field"> <label for="post-tags-input" class="control-label"> <span>Tags</span> <abbr title="Optional" class="optional"> </abbr> </label> <div class="controls"> <input data-type="array" id="post-tags-input" name="post[tags]" value="ruby, javascript" class="array tags optional input" aria-required="false" /> </div> </li> </ol> </fieldset> </form> """ ### test 'date', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "date" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ test 'time', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "time" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ test 'datetime', -> post = new App.Post(createdAt: new Date()) template = -> formFor @post, (form) -> form.fieldset (fields) -> fields.field "createdAt", as: "datetime" view.render template: template, locals: post: post, (error, result) -> console.log result throw error if error assert.equal result, """ """ ###
[ { "context": "\n # \n allMeta = [[[\"name\",\"author\"],[\"content\",\"James A. Hinds: The Celarien's best friend. I'm not him, I wear", "end": 1072, "score": 0.9998308420181274, "start": 1058, "tag": "NAME", "value": "James A. Hinds" }, { "context": "5229129\n debug: \"\"\n aut...
templates/error/404.coffee
jahbini/aframe-lowroller-component
0
# #-------- class start renderer = class index extends celarientemplate # # section html # # # section celarien_body # # # section cover # cover: => T.div "#cover", style: "background-image:url(/assets/images/hooray-fade2.jpg);-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH" # # section footer # # # section sidecar # # # section fb_status # # # section sidebar # # # section storybar # storybar: => T.div "#storybar.o-grid__cell.order-2.bg-lighten-2", => T.h1 => T.raw "Celarien -- The tools of the spiritual bodyguard" T.hr() @bloviation() # # section bloviation # bloviation: => T.div "#bloviation.contents", => T.raw "Sorry, that does not exist... Yet." T.a href: "/announcement/two-years-with-bamboo-snow.html", => T.raw " but check out an incredible life with Bamboo Snow." # # section header # allMeta = [[["name","author"],["content","James A. Hinds: The Celarien's best friend. I'm not him, I wear glasses"]],[["http-equiv","Content-Type"],["content","text/html"],["charset","UTF-8"]],[["name","viewport"],["content","width=device-width, initial-scale=1"]],[["name","description"],["content","some good thoughts. Maybe."]],[["name","keywords"],["content","romance, wisdom, tarot"]],[["property","fb:admins"],["content","1981510532097452"]],[["name","msapplication-TileColor"],["content","#ffffff"]],[["name","msapplication-TileImage"],["content","/assets/icons/ms-icon-144x144.png"]],[["name","theme-color"],["content","#ffffff"]]] htmlTitle = "Practical Metaphysics and Harmonious Mana." #-------- class end # ------- db start db = {} unless db #end of story# db[id="celarienerror404"] = title: "404" slug: "404" category: "error" site: "celarien" accepted: true index: false headlines: [] tags: [] snippets: "{\"first name\":\"first name\"}" memberOf: [] created: "2018-03-05T04:47:09.128Z" lastEdited: "2018-03-05T04:47:09.129Z" published: "2018-03-05T04:47:09.129Z" embargo: "2018-03-05T04:47:09.129Z" captureDate: "2018-03-05T04:47:09.129Z" TimeStamp: 1520225229129 debug: "" author: "Copyright 2010-2018 James A. Hinds: The Celarien's best friend. I'm not him, I wear glasses" id: "celarienerror404" name: "404" # db[id="celarien/error/404"] = title: "404" slug: "404" category: "error" site: "celarien" accepted: true index: false headlines: [] tags: [] snippets: "{\"first name\":\"first name\"}" memberOf: [] created: "2018-03-05T04:47:09.128Z" lastEdited: "2018-03-05T04:47:09.129Z" published: "2018-03-05T04:47:09.129Z" embargo: "2018-03-05T04:47:09.129Z" captureDate: "2018-03-05T04:47:09.129Z" TimeStamp: 1520225229129 debug: "" author: "Copyright 2010-2018 James A. Hinds: The Celarien's best friend. I'm not him, I wear glasses" id: "celarien/error/404" name: "404" #
16824
# #-------- class start renderer = class index extends celarientemplate # # section html # # # section celarien_body # # # section cover # cover: => T.div "#cover", style: "background-image:url(/assets/images/hooray-fade2.jpg);-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH" # # section footer # # # section sidecar # # # section fb_status # # # section sidebar # # # section storybar # storybar: => T.div "#storybar.o-grid__cell.order-2.bg-lighten-2", => T.h1 => T.raw "Celarien -- The tools of the spiritual bodyguard" T.hr() @bloviation() # # section bloviation # bloviation: => T.div "#bloviation.contents", => T.raw "Sorry, that does not exist... Yet." T.a href: "/announcement/two-years-with-bamboo-snow.html", => T.raw " but check out an incredible life with Bamboo Snow." # # section header # allMeta = [[["name","author"],["content","<NAME>: The Celarien's best friend. I'm not him, I wear glasses"]],[["http-equiv","Content-Type"],["content","text/html"],["charset","UTF-8"]],[["name","viewport"],["content","width=device-width, initial-scale=1"]],[["name","description"],["content","some good thoughts. Maybe."]],[["name","keywords"],["content","romance, wisdom, tarot"]],[["property","fb:admins"],["content","1981510532097452"]],[["name","msapplication-TileColor"],["content","#ffffff"]],[["name","msapplication-TileImage"],["content","/assets/icons/ms-icon-144x144.png"]],[["name","theme-color"],["content","#ffffff"]]] htmlTitle = "Practical Metaphysics and Harmonious Mana." #-------- class end # ------- db start db = {} unless db #end of story# db[id="celarienerror404"] = title: "404" slug: "404" category: "error" site: "celarien" accepted: true index: false headlines: [] tags: [] snippets: "{\"first name\":\"first name\"}" memberOf: [] created: "2018-03-05T04:47:09.128Z" lastEdited: "2018-03-05T04:47:09.129Z" published: "2018-03-05T04:47:09.129Z" embargo: "2018-03-05T04:47:09.129Z" captureDate: "2018-03-05T04:47:09.129Z" TimeStamp: 1520225229129 debug: "" author: "Copyright 2010-2018 <NAME>: The Celarien's best friend. I'm not him, I wear glasses" id: "celarienerror404" name: "404" # db[id="celarien/error/404"] = title: "404" slug: "404" category: "error" site: "celarien" accepted: true index: false headlines: [] tags: [] snippets: "{\"first name\":\"first name\"}" memberOf: [] created: "2018-03-05T04:47:09.128Z" lastEdited: "2018-03-05T04:47:09.129Z" published: "2018-03-05T04:47:09.129Z" embargo: "2018-03-05T04:47:09.129Z" captureDate: "2018-03-05T04:47:09.129Z" TimeStamp: 1520225229129 debug: "" author: "Copyright 2010-2018 <NAME>: The Celarien's best friend. I'm not him, I wear glasses" id: "celarien/error/404" name: "404" #
true
# #-------- class start renderer = class index extends celarientemplate # # section html # # # section celarien_body # # # section cover # cover: => T.div "#cover", style: "background-image:url(/assets/images/hooray-fade2.jpg);-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH" # # section footer # # # section sidecar # # # section fb_status # # # section sidebar # # # section storybar # storybar: => T.div "#storybar.o-grid__cell.order-2.bg-lighten-2", => T.h1 => T.raw "Celarien -- The tools of the spiritual bodyguard" T.hr() @bloviation() # # section bloviation # bloviation: => T.div "#bloviation.contents", => T.raw "Sorry, that does not exist... Yet." T.a href: "/announcement/two-years-with-bamboo-snow.html", => T.raw " but check out an incredible life with Bamboo Snow." # # section header # allMeta = [[["name","author"],["content","PI:NAME:<NAME>END_PI: The Celarien's best friend. I'm not him, I wear glasses"]],[["http-equiv","Content-Type"],["content","text/html"],["charset","UTF-8"]],[["name","viewport"],["content","width=device-width, initial-scale=1"]],[["name","description"],["content","some good thoughts. Maybe."]],[["name","keywords"],["content","romance, wisdom, tarot"]],[["property","fb:admins"],["content","1981510532097452"]],[["name","msapplication-TileColor"],["content","#ffffff"]],[["name","msapplication-TileImage"],["content","/assets/icons/ms-icon-144x144.png"]],[["name","theme-color"],["content","#ffffff"]]] htmlTitle = "Practical Metaphysics and Harmonious Mana." #-------- class end # ------- db start db = {} unless db #end of story# db[id="celarienerror404"] = title: "404" slug: "404" category: "error" site: "celarien" accepted: true index: false headlines: [] tags: [] snippets: "{\"first name\":\"first name\"}" memberOf: [] created: "2018-03-05T04:47:09.128Z" lastEdited: "2018-03-05T04:47:09.129Z" published: "2018-03-05T04:47:09.129Z" embargo: "2018-03-05T04:47:09.129Z" captureDate: "2018-03-05T04:47:09.129Z" TimeStamp: 1520225229129 debug: "" author: "Copyright 2010-2018 PI:NAME:<NAME>END_PI: The Celarien's best friend. I'm not him, I wear glasses" id: "celarienerror404" name: "404" # db[id="celarien/error/404"] = title: "404" slug: "404" category: "error" site: "celarien" accepted: true index: false headlines: [] tags: [] snippets: "{\"first name\":\"first name\"}" memberOf: [] created: "2018-03-05T04:47:09.128Z" lastEdited: "2018-03-05T04:47:09.129Z" published: "2018-03-05T04:47:09.129Z" embargo: "2018-03-05T04:47:09.129Z" captureDate: "2018-03-05T04:47:09.129Z" TimeStamp: 1520225229129 debug: "" author: "Copyright 2010-2018 PI:NAME:<NAME>END_PI: The Celarien's best friend. I'm not him, I wear glasses" id: "celarien/error/404" name: "404" #
[ { "context": " for i in [1..5]\n\n levelNameKey = \"level#{i}\"\n levelNameData = classification[levelNa", "end": 14283, "score": 0.8302452564239502, "start": 14281, "tag": "KEY", "value": "#{" }, { "context": "\n if i != 5\n levelDescKey = \"level#{i...
src/glados/static/coffee/models/Compound.coffee
BNext-IQT/glados-frontend-chembl-main-interface
0
Compound = Backbone.Model.extend(DownloadModelOrCollectionExt).extend entityName: 'Compound' entityNamePlural: 'Compounds' idAttribute: 'molecule_chembl_id' defaults: fetch_from_elastic: true indexName: 'chembl_molecule' initialize: -> id = @get('id') id ?= @get('molecule_chembl_id') @set('id', id) @set('molecule_chembl_id', id) if @get('fetch_from_elastic') @url = "#{glados.Settings.ES_PROXY_API_BASE_URL}/es_data/get_es_document/#{Compound.ES_INDEX}/#{id}" else @url = glados.Settings.WS_BASE_URL + 'molecule/' + id + '.json' if @get('enable_similarity_map') @set('loading_similarity_map', true) @loadSimilarityMap() @on 'change:molecule_chembl_id', @loadSimilarityMap, @ @on 'change:reference_smiles', @loadSimilarityMap, @ @on 'change:reference_smiles_error', @loadSimilarityMap, @ if @get('enable_substructure_highlighting') @set('loading_substructure_highlight', true) @loadStructureHighlight() @on 'change:molecule_chembl_id', @loadStructureHighlight, @ @on 'change:reference_ctab', @loadStructureHighlight, @ @on 'change:reference_smarts', @loadStructureHighlight, @ @on 'change:reference_smiles_error', @loadStructureHighlight, @ isParent: -> metadata = @get('_metadata') if not metadata.hierarchy.parent? return true else return false # -------------------------------------------------------------------------------------------------------------------- # Sources # -------------------------------------------------------------------------------------------------------------------- hasAdditionalSources: -> additionalSourcesState = @get('has_additional_sources') if not additionalSourcesState? @getAdditionalSources() additionalSourcesState = @get('has_additional_sources') return additionalSourcesState getAdditionalSources: -> aditionalSourcesCache = @get('additional_sources') if aditionalSourcesCache? return aditionalSourcesCache metadata = @get('_metadata') ownSources = _.unique(v.src_description for v in metadata.compound_records) if @isParent() childrenSourcesList = (c.sources for c in metadata.hierarchy.children) uniqueSourcesObj = {} sourcesFromChildren = [] for sourcesObj in childrenSourcesList for source in _.values(sourcesObj) srcDescription = source.src_description if not uniqueSourcesObj[srcDescription]? uniqueSourcesObj[srcDescription] = true sourcesFromChildren.push(srcDescription) additionalSources = _.difference(sourcesFromChildren, ownSources) else sourcesFromParent = (v.src_description for v in _.values(metadata.hierarchy.parent.sources)) additionalSources = _.difference(sourcesFromParent, ownSources) if additionalSources.length == 0 @set({has_additional_sources: false}, {silent:true}) else @set({has_additional_sources: true}, {silent:true}) additionalSources.sort() @set({additional_sources: additionalSources}, {silent:true}) return additionalSources # -------------------------------------------------------------------------------------------------------------------- # Synonyms and trade names # -------------------------------------------------------------------------------------------------------------------- separateSynonymsAndTradeNames: (rawSynonymsAndTradeNames) -> uniqueSynonymsObj = {} uniqueSynonymsList = [] uniqueTradeNamesObj = {} uniqueTradeNamesList = [] for rawItem in rawSynonymsAndTradeNames itemName = rawItem.synonyms # is this a proper synonym? if rawItem.syn_type != 'TRADE_NAME' if not uniqueSynonymsObj[itemName]? uniqueSynonymsObj[itemName] = true uniqueSynonymsList.push(itemName) #or is is a tradename? else if not uniqueTradeNamesObj[itemName]? uniqueTradeNamesObj[itemName] = true uniqueTradeNamesList.push(itemName) return [uniqueSynonymsList, uniqueTradeNamesList] calculateSynonymsAndTradeNames: -> rawSynonymsAndTradeNames = @get('molecule_synonyms') [uniqueSynonymsList, uniqueTradeNamesList] = @separateSynonymsAndTradeNames(rawSynonymsAndTradeNames) metadata = @get('_metadata') if @isParent() rawChildrenSynonymsAndTradeNamesLists = (c.synonyms for c in metadata.hierarchy.children) rawChildrenSynonyms = [] for rawSynAndTNList in rawChildrenSynonymsAndTradeNamesLists for syn in rawSynAndTNList rawChildrenSynonyms.push(syn) [synsFromChildren, tnsFromChildren] = @separateSynonymsAndTradeNames(rawChildrenSynonyms) additionalSynsList = _.difference(synsFromChildren, uniqueSynonymsList) additionalTnsList = _.difference(tnsFromChildren, uniqueTradeNamesList) else console.log 'metadata: ', metadata rawSynonymsAndTradeNamesFromParent = _.values(metadata.hierarchy.parent.synonyms) [synsFromParent, tnsFromParent] = @separateSynonymsAndTradeNames(rawSynonymsAndTradeNamesFromParent) additionalSynsList = _.difference(synsFromParent, uniqueSynonymsList) additionalTnsList = _.difference(tnsFromParent, uniqueTradeNamesList) @set only_synonyms: uniqueSynonymsList additional_only_synonyms: additionalSynsList only_trade_names: uniqueTradeNamesList additional_trade_names: additionalTnsList , silent: true getSynonyms: -> @getWithCache('only_synonyms', @calculateSynonymsAndTradeNames.bind(@)) getTradenames: -> @getWithCache('only_trade_names', @calculateSynonymsAndTradeNames.bind(@)) getAdditionalSynonyms: -> @getWithCache('additional_only_synonyms', @calculateSynonymsAndTradeNames.bind(@)) getAdditionalTradenames: -> @getWithCache('additional_trade_names', @calculateSynonymsAndTradeNames.bind(@)) getOwnAndAdditionalSynonyms: -> synonyms = @getSynonyms() additionalSynonyms = @getAdditionalSynonyms() return _.union(synonyms, additionalSynonyms) getOwnAndAdditionalTradenames: -> tradenames = @getTradenames() additionalTradenames = @getAdditionalTradenames() return _.union(tradenames, additionalTradenames) # -------------------------------------------------------------------------------------------------------------------- # instance cache # -------------------------------------------------------------------------------------------------------------------- getWithCache: (propName, generator) -> cache = @get(propName) if not cache? generator() cache = @get(propName) return cache # -------------------------------------------------------------------------------------------------------------------- # Family ids # -------------------------------------------------------------------------------------------------------------------- calculateChildrenIDs: -> metadata = @get('_metadata') childrenIDs = (c.chembl_id for c in metadata.hierarchy.children) @set children_ids: childrenIDs , silent: true getChildrenIDs: -> @getWithCache('children_ids', @calculateChildrenIDs.bind(@)) getParentID: -> metadata = @get('_metadata') if @isParent() return @get('id') else return metadata.hierarchy.parent.chembl_id calculateAdditionalIDs: -> metadata = @get('_metadata') additionalIDs = [] if metadata.hierarchy? if @.isParent() childrenIDs = @getChildrenIDs() for childID in childrenIDs additionalIDs.push childID else parentID = @getParentID() additionalIDs.push parentID @set additional_ids: additionalIDs , silent: true getOwnAndAdditionalIDs: -> ownID = @get('id') ids = [ownID] additionalIDs = @getWithCache('additional_ids', @calculateAdditionalIDs.bind(@)) for id in additionalIDs ids.push id return ids loadSimilarityMap: -> if @get('reference_smiles_error') @set('loading_similarity_map', false) @trigger glados.Events.Compound.SIMILARITY_MAP_ERROR return # to start I need the smiles of the compound and the compared one structures = @get('molecule_structures') if not structures? return referenceSmiles = @get('reference_smiles') if not referenceSmiles? return @downloadSimilaritySVG() loadStructureHighlight: -> if @get('reference_smiles_error') @set('loading_substructure_highlight', false) @trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_ERROR return referenceSmiles = @get('reference_smiles') if not referenceSmiles? return referenceCTAB = @get('reference_ctab') if not referenceCTAB? return referenceSmarts = @get('reference_smarts') if not referenceSmarts? return model = @ downloadHighlighted = -> model.downloadHighlightedSVG() @download2DSDF().then downloadHighlighted, downloadHighlighted #--------------------------------------------------------------------------------------------------------------------- # Parsing #--------------------------------------------------------------------------------------------------------------------- parse: (response) -> # get data when it comes from elastic if response._source? objData = response._source else objData = response filterForActivities = 'molecule_chembl_id:' + objData.molecule_chembl_id objData.activities_url = Activity.getActivitiesListURL(filterForActivities) # Lazy definition for sdf content retrieving objData.sdf_url = glados.Settings.WS_BASE_URL + 'molecule/' + objData.molecule_chembl_id + '.sdf' objData.sdf_promise = null objData.get_sdf_content_promise = -> if not objData.sdf_promise objData.sdf_promise = $.ajax(objData.sdf_url) return objData.sdf_promise # Calculate the rule of five from other properties if objData.molecule_properties? objData.ro5 = objData.molecule_properties.num_ro5_violations == 0 else objData.ro5 = false # Computed Image and report card URL's for Compounds objData.structure_image = false if objData.structure_type == 'NONE' or objData.structure_type == 'SEQ' # see the cases here: https://www.ebi.ac.uk/seqdb/confluence/pages/viewpage.action?spaceKey=CHEMBL&title=ChEMBL+Interface # in the section Placeholder Compound Images if objData.molecule_properties? if glados.Utils.Compounds.containsMetals(objData.molecule_properties.full_molformula) objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/metalContaining.svg' else if objData.molecule_type == 'Oligosaccharide' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/oligosaccharide.svg' else if objData.molecule_type == 'Small molecule' if objData.natural_product == '1' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/naturalProduct.svg' else if objData.polymer_flag == true objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/smallMolPolymer.svg' else objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/smallMolecule.svg' else if objData.molecule_type == 'Antibody' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/antibody.svg' else if objData.molecule_type == 'Protein' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/peptide.svg' else if objData.molecule_type == 'Oligonucleotide' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/oligonucleotide.svg' else if objData.molecule_type == 'Enzyme' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/enzyme.svg' else if objData.molecule_type == 'Cell' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/cell.svg' else #if response.molecule_type == 'Unclassified' or response.molecule_type = 'Unknown' or not response.molecule_type? objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/unknown.svg' #response.image_url = glados.Settings.OLD_DEFAULT_IMAGES_BASE_URL + response.molecule_chembl_id else objData.image_url = glados.Settings.WS_BASE_URL + 'image/' + objData.molecule_chembl_id + '.svg' objData.structure_image = true objData.report_card_url = Compound.get_report_card_url(objData.molecule_chembl_id) filterForTargets = '_metadata.related_compounds.all_chembl_ids:' + objData.molecule_chembl_id objData.targets_url = Target.getTargetsListURL(filterForTargets) @parseChemSpiderXref(objData) @parseATCXrefs(objData) return objData; #--------------------------------------------------------------------------------------------------------------------- # Get extra xrefs #--------------------------------------------------------------------------------------------------------------------- parseChemSpiderXref: (objData) -> molStructures = objData.molecule_structures if not molStructures? return inchiKey = molStructures.standard_inchi_key if not inchiKey? return chemSpiderLink = "https://www.chemspider.com/Search.aspx?q=#{inchiKey}" chemSpiderSourceLink = "https://www.chemspider.com/" chemSpidetLinkText = "ChemSpider:#{inchiKey}" if not objData.cross_references? objData.cross_references = [] objData.cross_references.push xref_name: chemSpidetLinkText, xref_src: 'ChemSpider', xref_id: inchiKey, xref_url: chemSpiderLink, xref_src_url: chemSpiderSourceLink parseATCXrefs: (objData) -> metadata = objData._metadata if not metadata? return atcClassifications = metadata.atc_classifications if not atcClassifications? return if atcClassifications.length == 0 return for classification in atcClassifications levelsList = [] for i in [1..5] levelNameKey = "level#{i}" levelNameData = classification[levelNameKey] levelLink = "http://www.whocc.no/atc_ddd_index/?code=#{levelNameData}&showdescription=yes" if i != 5 levelDescKey = "level#{i}_description" levelDescData = classification[levelDescKey].split(' - ')[1] else levelDescData = classification.who_name levelsList.push name: levelNameData description: levelDescData link: levelLink refsOBJ = xref_src: 'ATC' xref_src_url: 'https://www.whocc.no/atc_ddd_index/' xref_name: 'One ATC Group' levels_refs: levelsList if not objData.cross_references? objData.cross_references = [] objData.cross_references.push refsOBJ #--------------------------------------------------------------------------------------------------------------------- # Similarity #--------------------------------------------------------------------------------------------------------------------- downloadSimilaritySVG: ()-> @set reference_smiles_error: false download_similarity_map_error: false , silent: true model = @ promiseFunc = (resolve, reject)-> referenceSmiles = model.get('reference_smiles') structures = model.get('molecule_structures') if not referenceSmiles? reject('Error, there is no reference SMILES PRESENT!') return if not structures? reject('Error, the compound does not have structures data!') return mySmiles = structures.canonical_smiles if not mySmiles? reject('Error, the compound does not have SMILES data!') return if model.get('similarity_map_base64_img')? resolve(model.get('similarity_map_base64_img')) else formData = new FormData() formData.append('file', new Blob([referenceSmiles+'\n'+mySmiles], {type: 'chemical/x-daylight-smiles'}), 'sim.smi') formData.append('format', 'svg') formData.append('height', '500') formData.append('width', '500') formData.append('sanitize', 0) ajax_deferred = $.post url: Compound.SMILES_2_SIMILARITY_MAP_URL data: formData enctype: 'multipart/form-data' processData: false contentType: false cache: false converters: 'text xml': String ajax_deferred.done (ajaxData)-> model.set loading_similarity_map: false similarity_map_base64_img: 'data:image/svg+xml;base64,'+btoa(ajaxData) reference_smiles_error: false reference_smiles_error_jqxhr: undefined , silent: true model.trigger glados.Events.Compound.SIMILARITY_MAP_READY resolve(ajaxData) ajax_deferred.fail (jqxhrError)-> reject(jqxhrError) promise = new Promise(promiseFunc) promise.then null, (jqxhrError)-> model.set download_similarity_map_error: true loading_similarity_map: false reference_smiles_error: true reference_smiles_error_jqxhr: jqxhrError , silent: true model.trigger glados.Events.Compound.SIMILARITY_MAP_ERROR return promise #--------------------------------------------------------------------------------------------------------------------- # Highlighting #--------------------------------------------------------------------------------------------------------------------- downloadHighlightedSVG: ()-> @set 'reference_smiles_error': false 'download_highlighted_error': false , silent: true model = @ promiseFunc = (resolve, reject)-> referenceSmarts = model.get('reference_smarts') # Tries to use the 2d sdf without alignment if the alignment failed if model.get('aligned_sdf')? alignedSdf = model.get('aligned_sdf') else alignedSdf = model.get('sdf2DData') if not referenceSmarts? reject('Error, the reference SMARTS is not present!') return if not alignedSdf? reject('Error, the compound '+model.get('molecule_chembl_id')+' ALIGNED CTAB is not present!') return if model.get('substructure_highlight_base64_img')? resolve(model.get('substructure_highlight_base64_img')) else formData = new FormData() formData.append('file', new Blob([alignedSdf], {type: 'chemical/x-mdl-molfile'}), 'aligned.mol') formData.append('smarts', referenceSmarts) formData.append('computeCoords', 0) formData.append('force', 'true') formData.append('sanitize', 0) ajax_deferred = $.post url: Compound.SDF_2D_HIGHLIGHT_URL data: formData enctype: 'multipart/form-data' processData: false contentType: false cache: false converters: 'text xml': String ajax_deferred.done (ajaxData)-> model.set loading_substructure_highlight: false substructure_highlight_base64_img: 'data:image/svg+xml;base64,'+btoa(ajaxData) reference_smiles_error: false reference_smiles_error_jqxhr: undefined , silent: true model.trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_READY resolve(ajaxData) ajax_deferred.fail (jqxhrError)-> reject(jqxhrError) promise = new Promise(promiseFunc) promise.then null, (jqxhrError)-> model.set loading_substructure_highlight: false download_highlighted_error: true reference_smiles_error: true reference_smiles_error_jqxhr: jqxhrError model.trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_ERROR return promise #--------------------------------------------------------------------------------------------------------------------- # SDF #--------------------------------------------------------------------------------------------------------------------- download2DSDF: ()-> @set('sdf2DError', false, {silent: true}) promiseFunc = (resolve, reject)-> if @get('sdf2DData')? resolve(@get('sdf2DData')) else ajax_deferred = $.get(Compound.SDF_2D_URL + @get('molecule_chembl_id') + '.sdf') compoundModel = @ ajax_deferred.done (ajaxData)-> compoundModel.set('sdf2DData', ajaxData) resolve(ajaxData) ajax_deferred.fail (error)-> compoundModel.set('sdf2DError', true) reject(error) return new Promise(promiseFunc.bind(@)) #--------------------------------------------------------------------------------------------------------------------- # instance urls #--------------------------------------------------------------------------------------------------------------------- getSimilaritySearchURL: (threshold=glados.Settings.DEFAULT_SIMILARITY_THRESHOLD) -> glados.Settings.SIMILARITY_URL_GENERATOR term: @get('id') threshold: threshold #----------------------------------------------------------------------------------------------------------------------- # 3D SDF Constants #----------------------------------------------------------------------------------------------------------------------- Compound.SDF_2D_HIGHLIGHT_URL = glados.Settings.BEAKER_BASE_URL + 'highlightCtabFragmentSvg' Compound.SDF_2D_URL = glados.Settings.WS_BASE_URL + 'molecule/' Compound.SMILES_2_SIMILARITY_MAP_URL = glados.Settings.BEAKER_BASE_URL + 'smiles2SimilarityMapSvg' # Constant definition for ReportCardEntity model functionalities _.extend(Compound, glados.models.base.ReportCardEntity) Compound.color = 'cyan' Compound.reportCardPath = 'compound_report_card/' Compound.getSDFURL = (chemblId) -> glados.Settings.WS_BASE_URL + 'molecule/' + chemblId + '.sdf' Compound.ES_INDEX = 'chembl_molecule' Compound.INDEX_NAME = Compound.ES_INDEX Compound.PROPERTIES_VISUAL_CONFIG = { 'molecule_chembl_id': { link_base: 'report_card_url' image_base_url: 'image_url' hide_label: true }, 'molecule_synonyms': { parse_function: (values) -> _.uniq(v.molecule_synonym for v in values).join(', ') }, '_metadata.related_targets.count': { format_as_number: true link_base: 'targets_url' on_click: CompoundReportCardApp.initMiniHistogramFromFunctionLink function_parameters: ['molecule_chembl_id'] function_constant_parameters: ['targets'] function_key: 'targets' function_link: true execute_on_render: true format_class: 'number-cell-center' }, '_metadata.related_activities.count': { link_base: 'activities_url' on_click: CompoundReportCardApp.initMiniHistogramFromFunctionLink function_parameters: ['molecule_chembl_id'] function_constant_parameters: ['activities'] # to help bind the link to the function, it could be necessary to always use the key of the columns descriptions # or probably not, depending on how this evolves function_key: 'bioactivities' function_link: true execute_on_render: true format_class: 'number-cell-center' }, 'similarity': { 'show': true 'comparator': '_context.similarity' 'sort_disabled': false 'is_sorting': 0 'sort_class': 'fa-sort' 'is_contextual': true } 'sources_list': { parse_function: (values) -> _.unique(v.src_description for v in values) } 'additional_sources_list': { name_to_show_function: (model) -> switch model.isParent() when true then return 'Additional Sources From Alternate Forms:' when false then return 'Additional Sources From Parent:' col_value_function: (model) -> model.getAdditionalSources() show_function: (model) -> model.hasAdditionalSources() } 'chochrane_terms': { comparator: 'pref_name' additional_parsing: encoded_value: (value) -> value.replace(/[ ]/g, '+') } 'clinical_trials_terms': { parse_function: (values) -> _.uniq(v.molecule_synonym for v in values).join(', ') parse_from_model: true additional_parsing: search_term: (model) -> synonyms = if model.isParent() then model.getOwnAndAdditionalSynonyms() else model.getSynonyms() tradenames = if model.isParent() then model.getOwnAndAdditionalTradenames() else model.getTradenames() fullList = _.union(synonyms, tradenames) linkText = _.uniq(v for v in fullList).join(' OR ') maxTextLength = 100 if linkText.length > maxTextLength linkText = "#{linkText.substring(0, (maxTextLength-3))}..." return linkText encoded_search_term: (model) -> synonyms = if model.isParent() then model.getOwnAndAdditionalSynonyms() else model.getSynonyms() tradenames = if model.isParent() then model.getOwnAndAdditionalTradenames() else model.getTradenames() fullList = _.union(synonyms, tradenames) return encodeURIComponent(_.uniq(v for v in fullList).join(' OR ')) } } Compound.COLUMNS = { CHEMBL_ID: aggregatable: true comparator: "molecule_chembl_id" hide_label: true id: "molecule_chembl_id" image_base_url: "image_url" is_sorting: 0 link_base: "report_card_url" name_to_show: "ChEMBL ID" name_to_show_short: "ChEMBL ID" show: true sort_class: "fa-sort" sort_disabled: false PREF_NAME: aggregatable: true comparator: "pref_name" id: "pref_name" is_sorting: 0 name_to_show: "Name" name_to_show_short: "Name" prop_id: "pref_name" show: true sort_class: "fa-sort" sort_disabled: false MAX_PHASE: aggregatable: true comparator: "max_phase" id: "max_phase" integer: true is_sorting: 0 name_to_show: "Max Phase" name_to_show_short: "Max Phase" prop_id: "max_phase" show: true sort_class: "fa-sort" sort_disabled: false year: false FULL_MWT: aggregatable: true comparator: "molecule_properties.full_mwt" id: "molecule_properties.full_mwt" integer: false is_sorting: 0 name_to_show: "Molecular Weight" name_to_show_short: "Full Mwt" prop_id: "molecule_properties.full_mwt" show: true sort_class: "fa-sort" sort_disabled: false year: false ALOGP: aggregatable: true comparator: "molecule_properties.alogp" id: "molecule_properties.alogp" integer: false is_sorting: 0 name_to_show: "AlogP" name_to_show_short: "Alogp" prop_id: "molecule_properties.alogp" show: true sort_class: "fa-sort" sort_disabled: false year: false } Compound.ID_COLUMN = Compound.COLUMNS.CHEMBL_ID Compound.COLUMNS_SETTINGS = { RESULTS_LIST_REPORT_CARD_LONG:[ Compound.COLUMNS.CHEMBL_ID, Compound.COLUMNS.PREF_NAME, Compound.COLUMNS.MAX_PHASE, Compound.COLUMNS.FULL_MWT, Compound.COLUMNS.ALOGP ] RESULTS_LIST_REPORT_CARD_CAROUSEL: [ Compound.COLUMNS.CHEMBL_ID ] } Compound.MINI_REPORT_CARD = LOADING_TEMPLATE: 'Handlebars-Common-MiniRepCardPreloader' TEMPLATE: 'Handlebars-Common-MiniReportCard' Compound.getCompoundsListURL = (filter, isFullState=false, fragmentOnly=false) -> if isFullState filter = btoa(JSON.stringify(filter)) return glados.Settings.ENTITY_BROWSERS_URL_GENERATOR fragment_only: fragmentOnly entity: 'compounds' filter: encodeURIComponent(filter) unless not filter? is_full_state: isFullState
72867
Compound = Backbone.Model.extend(DownloadModelOrCollectionExt).extend entityName: 'Compound' entityNamePlural: 'Compounds' idAttribute: 'molecule_chembl_id' defaults: fetch_from_elastic: true indexName: 'chembl_molecule' initialize: -> id = @get('id') id ?= @get('molecule_chembl_id') @set('id', id) @set('molecule_chembl_id', id) if @get('fetch_from_elastic') @url = "#{glados.Settings.ES_PROXY_API_BASE_URL}/es_data/get_es_document/#{Compound.ES_INDEX}/#{id}" else @url = glados.Settings.WS_BASE_URL + 'molecule/' + id + '.json' if @get('enable_similarity_map') @set('loading_similarity_map', true) @loadSimilarityMap() @on 'change:molecule_chembl_id', @loadSimilarityMap, @ @on 'change:reference_smiles', @loadSimilarityMap, @ @on 'change:reference_smiles_error', @loadSimilarityMap, @ if @get('enable_substructure_highlighting') @set('loading_substructure_highlight', true) @loadStructureHighlight() @on 'change:molecule_chembl_id', @loadStructureHighlight, @ @on 'change:reference_ctab', @loadStructureHighlight, @ @on 'change:reference_smarts', @loadStructureHighlight, @ @on 'change:reference_smiles_error', @loadStructureHighlight, @ isParent: -> metadata = @get('_metadata') if not metadata.hierarchy.parent? return true else return false # -------------------------------------------------------------------------------------------------------------------- # Sources # -------------------------------------------------------------------------------------------------------------------- hasAdditionalSources: -> additionalSourcesState = @get('has_additional_sources') if not additionalSourcesState? @getAdditionalSources() additionalSourcesState = @get('has_additional_sources') return additionalSourcesState getAdditionalSources: -> aditionalSourcesCache = @get('additional_sources') if aditionalSourcesCache? return aditionalSourcesCache metadata = @get('_metadata') ownSources = _.unique(v.src_description for v in metadata.compound_records) if @isParent() childrenSourcesList = (c.sources for c in metadata.hierarchy.children) uniqueSourcesObj = {} sourcesFromChildren = [] for sourcesObj in childrenSourcesList for source in _.values(sourcesObj) srcDescription = source.src_description if not uniqueSourcesObj[srcDescription]? uniqueSourcesObj[srcDescription] = true sourcesFromChildren.push(srcDescription) additionalSources = _.difference(sourcesFromChildren, ownSources) else sourcesFromParent = (v.src_description for v in _.values(metadata.hierarchy.parent.sources)) additionalSources = _.difference(sourcesFromParent, ownSources) if additionalSources.length == 0 @set({has_additional_sources: false}, {silent:true}) else @set({has_additional_sources: true}, {silent:true}) additionalSources.sort() @set({additional_sources: additionalSources}, {silent:true}) return additionalSources # -------------------------------------------------------------------------------------------------------------------- # Synonyms and trade names # -------------------------------------------------------------------------------------------------------------------- separateSynonymsAndTradeNames: (rawSynonymsAndTradeNames) -> uniqueSynonymsObj = {} uniqueSynonymsList = [] uniqueTradeNamesObj = {} uniqueTradeNamesList = [] for rawItem in rawSynonymsAndTradeNames itemName = rawItem.synonyms # is this a proper synonym? if rawItem.syn_type != 'TRADE_NAME' if not uniqueSynonymsObj[itemName]? uniqueSynonymsObj[itemName] = true uniqueSynonymsList.push(itemName) #or is is a tradename? else if not uniqueTradeNamesObj[itemName]? uniqueTradeNamesObj[itemName] = true uniqueTradeNamesList.push(itemName) return [uniqueSynonymsList, uniqueTradeNamesList] calculateSynonymsAndTradeNames: -> rawSynonymsAndTradeNames = @get('molecule_synonyms') [uniqueSynonymsList, uniqueTradeNamesList] = @separateSynonymsAndTradeNames(rawSynonymsAndTradeNames) metadata = @get('_metadata') if @isParent() rawChildrenSynonymsAndTradeNamesLists = (c.synonyms for c in metadata.hierarchy.children) rawChildrenSynonyms = [] for rawSynAndTNList in rawChildrenSynonymsAndTradeNamesLists for syn in rawSynAndTNList rawChildrenSynonyms.push(syn) [synsFromChildren, tnsFromChildren] = @separateSynonymsAndTradeNames(rawChildrenSynonyms) additionalSynsList = _.difference(synsFromChildren, uniqueSynonymsList) additionalTnsList = _.difference(tnsFromChildren, uniqueTradeNamesList) else console.log 'metadata: ', metadata rawSynonymsAndTradeNamesFromParent = _.values(metadata.hierarchy.parent.synonyms) [synsFromParent, tnsFromParent] = @separateSynonymsAndTradeNames(rawSynonymsAndTradeNamesFromParent) additionalSynsList = _.difference(synsFromParent, uniqueSynonymsList) additionalTnsList = _.difference(tnsFromParent, uniqueTradeNamesList) @set only_synonyms: uniqueSynonymsList additional_only_synonyms: additionalSynsList only_trade_names: uniqueTradeNamesList additional_trade_names: additionalTnsList , silent: true getSynonyms: -> @getWithCache('only_synonyms', @calculateSynonymsAndTradeNames.bind(@)) getTradenames: -> @getWithCache('only_trade_names', @calculateSynonymsAndTradeNames.bind(@)) getAdditionalSynonyms: -> @getWithCache('additional_only_synonyms', @calculateSynonymsAndTradeNames.bind(@)) getAdditionalTradenames: -> @getWithCache('additional_trade_names', @calculateSynonymsAndTradeNames.bind(@)) getOwnAndAdditionalSynonyms: -> synonyms = @getSynonyms() additionalSynonyms = @getAdditionalSynonyms() return _.union(synonyms, additionalSynonyms) getOwnAndAdditionalTradenames: -> tradenames = @getTradenames() additionalTradenames = @getAdditionalTradenames() return _.union(tradenames, additionalTradenames) # -------------------------------------------------------------------------------------------------------------------- # instance cache # -------------------------------------------------------------------------------------------------------------------- getWithCache: (propName, generator) -> cache = @get(propName) if not cache? generator() cache = @get(propName) return cache # -------------------------------------------------------------------------------------------------------------------- # Family ids # -------------------------------------------------------------------------------------------------------------------- calculateChildrenIDs: -> metadata = @get('_metadata') childrenIDs = (c.chembl_id for c in metadata.hierarchy.children) @set children_ids: childrenIDs , silent: true getChildrenIDs: -> @getWithCache('children_ids', @calculateChildrenIDs.bind(@)) getParentID: -> metadata = @get('_metadata') if @isParent() return @get('id') else return metadata.hierarchy.parent.chembl_id calculateAdditionalIDs: -> metadata = @get('_metadata') additionalIDs = [] if metadata.hierarchy? if @.isParent() childrenIDs = @getChildrenIDs() for childID in childrenIDs additionalIDs.push childID else parentID = @getParentID() additionalIDs.push parentID @set additional_ids: additionalIDs , silent: true getOwnAndAdditionalIDs: -> ownID = @get('id') ids = [ownID] additionalIDs = @getWithCache('additional_ids', @calculateAdditionalIDs.bind(@)) for id in additionalIDs ids.push id return ids loadSimilarityMap: -> if @get('reference_smiles_error') @set('loading_similarity_map', false) @trigger glados.Events.Compound.SIMILARITY_MAP_ERROR return # to start I need the smiles of the compound and the compared one structures = @get('molecule_structures') if not structures? return referenceSmiles = @get('reference_smiles') if not referenceSmiles? return @downloadSimilaritySVG() loadStructureHighlight: -> if @get('reference_smiles_error') @set('loading_substructure_highlight', false) @trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_ERROR return referenceSmiles = @get('reference_smiles') if not referenceSmiles? return referenceCTAB = @get('reference_ctab') if not referenceCTAB? return referenceSmarts = @get('reference_smarts') if not referenceSmarts? return model = @ downloadHighlighted = -> model.downloadHighlightedSVG() @download2DSDF().then downloadHighlighted, downloadHighlighted #--------------------------------------------------------------------------------------------------------------------- # Parsing #--------------------------------------------------------------------------------------------------------------------- parse: (response) -> # get data when it comes from elastic if response._source? objData = response._source else objData = response filterForActivities = 'molecule_chembl_id:' + objData.molecule_chembl_id objData.activities_url = Activity.getActivitiesListURL(filterForActivities) # Lazy definition for sdf content retrieving objData.sdf_url = glados.Settings.WS_BASE_URL + 'molecule/' + objData.molecule_chembl_id + '.sdf' objData.sdf_promise = null objData.get_sdf_content_promise = -> if not objData.sdf_promise objData.sdf_promise = $.ajax(objData.sdf_url) return objData.sdf_promise # Calculate the rule of five from other properties if objData.molecule_properties? objData.ro5 = objData.molecule_properties.num_ro5_violations == 0 else objData.ro5 = false # Computed Image and report card URL's for Compounds objData.structure_image = false if objData.structure_type == 'NONE' or objData.structure_type == 'SEQ' # see the cases here: https://www.ebi.ac.uk/seqdb/confluence/pages/viewpage.action?spaceKey=CHEMBL&title=ChEMBL+Interface # in the section Placeholder Compound Images if objData.molecule_properties? if glados.Utils.Compounds.containsMetals(objData.molecule_properties.full_molformula) objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/metalContaining.svg' else if objData.molecule_type == 'Oligosaccharide' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/oligosaccharide.svg' else if objData.molecule_type == 'Small molecule' if objData.natural_product == '1' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/naturalProduct.svg' else if objData.polymer_flag == true objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/smallMolPolymer.svg' else objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/smallMolecule.svg' else if objData.molecule_type == 'Antibody' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/antibody.svg' else if objData.molecule_type == 'Protein' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/peptide.svg' else if objData.molecule_type == 'Oligonucleotide' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/oligonucleotide.svg' else if objData.molecule_type == 'Enzyme' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/enzyme.svg' else if objData.molecule_type == 'Cell' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/cell.svg' else #if response.molecule_type == 'Unclassified' or response.molecule_type = 'Unknown' or not response.molecule_type? objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/unknown.svg' #response.image_url = glados.Settings.OLD_DEFAULT_IMAGES_BASE_URL + response.molecule_chembl_id else objData.image_url = glados.Settings.WS_BASE_URL + 'image/' + objData.molecule_chembl_id + '.svg' objData.structure_image = true objData.report_card_url = Compound.get_report_card_url(objData.molecule_chembl_id) filterForTargets = '_metadata.related_compounds.all_chembl_ids:' + objData.molecule_chembl_id objData.targets_url = Target.getTargetsListURL(filterForTargets) @parseChemSpiderXref(objData) @parseATCXrefs(objData) return objData; #--------------------------------------------------------------------------------------------------------------------- # Get extra xrefs #--------------------------------------------------------------------------------------------------------------------- parseChemSpiderXref: (objData) -> molStructures = objData.molecule_structures if not molStructures? return inchiKey = molStructures.standard_inchi_key if not inchiKey? return chemSpiderLink = "https://www.chemspider.com/Search.aspx?q=#{inchiKey}" chemSpiderSourceLink = "https://www.chemspider.com/" chemSpidetLinkText = "ChemSpider:#{inchiKey}" if not objData.cross_references? objData.cross_references = [] objData.cross_references.push xref_name: chemSpidetLinkText, xref_src: 'ChemSpider', xref_id: inchiKey, xref_url: chemSpiderLink, xref_src_url: chemSpiderSourceLink parseATCXrefs: (objData) -> metadata = objData._metadata if not metadata? return atcClassifications = metadata.atc_classifications if not atcClassifications? return if atcClassifications.length == 0 return for classification in atcClassifications levelsList = [] for i in [1..5] levelNameKey = "level<KEY>i}" levelNameData = classification[levelNameKey] levelLink = "http://www.whocc.no/atc_ddd_index/?code=#{levelNameData}&showdescription=yes" if i != 5 levelDescKey = "level<KEY>i}_<KEY>" levelDescData = classification[levelDescKey].split(' - ')[1] else levelDescData = classification.who_name levelsList.push name: levelNameData description: levelDescData link: levelLink refsOBJ = xref_src: 'ATC' xref_src_url: 'https://www.whocc.no/atc_ddd_index/' xref_name: 'One ATC Group' levels_refs: levelsList if not objData.cross_references? objData.cross_references = [] objData.cross_references.push refsOBJ #--------------------------------------------------------------------------------------------------------------------- # Similarity #--------------------------------------------------------------------------------------------------------------------- downloadSimilaritySVG: ()-> @set reference_smiles_error: false download_similarity_map_error: false , silent: true model = @ promiseFunc = (resolve, reject)-> referenceSmiles = model.get('reference_smiles') structures = model.get('molecule_structures') if not referenceSmiles? reject('Error, there is no reference SMILES PRESENT!') return if not structures? reject('Error, the compound does not have structures data!') return mySmiles = structures.canonical_smiles if not mySmiles? reject('Error, the compound does not have SMILES data!') return if model.get('similarity_map_base64_img')? resolve(model.get('similarity_map_base64_img')) else formData = new FormData() formData.append('file', new Blob([referenceSmiles+'\n'+mySmiles], {type: 'chemical/x-daylight-smiles'}), 'sim.smi') formData.append('format', 'svg') formData.append('height', '500') formData.append('width', '500') formData.append('sanitize', 0) ajax_deferred = $.post url: Compound.SMILES_2_SIMILARITY_MAP_URL data: formData enctype: 'multipart/form-data' processData: false contentType: false cache: false converters: 'text xml': String ajax_deferred.done (ajaxData)-> model.set loading_similarity_map: false similarity_map_base64_img: 'data:image/svg+xml;base64,'+btoa(ajaxData) reference_smiles_error: false reference_smiles_error_jqxhr: undefined , silent: true model.trigger glados.Events.Compound.SIMILARITY_MAP_READY resolve(ajaxData) ajax_deferred.fail (jqxhrError)-> reject(jqxhrError) promise = new Promise(promiseFunc) promise.then null, (jqxhrError)-> model.set download_similarity_map_error: true loading_similarity_map: false reference_smiles_error: true reference_smiles_error_jqxhr: jqxhrError , silent: true model.trigger glados.Events.Compound.SIMILARITY_MAP_ERROR return promise #--------------------------------------------------------------------------------------------------------------------- # Highlighting #--------------------------------------------------------------------------------------------------------------------- downloadHighlightedSVG: ()-> @set 'reference_smiles_error': false 'download_highlighted_error': false , silent: true model = @ promiseFunc = (resolve, reject)-> referenceSmarts = model.get('reference_smarts') # Tries to use the 2d sdf without alignment if the alignment failed if model.get('aligned_sdf')? alignedSdf = model.get('aligned_sdf') else alignedSdf = model.get('sdf2DData') if not referenceSmarts? reject('Error, the reference SMARTS is not present!') return if not alignedSdf? reject('Error, the compound '+model.get('molecule_chembl_id')+' ALIGNED CTAB is not present!') return if model.get('substructure_highlight_base64_img')? resolve(model.get('substructure_highlight_base64_img')) else formData = new FormData() formData.append('file', new Blob([alignedSdf], {type: 'chemical/x-mdl-molfile'}), 'aligned.mol') formData.append('smarts', referenceSmarts) formData.append('computeCoords', 0) formData.append('force', 'true') formData.append('sanitize', 0) ajax_deferred = $.post url: Compound.SDF_2D_HIGHLIGHT_URL data: formData enctype: 'multipart/form-data' processData: false contentType: false cache: false converters: 'text xml': String ajax_deferred.done (ajaxData)-> model.set loading_substructure_highlight: false substructure_highlight_base64_img: 'data:image/svg+xml;base64,'+btoa(ajaxData) reference_smiles_error: false reference_smiles_error_jqxhr: undefined , silent: true model.trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_READY resolve(ajaxData) ajax_deferred.fail (jqxhrError)-> reject(jqxhrError) promise = new Promise(promiseFunc) promise.then null, (jqxhrError)-> model.set loading_substructure_highlight: false download_highlighted_error: true reference_smiles_error: true reference_smiles_error_jqxhr: jqxhrError model.trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_ERROR return promise #--------------------------------------------------------------------------------------------------------------------- # SDF #--------------------------------------------------------------------------------------------------------------------- download2DSDF: ()-> @set('sdf2DError', false, {silent: true}) promiseFunc = (resolve, reject)-> if @get('sdf2DData')? resolve(@get('sdf2DData')) else ajax_deferred = $.get(Compound.SDF_2D_URL + @get('molecule_chembl_id') + '.sdf') compoundModel = @ ajax_deferred.done (ajaxData)-> compoundModel.set('sdf2DData', ajaxData) resolve(ajaxData) ajax_deferred.fail (error)-> compoundModel.set('sdf2DError', true) reject(error) return new Promise(promiseFunc.bind(@)) #--------------------------------------------------------------------------------------------------------------------- # instance urls #--------------------------------------------------------------------------------------------------------------------- getSimilaritySearchURL: (threshold=glados.Settings.DEFAULT_SIMILARITY_THRESHOLD) -> glados.Settings.SIMILARITY_URL_GENERATOR term: @get('id') threshold: threshold #----------------------------------------------------------------------------------------------------------------------- # 3D SDF Constants #----------------------------------------------------------------------------------------------------------------------- Compound.SDF_2D_HIGHLIGHT_URL = glados.Settings.BEAKER_BASE_URL + 'highlightCtabFragmentSvg' Compound.SDF_2D_URL = glados.Settings.WS_BASE_URL + 'molecule/' Compound.SMILES_2_SIMILARITY_MAP_URL = glados.Settings.BEAKER_BASE_URL + 'smiles2SimilarityMapSvg' # Constant definition for ReportCardEntity model functionalities _.extend(Compound, glados.models.base.ReportCardEntity) Compound.color = 'cyan' Compound.reportCardPath = 'compound_report_card/' Compound.getSDFURL = (chemblId) -> glados.Settings.WS_BASE_URL + 'molecule/' + chemblId + '.sdf' Compound.ES_INDEX = 'chembl_molecule' Compound.INDEX_NAME = Compound.ES_INDEX Compound.PROPERTIES_VISUAL_CONFIG = { 'molecule_chembl_id': { link_base: 'report_card_url' image_base_url: 'image_url' hide_label: true }, 'molecule_synonyms': { parse_function: (values) -> _.uniq(v.molecule_synonym for v in values).join(', ') }, '_metadata.related_targets.count': { format_as_number: true link_base: 'targets_url' on_click: CompoundReportCardApp.initMiniHistogramFromFunctionLink function_parameters: ['molecule_chembl_id'] function_constant_parameters: ['targets'] function_key: 'targets' function_link: true execute_on_render: true format_class: 'number-cell-center' }, '_metadata.related_activities.count': { link_base: 'activities_url' on_click: CompoundReportCardApp.initMiniHistogramFromFunctionLink function_parameters: ['molecule_chembl_id'] function_constant_parameters: ['activities'] # to help bind the link to the function, it could be necessary to always use the key of the columns descriptions # or probably not, depending on how this evolves function_key: 'bioactivities' function_link: true execute_on_render: true format_class: 'number-cell-center' }, 'similarity': { 'show': true 'comparator': '_context.similarity' 'sort_disabled': false 'is_sorting': 0 'sort_class': 'fa-sort' 'is_contextual': true } 'sources_list': { parse_function: (values) -> _.unique(v.src_description for v in values) } 'additional_sources_list': { name_to_show_function: (model) -> switch model.isParent() when true then return 'Additional Sources From Alternate Forms:' when false then return 'Additional Sources From Parent:' col_value_function: (model) -> model.getAdditionalSources() show_function: (model) -> model.hasAdditionalSources() } 'chochrane_terms': { comparator: 'pref_name' additional_parsing: encoded_value: (value) -> value.replace(/[ ]/g, '+') } 'clinical_trials_terms': { parse_function: (values) -> _.uniq(v.molecule_synonym for v in values).join(', ') parse_from_model: true additional_parsing: search_term: (model) -> synonyms = if model.isParent() then model.getOwnAndAdditionalSynonyms() else model.getSynonyms() tradenames = if model.isParent() then model.getOwnAndAdditionalTradenames() else model.getTradenames() fullList = _.union(synonyms, tradenames) linkText = _.uniq(v for v in fullList).join(' OR ') maxTextLength = 100 if linkText.length > maxTextLength linkText = "#{linkText.substring(0, (maxTextLength-3))}..." return linkText encoded_search_term: (model) -> synonyms = if model.isParent() then model.getOwnAndAdditionalSynonyms() else model.getSynonyms() tradenames = if model.isParent() then model.getOwnAndAdditionalTradenames() else model.getTradenames() fullList = _.union(synonyms, tradenames) return encodeURIComponent(_.uniq(v for v in fullList).join(' OR ')) } } Compound.COLUMNS = { CHEMBL_ID: aggregatable: true comparator: "molecule_chembl_id" hide_label: true id: "molecule_chembl_id" image_base_url: "image_url" is_sorting: 0 link_base: "report_card_url" name_to_show: "ChEMBL ID" name_to_show_short: "ChEMBL ID" show: true sort_class: "fa-sort" sort_disabled: false PREF_NAME: aggregatable: true comparator: "pref_name" id: "pref_name" is_sorting: 0 name_to_show: "Name" name_to_show_short: "Name" prop_id: "pref_name" show: true sort_class: "fa-sort" sort_disabled: false MAX_PHASE: aggregatable: true comparator: "max_phase" id: "max_phase" integer: true is_sorting: 0 name_to_show: "Max Phase" name_to_show_short: "Max Phase" prop_id: "max_phase" show: true sort_class: "fa-sort" sort_disabled: false year: false FULL_MWT: aggregatable: true comparator: "molecule_properties.full_mwt" id: "molecule_properties.full_mwt" integer: false is_sorting: 0 name_to_show: "Molecular Weight" name_to_show_short: "Full Mwt" prop_id: "molecule_properties.full_mwt" show: true sort_class: "fa-sort" sort_disabled: false year: false ALOGP: aggregatable: true comparator: "molecule_properties.alogp" id: "molecule_properties.alogp" integer: false is_sorting: 0 name_to_show: "AlogP" name_to_show_short: "Alogp" prop_id: "molecule_properties.alogp" show: true sort_class: "fa-sort" sort_disabled: false year: false } Compound.ID_COLUMN = Compound.COLUMNS.CHEMBL_ID Compound.COLUMNS_SETTINGS = { RESULTS_LIST_REPORT_CARD_LONG:[ Compound.COLUMNS.CHEMBL_ID, Compound.COLUMNS.PREF_NAME, Compound.COLUMNS.MAX_PHASE, Compound.COLUMNS.FULL_MWT, Compound.COLUMNS.ALOGP ] RESULTS_LIST_REPORT_CARD_CAROUSEL: [ Compound.COLUMNS.CHEMBL_ID ] } Compound.MINI_REPORT_CARD = LOADING_TEMPLATE: 'Handlebars-Common-MiniRepCardPreloader' TEMPLATE: 'Handlebars-Common-MiniReportCard' Compound.getCompoundsListURL = (filter, isFullState=false, fragmentOnly=false) -> if isFullState filter = btoa(JSON.stringify(filter)) return glados.Settings.ENTITY_BROWSERS_URL_GENERATOR fragment_only: fragmentOnly entity: 'compounds' filter: encodeURIComponent(filter) unless not filter? is_full_state: isFullState
true
Compound = Backbone.Model.extend(DownloadModelOrCollectionExt).extend entityName: 'Compound' entityNamePlural: 'Compounds' idAttribute: 'molecule_chembl_id' defaults: fetch_from_elastic: true indexName: 'chembl_molecule' initialize: -> id = @get('id') id ?= @get('molecule_chembl_id') @set('id', id) @set('molecule_chembl_id', id) if @get('fetch_from_elastic') @url = "#{glados.Settings.ES_PROXY_API_BASE_URL}/es_data/get_es_document/#{Compound.ES_INDEX}/#{id}" else @url = glados.Settings.WS_BASE_URL + 'molecule/' + id + '.json' if @get('enable_similarity_map') @set('loading_similarity_map', true) @loadSimilarityMap() @on 'change:molecule_chembl_id', @loadSimilarityMap, @ @on 'change:reference_smiles', @loadSimilarityMap, @ @on 'change:reference_smiles_error', @loadSimilarityMap, @ if @get('enable_substructure_highlighting') @set('loading_substructure_highlight', true) @loadStructureHighlight() @on 'change:molecule_chembl_id', @loadStructureHighlight, @ @on 'change:reference_ctab', @loadStructureHighlight, @ @on 'change:reference_smarts', @loadStructureHighlight, @ @on 'change:reference_smiles_error', @loadStructureHighlight, @ isParent: -> metadata = @get('_metadata') if not metadata.hierarchy.parent? return true else return false # -------------------------------------------------------------------------------------------------------------------- # Sources # -------------------------------------------------------------------------------------------------------------------- hasAdditionalSources: -> additionalSourcesState = @get('has_additional_sources') if not additionalSourcesState? @getAdditionalSources() additionalSourcesState = @get('has_additional_sources') return additionalSourcesState getAdditionalSources: -> aditionalSourcesCache = @get('additional_sources') if aditionalSourcesCache? return aditionalSourcesCache metadata = @get('_metadata') ownSources = _.unique(v.src_description for v in metadata.compound_records) if @isParent() childrenSourcesList = (c.sources for c in metadata.hierarchy.children) uniqueSourcesObj = {} sourcesFromChildren = [] for sourcesObj in childrenSourcesList for source in _.values(sourcesObj) srcDescription = source.src_description if not uniqueSourcesObj[srcDescription]? uniqueSourcesObj[srcDescription] = true sourcesFromChildren.push(srcDescription) additionalSources = _.difference(sourcesFromChildren, ownSources) else sourcesFromParent = (v.src_description for v in _.values(metadata.hierarchy.parent.sources)) additionalSources = _.difference(sourcesFromParent, ownSources) if additionalSources.length == 0 @set({has_additional_sources: false}, {silent:true}) else @set({has_additional_sources: true}, {silent:true}) additionalSources.sort() @set({additional_sources: additionalSources}, {silent:true}) return additionalSources # -------------------------------------------------------------------------------------------------------------------- # Synonyms and trade names # -------------------------------------------------------------------------------------------------------------------- separateSynonymsAndTradeNames: (rawSynonymsAndTradeNames) -> uniqueSynonymsObj = {} uniqueSynonymsList = [] uniqueTradeNamesObj = {} uniqueTradeNamesList = [] for rawItem in rawSynonymsAndTradeNames itemName = rawItem.synonyms # is this a proper synonym? if rawItem.syn_type != 'TRADE_NAME' if not uniqueSynonymsObj[itemName]? uniqueSynonymsObj[itemName] = true uniqueSynonymsList.push(itemName) #or is is a tradename? else if not uniqueTradeNamesObj[itemName]? uniqueTradeNamesObj[itemName] = true uniqueTradeNamesList.push(itemName) return [uniqueSynonymsList, uniqueTradeNamesList] calculateSynonymsAndTradeNames: -> rawSynonymsAndTradeNames = @get('molecule_synonyms') [uniqueSynonymsList, uniqueTradeNamesList] = @separateSynonymsAndTradeNames(rawSynonymsAndTradeNames) metadata = @get('_metadata') if @isParent() rawChildrenSynonymsAndTradeNamesLists = (c.synonyms for c in metadata.hierarchy.children) rawChildrenSynonyms = [] for rawSynAndTNList in rawChildrenSynonymsAndTradeNamesLists for syn in rawSynAndTNList rawChildrenSynonyms.push(syn) [synsFromChildren, tnsFromChildren] = @separateSynonymsAndTradeNames(rawChildrenSynonyms) additionalSynsList = _.difference(synsFromChildren, uniqueSynonymsList) additionalTnsList = _.difference(tnsFromChildren, uniqueTradeNamesList) else console.log 'metadata: ', metadata rawSynonymsAndTradeNamesFromParent = _.values(metadata.hierarchy.parent.synonyms) [synsFromParent, tnsFromParent] = @separateSynonymsAndTradeNames(rawSynonymsAndTradeNamesFromParent) additionalSynsList = _.difference(synsFromParent, uniqueSynonymsList) additionalTnsList = _.difference(tnsFromParent, uniqueTradeNamesList) @set only_synonyms: uniqueSynonymsList additional_only_synonyms: additionalSynsList only_trade_names: uniqueTradeNamesList additional_trade_names: additionalTnsList , silent: true getSynonyms: -> @getWithCache('only_synonyms', @calculateSynonymsAndTradeNames.bind(@)) getTradenames: -> @getWithCache('only_trade_names', @calculateSynonymsAndTradeNames.bind(@)) getAdditionalSynonyms: -> @getWithCache('additional_only_synonyms', @calculateSynonymsAndTradeNames.bind(@)) getAdditionalTradenames: -> @getWithCache('additional_trade_names', @calculateSynonymsAndTradeNames.bind(@)) getOwnAndAdditionalSynonyms: -> synonyms = @getSynonyms() additionalSynonyms = @getAdditionalSynonyms() return _.union(synonyms, additionalSynonyms) getOwnAndAdditionalTradenames: -> tradenames = @getTradenames() additionalTradenames = @getAdditionalTradenames() return _.union(tradenames, additionalTradenames) # -------------------------------------------------------------------------------------------------------------------- # instance cache # -------------------------------------------------------------------------------------------------------------------- getWithCache: (propName, generator) -> cache = @get(propName) if not cache? generator() cache = @get(propName) return cache # -------------------------------------------------------------------------------------------------------------------- # Family ids # -------------------------------------------------------------------------------------------------------------------- calculateChildrenIDs: -> metadata = @get('_metadata') childrenIDs = (c.chembl_id for c in metadata.hierarchy.children) @set children_ids: childrenIDs , silent: true getChildrenIDs: -> @getWithCache('children_ids', @calculateChildrenIDs.bind(@)) getParentID: -> metadata = @get('_metadata') if @isParent() return @get('id') else return metadata.hierarchy.parent.chembl_id calculateAdditionalIDs: -> metadata = @get('_metadata') additionalIDs = [] if metadata.hierarchy? if @.isParent() childrenIDs = @getChildrenIDs() for childID in childrenIDs additionalIDs.push childID else parentID = @getParentID() additionalIDs.push parentID @set additional_ids: additionalIDs , silent: true getOwnAndAdditionalIDs: -> ownID = @get('id') ids = [ownID] additionalIDs = @getWithCache('additional_ids', @calculateAdditionalIDs.bind(@)) for id in additionalIDs ids.push id return ids loadSimilarityMap: -> if @get('reference_smiles_error') @set('loading_similarity_map', false) @trigger glados.Events.Compound.SIMILARITY_MAP_ERROR return # to start I need the smiles of the compound and the compared one structures = @get('molecule_structures') if not structures? return referenceSmiles = @get('reference_smiles') if not referenceSmiles? return @downloadSimilaritySVG() loadStructureHighlight: -> if @get('reference_smiles_error') @set('loading_substructure_highlight', false) @trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_ERROR return referenceSmiles = @get('reference_smiles') if not referenceSmiles? return referenceCTAB = @get('reference_ctab') if not referenceCTAB? return referenceSmarts = @get('reference_smarts') if not referenceSmarts? return model = @ downloadHighlighted = -> model.downloadHighlightedSVG() @download2DSDF().then downloadHighlighted, downloadHighlighted #--------------------------------------------------------------------------------------------------------------------- # Parsing #--------------------------------------------------------------------------------------------------------------------- parse: (response) -> # get data when it comes from elastic if response._source? objData = response._source else objData = response filterForActivities = 'molecule_chembl_id:' + objData.molecule_chembl_id objData.activities_url = Activity.getActivitiesListURL(filterForActivities) # Lazy definition for sdf content retrieving objData.sdf_url = glados.Settings.WS_BASE_URL + 'molecule/' + objData.molecule_chembl_id + '.sdf' objData.sdf_promise = null objData.get_sdf_content_promise = -> if not objData.sdf_promise objData.sdf_promise = $.ajax(objData.sdf_url) return objData.sdf_promise # Calculate the rule of five from other properties if objData.molecule_properties? objData.ro5 = objData.molecule_properties.num_ro5_violations == 0 else objData.ro5 = false # Computed Image and report card URL's for Compounds objData.structure_image = false if objData.structure_type == 'NONE' or objData.structure_type == 'SEQ' # see the cases here: https://www.ebi.ac.uk/seqdb/confluence/pages/viewpage.action?spaceKey=CHEMBL&title=ChEMBL+Interface # in the section Placeholder Compound Images if objData.molecule_properties? if glados.Utils.Compounds.containsMetals(objData.molecule_properties.full_molformula) objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/metalContaining.svg' else if objData.molecule_type == 'Oligosaccharide' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/oligosaccharide.svg' else if objData.molecule_type == 'Small molecule' if objData.natural_product == '1' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/naturalProduct.svg' else if objData.polymer_flag == true objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/smallMolPolymer.svg' else objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/smallMolecule.svg' else if objData.molecule_type == 'Antibody' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/antibody.svg' else if objData.molecule_type == 'Protein' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/peptide.svg' else if objData.molecule_type == 'Oligonucleotide' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/oligonucleotide.svg' else if objData.molecule_type == 'Enzyme' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/enzyme.svg' else if objData.molecule_type == 'Cell' objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/cell.svg' else #if response.molecule_type == 'Unclassified' or response.molecule_type = 'Unknown' or not response.molecule_type? objData.image_url = glados.Settings.STATIC_IMAGES_URL + 'compound_placeholders/unknown.svg' #response.image_url = glados.Settings.OLD_DEFAULT_IMAGES_BASE_URL + response.molecule_chembl_id else objData.image_url = glados.Settings.WS_BASE_URL + 'image/' + objData.molecule_chembl_id + '.svg' objData.structure_image = true objData.report_card_url = Compound.get_report_card_url(objData.molecule_chembl_id) filterForTargets = '_metadata.related_compounds.all_chembl_ids:' + objData.molecule_chembl_id objData.targets_url = Target.getTargetsListURL(filterForTargets) @parseChemSpiderXref(objData) @parseATCXrefs(objData) return objData; #--------------------------------------------------------------------------------------------------------------------- # Get extra xrefs #--------------------------------------------------------------------------------------------------------------------- parseChemSpiderXref: (objData) -> molStructures = objData.molecule_structures if not molStructures? return inchiKey = molStructures.standard_inchi_key if not inchiKey? return chemSpiderLink = "https://www.chemspider.com/Search.aspx?q=#{inchiKey}" chemSpiderSourceLink = "https://www.chemspider.com/" chemSpidetLinkText = "ChemSpider:#{inchiKey}" if not objData.cross_references? objData.cross_references = [] objData.cross_references.push xref_name: chemSpidetLinkText, xref_src: 'ChemSpider', xref_id: inchiKey, xref_url: chemSpiderLink, xref_src_url: chemSpiderSourceLink parseATCXrefs: (objData) -> metadata = objData._metadata if not metadata? return atcClassifications = metadata.atc_classifications if not atcClassifications? return if atcClassifications.length == 0 return for classification in atcClassifications levelsList = [] for i in [1..5] levelNameKey = "levelPI:KEY:<KEY>END_PIi}" levelNameData = classification[levelNameKey] levelLink = "http://www.whocc.no/atc_ddd_index/?code=#{levelNameData}&showdescription=yes" if i != 5 levelDescKey = "levelPI:KEY:<KEY>END_PIi}_PI:KEY:<KEY>END_PI" levelDescData = classification[levelDescKey].split(' - ')[1] else levelDescData = classification.who_name levelsList.push name: levelNameData description: levelDescData link: levelLink refsOBJ = xref_src: 'ATC' xref_src_url: 'https://www.whocc.no/atc_ddd_index/' xref_name: 'One ATC Group' levels_refs: levelsList if not objData.cross_references? objData.cross_references = [] objData.cross_references.push refsOBJ #--------------------------------------------------------------------------------------------------------------------- # Similarity #--------------------------------------------------------------------------------------------------------------------- downloadSimilaritySVG: ()-> @set reference_smiles_error: false download_similarity_map_error: false , silent: true model = @ promiseFunc = (resolve, reject)-> referenceSmiles = model.get('reference_smiles') structures = model.get('molecule_structures') if not referenceSmiles? reject('Error, there is no reference SMILES PRESENT!') return if not structures? reject('Error, the compound does not have structures data!') return mySmiles = structures.canonical_smiles if not mySmiles? reject('Error, the compound does not have SMILES data!') return if model.get('similarity_map_base64_img')? resolve(model.get('similarity_map_base64_img')) else formData = new FormData() formData.append('file', new Blob([referenceSmiles+'\n'+mySmiles], {type: 'chemical/x-daylight-smiles'}), 'sim.smi') formData.append('format', 'svg') formData.append('height', '500') formData.append('width', '500') formData.append('sanitize', 0) ajax_deferred = $.post url: Compound.SMILES_2_SIMILARITY_MAP_URL data: formData enctype: 'multipart/form-data' processData: false contentType: false cache: false converters: 'text xml': String ajax_deferred.done (ajaxData)-> model.set loading_similarity_map: false similarity_map_base64_img: 'data:image/svg+xml;base64,'+btoa(ajaxData) reference_smiles_error: false reference_smiles_error_jqxhr: undefined , silent: true model.trigger glados.Events.Compound.SIMILARITY_MAP_READY resolve(ajaxData) ajax_deferred.fail (jqxhrError)-> reject(jqxhrError) promise = new Promise(promiseFunc) promise.then null, (jqxhrError)-> model.set download_similarity_map_error: true loading_similarity_map: false reference_smiles_error: true reference_smiles_error_jqxhr: jqxhrError , silent: true model.trigger glados.Events.Compound.SIMILARITY_MAP_ERROR return promise #--------------------------------------------------------------------------------------------------------------------- # Highlighting #--------------------------------------------------------------------------------------------------------------------- downloadHighlightedSVG: ()-> @set 'reference_smiles_error': false 'download_highlighted_error': false , silent: true model = @ promiseFunc = (resolve, reject)-> referenceSmarts = model.get('reference_smarts') # Tries to use the 2d sdf without alignment if the alignment failed if model.get('aligned_sdf')? alignedSdf = model.get('aligned_sdf') else alignedSdf = model.get('sdf2DData') if not referenceSmarts? reject('Error, the reference SMARTS is not present!') return if not alignedSdf? reject('Error, the compound '+model.get('molecule_chembl_id')+' ALIGNED CTAB is not present!') return if model.get('substructure_highlight_base64_img')? resolve(model.get('substructure_highlight_base64_img')) else formData = new FormData() formData.append('file', new Blob([alignedSdf], {type: 'chemical/x-mdl-molfile'}), 'aligned.mol') formData.append('smarts', referenceSmarts) formData.append('computeCoords', 0) formData.append('force', 'true') formData.append('sanitize', 0) ajax_deferred = $.post url: Compound.SDF_2D_HIGHLIGHT_URL data: formData enctype: 'multipart/form-data' processData: false contentType: false cache: false converters: 'text xml': String ajax_deferred.done (ajaxData)-> model.set loading_substructure_highlight: false substructure_highlight_base64_img: 'data:image/svg+xml;base64,'+btoa(ajaxData) reference_smiles_error: false reference_smiles_error_jqxhr: undefined , silent: true model.trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_READY resolve(ajaxData) ajax_deferred.fail (jqxhrError)-> reject(jqxhrError) promise = new Promise(promiseFunc) promise.then null, (jqxhrError)-> model.set loading_substructure_highlight: false download_highlighted_error: true reference_smiles_error: true reference_smiles_error_jqxhr: jqxhrError model.trigger glados.Events.Compound.STRUCTURE_HIGHLIGHT_ERROR return promise #--------------------------------------------------------------------------------------------------------------------- # SDF #--------------------------------------------------------------------------------------------------------------------- download2DSDF: ()-> @set('sdf2DError', false, {silent: true}) promiseFunc = (resolve, reject)-> if @get('sdf2DData')? resolve(@get('sdf2DData')) else ajax_deferred = $.get(Compound.SDF_2D_URL + @get('molecule_chembl_id') + '.sdf') compoundModel = @ ajax_deferred.done (ajaxData)-> compoundModel.set('sdf2DData', ajaxData) resolve(ajaxData) ajax_deferred.fail (error)-> compoundModel.set('sdf2DError', true) reject(error) return new Promise(promiseFunc.bind(@)) #--------------------------------------------------------------------------------------------------------------------- # instance urls #--------------------------------------------------------------------------------------------------------------------- getSimilaritySearchURL: (threshold=glados.Settings.DEFAULT_SIMILARITY_THRESHOLD) -> glados.Settings.SIMILARITY_URL_GENERATOR term: @get('id') threshold: threshold #----------------------------------------------------------------------------------------------------------------------- # 3D SDF Constants #----------------------------------------------------------------------------------------------------------------------- Compound.SDF_2D_HIGHLIGHT_URL = glados.Settings.BEAKER_BASE_URL + 'highlightCtabFragmentSvg' Compound.SDF_2D_URL = glados.Settings.WS_BASE_URL + 'molecule/' Compound.SMILES_2_SIMILARITY_MAP_URL = glados.Settings.BEAKER_BASE_URL + 'smiles2SimilarityMapSvg' # Constant definition for ReportCardEntity model functionalities _.extend(Compound, glados.models.base.ReportCardEntity) Compound.color = 'cyan' Compound.reportCardPath = 'compound_report_card/' Compound.getSDFURL = (chemblId) -> glados.Settings.WS_BASE_URL + 'molecule/' + chemblId + '.sdf' Compound.ES_INDEX = 'chembl_molecule' Compound.INDEX_NAME = Compound.ES_INDEX Compound.PROPERTIES_VISUAL_CONFIG = { 'molecule_chembl_id': { link_base: 'report_card_url' image_base_url: 'image_url' hide_label: true }, 'molecule_synonyms': { parse_function: (values) -> _.uniq(v.molecule_synonym for v in values).join(', ') }, '_metadata.related_targets.count': { format_as_number: true link_base: 'targets_url' on_click: CompoundReportCardApp.initMiniHistogramFromFunctionLink function_parameters: ['molecule_chembl_id'] function_constant_parameters: ['targets'] function_key: 'targets' function_link: true execute_on_render: true format_class: 'number-cell-center' }, '_metadata.related_activities.count': { link_base: 'activities_url' on_click: CompoundReportCardApp.initMiniHistogramFromFunctionLink function_parameters: ['molecule_chembl_id'] function_constant_parameters: ['activities'] # to help bind the link to the function, it could be necessary to always use the key of the columns descriptions # or probably not, depending on how this evolves function_key: 'bioactivities' function_link: true execute_on_render: true format_class: 'number-cell-center' }, 'similarity': { 'show': true 'comparator': '_context.similarity' 'sort_disabled': false 'is_sorting': 0 'sort_class': 'fa-sort' 'is_contextual': true } 'sources_list': { parse_function: (values) -> _.unique(v.src_description for v in values) } 'additional_sources_list': { name_to_show_function: (model) -> switch model.isParent() when true then return 'Additional Sources From Alternate Forms:' when false then return 'Additional Sources From Parent:' col_value_function: (model) -> model.getAdditionalSources() show_function: (model) -> model.hasAdditionalSources() } 'chochrane_terms': { comparator: 'pref_name' additional_parsing: encoded_value: (value) -> value.replace(/[ ]/g, '+') } 'clinical_trials_terms': { parse_function: (values) -> _.uniq(v.molecule_synonym for v in values).join(', ') parse_from_model: true additional_parsing: search_term: (model) -> synonyms = if model.isParent() then model.getOwnAndAdditionalSynonyms() else model.getSynonyms() tradenames = if model.isParent() then model.getOwnAndAdditionalTradenames() else model.getTradenames() fullList = _.union(synonyms, tradenames) linkText = _.uniq(v for v in fullList).join(' OR ') maxTextLength = 100 if linkText.length > maxTextLength linkText = "#{linkText.substring(0, (maxTextLength-3))}..." return linkText encoded_search_term: (model) -> synonyms = if model.isParent() then model.getOwnAndAdditionalSynonyms() else model.getSynonyms() tradenames = if model.isParent() then model.getOwnAndAdditionalTradenames() else model.getTradenames() fullList = _.union(synonyms, tradenames) return encodeURIComponent(_.uniq(v for v in fullList).join(' OR ')) } } Compound.COLUMNS = { CHEMBL_ID: aggregatable: true comparator: "molecule_chembl_id" hide_label: true id: "molecule_chembl_id" image_base_url: "image_url" is_sorting: 0 link_base: "report_card_url" name_to_show: "ChEMBL ID" name_to_show_short: "ChEMBL ID" show: true sort_class: "fa-sort" sort_disabled: false PREF_NAME: aggregatable: true comparator: "pref_name" id: "pref_name" is_sorting: 0 name_to_show: "Name" name_to_show_short: "Name" prop_id: "pref_name" show: true sort_class: "fa-sort" sort_disabled: false MAX_PHASE: aggregatable: true comparator: "max_phase" id: "max_phase" integer: true is_sorting: 0 name_to_show: "Max Phase" name_to_show_short: "Max Phase" prop_id: "max_phase" show: true sort_class: "fa-sort" sort_disabled: false year: false FULL_MWT: aggregatable: true comparator: "molecule_properties.full_mwt" id: "molecule_properties.full_mwt" integer: false is_sorting: 0 name_to_show: "Molecular Weight" name_to_show_short: "Full Mwt" prop_id: "molecule_properties.full_mwt" show: true sort_class: "fa-sort" sort_disabled: false year: false ALOGP: aggregatable: true comparator: "molecule_properties.alogp" id: "molecule_properties.alogp" integer: false is_sorting: 0 name_to_show: "AlogP" name_to_show_short: "Alogp" prop_id: "molecule_properties.alogp" show: true sort_class: "fa-sort" sort_disabled: false year: false } Compound.ID_COLUMN = Compound.COLUMNS.CHEMBL_ID Compound.COLUMNS_SETTINGS = { RESULTS_LIST_REPORT_CARD_LONG:[ Compound.COLUMNS.CHEMBL_ID, Compound.COLUMNS.PREF_NAME, Compound.COLUMNS.MAX_PHASE, Compound.COLUMNS.FULL_MWT, Compound.COLUMNS.ALOGP ] RESULTS_LIST_REPORT_CARD_CAROUSEL: [ Compound.COLUMNS.CHEMBL_ID ] } Compound.MINI_REPORT_CARD = LOADING_TEMPLATE: 'Handlebars-Common-MiniRepCardPreloader' TEMPLATE: 'Handlebars-Common-MiniReportCard' Compound.getCompoundsListURL = (filter, isFullState=false, fragmentOnly=false) -> if isFullState filter = btoa(JSON.stringify(filter)) return glados.Settings.ENTITY_BROWSERS_URL_GENERATOR fragment_only: fragmentOnly entity: 'compounds' filter: encodeURIComponent(filter) unless not filter? is_full_state: isFullState
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999105334281921, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/lib/back-to-top.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 { createElement as el, createRef, PureComponent } from 'react' import * as React from 'react' import { button, div, i } from 'react-dom-factories' export class BackToTop extends PureComponent constructor: (props) -> super props @state = lastScrollY: null componentWillUnmount: => document.removeEventListener 'scroll', @onScroll if @observer? @observer.disconnect() @observer = null onClick: (_e) => if @state.lastScrollY? window.scrollTo(window.pageXOffset, @state.lastScrollY) @setState lastScrollY: null else scrollY = if @props.anchor?.current? then $(@props.anchor.current).offset().top else 0 if window.pageYOffset > scrollY @setState lastScrollY: window.pageYOffset window.scrollTo(window.pageXOffset, scrollY) @mountObserver() onScroll: (_e) => @setState lastScrollY: null document.removeEventListener 'scroll', @onScroll if @observer? @observer.disconnect() @observer = null mountObserver: => # Workaround Firefox scrollTo and setTimeout(fn, 0) not being dispatched serially. # Browsers without IntersectionObservers don't have this problem :D if window.IntersectionObserver? # anchor to body if none specified; assumes body's top is 0. target = @props.anchor?.current ? document.body @observer = new IntersectionObserver (entries) => for entry in entries if entry.target == target && entry.boundingClientRect.top == 0 document.addEventListener 'scroll', @onScroll break @observer.observe(target) else Timeout.set 0, () => document.addEventListener 'scroll', @onScroll render: => button className: 'back-to-top' 'data-tooltip-float': 'fixed' onClick: @onClick title: if @state.lastScrollY? then osu.trans('common.buttons.back_to_previous') else osu.trans('common.buttons.back_to_top') i className: if @state.lastScrollY? then 'fas fa-angle-down' else 'fas fa-angle-up' reset: () => @setState lastScrollY: null
64116
# 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 { createElement as el, createRef, PureComponent } from 'react' import * as React from 'react' import { button, div, i } from 'react-dom-factories' export class BackToTop extends PureComponent constructor: (props) -> super props @state = lastScrollY: null componentWillUnmount: => document.removeEventListener 'scroll', @onScroll if @observer? @observer.disconnect() @observer = null onClick: (_e) => if @state.lastScrollY? window.scrollTo(window.pageXOffset, @state.lastScrollY) @setState lastScrollY: null else scrollY = if @props.anchor?.current? then $(@props.anchor.current).offset().top else 0 if window.pageYOffset > scrollY @setState lastScrollY: window.pageYOffset window.scrollTo(window.pageXOffset, scrollY) @mountObserver() onScroll: (_e) => @setState lastScrollY: null document.removeEventListener 'scroll', @onScroll if @observer? @observer.disconnect() @observer = null mountObserver: => # Workaround Firefox scrollTo and setTimeout(fn, 0) not being dispatched serially. # Browsers without IntersectionObservers don't have this problem :D if window.IntersectionObserver? # anchor to body if none specified; assumes body's top is 0. target = @props.anchor?.current ? document.body @observer = new IntersectionObserver (entries) => for entry in entries if entry.target == target && entry.boundingClientRect.top == 0 document.addEventListener 'scroll', @onScroll break @observer.observe(target) else Timeout.set 0, () => document.addEventListener 'scroll', @onScroll render: => button className: 'back-to-top' 'data-tooltip-float': 'fixed' onClick: @onClick title: if @state.lastScrollY? then osu.trans('common.buttons.back_to_previous') else osu.trans('common.buttons.back_to_top') i className: if @state.lastScrollY? then 'fas fa-angle-down' else 'fas fa-angle-up' reset: () => @setState lastScrollY: null
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 { createElement as el, createRef, PureComponent } from 'react' import * as React from 'react' import { button, div, i } from 'react-dom-factories' export class BackToTop extends PureComponent constructor: (props) -> super props @state = lastScrollY: null componentWillUnmount: => document.removeEventListener 'scroll', @onScroll if @observer? @observer.disconnect() @observer = null onClick: (_e) => if @state.lastScrollY? window.scrollTo(window.pageXOffset, @state.lastScrollY) @setState lastScrollY: null else scrollY = if @props.anchor?.current? then $(@props.anchor.current).offset().top else 0 if window.pageYOffset > scrollY @setState lastScrollY: window.pageYOffset window.scrollTo(window.pageXOffset, scrollY) @mountObserver() onScroll: (_e) => @setState lastScrollY: null document.removeEventListener 'scroll', @onScroll if @observer? @observer.disconnect() @observer = null mountObserver: => # Workaround Firefox scrollTo and setTimeout(fn, 0) not being dispatched serially. # Browsers without IntersectionObservers don't have this problem :D if window.IntersectionObserver? # anchor to body if none specified; assumes body's top is 0. target = @props.anchor?.current ? document.body @observer = new IntersectionObserver (entries) => for entry in entries if entry.target == target && entry.boundingClientRect.top == 0 document.addEventListener 'scroll', @onScroll break @observer.observe(target) else Timeout.set 0, () => document.addEventListener 'scroll', @onScroll render: => button className: 'back-to-top' 'data-tooltip-float': 'fixed' onClick: @onClick title: if @state.lastScrollY? then osu.trans('common.buttons.back_to_previous') else osu.trans('common.buttons.back_to_top') i className: if @state.lastScrollY? then 'fas fa-angle-down' else 'fas fa-angle-up' reset: () => @setState lastScrollY: null
[ { "context": "ncremental flip algorithm.\n#\n# _Copyright (c) 2011 Olaf Delgado-Friedrichs_\n\n# ----\n\n# First, we import some necessary data ", "end": 174, "score": 0.9998041987419128, "start": 151, "tag": "NAME", "value": "Olaf Delgado-Friedrichs" } ]
examples/delaunay.coffee
odf/pazy.js
0
# These are the beginnings of a package to compute 2-dimensional Delaunay # triangulations via the incremental flip algorithm. # # _Copyright (c) 2011 Olaf Delgado-Friedrichs_ # ---- # First, we import some necessary data structures (**TODO**: use a better # package system). if typeof(require) != 'undefined' { equal, hashCode } = require 'core_extensions' { bounce } = require 'functional' { seq } = require 'sequence' { IntMap, HashSet, HashMap } = require 'indexed' { Queue } = require 'queue' else { equal, hashCode, bounce, seq, IntMap, HashSet, HashMap, Queue } = this.pazy # ---- # Here's a quick hack for switching traces on and off. trace = (s) -> #console.log s() # ---- # A method to be used in class bodies in order to create a method with a # memoized result. memo = (klass, name, f) -> klass::[name] = -> x = f.call(this); (@[name] = -> x)() # ---- # The class `Point2d` represents points in the x,y-plane and provides just the # bare minimum of operations we need here. class Point2d constructor: (@x, @y) -> isInfinite: -> false plus: (p) -> new Point2d @x + p.x, @y + p.y minus: (p) -> new Point2d @x - p.x, @y - p.y times: (f) -> new Point2d @x * f, @y * f # The method `lift` computes the projection or _lift_ of this point onto the # standard parabola z = x * x + y * y. memo @, 'lift', -> new Point3d @x, @y, @x * @x + @y * @y equals: (p) -> @constructor == p?.constructor and @x == p.x and @y == p.y memo @, 'toString', -> "(#{@x}, #{@y})" memo @, 'hashCode', -> hashCode @toString() # ---- # The class `Point2d` represents points in the x,y-plane and provides just the # bare minimum of operations we need here. class PointAtInfinity constructor: (@x, @y) -> isInfinite: -> true equals: (p) -> @constructor == p?.constructor and @x == p.x and @y == p.y memo @, 'toString', -> "inf(#{@x}, #{@y})" memo @, 'hashCode', -> hashCode @toString() # ---- # The class `Point3d` represents points in 3-dimensional space and provides # just the bare minimum of operations we need here. class Point3d constructor: (@x, @y, @z) -> minus: (p) -> new Point3d @x - p.x, @y - p.y, @z - p.z times: (f) -> new Point3d @x * f, @y * f, @z * f dot: (p) -> @x * p.x + @y * p.y + @z * p.z cross: (p) -> new Point3d @y*p.z - @z*p.y, @z*p.x - @x*p.z, @x*p.y - @y*p.x # ---- # The class `Triangle` represents an oriented triangle in the euclidean plane # with no specified origin. In other words, the sequences `a, b, c`, `b, c, a` # and `c, a,b` describe the same oriented triangle for given `a`, `b` and `c`, # but `a, c, a` does not. class Triangle constructor: (@a, @b, @c) -> memo @, 'vertices', -> if @a.toString() < @b.toString() and @a.toString() < @c.toString() [@a, @b, @c] else if @b.toString() < @c.toString() [@b, @c, @a] else [@c, @a, @b] # The method `liftedNormal` computes the downward-facing normal to the plane # formed by the lifts of this triangle's vertices. memo @, 'liftedNormal', -> n = @b.lift().minus(@a.lift()).cross @c.lift().minus(@a.lift()) if n.z <= 0 then n else n.times -1 # The method `circumCircleCenter` computes the center of the circum-circle # of this triangle. memo @, 'circumCircleCenter', -> n = @liftedNormal() new Point2d(n.x, n.y).times -0.5 / n.z if 1e-6 < Math.abs n.z # The method `circumCircleCenter` computes the center of the circum-circle # of this triangle. memo @, 'circumCircleRadius', -> c = @circumCircleCenter() square = (x) -> x * x Math.sqrt square(c.x - @a.x) + square(c.y - @a.y) # The function `inclusionInCircumCircle` checks whether a point d is inside, # outside or on the circle through this triangle's vertices. A positive # return value means inside, zero means on and a negative value means # outside. inclusionInCircumCircle: (d) -> @liftedNormal().dot d.lift().minus @a.lift() memo @, 'toSeq', -> seq @vertices() memo @, 'toString', -> "T(#{seq.join @, ', '})" memo @, 'hashCode', -> hashCode @toString() equals: (other) -> seq.equals @, other # ---- # The function `triangulation` creates an oriented triangulation in the # euclidean plane. By _oriented_, we mean that the vertices of each triangle # are assigned one out of two possible circular orders. Whenever two triangles # share an edge, we moreover require the orientations of these to 'match' in # such a way that the induced orders on the pair of vertices defining the edge # are exactly opposite. triangulation = do -> # The hidden class `Triangulation` implements our data structure. class Triangulation # The constructor takes a map specifying the associated third triangle # vertex for any oriented edge that is part of an oriented triangle. constructor: (@third__ = new HashMap()) -> # The method `toSeq` returns the triangles contained in the triangulation # as a lazy sequence. memo @, 'toSeq', -> seq.map(@third__, ([e, [t, c]]) -> t if equal c, t.a)?.select (x) -> x? # The method `third` finds the unique third vertex forming a triangle with # the two given ones in the given orientation, if any. third: (a, b) -> @third__.get([a, b])?[1] # The method `triangle` finds the unique oriented triangle with the two # given pair of vertices in the order, if any. triangle: (a, b) -> @third__.get([a, b])?[0] # The method `plus` returns a triangulation with the given triangle added # unless it is already present or creates an orientation mismatch. In the # first case, the original triangulation is returned without changes; in # the second, an exception is raised. plus: (a, b, c) -> if equal @third(a, b), c this else if seq.find([[a, b], [b, c], [c, a]], ([p, q]) => @third p, q) throw new Error "Orientation mismatch." else t = new Triangle a, b, c added = [[[a, b], [t, c]], [[b, c], [t, a]], [[c, a], [t, b]]] new Triangulation @third__.plusAll added # The method `minus` returns a triangulation with the given triangle # removed, if present. minus: (a, b, c) -> if not equal @third(a, b), c this else new Triangulation @third__.minusAll [[a, b], [b, c], [c, a]] # Here we define our access point. The function `triangulation` takes a list # of triangles, each given as an array of three abstract vertices. (args...) -> seq.reduce args, new Triangulation(), (t, x) -> t.plus x... # ---- # The function `delaunayTriangulation` creates the Delaunay triangulation of a # set of sites in the x,y-plane using the so-called incremental flip method. delaunayTriangulation = do -> # Again, we use a hidden class to encapsulate the implementation details. class Triangulation # The triangle `outer` is a virtual, 'infinitely large' triangle which is # added internally to avoid special boundary considerations within the # algorithm. outer = new Triangle new PointAtInfinity( 1, 0), new PointAtInfinity(-1, 1), new PointAtInfinity(-1, -1) # The constructor is called with implementation specific data for the new # instance, specifically: # # 1. The underlying abstract triangulation. # 2. The set of all sites present. # 3. The child relation of the history DAG which is used to locate which # triangle a new site is in. constructor: (args...) -> @triangulation__ = args[0] || triangulation(outer.vertices()) @sites__ = args[1] || new HashSet() @children__ = args[2] || new HashMap() # The method `toSeq` returns the proper (non-virtual) triangles contained # in this triangulation as a lazy sequence. It does so by removing any # triangles from the underlying triangulation object which contain a # virtual vertex. memo @, 'toSeq', -> seq.select @triangulation__, (t) -> seq.forall t, (p) -> not p.isInfinite() # The method `third` finds the unique third vertex forming a triangle with # the two given ones in the given orientation, if any. third: (a, b) -> @triangulation__.third a, b # The method `triangle` finds the unique oriented triangle with the two # given pair of vertices in the order, if any. triangle: (a, b) -> @triangulation__.triangle a, b # The method `sideOf` determines which side of the oriented line given by # the sites with indices `a` and `b` the point `p` (a `Point2d` instance) # lies on. A positive value means it is to the right, a negative value to # the left, and a zero value on the line. sideOf: (a, b, p) -> if a.isInfinite() and b.isInfinite() -1 else if a.isInfinite() - @sideOf b, a, p else ab = if b.isInfinite() then new Point2d b.x, b.y else b.minus a ap = p.minus a ap.x * ab.y - ap.y * ab.x # The method `isInTriangle` returns true if the given `Point2d` instance # `p` is contained in the triangle `t` given as a sequence of site # indices. isInTriangle: (t, p) -> [a, b, c] = t.vertices() seq([[a, b], [b, c], [c, a]]).forall ([r, s]) => @sideOf(r, s, p) <= 0 # The method `containingTriangle` returns the triangle the given point is # in. containingTriangle: (p) -> step = (t) => candidates = @children__.get t if seq.empty candidates t else => step candidates.find (s) => @isInTriangle s, p bounce step outer # The method `mustFlip` determines whether the triangles adjacent to the # given edge from `a` to `b` violates the Delaunay condition, in which case # it must be flipped. # # Some special considerations are necessary in the case that virtual # vertices are involved. mustFlip: (a, b) -> c = @third a, b d = @third b, a if (a.isInfinite() and b.isInfinite()) or not c? or not d? false else if a.isInfinite() @sideOf(d, c, b) > 0 else if b.isInfinite() @sideOf(c, d, a) > 0 else if c.isInfinite() or d.isInfinite() false else @triangle(a, b).inclusionInCircumCircle(d) > 0 # The private function `subdivide` takes a triangulation `T`, a triangle # `t` and a site `p` inside that triangle and creates a new triangulation # in which `t` is divided into three new triangles with `p` as a common # vertex. subdivide = (T, t, p) -> trace -> "subdivide [#{T.triangulation__.toSeq().join ', '}], #{t}, #{p}" [a, b, c] = t.vertices() S = T.triangulation__.minus(a,b,c).plus(a,b,p).plus(b,c,p).plus(c,a,p) new T.constructor( S, T.sites__.plus(p), T.children__.plus([T.triangle(a,b), seq [S.triangle(a,b), S.triangle(b,c), S.triangle(c,a)]]) ) # The private function `flip` creates a new triangulation from `T` with the # edge defined by the indices `a` and `b` _flipped_. In other words, if the # edge `ab` lies in triangles `abc` and `bad`, then after the flip those # are replaced by new triangle `bcd` and `adc`. flip = (T, a, b) -> trace -> "flip [#{T.triangulation__.toSeq().join ', '}], #{a}, #{b}" c = T.third a, b d = T.third b, a S = T.triangulation__.minus(a,b,c).minus(b,a,d).plus(b,c,d).plus(a,d,c) children = seq [S.triangle(c, d), S.triangle(d, c)] new T.constructor( S, T.sites__, T.children__.plus([T.triangle(a,b), children], [T.triangle(b,a), children]) ) # The private function `doFlips` takes a triangulation and a stack of # edges. If the topmost edge on the stack needs to be flipped, the function # calls itself recursively with the resulting triangulation and a stack in # which that edge is replaced by the two remaining edges of the opposite # triangle. doFlips = (T, stack) -> if seq.empty stack T else [a, b] = stack.first() if T.mustFlip a, b c = T.third a, b -> doFlips flip(T, a, b), seq([[a,c], [c,b]]).concat stack.rest() else -> doFlips T, stack.rest() # The method `plus` creates a new Delaunay triangulation with the given # (x, y) location added as a site. plus: (x, y) -> p = new Point2d x, y if @sites__.contains p this else t = @containingTriangle p [a, b, c] = t.vertices() seq([[b,a], [c,b], [a,c]]).reduce subdivide(this, t, p), (T, [u, v]) -> if T.sideOf(u, v, p) == 0 w = T.third u, v if w? bounce doFlips flip(T, u, v), seq [[u, w], [w, v]] else T else bounce doFlips T, seq [[u, v]] # Here we define our access point. The function `delaunayTriangulation` takes # a list of sites, each given as a `Point2d` instance. (args...) -> seq.reduce args, new Triangulation(), (t, x) -> t.plus x... # ---- # Exporting. exports = module?.exports or this.pazy ?= {} exports.Triangle = Triangle exports.Point2d = Point2d exports.delaunayTriangulation = delaunayTriangulation # ---- # Some testing. test = (n = 100, m = 10) -> seq.range(1, n).each (i) -> console.log "Run #{i}" rnd = -> Math.floor(Math.random() * 100) t = seq.range(1, m).reduce delaunayTriangulation(), (s, j) -> p = [rnd(), rnd()] try s.plus p... catch ex console.log seq.join s, ', ' console.log p console.log ex.stacktrace throw "Oops!" if module? and not module.parent args = seq.map(process.argv[2..], parseInt)?.into [] test args...
188938
# These are the beginnings of a package to compute 2-dimensional Delaunay # triangulations via the incremental flip algorithm. # # _Copyright (c) 2011 <NAME>_ # ---- # First, we import some necessary data structures (**TODO**: use a better # package system). if typeof(require) != 'undefined' { equal, hashCode } = require 'core_extensions' { bounce } = require 'functional' { seq } = require 'sequence' { IntMap, HashSet, HashMap } = require 'indexed' { Queue } = require 'queue' else { equal, hashCode, bounce, seq, IntMap, HashSet, HashMap, Queue } = this.pazy # ---- # Here's a quick hack for switching traces on and off. trace = (s) -> #console.log s() # ---- # A method to be used in class bodies in order to create a method with a # memoized result. memo = (klass, name, f) -> klass::[name] = -> x = f.call(this); (@[name] = -> x)() # ---- # The class `Point2d` represents points in the x,y-plane and provides just the # bare minimum of operations we need here. class Point2d constructor: (@x, @y) -> isInfinite: -> false plus: (p) -> new Point2d @x + p.x, @y + p.y minus: (p) -> new Point2d @x - p.x, @y - p.y times: (f) -> new Point2d @x * f, @y * f # The method `lift` computes the projection or _lift_ of this point onto the # standard parabola z = x * x + y * y. memo @, 'lift', -> new Point3d @x, @y, @x * @x + @y * @y equals: (p) -> @constructor == p?.constructor and @x == p.x and @y == p.y memo @, 'toString', -> "(#{@x}, #{@y})" memo @, 'hashCode', -> hashCode @toString() # ---- # The class `Point2d` represents points in the x,y-plane and provides just the # bare minimum of operations we need here. class PointAtInfinity constructor: (@x, @y) -> isInfinite: -> true equals: (p) -> @constructor == p?.constructor and @x == p.x and @y == p.y memo @, 'toString', -> "inf(#{@x}, #{@y})" memo @, 'hashCode', -> hashCode @toString() # ---- # The class `Point3d` represents points in 3-dimensional space and provides # just the bare minimum of operations we need here. class Point3d constructor: (@x, @y, @z) -> minus: (p) -> new Point3d @x - p.x, @y - p.y, @z - p.z times: (f) -> new Point3d @x * f, @y * f, @z * f dot: (p) -> @x * p.x + @y * p.y + @z * p.z cross: (p) -> new Point3d @y*p.z - @z*p.y, @z*p.x - @x*p.z, @x*p.y - @y*p.x # ---- # The class `Triangle` represents an oriented triangle in the euclidean plane # with no specified origin. In other words, the sequences `a, b, c`, `b, c, a` # and `c, a,b` describe the same oriented triangle for given `a`, `b` and `c`, # but `a, c, a` does not. class Triangle constructor: (@a, @b, @c) -> memo @, 'vertices', -> if @a.toString() < @b.toString() and @a.toString() < @c.toString() [@a, @b, @c] else if @b.toString() < @c.toString() [@b, @c, @a] else [@c, @a, @b] # The method `liftedNormal` computes the downward-facing normal to the plane # formed by the lifts of this triangle's vertices. memo @, 'liftedNormal', -> n = @b.lift().minus(@a.lift()).cross @c.lift().minus(@a.lift()) if n.z <= 0 then n else n.times -1 # The method `circumCircleCenter` computes the center of the circum-circle # of this triangle. memo @, 'circumCircleCenter', -> n = @liftedNormal() new Point2d(n.x, n.y).times -0.5 / n.z if 1e-6 < Math.abs n.z # The method `circumCircleCenter` computes the center of the circum-circle # of this triangle. memo @, 'circumCircleRadius', -> c = @circumCircleCenter() square = (x) -> x * x Math.sqrt square(c.x - @a.x) + square(c.y - @a.y) # The function `inclusionInCircumCircle` checks whether a point d is inside, # outside or on the circle through this triangle's vertices. A positive # return value means inside, zero means on and a negative value means # outside. inclusionInCircumCircle: (d) -> @liftedNormal().dot d.lift().minus @a.lift() memo @, 'toSeq', -> seq @vertices() memo @, 'toString', -> "T(#{seq.join @, ', '})" memo @, 'hashCode', -> hashCode @toString() equals: (other) -> seq.equals @, other # ---- # The function `triangulation` creates an oriented triangulation in the # euclidean plane. By _oriented_, we mean that the vertices of each triangle # are assigned one out of two possible circular orders. Whenever two triangles # share an edge, we moreover require the orientations of these to 'match' in # such a way that the induced orders on the pair of vertices defining the edge # are exactly opposite. triangulation = do -> # The hidden class `Triangulation` implements our data structure. class Triangulation # The constructor takes a map specifying the associated third triangle # vertex for any oriented edge that is part of an oriented triangle. constructor: (@third__ = new HashMap()) -> # The method `toSeq` returns the triangles contained in the triangulation # as a lazy sequence. memo @, 'toSeq', -> seq.map(@third__, ([e, [t, c]]) -> t if equal c, t.a)?.select (x) -> x? # The method `third` finds the unique third vertex forming a triangle with # the two given ones in the given orientation, if any. third: (a, b) -> @third__.get([a, b])?[1] # The method `triangle` finds the unique oriented triangle with the two # given pair of vertices in the order, if any. triangle: (a, b) -> @third__.get([a, b])?[0] # The method `plus` returns a triangulation with the given triangle added # unless it is already present or creates an orientation mismatch. In the # first case, the original triangulation is returned without changes; in # the second, an exception is raised. plus: (a, b, c) -> if equal @third(a, b), c this else if seq.find([[a, b], [b, c], [c, a]], ([p, q]) => @third p, q) throw new Error "Orientation mismatch." else t = new Triangle a, b, c added = [[[a, b], [t, c]], [[b, c], [t, a]], [[c, a], [t, b]]] new Triangulation @third__.plusAll added # The method `minus` returns a triangulation with the given triangle # removed, if present. minus: (a, b, c) -> if not equal @third(a, b), c this else new Triangulation @third__.minusAll [[a, b], [b, c], [c, a]] # Here we define our access point. The function `triangulation` takes a list # of triangles, each given as an array of three abstract vertices. (args...) -> seq.reduce args, new Triangulation(), (t, x) -> t.plus x... # ---- # The function `delaunayTriangulation` creates the Delaunay triangulation of a # set of sites in the x,y-plane using the so-called incremental flip method. delaunayTriangulation = do -> # Again, we use a hidden class to encapsulate the implementation details. class Triangulation # The triangle `outer` is a virtual, 'infinitely large' triangle which is # added internally to avoid special boundary considerations within the # algorithm. outer = new Triangle new PointAtInfinity( 1, 0), new PointAtInfinity(-1, 1), new PointAtInfinity(-1, -1) # The constructor is called with implementation specific data for the new # instance, specifically: # # 1. The underlying abstract triangulation. # 2. The set of all sites present. # 3. The child relation of the history DAG which is used to locate which # triangle a new site is in. constructor: (args...) -> @triangulation__ = args[0] || triangulation(outer.vertices()) @sites__ = args[1] || new HashSet() @children__ = args[2] || new HashMap() # The method `toSeq` returns the proper (non-virtual) triangles contained # in this triangulation as a lazy sequence. It does so by removing any # triangles from the underlying triangulation object which contain a # virtual vertex. memo @, 'toSeq', -> seq.select @triangulation__, (t) -> seq.forall t, (p) -> not p.isInfinite() # The method `third` finds the unique third vertex forming a triangle with # the two given ones in the given orientation, if any. third: (a, b) -> @triangulation__.third a, b # The method `triangle` finds the unique oriented triangle with the two # given pair of vertices in the order, if any. triangle: (a, b) -> @triangulation__.triangle a, b # The method `sideOf` determines which side of the oriented line given by # the sites with indices `a` and `b` the point `p` (a `Point2d` instance) # lies on. A positive value means it is to the right, a negative value to # the left, and a zero value on the line. sideOf: (a, b, p) -> if a.isInfinite() and b.isInfinite() -1 else if a.isInfinite() - @sideOf b, a, p else ab = if b.isInfinite() then new Point2d b.x, b.y else b.minus a ap = p.minus a ap.x * ab.y - ap.y * ab.x # The method `isInTriangle` returns true if the given `Point2d` instance # `p` is contained in the triangle `t` given as a sequence of site # indices. isInTriangle: (t, p) -> [a, b, c] = t.vertices() seq([[a, b], [b, c], [c, a]]).forall ([r, s]) => @sideOf(r, s, p) <= 0 # The method `containingTriangle` returns the triangle the given point is # in. containingTriangle: (p) -> step = (t) => candidates = @children__.get t if seq.empty candidates t else => step candidates.find (s) => @isInTriangle s, p bounce step outer # The method `mustFlip` determines whether the triangles adjacent to the # given edge from `a` to `b` violates the Delaunay condition, in which case # it must be flipped. # # Some special considerations are necessary in the case that virtual # vertices are involved. mustFlip: (a, b) -> c = @third a, b d = @third b, a if (a.isInfinite() and b.isInfinite()) or not c? or not d? false else if a.isInfinite() @sideOf(d, c, b) > 0 else if b.isInfinite() @sideOf(c, d, a) > 0 else if c.isInfinite() or d.isInfinite() false else @triangle(a, b).inclusionInCircumCircle(d) > 0 # The private function `subdivide` takes a triangulation `T`, a triangle # `t` and a site `p` inside that triangle and creates a new triangulation # in which `t` is divided into three new triangles with `p` as a common # vertex. subdivide = (T, t, p) -> trace -> "subdivide [#{T.triangulation__.toSeq().join ', '}], #{t}, #{p}" [a, b, c] = t.vertices() S = T.triangulation__.minus(a,b,c).plus(a,b,p).plus(b,c,p).plus(c,a,p) new T.constructor( S, T.sites__.plus(p), T.children__.plus([T.triangle(a,b), seq [S.triangle(a,b), S.triangle(b,c), S.triangle(c,a)]]) ) # The private function `flip` creates a new triangulation from `T` with the # edge defined by the indices `a` and `b` _flipped_. In other words, if the # edge `ab` lies in triangles `abc` and `bad`, then after the flip those # are replaced by new triangle `bcd` and `adc`. flip = (T, a, b) -> trace -> "flip [#{T.triangulation__.toSeq().join ', '}], #{a}, #{b}" c = T.third a, b d = T.third b, a S = T.triangulation__.minus(a,b,c).minus(b,a,d).plus(b,c,d).plus(a,d,c) children = seq [S.triangle(c, d), S.triangle(d, c)] new T.constructor( S, T.sites__, T.children__.plus([T.triangle(a,b), children], [T.triangle(b,a), children]) ) # The private function `doFlips` takes a triangulation and a stack of # edges. If the topmost edge on the stack needs to be flipped, the function # calls itself recursively with the resulting triangulation and a stack in # which that edge is replaced by the two remaining edges of the opposite # triangle. doFlips = (T, stack) -> if seq.empty stack T else [a, b] = stack.first() if T.mustFlip a, b c = T.third a, b -> doFlips flip(T, a, b), seq([[a,c], [c,b]]).concat stack.rest() else -> doFlips T, stack.rest() # The method `plus` creates a new Delaunay triangulation with the given # (x, y) location added as a site. plus: (x, y) -> p = new Point2d x, y if @sites__.contains p this else t = @containingTriangle p [a, b, c] = t.vertices() seq([[b,a], [c,b], [a,c]]).reduce subdivide(this, t, p), (T, [u, v]) -> if T.sideOf(u, v, p) == 0 w = T.third u, v if w? bounce doFlips flip(T, u, v), seq [[u, w], [w, v]] else T else bounce doFlips T, seq [[u, v]] # Here we define our access point. The function `delaunayTriangulation` takes # a list of sites, each given as a `Point2d` instance. (args...) -> seq.reduce args, new Triangulation(), (t, x) -> t.plus x... # ---- # Exporting. exports = module?.exports or this.pazy ?= {} exports.Triangle = Triangle exports.Point2d = Point2d exports.delaunayTriangulation = delaunayTriangulation # ---- # Some testing. test = (n = 100, m = 10) -> seq.range(1, n).each (i) -> console.log "Run #{i}" rnd = -> Math.floor(Math.random() * 100) t = seq.range(1, m).reduce delaunayTriangulation(), (s, j) -> p = [rnd(), rnd()] try s.plus p... catch ex console.log seq.join s, ', ' console.log p console.log ex.stacktrace throw "Oops!" if module? and not module.parent args = seq.map(process.argv[2..], parseInt)?.into [] test args...
true
# These are the beginnings of a package to compute 2-dimensional Delaunay # triangulations via the incremental flip algorithm. # # _Copyright (c) 2011 PI:NAME:<NAME>END_PI_ # ---- # First, we import some necessary data structures (**TODO**: use a better # package system). if typeof(require) != 'undefined' { equal, hashCode } = require 'core_extensions' { bounce } = require 'functional' { seq } = require 'sequence' { IntMap, HashSet, HashMap } = require 'indexed' { Queue } = require 'queue' else { equal, hashCode, bounce, seq, IntMap, HashSet, HashMap, Queue } = this.pazy # ---- # Here's a quick hack for switching traces on and off. trace = (s) -> #console.log s() # ---- # A method to be used in class bodies in order to create a method with a # memoized result. memo = (klass, name, f) -> klass::[name] = -> x = f.call(this); (@[name] = -> x)() # ---- # The class `Point2d` represents points in the x,y-plane and provides just the # bare minimum of operations we need here. class Point2d constructor: (@x, @y) -> isInfinite: -> false plus: (p) -> new Point2d @x + p.x, @y + p.y minus: (p) -> new Point2d @x - p.x, @y - p.y times: (f) -> new Point2d @x * f, @y * f # The method `lift` computes the projection or _lift_ of this point onto the # standard parabola z = x * x + y * y. memo @, 'lift', -> new Point3d @x, @y, @x * @x + @y * @y equals: (p) -> @constructor == p?.constructor and @x == p.x and @y == p.y memo @, 'toString', -> "(#{@x}, #{@y})" memo @, 'hashCode', -> hashCode @toString() # ---- # The class `Point2d` represents points in the x,y-plane and provides just the # bare minimum of operations we need here. class PointAtInfinity constructor: (@x, @y) -> isInfinite: -> true equals: (p) -> @constructor == p?.constructor and @x == p.x and @y == p.y memo @, 'toString', -> "inf(#{@x}, #{@y})" memo @, 'hashCode', -> hashCode @toString() # ---- # The class `Point3d` represents points in 3-dimensional space and provides # just the bare minimum of operations we need here. class Point3d constructor: (@x, @y, @z) -> minus: (p) -> new Point3d @x - p.x, @y - p.y, @z - p.z times: (f) -> new Point3d @x * f, @y * f, @z * f dot: (p) -> @x * p.x + @y * p.y + @z * p.z cross: (p) -> new Point3d @y*p.z - @z*p.y, @z*p.x - @x*p.z, @x*p.y - @y*p.x # ---- # The class `Triangle` represents an oriented triangle in the euclidean plane # with no specified origin. In other words, the sequences `a, b, c`, `b, c, a` # and `c, a,b` describe the same oriented triangle for given `a`, `b` and `c`, # but `a, c, a` does not. class Triangle constructor: (@a, @b, @c) -> memo @, 'vertices', -> if @a.toString() < @b.toString() and @a.toString() < @c.toString() [@a, @b, @c] else if @b.toString() < @c.toString() [@b, @c, @a] else [@c, @a, @b] # The method `liftedNormal` computes the downward-facing normal to the plane # formed by the lifts of this triangle's vertices. memo @, 'liftedNormal', -> n = @b.lift().minus(@a.lift()).cross @c.lift().minus(@a.lift()) if n.z <= 0 then n else n.times -1 # The method `circumCircleCenter` computes the center of the circum-circle # of this triangle. memo @, 'circumCircleCenter', -> n = @liftedNormal() new Point2d(n.x, n.y).times -0.5 / n.z if 1e-6 < Math.abs n.z # The method `circumCircleCenter` computes the center of the circum-circle # of this triangle. memo @, 'circumCircleRadius', -> c = @circumCircleCenter() square = (x) -> x * x Math.sqrt square(c.x - @a.x) + square(c.y - @a.y) # The function `inclusionInCircumCircle` checks whether a point d is inside, # outside or on the circle through this triangle's vertices. A positive # return value means inside, zero means on and a negative value means # outside. inclusionInCircumCircle: (d) -> @liftedNormal().dot d.lift().minus @a.lift() memo @, 'toSeq', -> seq @vertices() memo @, 'toString', -> "T(#{seq.join @, ', '})" memo @, 'hashCode', -> hashCode @toString() equals: (other) -> seq.equals @, other # ---- # The function `triangulation` creates an oriented triangulation in the # euclidean plane. By _oriented_, we mean that the vertices of each triangle # are assigned one out of two possible circular orders. Whenever two triangles # share an edge, we moreover require the orientations of these to 'match' in # such a way that the induced orders on the pair of vertices defining the edge # are exactly opposite. triangulation = do -> # The hidden class `Triangulation` implements our data structure. class Triangulation # The constructor takes a map specifying the associated third triangle # vertex for any oriented edge that is part of an oriented triangle. constructor: (@third__ = new HashMap()) -> # The method `toSeq` returns the triangles contained in the triangulation # as a lazy sequence. memo @, 'toSeq', -> seq.map(@third__, ([e, [t, c]]) -> t if equal c, t.a)?.select (x) -> x? # The method `third` finds the unique third vertex forming a triangle with # the two given ones in the given orientation, if any. third: (a, b) -> @third__.get([a, b])?[1] # The method `triangle` finds the unique oriented triangle with the two # given pair of vertices in the order, if any. triangle: (a, b) -> @third__.get([a, b])?[0] # The method `plus` returns a triangulation with the given triangle added # unless it is already present or creates an orientation mismatch. In the # first case, the original triangulation is returned without changes; in # the second, an exception is raised. plus: (a, b, c) -> if equal @third(a, b), c this else if seq.find([[a, b], [b, c], [c, a]], ([p, q]) => @third p, q) throw new Error "Orientation mismatch." else t = new Triangle a, b, c added = [[[a, b], [t, c]], [[b, c], [t, a]], [[c, a], [t, b]]] new Triangulation @third__.plusAll added # The method `minus` returns a triangulation with the given triangle # removed, if present. minus: (a, b, c) -> if not equal @third(a, b), c this else new Triangulation @third__.minusAll [[a, b], [b, c], [c, a]] # Here we define our access point. The function `triangulation` takes a list # of triangles, each given as an array of three abstract vertices. (args...) -> seq.reduce args, new Triangulation(), (t, x) -> t.plus x... # ---- # The function `delaunayTriangulation` creates the Delaunay triangulation of a # set of sites in the x,y-plane using the so-called incremental flip method. delaunayTriangulation = do -> # Again, we use a hidden class to encapsulate the implementation details. class Triangulation # The triangle `outer` is a virtual, 'infinitely large' triangle which is # added internally to avoid special boundary considerations within the # algorithm. outer = new Triangle new PointAtInfinity( 1, 0), new PointAtInfinity(-1, 1), new PointAtInfinity(-1, -1) # The constructor is called with implementation specific data for the new # instance, specifically: # # 1. The underlying abstract triangulation. # 2. The set of all sites present. # 3. The child relation of the history DAG which is used to locate which # triangle a new site is in. constructor: (args...) -> @triangulation__ = args[0] || triangulation(outer.vertices()) @sites__ = args[1] || new HashSet() @children__ = args[2] || new HashMap() # The method `toSeq` returns the proper (non-virtual) triangles contained # in this triangulation as a lazy sequence. It does so by removing any # triangles from the underlying triangulation object which contain a # virtual vertex. memo @, 'toSeq', -> seq.select @triangulation__, (t) -> seq.forall t, (p) -> not p.isInfinite() # The method `third` finds the unique third vertex forming a triangle with # the two given ones in the given orientation, if any. third: (a, b) -> @triangulation__.third a, b # The method `triangle` finds the unique oriented triangle with the two # given pair of vertices in the order, if any. triangle: (a, b) -> @triangulation__.triangle a, b # The method `sideOf` determines which side of the oriented line given by # the sites with indices `a` and `b` the point `p` (a `Point2d` instance) # lies on. A positive value means it is to the right, a negative value to # the left, and a zero value on the line. sideOf: (a, b, p) -> if a.isInfinite() and b.isInfinite() -1 else if a.isInfinite() - @sideOf b, a, p else ab = if b.isInfinite() then new Point2d b.x, b.y else b.minus a ap = p.minus a ap.x * ab.y - ap.y * ab.x # The method `isInTriangle` returns true if the given `Point2d` instance # `p` is contained in the triangle `t` given as a sequence of site # indices. isInTriangle: (t, p) -> [a, b, c] = t.vertices() seq([[a, b], [b, c], [c, a]]).forall ([r, s]) => @sideOf(r, s, p) <= 0 # The method `containingTriangle` returns the triangle the given point is # in. containingTriangle: (p) -> step = (t) => candidates = @children__.get t if seq.empty candidates t else => step candidates.find (s) => @isInTriangle s, p bounce step outer # The method `mustFlip` determines whether the triangles adjacent to the # given edge from `a` to `b` violates the Delaunay condition, in which case # it must be flipped. # # Some special considerations are necessary in the case that virtual # vertices are involved. mustFlip: (a, b) -> c = @third a, b d = @third b, a if (a.isInfinite() and b.isInfinite()) or not c? or not d? false else if a.isInfinite() @sideOf(d, c, b) > 0 else if b.isInfinite() @sideOf(c, d, a) > 0 else if c.isInfinite() or d.isInfinite() false else @triangle(a, b).inclusionInCircumCircle(d) > 0 # The private function `subdivide` takes a triangulation `T`, a triangle # `t` and a site `p` inside that triangle and creates a new triangulation # in which `t` is divided into three new triangles with `p` as a common # vertex. subdivide = (T, t, p) -> trace -> "subdivide [#{T.triangulation__.toSeq().join ', '}], #{t}, #{p}" [a, b, c] = t.vertices() S = T.triangulation__.minus(a,b,c).plus(a,b,p).plus(b,c,p).plus(c,a,p) new T.constructor( S, T.sites__.plus(p), T.children__.plus([T.triangle(a,b), seq [S.triangle(a,b), S.triangle(b,c), S.triangle(c,a)]]) ) # The private function `flip` creates a new triangulation from `T` with the # edge defined by the indices `a` and `b` _flipped_. In other words, if the # edge `ab` lies in triangles `abc` and `bad`, then after the flip those # are replaced by new triangle `bcd` and `adc`. flip = (T, a, b) -> trace -> "flip [#{T.triangulation__.toSeq().join ', '}], #{a}, #{b}" c = T.third a, b d = T.third b, a S = T.triangulation__.minus(a,b,c).minus(b,a,d).plus(b,c,d).plus(a,d,c) children = seq [S.triangle(c, d), S.triangle(d, c)] new T.constructor( S, T.sites__, T.children__.plus([T.triangle(a,b), children], [T.triangle(b,a), children]) ) # The private function `doFlips` takes a triangulation and a stack of # edges. If the topmost edge on the stack needs to be flipped, the function # calls itself recursively with the resulting triangulation and a stack in # which that edge is replaced by the two remaining edges of the opposite # triangle. doFlips = (T, stack) -> if seq.empty stack T else [a, b] = stack.first() if T.mustFlip a, b c = T.third a, b -> doFlips flip(T, a, b), seq([[a,c], [c,b]]).concat stack.rest() else -> doFlips T, stack.rest() # The method `plus` creates a new Delaunay triangulation with the given # (x, y) location added as a site. plus: (x, y) -> p = new Point2d x, y if @sites__.contains p this else t = @containingTriangle p [a, b, c] = t.vertices() seq([[b,a], [c,b], [a,c]]).reduce subdivide(this, t, p), (T, [u, v]) -> if T.sideOf(u, v, p) == 0 w = T.third u, v if w? bounce doFlips flip(T, u, v), seq [[u, w], [w, v]] else T else bounce doFlips T, seq [[u, v]] # Here we define our access point. The function `delaunayTriangulation` takes # a list of sites, each given as a `Point2d` instance. (args...) -> seq.reduce args, new Triangulation(), (t, x) -> t.plus x... # ---- # Exporting. exports = module?.exports or this.pazy ?= {} exports.Triangle = Triangle exports.Point2d = Point2d exports.delaunayTriangulation = delaunayTriangulation # ---- # Some testing. test = (n = 100, m = 10) -> seq.range(1, n).each (i) -> console.log "Run #{i}" rnd = -> Math.floor(Math.random() * 100) t = seq.range(1, m).reduce delaunayTriangulation(), (s, j) -> p = [rnd(), rnd()] try s.plus p... catch ex console.log seq.join s, ', ' console.log p console.log ex.stacktrace throw "Oops!" if module? and not module.parent args = seq.map(process.argv[2..], parseInt)?.into [] test args...
[ { "context": "ssword'\n current: 'Current password'\n new: 'New password'\n confirm: 'Confirm new password'\n changeBu", "end": 400, "score": 0.6829510927200317, "start": 388, "tag": "PASSWORD", "value": "New password" } ]
app/pages/settings/account.cjsx
Crentist/Panoptes-frontend-spanish
0
React = require 'react' counterpart = require 'counterpart' Translate = require 'react-translate-component' AutoSave = require '../../components/auto-save' handleInputChange = require '../../lib/handle-input-change' auth = require 'panoptes-client/lib/auth' counterpart.registerTranslations 'en', pass: changeLabel: 'Change your password' current: 'Current password' new: 'New password' confirm: 'Confirm new password' changeButton: 'Change' tooShort: 'That\'s too short' dontMatch: 'These don\'t match' name: display: label: 'Display name' note: 'How your name will appear to other users in Talk and on your Profile Page' credited: label: 'Credited name' note: 'Public; we’ll use this to give acknowledgement in papers, on posters, etc.' counterpart.registerTranslations 'es', pass: changeLabel: 'Cambiar contraseña' current: 'Contraseña actual' new: 'Nueva contraseña' confirm: 'Confirmar contraseña nueva' changeButton: 'Cambiar' tooShort: 'Es muy corta' dontMatch: 'No coinciden' name: display: label: 'Nombre a mostrar' note: 'El nombre que aparecerá en los foros y en tu perfil' credited: label: 'Nombre real a acreditar' note: 'Público; se utilizará para darte crédito en papers, posters, etc' MIN_PASSWORD_LENGTH = 8 ChangePasswordForm = React.createClass displayName: 'ChangePasswordForm' getDefaultProps: -> user: {} getInitialState: -> old: '' new: '' confirmation: '' inProgress: false success: false error: null render: -> <form ref="form" method="POST" onSubmit={@handleSubmit}> <p> <strong><Translate content="pass.changeLabel" /></strong> </p> <table className="standard-table"> <tbody> <tr> <td><Translate content="pass.current" /></td> <td><input type="password" className="standard-input" size="20" onChange={(e) => @setState old: e.target.value} /></td> </tr> <tr> <td><Translate content="pass.new" /></td> <td> <input type="password" className="standard-input" size="20" onChange={(e) => @setState new: e.target.value} /> {if @state.new.length isnt 0 and @tooShort() <small className="form-help error"><Translate content="pass.tooShort" /></small>} </td> </tr> <tr> <td><Translate content="pass.confirm" /></td> <td> <input type="password" className="standard-input" size="20" onChange={(e) => @setState confirmation: e.target.value} /> {if @state.confirmation.length >= @state.new.length - 1 and @doesntMatch() <small className="form-help error"><Translate content="pass.dontMatch" /></small>} </td> </tr> </tbody> </table> <p> <button type="submit" className="standard-button" disabled={not @state.old or not @state.new or @tooShort() or @doesntMatch() or @state.inProgress}><Translate content="pass.changeButton" /></button>{' '} {if @state.inProgress <i className="fa fa-spinner fa-spin form-help"></i> else if @state.success <i className="fa fa-check-circle form-help success"></i> else if @state.error <small className="form-help error">{@state.error.toString()}</small>} </p> </form> tooShort: -> @state.new.length < MIN_PASSWORD_LENGTH doesntMatch: -> @state.new isnt @state.confirmation handleSubmit: (e) -> e.preventDefault() current = @state.old replacement = @state.new @setState inProgress: true success: false error: null auth.changePassword {current, replacement} .then => @setState success: true @refs.form.reset() .catch (error) => @setState {error} .then => @setState inProgress: false module.exports = React.createClass displayName: "AccountInformationPage" render: -> <div className="account-information-tab"> <div className="columns-container"> <div className="content-container column"> <p> <AutoSave resource={@props.user}> <span className="form-label"><Translate content="name.display.label" /></span> <br /> <input type="text" className="standard-input full" name="display_name" value={@props.user.display_name} onChange={handleInputChange.bind @props.user} /> </AutoSave> <span className="form-help"><Translate content="name.display.note" /></span> <br /> <AutoSave resource={@props.user}> <span className="form-label"><Translate content="name.credited.label" /></span> <br /> <input type="text" className="standard-input full" name="credited_name" value={@props.user.credited_name} onChange={handleInputChange.bind @props.user} /> </AutoSave> <span className="form-help"><Translate content="name.credited.note" /></span> </p> </div> </div> <hr /> <div className="content-container"> <ChangePasswordForm {...@props} /> </div> </div>
33664
React = require 'react' counterpart = require 'counterpart' Translate = require 'react-translate-component' AutoSave = require '../../components/auto-save' handleInputChange = require '../../lib/handle-input-change' auth = require 'panoptes-client/lib/auth' counterpart.registerTranslations 'en', pass: changeLabel: 'Change your password' current: 'Current password' new: '<PASSWORD>' confirm: 'Confirm new password' changeButton: 'Change' tooShort: 'That\'s too short' dontMatch: 'These don\'t match' name: display: label: 'Display name' note: 'How your name will appear to other users in Talk and on your Profile Page' credited: label: 'Credited name' note: 'Public; we’ll use this to give acknowledgement in papers, on posters, etc.' counterpart.registerTranslations 'es', pass: changeLabel: 'Cambiar contraseña' current: 'Contraseña actual' new: 'Nueva contraseña' confirm: 'Confirmar contraseña nueva' changeButton: 'Cambiar' tooShort: 'Es muy corta' dontMatch: 'No coinciden' name: display: label: 'Nombre a mostrar' note: 'El nombre que aparecerá en los foros y en tu perfil' credited: label: 'Nombre real a acreditar' note: 'Público; se utilizará para darte crédito en papers, posters, etc' MIN_PASSWORD_LENGTH = 8 ChangePasswordForm = React.createClass displayName: 'ChangePasswordForm' getDefaultProps: -> user: {} getInitialState: -> old: '' new: '' confirmation: '' inProgress: false success: false error: null render: -> <form ref="form" method="POST" onSubmit={@handleSubmit}> <p> <strong><Translate content="pass.changeLabel" /></strong> </p> <table className="standard-table"> <tbody> <tr> <td><Translate content="pass.current" /></td> <td><input type="password" className="standard-input" size="20" onChange={(e) => @setState old: e.target.value} /></td> </tr> <tr> <td><Translate content="pass.new" /></td> <td> <input type="password" className="standard-input" size="20" onChange={(e) => @setState new: e.target.value} /> {if @state.new.length isnt 0 and @tooShort() <small className="form-help error"><Translate content="pass.tooShort" /></small>} </td> </tr> <tr> <td><Translate content="pass.confirm" /></td> <td> <input type="password" className="standard-input" size="20" onChange={(e) => @setState confirmation: e.target.value} /> {if @state.confirmation.length >= @state.new.length - 1 and @doesntMatch() <small className="form-help error"><Translate content="pass.dontMatch" /></small>} </td> </tr> </tbody> </table> <p> <button type="submit" className="standard-button" disabled={not @state.old or not @state.new or @tooShort() or @doesntMatch() or @state.inProgress}><Translate content="pass.changeButton" /></button>{' '} {if @state.inProgress <i className="fa fa-spinner fa-spin form-help"></i> else if @state.success <i className="fa fa-check-circle form-help success"></i> else if @state.error <small className="form-help error">{@state.error.toString()}</small>} </p> </form> tooShort: -> @state.new.length < MIN_PASSWORD_LENGTH doesntMatch: -> @state.new isnt @state.confirmation handleSubmit: (e) -> e.preventDefault() current = @state.old replacement = @state.new @setState inProgress: true success: false error: null auth.changePassword {current, replacement} .then => @setState success: true @refs.form.reset() .catch (error) => @setState {error} .then => @setState inProgress: false module.exports = React.createClass displayName: "AccountInformationPage" render: -> <div className="account-information-tab"> <div className="columns-container"> <div className="content-container column"> <p> <AutoSave resource={@props.user}> <span className="form-label"><Translate content="name.display.label" /></span> <br /> <input type="text" className="standard-input full" name="display_name" value={@props.user.display_name} onChange={handleInputChange.bind @props.user} /> </AutoSave> <span className="form-help"><Translate content="name.display.note" /></span> <br /> <AutoSave resource={@props.user}> <span className="form-label"><Translate content="name.credited.label" /></span> <br /> <input type="text" className="standard-input full" name="credited_name" value={@props.user.credited_name} onChange={handleInputChange.bind @props.user} /> </AutoSave> <span className="form-help"><Translate content="name.credited.note" /></span> </p> </div> </div> <hr /> <div className="content-container"> <ChangePasswordForm {...@props} /> </div> </div>
true
React = require 'react' counterpart = require 'counterpart' Translate = require 'react-translate-component' AutoSave = require '../../components/auto-save' handleInputChange = require '../../lib/handle-input-change' auth = require 'panoptes-client/lib/auth' counterpart.registerTranslations 'en', pass: changeLabel: 'Change your password' current: 'Current password' new: 'PI:PASSWORD:<PASSWORD>END_PI' confirm: 'Confirm new password' changeButton: 'Change' tooShort: 'That\'s too short' dontMatch: 'These don\'t match' name: display: label: 'Display name' note: 'How your name will appear to other users in Talk and on your Profile Page' credited: label: 'Credited name' note: 'Public; we’ll use this to give acknowledgement in papers, on posters, etc.' counterpart.registerTranslations 'es', pass: changeLabel: 'Cambiar contraseña' current: 'Contraseña actual' new: 'Nueva contraseña' confirm: 'Confirmar contraseña nueva' changeButton: 'Cambiar' tooShort: 'Es muy corta' dontMatch: 'No coinciden' name: display: label: 'Nombre a mostrar' note: 'El nombre que aparecerá en los foros y en tu perfil' credited: label: 'Nombre real a acreditar' note: 'Público; se utilizará para darte crédito en papers, posters, etc' MIN_PASSWORD_LENGTH = 8 ChangePasswordForm = React.createClass displayName: 'ChangePasswordForm' getDefaultProps: -> user: {} getInitialState: -> old: '' new: '' confirmation: '' inProgress: false success: false error: null render: -> <form ref="form" method="POST" onSubmit={@handleSubmit}> <p> <strong><Translate content="pass.changeLabel" /></strong> </p> <table className="standard-table"> <tbody> <tr> <td><Translate content="pass.current" /></td> <td><input type="password" className="standard-input" size="20" onChange={(e) => @setState old: e.target.value} /></td> </tr> <tr> <td><Translate content="pass.new" /></td> <td> <input type="password" className="standard-input" size="20" onChange={(e) => @setState new: e.target.value} /> {if @state.new.length isnt 0 and @tooShort() <small className="form-help error"><Translate content="pass.tooShort" /></small>} </td> </tr> <tr> <td><Translate content="pass.confirm" /></td> <td> <input type="password" className="standard-input" size="20" onChange={(e) => @setState confirmation: e.target.value} /> {if @state.confirmation.length >= @state.new.length - 1 and @doesntMatch() <small className="form-help error"><Translate content="pass.dontMatch" /></small>} </td> </tr> </tbody> </table> <p> <button type="submit" className="standard-button" disabled={not @state.old or not @state.new or @tooShort() or @doesntMatch() or @state.inProgress}><Translate content="pass.changeButton" /></button>{' '} {if @state.inProgress <i className="fa fa-spinner fa-spin form-help"></i> else if @state.success <i className="fa fa-check-circle form-help success"></i> else if @state.error <small className="form-help error">{@state.error.toString()}</small>} </p> </form> tooShort: -> @state.new.length < MIN_PASSWORD_LENGTH doesntMatch: -> @state.new isnt @state.confirmation handleSubmit: (e) -> e.preventDefault() current = @state.old replacement = @state.new @setState inProgress: true success: false error: null auth.changePassword {current, replacement} .then => @setState success: true @refs.form.reset() .catch (error) => @setState {error} .then => @setState inProgress: false module.exports = React.createClass displayName: "AccountInformationPage" render: -> <div className="account-information-tab"> <div className="columns-container"> <div className="content-container column"> <p> <AutoSave resource={@props.user}> <span className="form-label"><Translate content="name.display.label" /></span> <br /> <input type="text" className="standard-input full" name="display_name" value={@props.user.display_name} onChange={handleInputChange.bind @props.user} /> </AutoSave> <span className="form-help"><Translate content="name.display.note" /></span> <br /> <AutoSave resource={@props.user}> <span className="form-label"><Translate content="name.credited.label" /></span> <br /> <input type="text" className="standard-input full" name="credited_name" value={@props.user.credited_name} onChange={handleInputChange.bind @props.user} /> </AutoSave> <span className="form-help"><Translate content="name.credited.note" /></span> </p> </div> </div> <hr /> <div className="content-container"> <ChangePasswordForm {...@props} /> </div> </div>
[ { "context": " fails\", (done) ->\n connectionInfo.password = 'absolute_nonsense'\n Vertica.connect connectionInfo, (err, _) ->\n", "end": 1345, "score": 0.9992319345474243, "start": 1328, "tag": "PASSWORD", "value": "absolute_nonsense" } ]
test/functional/connection_test.coffee
gauravbansal74/node-vertica
25
path = require 'path' fs = require 'fs' assert = require 'assert' Vertica = require '../../src/vertica' errors = require '../../src/errors' describe 'Vertica.connect', -> connectionInfo = null beforeEach -> if !fs.existsSync('./test/connection.json') throw new Error("Create test/connection.json to run functional tests") else connectionInfo = JSON.parse(fs.readFileSync('./test/connection.json')) it "should connect with proper credentials and yield a functional connection", (done) -> Vertica.connect connectionInfo, (err, connection) -> assert.equal err, null assert.ok !connection.busy assert.ok connection.connected connection.query "SELECT 1", (err, resultset) -> assert.equal err, null assert.ok resultset instanceof Vertica.Resultset assert.ok !connection.busy assert.ok connection.connected done() assert.ok connection.busy assert.ok connection.connected it "should fail to connect to an invalid host", (done) -> connectionInfo.host = 'fake' Vertica.connect connectionInfo, (err) -> assert.ok err?, "Connecting should fail with a fake host." done() it "should return an error if the connection attempt fails", (done) -> connectionInfo.password = 'absolute_nonsense' Vertica.connect connectionInfo, (err, _) -> assert err instanceof errors.AuthenticationError assert.equal err.code, '28000' done() it "should use SSL if requested", (done) -> connectionInfo.ssl = 'required' Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? assert.ok connection.isSSL(), "Connection should be using SSL but isn't." done() it "should not use SSL if explicitely requested", (done) -> connectionInfo.ssl = false Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? assert.ok !connection.isSSL() done() it "should be able to interrupt the session", (done) -> connectionInfo.interruptible = true Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? setTimeout connection.interruptSession.bind(connection), 100 connection.query "SELECT sleep(10)", (err, resultset) -> assert err instanceof errors.ConnectionError assert.equal err.message, 'The connection was closed.' done() describe 'Statement interruption', -> beforeEach (done) -> if !fs.existsSync('./test/connection.json') throw new Error("Create test/connection.json to run functional tests") else connectionInfo = JSON.parse(fs.readFileSync('./test/connection.json')) Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? connection.query 'DROP TABLE IF EXISTS test_node_vertica_temp CASCADE', (err, rs) -> return done(err) if err? connection.query 'CREATE TABLE IF NOT EXISTS test_node_vertica_temp (value int);', (err, rs) -> return done(err) if err? dataHandler = (data, success) -> data([0...100].join('\n')) success() connection.copy 'COPY test_node_vertica_temp FROM STDIN ABORT ON ERROR', dataHandler, (err, rs) -> return done(err) if err? done() afterEach (done) -> Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? connection.query 'DROP TABLE IF EXISTS test_node_vertica_temp CASCADE', (err, rs) -> return done(err) if err? done() it "should be able to interrupt a statement", (done) -> connectionInfo.interruptible = true Vertica.connect connectionInfo, (err, connection) -> # According to the Vertica documentation, SLEEP is not an # interruptiple operation. Therefore, we have to create an actual # long-running query. The simplest way to do this is to create a # multi full join of a table with itself. # # https://my.vertica.com/docs/7.0.x/HTML/Content/Authoring/SQLReferenceManual/Functions/VerticaFunctions/SLEEP.htm # setTimeout connection.interruptStatement.bind(connection), 100 connection.query ''' SELECT SUM(t0.value) FROM test_node_vertica_temp t0 FULL OUTER JOIN test_node_vertica_temp t1 ON true FULL OUTER JOIN test_node_vertica_temp t2 ON true FULL OUTER JOIN test_node_vertica_temp t3 ON true FULL OUTER JOIN test_node_vertica_temp t4 ON true FULL OUTER JOIN test_node_vertica_temp t5 ON true ''', (err, resultset) -> assert err instanceof errors.QueryErrorResponse assert.equal err.message, 'Execution canceled by operator' done()
49501
path = require 'path' fs = require 'fs' assert = require 'assert' Vertica = require '../../src/vertica' errors = require '../../src/errors' describe 'Vertica.connect', -> connectionInfo = null beforeEach -> if !fs.existsSync('./test/connection.json') throw new Error("Create test/connection.json to run functional tests") else connectionInfo = JSON.parse(fs.readFileSync('./test/connection.json')) it "should connect with proper credentials and yield a functional connection", (done) -> Vertica.connect connectionInfo, (err, connection) -> assert.equal err, null assert.ok !connection.busy assert.ok connection.connected connection.query "SELECT 1", (err, resultset) -> assert.equal err, null assert.ok resultset instanceof Vertica.Resultset assert.ok !connection.busy assert.ok connection.connected done() assert.ok connection.busy assert.ok connection.connected it "should fail to connect to an invalid host", (done) -> connectionInfo.host = 'fake' Vertica.connect connectionInfo, (err) -> assert.ok err?, "Connecting should fail with a fake host." done() it "should return an error if the connection attempt fails", (done) -> connectionInfo.password = '<PASSWORD>' Vertica.connect connectionInfo, (err, _) -> assert err instanceof errors.AuthenticationError assert.equal err.code, '28000' done() it "should use SSL if requested", (done) -> connectionInfo.ssl = 'required' Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? assert.ok connection.isSSL(), "Connection should be using SSL but isn't." done() it "should not use SSL if explicitely requested", (done) -> connectionInfo.ssl = false Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? assert.ok !connection.isSSL() done() it "should be able to interrupt the session", (done) -> connectionInfo.interruptible = true Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? setTimeout connection.interruptSession.bind(connection), 100 connection.query "SELECT sleep(10)", (err, resultset) -> assert err instanceof errors.ConnectionError assert.equal err.message, 'The connection was closed.' done() describe 'Statement interruption', -> beforeEach (done) -> if !fs.existsSync('./test/connection.json') throw new Error("Create test/connection.json to run functional tests") else connectionInfo = JSON.parse(fs.readFileSync('./test/connection.json')) Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? connection.query 'DROP TABLE IF EXISTS test_node_vertica_temp CASCADE', (err, rs) -> return done(err) if err? connection.query 'CREATE TABLE IF NOT EXISTS test_node_vertica_temp (value int);', (err, rs) -> return done(err) if err? dataHandler = (data, success) -> data([0...100].join('\n')) success() connection.copy 'COPY test_node_vertica_temp FROM STDIN ABORT ON ERROR', dataHandler, (err, rs) -> return done(err) if err? done() afterEach (done) -> Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? connection.query 'DROP TABLE IF EXISTS test_node_vertica_temp CASCADE', (err, rs) -> return done(err) if err? done() it "should be able to interrupt a statement", (done) -> connectionInfo.interruptible = true Vertica.connect connectionInfo, (err, connection) -> # According to the Vertica documentation, SLEEP is not an # interruptiple operation. Therefore, we have to create an actual # long-running query. The simplest way to do this is to create a # multi full join of a table with itself. # # https://my.vertica.com/docs/7.0.x/HTML/Content/Authoring/SQLReferenceManual/Functions/VerticaFunctions/SLEEP.htm # setTimeout connection.interruptStatement.bind(connection), 100 connection.query ''' SELECT SUM(t0.value) FROM test_node_vertica_temp t0 FULL OUTER JOIN test_node_vertica_temp t1 ON true FULL OUTER JOIN test_node_vertica_temp t2 ON true FULL OUTER JOIN test_node_vertica_temp t3 ON true FULL OUTER JOIN test_node_vertica_temp t4 ON true FULL OUTER JOIN test_node_vertica_temp t5 ON true ''', (err, resultset) -> assert err instanceof errors.QueryErrorResponse assert.equal err.message, 'Execution canceled by operator' done()
true
path = require 'path' fs = require 'fs' assert = require 'assert' Vertica = require '../../src/vertica' errors = require '../../src/errors' describe 'Vertica.connect', -> connectionInfo = null beforeEach -> if !fs.existsSync('./test/connection.json') throw new Error("Create test/connection.json to run functional tests") else connectionInfo = JSON.parse(fs.readFileSync('./test/connection.json')) it "should connect with proper credentials and yield a functional connection", (done) -> Vertica.connect connectionInfo, (err, connection) -> assert.equal err, null assert.ok !connection.busy assert.ok connection.connected connection.query "SELECT 1", (err, resultset) -> assert.equal err, null assert.ok resultset instanceof Vertica.Resultset assert.ok !connection.busy assert.ok connection.connected done() assert.ok connection.busy assert.ok connection.connected it "should fail to connect to an invalid host", (done) -> connectionInfo.host = 'fake' Vertica.connect connectionInfo, (err) -> assert.ok err?, "Connecting should fail with a fake host." done() it "should return an error if the connection attempt fails", (done) -> connectionInfo.password = 'PI:PASSWORD:<PASSWORD>END_PI' Vertica.connect connectionInfo, (err, _) -> assert err instanceof errors.AuthenticationError assert.equal err.code, '28000' done() it "should use SSL if requested", (done) -> connectionInfo.ssl = 'required' Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? assert.ok connection.isSSL(), "Connection should be using SSL but isn't." done() it "should not use SSL if explicitely requested", (done) -> connectionInfo.ssl = false Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? assert.ok !connection.isSSL() done() it "should be able to interrupt the session", (done) -> connectionInfo.interruptible = true Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? setTimeout connection.interruptSession.bind(connection), 100 connection.query "SELECT sleep(10)", (err, resultset) -> assert err instanceof errors.ConnectionError assert.equal err.message, 'The connection was closed.' done() describe 'Statement interruption', -> beforeEach (done) -> if !fs.existsSync('./test/connection.json') throw new Error("Create test/connection.json to run functional tests") else connectionInfo = JSON.parse(fs.readFileSync('./test/connection.json')) Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? connection.query 'DROP TABLE IF EXISTS test_node_vertica_temp CASCADE', (err, rs) -> return done(err) if err? connection.query 'CREATE TABLE IF NOT EXISTS test_node_vertica_temp (value int);', (err, rs) -> return done(err) if err? dataHandler = (data, success) -> data([0...100].join('\n')) success() connection.copy 'COPY test_node_vertica_temp FROM STDIN ABORT ON ERROR', dataHandler, (err, rs) -> return done(err) if err? done() afterEach (done) -> Vertica.connect connectionInfo, (err, connection) -> return done(err) if err? connection.query 'DROP TABLE IF EXISTS test_node_vertica_temp CASCADE', (err, rs) -> return done(err) if err? done() it "should be able to interrupt a statement", (done) -> connectionInfo.interruptible = true Vertica.connect connectionInfo, (err, connection) -> # According to the Vertica documentation, SLEEP is not an # interruptiple operation. Therefore, we have to create an actual # long-running query. The simplest way to do this is to create a # multi full join of a table with itself. # # https://my.vertica.com/docs/7.0.x/HTML/Content/Authoring/SQLReferenceManual/Functions/VerticaFunctions/SLEEP.htm # setTimeout connection.interruptStatement.bind(connection), 100 connection.query ''' SELECT SUM(t0.value) FROM test_node_vertica_temp t0 FULL OUTER JOIN test_node_vertica_temp t1 ON true FULL OUTER JOIN test_node_vertica_temp t2 ON true FULL OUTER JOIN test_node_vertica_temp t3 ON true FULL OUTER JOIN test_node_vertica_temp t4 ON true FULL OUTER JOIN test_node_vertica_temp t5 ON true ''', (err, resultset) -> assert err instanceof errors.QueryErrorResponse assert.equal err.message, 'Execution canceled by operator' done()
[ { "context": "The `Event` unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\ndescribe 'Ev", "end": 72, "score": 0.999888002872467, "start": 55, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/dom/test/event_test.coffee
lovely-io/lovely.io-stl
2
# # The `Event` unit tests # # Copyright (C) 2011-2013 Nikolay Nemshilov # {Test,should} = require('lovely') describe 'Event', -> $ = Event = window = document = null before Test.load (dom, win)-> $ = dom Event = $.Event window = win document = win.document describe "constructor", -> it "should copy properties from a raw dom-event", -> raw = type: 'check' pageX: 222 pageY: 444 which: 2 keyCode: 88 altKey: false metaKey: true ctrlKey: false shiftKey: true event = new Event(raw) event.type.should.equal raw.type event.which.should.equal raw.which event.keyCode.should.equal raw.keyCode event.pageX.should.equal raw.pageX event.pageY.should.equal raw.pageY event.altKey.should.equal raw.altKey event.metaKey.should.equal raw.metaKey event.ctrlKey.should.equal raw.ctrlKey event.shiftKey.should.equal raw.shiftKey it "should wrap the target elements", -> target = document.createElement('div') related = document.createElement('div') current = document.createElement('div') event = new Event target: target relatedTarget: related currentTarget: current event.target.should.be.instanceOf $.Element event.currentTarget.should.be.instanceOf $.Element event.relatedTarget.should.be.instanceOf $.Element event.target._.should.equal target event.currentTarget._.should.equal current event.relatedTarget._.should.equal related it "should handle the webkit text-node triggered events", -> text = document.createTextNode('boo') element = document.createElement('div') element.appendChild(text) event = new Event(target: text) event.target._.should.equal element it "should allow to create events just by name", -> event = new Event('my-event') event.should.be.instanceOf Event event.type.should.equal 'my-event' event._.should.eql type: 'my-event' it "should copy custom properties to the custom events", -> event = new Event('my-event', myProperty: 'my-value') event.myProperty.should.equal 'my-value' event._.should.eql type: 'my-event' myProperty: 'my-value' describe "#stopPropagation()", -> it "should call 'stopPropagation()' on raw event when available", -> raw = type: 'click', stopPropagation: -> @called = true event = new Event(raw) event.stopPropagation() raw.called.should.be.true (raw.cancelBubble is undefined).should.be.true it "should set the @stopped = true property", -> event = new Event('my-event') event.stopPropagation() event.stopped.should.be.true it "should return the event itself back", -> event = new Event('my-event') event.stopPropagation().should.equal event describe "#preventDefault()", -> it "should call 'preventDefault()' on a raw event when available", -> raw = type: 'click', preventDefault: -> @called = true event = new Event(raw) event.preventDefault() raw.called.should.be.true (raw.returnValue is undefined).should.be.true it "should return the event itself back to the code", -> event = new Event('my-event') event.preventDefault().should.equal event describe "#stop()", -> it "should call 'preventDefault' and 'stopPropagation' methods", -> event = new Event('my-event') event.stopPropagation = -> @stopped = true; return @ event.preventDefault = -> @prevented = true; return @ event.stop() event.stopped.should.be.true event.prevented.should.be.true it "should return event itself back to the code", -> event = new Event('my-event') event.stop().should.equal event describe "#position()", -> it "should return the event's position in a standard x:NNN, y:NNN hash", -> event = new Event pageX: 222, pageY: 444 event.position().should.eql x: 222, y: 444 describe "#offset()", -> it "should return event's relative position in a standard x:NNN, y:NNN hash", -> target = new $.Element('div') target.position = -> x: 200, y: 300 event = new Event type: 'click', target: target, pageX: 250, pageY: 360 event.offset().should.eql x: 50, y: 60 it "should return 'null' if target is not an element", -> event = new Event type: 'click', target: new $.Document(document) (event.offset() is null).should.be.true describe "#find('css-rule')", -> it "should return 'null' if there is no 'target' property", -> event = new Event('my-event') (event.find('something') is null).should.be.true
39101
# # The `Event` unit tests # # Copyright (C) 2011-2013 <NAME> # {Test,should} = require('lovely') describe 'Event', -> $ = Event = window = document = null before Test.load (dom, win)-> $ = dom Event = $.Event window = win document = win.document describe "constructor", -> it "should copy properties from a raw dom-event", -> raw = type: 'check' pageX: 222 pageY: 444 which: 2 keyCode: 88 altKey: false metaKey: true ctrlKey: false shiftKey: true event = new Event(raw) event.type.should.equal raw.type event.which.should.equal raw.which event.keyCode.should.equal raw.keyCode event.pageX.should.equal raw.pageX event.pageY.should.equal raw.pageY event.altKey.should.equal raw.altKey event.metaKey.should.equal raw.metaKey event.ctrlKey.should.equal raw.ctrlKey event.shiftKey.should.equal raw.shiftKey it "should wrap the target elements", -> target = document.createElement('div') related = document.createElement('div') current = document.createElement('div') event = new Event target: target relatedTarget: related currentTarget: current event.target.should.be.instanceOf $.Element event.currentTarget.should.be.instanceOf $.Element event.relatedTarget.should.be.instanceOf $.Element event.target._.should.equal target event.currentTarget._.should.equal current event.relatedTarget._.should.equal related it "should handle the webkit text-node triggered events", -> text = document.createTextNode('boo') element = document.createElement('div') element.appendChild(text) event = new Event(target: text) event.target._.should.equal element it "should allow to create events just by name", -> event = new Event('my-event') event.should.be.instanceOf Event event.type.should.equal 'my-event' event._.should.eql type: 'my-event' it "should copy custom properties to the custom events", -> event = new Event('my-event', myProperty: 'my-value') event.myProperty.should.equal 'my-value' event._.should.eql type: 'my-event' myProperty: 'my-value' describe "#stopPropagation()", -> it "should call 'stopPropagation()' on raw event when available", -> raw = type: 'click', stopPropagation: -> @called = true event = new Event(raw) event.stopPropagation() raw.called.should.be.true (raw.cancelBubble is undefined).should.be.true it "should set the @stopped = true property", -> event = new Event('my-event') event.stopPropagation() event.stopped.should.be.true it "should return the event itself back", -> event = new Event('my-event') event.stopPropagation().should.equal event describe "#preventDefault()", -> it "should call 'preventDefault()' on a raw event when available", -> raw = type: 'click', preventDefault: -> @called = true event = new Event(raw) event.preventDefault() raw.called.should.be.true (raw.returnValue is undefined).should.be.true it "should return the event itself back to the code", -> event = new Event('my-event') event.preventDefault().should.equal event describe "#stop()", -> it "should call 'preventDefault' and 'stopPropagation' methods", -> event = new Event('my-event') event.stopPropagation = -> @stopped = true; return @ event.preventDefault = -> @prevented = true; return @ event.stop() event.stopped.should.be.true event.prevented.should.be.true it "should return event itself back to the code", -> event = new Event('my-event') event.stop().should.equal event describe "#position()", -> it "should return the event's position in a standard x:NNN, y:NNN hash", -> event = new Event pageX: 222, pageY: 444 event.position().should.eql x: 222, y: 444 describe "#offset()", -> it "should return event's relative position in a standard x:NNN, y:NNN hash", -> target = new $.Element('div') target.position = -> x: 200, y: 300 event = new Event type: 'click', target: target, pageX: 250, pageY: 360 event.offset().should.eql x: 50, y: 60 it "should return 'null' if target is not an element", -> event = new Event type: 'click', target: new $.Document(document) (event.offset() is null).should.be.true describe "#find('css-rule')", -> it "should return 'null' if there is no 'target' property", -> event = new Event('my-event') (event.find('something') is null).should.be.true
true
# # The `Event` unit tests # # Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI # {Test,should} = require('lovely') describe 'Event', -> $ = Event = window = document = null before Test.load (dom, win)-> $ = dom Event = $.Event window = win document = win.document describe "constructor", -> it "should copy properties from a raw dom-event", -> raw = type: 'check' pageX: 222 pageY: 444 which: 2 keyCode: 88 altKey: false metaKey: true ctrlKey: false shiftKey: true event = new Event(raw) event.type.should.equal raw.type event.which.should.equal raw.which event.keyCode.should.equal raw.keyCode event.pageX.should.equal raw.pageX event.pageY.should.equal raw.pageY event.altKey.should.equal raw.altKey event.metaKey.should.equal raw.metaKey event.ctrlKey.should.equal raw.ctrlKey event.shiftKey.should.equal raw.shiftKey it "should wrap the target elements", -> target = document.createElement('div') related = document.createElement('div') current = document.createElement('div') event = new Event target: target relatedTarget: related currentTarget: current event.target.should.be.instanceOf $.Element event.currentTarget.should.be.instanceOf $.Element event.relatedTarget.should.be.instanceOf $.Element event.target._.should.equal target event.currentTarget._.should.equal current event.relatedTarget._.should.equal related it "should handle the webkit text-node triggered events", -> text = document.createTextNode('boo') element = document.createElement('div') element.appendChild(text) event = new Event(target: text) event.target._.should.equal element it "should allow to create events just by name", -> event = new Event('my-event') event.should.be.instanceOf Event event.type.should.equal 'my-event' event._.should.eql type: 'my-event' it "should copy custom properties to the custom events", -> event = new Event('my-event', myProperty: 'my-value') event.myProperty.should.equal 'my-value' event._.should.eql type: 'my-event' myProperty: 'my-value' describe "#stopPropagation()", -> it "should call 'stopPropagation()' on raw event when available", -> raw = type: 'click', stopPropagation: -> @called = true event = new Event(raw) event.stopPropagation() raw.called.should.be.true (raw.cancelBubble is undefined).should.be.true it "should set the @stopped = true property", -> event = new Event('my-event') event.stopPropagation() event.stopped.should.be.true it "should return the event itself back", -> event = new Event('my-event') event.stopPropagation().should.equal event describe "#preventDefault()", -> it "should call 'preventDefault()' on a raw event when available", -> raw = type: 'click', preventDefault: -> @called = true event = new Event(raw) event.preventDefault() raw.called.should.be.true (raw.returnValue is undefined).should.be.true it "should return the event itself back to the code", -> event = new Event('my-event') event.preventDefault().should.equal event describe "#stop()", -> it "should call 'preventDefault' and 'stopPropagation' methods", -> event = new Event('my-event') event.stopPropagation = -> @stopped = true; return @ event.preventDefault = -> @prevented = true; return @ event.stop() event.stopped.should.be.true event.prevented.should.be.true it "should return event itself back to the code", -> event = new Event('my-event') event.stop().should.equal event describe "#position()", -> it "should return the event's position in a standard x:NNN, y:NNN hash", -> event = new Event pageX: 222, pageY: 444 event.position().should.eql x: 222, y: 444 describe "#offset()", -> it "should return event's relative position in a standard x:NNN, y:NNN hash", -> target = new $.Element('div') target.position = -> x: 200, y: 300 event = new Event type: 'click', target: target, pageX: 250, pageY: 360 event.offset().should.eql x: 50, y: 60 it "should return 'null' if target is not an element", -> event = new Event type: 'click', target: new $.Document(document) (event.offset() is null).should.be.true describe "#find('css-rule')", -> it "should return 'null' if there is no 'target' property", -> event = new Event('my-event') (event.find('something') is null).should.be.true
[ { "context": "\n VIDEO_UPLOAD_PATH = \"http://res.cloudinary.com/test123/video/upload/\"\n DEFAULT_UPLOAD_PATH = \"http://re", "end": 157, "score": 0.7228163480758667, "start": 150, "tag": "USERNAME", "value": "test123" }, { "context": " DEFAULT_UPLOAD_PATH = \"http://res.cloudinar...
countProject/countproject_temp/node_modules/keystone/node_modules/cloudinary/test/videospec.coffee
edagarli/countProjects
0
expect = require('expect.js') cloudinary = require('../cloudinary') describe "video tag helper", -> VIDEO_UPLOAD_PATH = "http://res.cloudinary.com/test123/video/upload/" DEFAULT_UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload/" beforeEach -> cloudinary.config(true) # Reset cloudinary.config(cloud_name: "test123", api_secret: "1234") it "should generate video tag", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie")).to.eql("<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with html5 attributes", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie", autoplay: 1, controls: true, loop: true, muted: "true", preload: true, style: "border: 1px")).to.eql( "<video autoplay='1' controls loop muted='true' poster='#{expected_url}.jpg' preload style='border: 1px'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with various attributes", -> options = { source_types: "mp4", html_height : "100", html_width : "200", video_codec : {codec: "h264"}, audio_codec : "acc", start_offset: 3 } expected_url = VIDEO_UPLOAD_PATH + "ac_acc,so_3,vc_h264/movie" expect(cloudinary.video("movie", options)).to.eql( "<video height='100' poster='#{expected_url}.jpg' src='#{expected_url}.mp4' width='200'></video>") delete options['source_types'] expect(cloudinary.video("movie", options)).to.eql( "<video height='100' poster='#{expected_url}.jpg' width='200'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") delete options['html_height'] delete options['html_width'] options['width'] = 250 options['crop'] = 'scale' expected_url = VIDEO_UPLOAD_PATH + "ac_acc,c_scale,so_3,vc_h264,w_250/movie" expect(cloudinary.video("movie", options)).to.eql( "<video poster='#{expected_url}.jpg' width='250'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") expected_url = VIDEO_UPLOAD_PATH + "ac_acc,c_fit,so_3,vc_h264,w_250/movie" options['crop'] = 'fit' expect(cloudinary.video("movie", options)).to.eql( "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with fallback", -> expected_url = VIDEO_UPLOAD_PATH + "movie" fallback = "<span id='spanid'>Cannot display video</span>" expect(cloudinary.video("movie", fallback_content: fallback), "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + fallback + "</video>") expect(cloudinary.video("movie", fallback_content: fallback, source_types: "mp4")).to.eql( "<video poster='#{expected_url}.jpg' src='#{expected_url}.mp4'>" + fallback + "</video>") it "should generate video tag with source types", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie", source_types: ['ogv', 'mp4'])).to.eql( "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "</video>") it "should generate video tag with source transformation", -> expected_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,w_100/movie" expected_ogv_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,q_70,w_100/movie" expected_mp4_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,q_30,w_100/movie" expect(cloudinary.video("movie", width: 100, crop: "scale", transformation: {'quality': 50}, source_transformation: {'ogv': {'quality': 70}, 'mp4': {'quality': 30}})).to.eql( "<video poster='#{expected_url}.jpg' width='100'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_mp4_url}.mp4' type='video/mp4'>" + "<source src='#{expected_ogv_url}.ogv' type='video/ogg'>" + "</video>") expect(cloudinary.video("movie", width: 100, crop: "scale", transformation: {'quality': 50}, source_transformation: {'ogv': {'quality': 70}, 'mp4': {'quality': 30}}, source_types: ['webm', 'mp4'])).to.eql( "<video poster='#{expected_url}.jpg' width='100'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_mp4_url}.mp4' type='video/mp4'>" + "</video>") it "should generate video tag with configurable poster", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expected_poster_url = 'http://image/somewhere.jpg' expect(cloudinary.video("movie", poster: expected_poster_url, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expected_poster_url = VIDEO_UPLOAD_PATH + "g_north/movie.jpg" expect(cloudinary.video("movie", poster: {'gravity': 'north'}, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expected_poster_url = DEFAULT_UPLOAD_PATH + "g_north/my_poster.jpg" expect(cloudinary.video("movie", poster: {'gravity': 'north', 'public_id': 'my_poster', 'format': 'jpg'}, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expect(cloudinary.video("movie", poster: "", source_types: "mp4")).to.eql( "<video src='#{expected_url}.mp4'></video>") expect(cloudinary.video("movie", poster: false, source_types: "mp4")).to.eql( "<video src='#{expected_url}.mp4'></video>") it "should not mutate the options argument", -> options = video_codec: 'auto' autoplay: true cloudinary.video('hello', options) expect(options.video_codec).to.eql('auto') expect(options.autoplay).to.be.true
53451
expect = require('expect.js') cloudinary = require('../cloudinary') describe "video tag helper", -> VIDEO_UPLOAD_PATH = "http://res.cloudinary.com/test123/video/upload/" DEFAULT_UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload/" beforeEach -> cloudinary.config(true) # Reset cloudinary.config(cloud_name: "test123", api_secret: "<KEY>") it "should generate video tag", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie")).to.eql("<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with html5 attributes", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie", autoplay: 1, controls: true, loop: true, muted: "true", preload: true, style: "border: 1px")).to.eql( "<video autoplay='1' controls loop muted='true' poster='#{expected_url}.jpg' preload style='border: 1px'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with various attributes", -> options = { source_types: "mp4", html_height : "100", html_width : "200", video_codec : {codec: "h264"}, audio_codec : "acc", start_offset: 3 } expected_url = VIDEO_UPLOAD_PATH + "ac_acc,so_3,vc_h264/movie" expect(cloudinary.video("movie", options)).to.eql( "<video height='100' poster='#{expected_url}.jpg' src='#{expected_url}.mp4' width='200'></video>") delete options['source_types'] expect(cloudinary.video("movie", options)).to.eql( "<video height='100' poster='#{expected_url}.jpg' width='200'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") delete options['html_height'] delete options['html_width'] options['width'] = 250 options['crop'] = 'scale' expected_url = VIDEO_UPLOAD_PATH + "ac_acc,c_scale,so_3,vc_h264,w_250/movie" expect(cloudinary.video("movie", options)).to.eql( "<video poster='#{expected_url}.jpg' width='250'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") expected_url = VIDEO_UPLOAD_PATH + "ac_acc,c_fit,so_3,vc_h264,w_250/movie" options['crop'] = 'fit' expect(cloudinary.video("movie", options)).to.eql( "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with fallback", -> expected_url = VIDEO_UPLOAD_PATH + "movie" fallback = "<span id='spanid'>Cannot display video</span>" expect(cloudinary.video("movie", fallback_content: fallback), "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + fallback + "</video>") expect(cloudinary.video("movie", fallback_content: fallback, source_types: "mp4")).to.eql( "<video poster='#{expected_url}.jpg' src='#{expected_url}.mp4'>" + fallback + "</video>") it "should generate video tag with source types", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie", source_types: ['ogv', 'mp4'])).to.eql( "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "</video>") it "should generate video tag with source transformation", -> expected_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,w_100/movie" expected_ogv_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,q_70,w_100/movie" expected_mp4_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,q_30,w_100/movie" expect(cloudinary.video("movie", width: 100, crop: "scale", transformation: {'quality': 50}, source_transformation: {'ogv': {'quality': 70}, 'mp4': {'quality': 30}})).to.eql( "<video poster='#{expected_url}.jpg' width='100'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_mp4_url}.mp4' type='video/mp4'>" + "<source src='#{expected_ogv_url}.ogv' type='video/ogg'>" + "</video>") expect(cloudinary.video("movie", width: 100, crop: "scale", transformation: {'quality': 50}, source_transformation: {'ogv': {'quality': 70}, 'mp4': {'quality': 30}}, source_types: ['webm', 'mp4'])).to.eql( "<video poster='#{expected_url}.jpg' width='100'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_mp4_url}.mp4' type='video/mp4'>" + "</video>") it "should generate video tag with configurable poster", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expected_poster_url = 'http://image/somewhere.jpg' expect(cloudinary.video("movie", poster: expected_poster_url, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expected_poster_url = VIDEO_UPLOAD_PATH + "g_north/movie.jpg" expect(cloudinary.video("movie", poster: {'gravity': 'north'}, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expected_poster_url = DEFAULT_UPLOAD_PATH + "g_north/my_poster.jpg" expect(cloudinary.video("movie", poster: {'gravity': 'north', 'public_id': 'my_poster', 'format': 'jpg'}, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expect(cloudinary.video("movie", poster: "", source_types: "mp4")).to.eql( "<video src='#{expected_url}.mp4'></video>") expect(cloudinary.video("movie", poster: false, source_types: "mp4")).to.eql( "<video src='#{expected_url}.mp4'></video>") it "should not mutate the options argument", -> options = video_codec: 'auto' autoplay: true cloudinary.video('hello', options) expect(options.video_codec).to.eql('auto') expect(options.autoplay).to.be.true
true
expect = require('expect.js') cloudinary = require('../cloudinary') describe "video tag helper", -> VIDEO_UPLOAD_PATH = "http://res.cloudinary.com/test123/video/upload/" DEFAULT_UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload/" beforeEach -> cloudinary.config(true) # Reset cloudinary.config(cloud_name: "test123", api_secret: "PI:KEY:<KEY>END_PI") it "should generate video tag", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie")).to.eql("<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with html5 attributes", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie", autoplay: 1, controls: true, loop: true, muted: "true", preload: true, style: "border: 1px")).to.eql( "<video autoplay='1' controls loop muted='true' poster='#{expected_url}.jpg' preload style='border: 1px'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with various attributes", -> options = { source_types: "mp4", html_height : "100", html_width : "200", video_codec : {codec: "h264"}, audio_codec : "acc", start_offset: 3 } expected_url = VIDEO_UPLOAD_PATH + "ac_acc,so_3,vc_h264/movie" expect(cloudinary.video("movie", options)).to.eql( "<video height='100' poster='#{expected_url}.jpg' src='#{expected_url}.mp4' width='200'></video>") delete options['source_types'] expect(cloudinary.video("movie", options)).to.eql( "<video height='100' poster='#{expected_url}.jpg' width='200'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") delete options['html_height'] delete options['html_width'] options['width'] = 250 options['crop'] = 'scale' expected_url = VIDEO_UPLOAD_PATH + "ac_acc,c_scale,so_3,vc_h264,w_250/movie" expect(cloudinary.video("movie", options)).to.eql( "<video poster='#{expected_url}.jpg' width='250'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") expected_url = VIDEO_UPLOAD_PATH + "ac_acc,c_fit,so_3,vc_h264,w_250/movie" options['crop'] = 'fit' expect(cloudinary.video("movie", options)).to.eql( "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "</video>") it "should generate video tag with fallback", -> expected_url = VIDEO_UPLOAD_PATH + "movie" fallback = "<span id='spanid'>Cannot display video</span>" expect(cloudinary.video("movie", fallback_content: fallback), "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + fallback + "</video>") expect(cloudinary.video("movie", fallback_content: fallback, source_types: "mp4")).to.eql( "<video poster='#{expected_url}.jpg' src='#{expected_url}.mp4'>" + fallback + "</video>") it "should generate video tag with source types", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expect(cloudinary.video("movie", source_types: ['ogv', 'mp4'])).to.eql( "<video poster='#{expected_url}.jpg'>" + "<source src='#{expected_url}.ogv' type='video/ogg'>" + "<source src='#{expected_url}.mp4' type='video/mp4'>" + "</video>") it "should generate video tag with source transformation", -> expected_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,w_100/movie" expected_ogv_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,q_70,w_100/movie" expected_mp4_url = VIDEO_UPLOAD_PATH + "q_50/c_scale,q_30,w_100/movie" expect(cloudinary.video("movie", width: 100, crop: "scale", transformation: {'quality': 50}, source_transformation: {'ogv': {'quality': 70}, 'mp4': {'quality': 30}})).to.eql( "<video poster='#{expected_url}.jpg' width='100'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_mp4_url}.mp4' type='video/mp4'>" + "<source src='#{expected_ogv_url}.ogv' type='video/ogg'>" + "</video>") expect(cloudinary.video("movie", width: 100, crop: "scale", transformation: {'quality': 50}, source_transformation: {'ogv': {'quality': 70}, 'mp4': {'quality': 30}}, source_types: ['webm', 'mp4'])).to.eql( "<video poster='#{expected_url}.jpg' width='100'>" + "<source src='#{expected_url}.webm' type='video/webm'>" + "<source src='#{expected_mp4_url}.mp4' type='video/mp4'>" + "</video>") it "should generate video tag with configurable poster", -> expected_url = VIDEO_UPLOAD_PATH + "movie" expected_poster_url = 'http://image/somewhere.jpg' expect(cloudinary.video("movie", poster: expected_poster_url, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expected_poster_url = VIDEO_UPLOAD_PATH + "g_north/movie.jpg" expect(cloudinary.video("movie", poster: {'gravity': 'north'}, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expected_poster_url = DEFAULT_UPLOAD_PATH + "g_north/my_poster.jpg" expect(cloudinary.video("movie", poster: {'gravity': 'north', 'public_id': 'my_poster', 'format': 'jpg'}, source_types: "mp4")).to.eql( "<video poster='#{expected_poster_url}' src='#{expected_url}.mp4'></video>") expect(cloudinary.video("movie", poster: "", source_types: "mp4")).to.eql( "<video src='#{expected_url}.mp4'></video>") expect(cloudinary.video("movie", poster: false, source_types: "mp4")).to.eql( "<video src='#{expected_url}.mp4'></video>") it "should not mutate the options argument", -> options = video_codec: 'auto' autoplay: true cloudinary.video('hello', options) expect(options.video_codec).to.eql('auto') expect(options.autoplay).to.be.true
[ { "context": "# @file vec2d.coffee\n# @Copyright (c) 2017 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 57, "score": 0.9996617436408997, "start": 43, "tag": "NAME", "value": "Taylor Siviter" } ]
src/maths/vec2d.coffee
siviter-t/lampyridae.coffee
4
# @file vec2d.coffee # @Copyright (c) 2017 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'lampyridae' class Lampyridae.Vec2D ### Construct a two-dimensional vector for the Lampyridae framework. # Lampyridae vectors are self-referencing and thus their methods can be compounded as # desired: e.g. vector.add(23, 2).unit().scale(2) # Basic operations can either take other instances of this class for arithmetic or two # numerical arguments representing the x and y coordinates of a vector respectively # For example: vector.add(vector2) [or] vector.add(3, 4) # # @param x [Number] x-coordinate # @param y [Number] y-coordinate ### constructor: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.constructor(1) requires a vector as an argument" @x = x.x ; @y = x.y ; return @ when 2 then @x = x ? 0.0 ; @y = y ? 0.0 ; return @ else throw new Error "Vec2D.constructor requires either 1 or 2 arguments" # Vector operations # ### Add another vector to this vector. ### add: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.add(1) requires a vector as an argument" @add x.x, x.y when 2 then @x += x ; @y += y ; return @ else throw new Error "Vec2D.add requires either 1 or 2 arguments" ### Return the angle (in radians) between the +x-axis and the vector coordinates. ### angle: () -> return Math.atan2 @y, @x ### Divide the vector components by a scalar parameter. ### ascale: (q) -> @x = @x / q ; @y = @y / q ; return @ ### Copy the contents of another vector to this one. ### copy: (vec) -> @x = vec.x ; @y = vec.y ; return @ ### Distance to another vector. ### distanceTo: (vec) -> return new Lampyridae.Vec2D(vec).subtract(@).length() ### Give the unit vector of the direction to another vector (new instance). ### directionTo: (vec) -> return new Lampyridae.Vec2D(vec).subtract(@).unit() ### Divide another vector component-wise to this vector. ### divide: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.divide(1) requires a vector as an argument" @divide x.x, x.y when 2 then @x = @x / x ; @y = @y / y ; return @ else throw new Error "Vec2D.divide requires either 1 or 2 arguments" ### Return the dot product of the vector components. ### dot: () -> return @x * @x + @y * @y ### Return the length or magnitude of the vector. ### length: () -> return Math.sqrt @dot() ### Multiply another vector component-wise to this vector. ### multiply: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.multiply(1) requires a vector as an argument" @multiply x.x, x.y when 2 then @x = @x * x ; @y = @y * y ; return @ else throw new Error "Vec2D.multiply requires either 1 or 2 arguments" ### Return a normal vector rotated 90 deg to the left; from x-axis anticlockwise. ### normalLeft: () -> @x = -@x ; return @ ### Return a normal vector rotated 90 deg to the right; from x-axis clockwise. ### normalRight: () -> @y = -@y ; return @ ### Return a vector rotated by the given angle in radians; from x-axis clockwise. ### rotate: (a) -> x = @x * Math.cos(a) - @y * Math.sin(a) y = @x * Math.sin(a) + @y * Math.cos(a) @x = `Math.abs(x) < 1e-10 ? 0 : x` ; @y = `Math.abs(y) < 1e-10 ? 0 : y`; return @ ### Multiply the vector components by a scalar parameter. ### scale: (q) -> @x = q * @x ; @y = q * @y ; return @ ### Subtract another vector to this vector. ### subtract: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.subtract(1) requires a vector as an argument" @subtract x.x, x.y when 2 then @x -= x ; @y -= y ; return @ else throw new Error "Vec2D.subtract requires either 1 or 2 arguments" ### Turn the vector around. ### turnAround: () -> @x = -@x ; @y = -@y ; return @ ### Return the unit vector. ### unit: () -> return @ascale @length() # end class Lampyridae.Vec2D module.exports = Lampyridae.Vec2D
35867
# @file vec2d.coffee # @Copyright (c) 2017 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'lampyridae' class Lampyridae.Vec2D ### Construct a two-dimensional vector for the Lampyridae framework. # Lampyridae vectors are self-referencing and thus their methods can be compounded as # desired: e.g. vector.add(23, 2).unit().scale(2) # Basic operations can either take other instances of this class for arithmetic or two # numerical arguments representing the x and y coordinates of a vector respectively # For example: vector.add(vector2) [or] vector.add(3, 4) # # @param x [Number] x-coordinate # @param y [Number] y-coordinate ### constructor: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.constructor(1) requires a vector as an argument" @x = x.x ; @y = x.y ; return @ when 2 then @x = x ? 0.0 ; @y = y ? 0.0 ; return @ else throw new Error "Vec2D.constructor requires either 1 or 2 arguments" # Vector operations # ### Add another vector to this vector. ### add: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.add(1) requires a vector as an argument" @add x.x, x.y when 2 then @x += x ; @y += y ; return @ else throw new Error "Vec2D.add requires either 1 or 2 arguments" ### Return the angle (in radians) between the +x-axis and the vector coordinates. ### angle: () -> return Math.atan2 @y, @x ### Divide the vector components by a scalar parameter. ### ascale: (q) -> @x = @x / q ; @y = @y / q ; return @ ### Copy the contents of another vector to this one. ### copy: (vec) -> @x = vec.x ; @y = vec.y ; return @ ### Distance to another vector. ### distanceTo: (vec) -> return new Lampyridae.Vec2D(vec).subtract(@).length() ### Give the unit vector of the direction to another vector (new instance). ### directionTo: (vec) -> return new Lampyridae.Vec2D(vec).subtract(@).unit() ### Divide another vector component-wise to this vector. ### divide: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.divide(1) requires a vector as an argument" @divide x.x, x.y when 2 then @x = @x / x ; @y = @y / y ; return @ else throw new Error "Vec2D.divide requires either 1 or 2 arguments" ### Return the dot product of the vector components. ### dot: () -> return @x * @x + @y * @y ### Return the length or magnitude of the vector. ### length: () -> return Math.sqrt @dot() ### Multiply another vector component-wise to this vector. ### multiply: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.multiply(1) requires a vector as an argument" @multiply x.x, x.y when 2 then @x = @x * x ; @y = @y * y ; return @ else throw new Error "Vec2D.multiply requires either 1 or 2 arguments" ### Return a normal vector rotated 90 deg to the left; from x-axis anticlockwise. ### normalLeft: () -> @x = -@x ; return @ ### Return a normal vector rotated 90 deg to the right; from x-axis clockwise. ### normalRight: () -> @y = -@y ; return @ ### Return a vector rotated by the given angle in radians; from x-axis clockwise. ### rotate: (a) -> x = @x * Math.cos(a) - @y * Math.sin(a) y = @x * Math.sin(a) + @y * Math.cos(a) @x = `Math.abs(x) < 1e-10 ? 0 : x` ; @y = `Math.abs(y) < 1e-10 ? 0 : y`; return @ ### Multiply the vector components by a scalar parameter. ### scale: (q) -> @x = q * @x ; @y = q * @y ; return @ ### Subtract another vector to this vector. ### subtract: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.subtract(1) requires a vector as an argument" @subtract x.x, x.y when 2 then @x -= x ; @y -= y ; return @ else throw new Error "Vec2D.subtract requires either 1 or 2 arguments" ### Turn the vector around. ### turnAround: () -> @x = -@x ; @y = -@y ; return @ ### Return the unit vector. ### unit: () -> return @ascale @length() # end class Lampyridae.Vec2D module.exports = Lampyridae.Vec2D
true
# @file vec2d.coffee # @Copyright (c) 2017 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. require 'lampyridae' class Lampyridae.Vec2D ### Construct a two-dimensional vector for the Lampyridae framework. # Lampyridae vectors are self-referencing and thus their methods can be compounded as # desired: e.g. vector.add(23, 2).unit().scale(2) # Basic operations can either take other instances of this class for arithmetic or two # numerical arguments representing the x and y coordinates of a vector respectively # For example: vector.add(vector2) [or] vector.add(3, 4) # # @param x [Number] x-coordinate # @param y [Number] y-coordinate ### constructor: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.constructor(1) requires a vector as an argument" @x = x.x ; @y = x.y ; return @ when 2 then @x = x ? 0.0 ; @y = y ? 0.0 ; return @ else throw new Error "Vec2D.constructor requires either 1 or 2 arguments" # Vector operations # ### Add another vector to this vector. ### add: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.add(1) requires a vector as an argument" @add x.x, x.y when 2 then @x += x ; @y += y ; return @ else throw new Error "Vec2D.add requires either 1 or 2 arguments" ### Return the angle (in radians) between the +x-axis and the vector coordinates. ### angle: () -> return Math.atan2 @y, @x ### Divide the vector components by a scalar parameter. ### ascale: (q) -> @x = @x / q ; @y = @y / q ; return @ ### Copy the contents of another vector to this one. ### copy: (vec) -> @x = vec.x ; @y = vec.y ; return @ ### Distance to another vector. ### distanceTo: (vec) -> return new Lampyridae.Vec2D(vec).subtract(@).length() ### Give the unit vector of the direction to another vector (new instance). ### directionTo: (vec) -> return new Lampyridae.Vec2D(vec).subtract(@).unit() ### Divide another vector component-wise to this vector. ### divide: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.divide(1) requires a vector as an argument" @divide x.x, x.y when 2 then @x = @x / x ; @y = @y / y ; return @ else throw new Error "Vec2D.divide requires either 1 or 2 arguments" ### Return the dot product of the vector components. ### dot: () -> return @x * @x + @y * @y ### Return the length or magnitude of the vector. ### length: () -> return Math.sqrt @dot() ### Multiply another vector component-wise to this vector. ### multiply: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.multiply(1) requires a vector as an argument" @multiply x.x, x.y when 2 then @x = @x * x ; @y = @y * y ; return @ else throw new Error "Vec2D.multiply requires either 1 or 2 arguments" ### Return a normal vector rotated 90 deg to the left; from x-axis anticlockwise. ### normalLeft: () -> @x = -@x ; return @ ### Return a normal vector rotated 90 deg to the right; from x-axis clockwise. ### normalRight: () -> @y = -@y ; return @ ### Return a vector rotated by the given angle in radians; from x-axis clockwise. ### rotate: (a) -> x = @x * Math.cos(a) - @y * Math.sin(a) y = @x * Math.sin(a) + @y * Math.cos(a) @x = `Math.abs(x) < 1e-10 ? 0 : x` ; @y = `Math.abs(y) < 1e-10 ? 0 : y`; return @ ### Multiply the vector components by a scalar parameter. ### scale: (q) -> @x = q * @x ; @y = q * @y ; return @ ### Subtract another vector to this vector. ### subtract: (x, y) -> switch arguments.length when 1 unless x instanceof Lampyridae.Vec2D throw new Error "Vec2D.subtract(1) requires a vector as an argument" @subtract x.x, x.y when 2 then @x -= x ; @y -= y ; return @ else throw new Error "Vec2D.subtract requires either 1 or 2 arguments" ### Turn the vector around. ### turnAround: () -> @x = -@x ; @y = -@y ; return @ ### Return the unit vector. ### unit: () -> return @ascale @length() # end class Lampyridae.Vec2D module.exports = Lampyridae.Vec2D
[ { "context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nFoldingTextService = requi", "end": 35, "score": 0.999719500541687, "start": 21, "tag": "NAME", "value": "Jesse Grosjean" } ]
atom/packages/foldingtext-for-atom/lib/extensions/ui/date-time-element.coffee
prookie/dotfiles-1
0
# Copyright (c) 2015 Jesse Grosjean. All rights reserved. FoldingTextService = require '../../foldingtext-service' {Disposable, CompositeDisposable} = require 'atom' class DateTimeElement extends HTMLElement constructor: -> super() createdCallback: -> attachedCallback: -> detachedCallback: -> ### Section: Rendering ### render: -> renderMonth: (date) -> renderDay: (date) -> module.exports = document.registerElement 'ft-date-time', prototype: DateTimeElement.prototype
86729
# Copyright (c) 2015 <NAME>. All rights reserved. FoldingTextService = require '../../foldingtext-service' {Disposable, CompositeDisposable} = require 'atom' class DateTimeElement extends HTMLElement constructor: -> super() createdCallback: -> attachedCallback: -> detachedCallback: -> ### Section: Rendering ### render: -> renderMonth: (date) -> renderDay: (date) -> module.exports = document.registerElement 'ft-date-time', prototype: DateTimeElement.prototype
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. FoldingTextService = require '../../foldingtext-service' {Disposable, CompositeDisposable} = require 'atom' class DateTimeElement extends HTMLElement constructor: -> super() createdCallback: -> attachedCallback: -> detachedCallback: -> ### Section: Rendering ### render: -> renderMonth: (date) -> renderDay: (date) -> module.exports = document.registerElement 'ft-date-time', prototype: DateTimeElement.prototype
[ { "context": "ersion: Keybase Go client (OpenPGP version 0.1.0)\n\nxA0DAAIBnGEbwJfFZzABrQIPYgBTPsOMeyJib2R5Ijp7ImNsaW", "end": 285, "score": 0.9926331043243408, "start": 285, "tag": "KEY", "value": "" }, { "context": "rsion: Keybase Go client (OpenPGP version 0.1.0)\n\nxA0DAAIBnGEbwJ...
test/files/sig_gocli.iced
thinq4yourself/kbpgp
1
{KeyManager} = require '../../lib/keymanager' {do_message,Processor} = require '../../lib/openpgp/processor' #================================================================== sigs = [ { sig : """ -----BEGIN PGP MESSAGE----- Version: Keybase Go client (OpenPGP version 0.1.0) xA0DAAIBnGEbwJfFZzABrQIPYgBTPsOMeyJib2R5Ijp7ImNsaWVudCI6eyJuYW1l IjoiS2V5YmFzZSBHbyBjbGllbnQiLCJ2ZXJzaW9uIjoiMS4wLjAifSwia2V5Ijp7 ImZpbmdlcnByaW50IjoiYWQ1ZTRhODkzYTMwYmUxYzA0MDgxYjRkOWM2MTFiYzA5 N2M1NjczMCIsImhvc3QiOiJrZXliYXNlLmlvIiwia2V5X2lkIjoiMDEwMTQ0MjFl MDM0OTkzZjk1NDQ3NjZiYWZjM2EzNTkxOWRiNjQ3YjRkNWFkMjQyNzU3ZWU1MTM3 OGEzZTJkY2M1MGIwYSIsInVpZCI6ImJmNzM4ZDI2MWFiODc0OTQ5YmU4NTI4YjNm OTBlMzAwIiwidXNlcm5hbWUiOiJoZXJiX2tpdGNoIn0sInNlcnZpY2UiOnsibmFt ZSI6InR3aXR0ZXIiLCJ1c2VybmFtZSI6InRhY292b250YWNvIn0sInR5cGUiOiJ3 ZWJfc2VydmljZV9iaW5kaW5nIiwidmVyc2lvbiI6MX0sImNyZWF0ZWQiOjEzOTY2 MjIyMTgsImV4cGlyZV9pbiI6MTU3NjgwMDAwLCJzZXFubyI6MTcsInByZXYiOiIy NGExOTA1MjI0NjU3NTRmMTQ1Njk0NTAzYTNmOGUxODA3NDYzZDNiMDY5NWNjOTdh YmM5YTE1MTA5YTlhNjA5In3CwVwEAAECABAFAlM+w4wJEJxhG8CXxWcwAAC/RhAA J8pe+ZT5aGemOM7m0lhchvtXHTQPbXhLFgX6Mz9K7CH2UCsLdpojObO2RkjM/WwZ 9kMgTlLV2NcavNgQeN9JnEGJAhZ6xeF+T0ysJS8hkrgp5XPqyHQ1ihuKgE0yxP50 p+k2qL2Fd92npxOSEHhUJCTSAzG/Qqzecb7Dy5427h8SGTJ0JXtLf6YTsZEwnJ0/ XhcvC8vI5KgY99dzLxGs6cebZycXrpxB/LT8WAUlK/dggbnq+JYhKouzKGhiLnQi 8j+Uay3EjdwXzt6zRSBq+hhGQD9EUf4q50D62yhq6YGdqPdn591uXLnyr9PEq4tW EcSgEUsXzcbc4jdWi17OssmD0m0Q2W1aTi2X+A9RWM4yGVGVzBGHQ3jYAtWWIy+2 283g1fZkzzzbiw8peXdOCw9J9L9dDiMf47cCRCNgFXRWS9cqqkK48Q5spGmnlMtv 9nXoM5o96/4TSydX9XkktouP4HguFJs6Mu2qE9EkNpgZUAwN2uqjcRFr0e09myHM AWUnbou0bDkiypuNC3B2qG/xQqmx1d7LMp/r+SGHeBobYC4aULVA2NtbV/K4eONt KshzAAbvkubZAD+WlHCr4GzrKaX96Z9YPmCqMRaKnzoJMlEtuMoCS0FtCY8JLvFE qFd18S+Phr28d/PT1WcR/wltm8qUlPt2Mk6/LrRjhtI= =H4wc -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mQINBFMgoiABEADGYnUERzYS026x0FjvV0lUB8c3a9TWXSVxpatVxjkoUtqsMi3E 9AVfpSrorbWZfkP6ogNtCrCim2AbVQlARKzghmZ3IupT7mvK4Uc4pS4sNA1S2DQq IRHEy8o9T6oUO/kBNhYI/rSqyvaqeL5NMG/6HJR1CAoIJpYAhbNcbzVWBKFqQY7+ /W6GdLtccUu1da3E/dSx+bE/TPg6Ia0F0Qh+iDJBlY5BrzbRAnc5V0f0e6Uq3M5Z aPEPSjbyeldl13tB9wRZX95IbF6aOMFj1MY5RC2u7kck1gCSeKjMp95Bp+ngScxF RDk5HFMMRU3VquIVdLkwTp/YZPmcXfPF46olRQnwKkiAnRR2t/A/vzWPdvOk2vK4 nFzeJd04ibo58Y5jCgURwxI1p8pMWtzp952WdQfqHZbGIrZZWe00npfdbvYJLLu4 yAP9XqeMzKGT1wm9IeZBbnLWtx6wf1eG0C6SeOzLUzS5CWPQ+A4jNP/A1mfnmtz0 CviIDCqaY7ho8bBSMWJSRwicpJWcmoXFwti0aa50uCzIrZxaki4HSs67acDR6YpU +njk3W3l1/AHxX2sBIYDpVKXX9g6/Gm8dSbqIimY02GlfpQY3YxVoiFOtgNHB2yr KSVrnyw40+si3+OUBz857p+jgI3CKaj0FRP3jvCPehLnDqLDCgCXLYy8dQARAQAB tC1rZXliYXNlLmlvL2hlcmJfa2l0Y2ggPGhlcmJfa2l0Y2hAa2V5YmFzZS5pbz6J Ai0EEwEKABcFAlMgoiACGy8DCwkHAxUKCAIeAQIXgAAKCRCcYRvAl8VnMKEyD/91 JpivpLuC6ylX6bNOnas5CqNrEg06yAURxYodGqMoM7RtJtj512ZHlzVgkmRTS3KH OUb+S7P7yFJ9KGWxjUUKRruYk5WdEuW+iUVb3xI7pWnxjiqhrG6D60ztFdiu8bUK 98SBFuH+bo4H7QtbTmYWCleG9+H5t7a3LanXjZ4BRreKaOEWKkxbfIz+mDvLTUu8 MDazVcMdhnU27B8a+UUzjK8oKYN8MihV1qYmjYZ2pKi4EKT4dL9B8aXsZ3prfSXX RuDWXg04oNdsYgzXidqAh96X6QuIEYEVMXvY2H5m59kg76/X3LjPkGI4zCZwi38F pE3F8phS9O0lpW3AkflGDVe3lvdVGr/RihlPUBx+zGThMCame6bp/JtrbXzXfQbe OSyC4RZEo5wB2Uh3LaFHB4JP1uCtbfQvJEtxOzihXkxPKlVTt/JVpLPUfIgRbAzo TPKPshS4WROUolFR4ckk6gMME+KsxkYxcfHw4MbY6qzI+140vnvkP2+84xV0Y4gv 3bQLtmfsWbCtOhVLeRTaX45T/IS16KTnwmPwxYnopo64GrqwMZEOmd37U6XFbTG1 qAZlsV42pRPYs8IkEkchJ57zkGRdbsYp55+xJXrk9ftfn/qcr5IUwW97OLqooBVA hW+mlnAN13WZ2eOS6G4Wtzegi78d/u8Z8ZcfRtQ4z7kBDQRTIKIgAQgA2psv+dEO dXkwT+PX6YYNg6mCwZA1kyMMG47UvAXRSM2jpfdQzBN5Aj67fG5k/B6RTkj2GzL5 PplePYGqjCyFhGHnZPyF1ZmWHNVJqvcO1nq9Pmrr/iyNDlfIuq4DRroKgOvt1fEj dBd+O0R5u21Q0R6LR3fiIh0nQcqAoGHimNW9nlYBOzaqyy1xhYe8UeSGobUsDanv tuQ+PdfFBzm7dKyMNBowLHoDisEiq3hB1NESDubmmVF9+u14TjL8Fkgzktp3kLX3 ezB69pAXq9wsMXZ3KVkSggJ7x3aRN30c3MrhPoMT6jZfMBA6O+X6tboce4fJyOOI lwX2ovJk3yFLDwARAQABiQNEBBgBCgAPBQJTIKIgBQkPCZwAAhsuASkJEJxhG8CX xWcwwF0gBBkBCgAGBQJTIKIgAAoJEMTEkRED6qq6KxQH/i+wnN2F2I2cebNwg6Bs xvtGHb6lKPCPqB2s+MhUbA30HKvepXL/cXYHJksUdj0dFCjjYTWeUId6QgjH5Rrk wVM8V54//+pB4g+GHQKbijvd1/g1p7INUPPrELmZACNTwIiKzSraMZFu/8zgK3wk RH1yZegOAp6caPSlfaYCfiCSPGu8V+8exx7zZ046Yju9fdRXUFlK+u6FoXAkHh/0 85B3IAPz3iqeyrvNZrhTtqg2VcMdSp0NyxZmtfg+l58QbDxVdWTAOipSd0SSKIvR c96Ij4JxVPOqzt2j3xLC05yxJvKlxIOYvz5rlN+tUuN2DGyZfu+8opHLRA1IHVMb vG8jMQ/+IPPUyRYFmsqp45kM/rsjZqq88rZUYZl+FK+fqlBvmWJ0dGl3/gcLBJRy hIBL2q/HAKp2HIoDUx7+edfVK0OcwoeCkCpu8RYdFgMe7G0MLaB0Tm3350WGFLuY pVtWabrwDsEGRSugbLJWjwrGYQNheXD+zy6d2SbYrIsMqVlFmb/rfrVAfH12zVtX x+ThLuKChRURoFQ6hjvi5/MbBzF2+ccBzj9NCdlDINeMKO88ztwWOi1J8qhYYlZa /MJR55g4tcWFT8CDGkmqQADB9KTPNCTKwplGbVYW/IOR/JEW913vQwIbYO+gW2R4 RXnn9/qiFFzGw0uLvrOJAwciJ41wMU7DDS4PIiS8pOLZ+ngCn6VxHzOGD2fN4GuK dG2NbnAxAEYXfaQgQ6wPUlsTTB/Mod4gHM61BkzZI+mZIHgkPtZHr9VL/TAMwK02 BavuM8+l+6Lcs8L0VZC8PQ8cwmDKh9hmtnRsh1o4oE7kvc5VYQ7iXTAGv+JdjAmy 0MKFPkBEERUXMih38O5Iwre47rfWWGUN+en2mGQKxBHVEGGGP8n1uu2lvn2gJ6pi cJrgflHwY0DsO2ljCA3hJBT8V4CgmOgrB7qOqxWDG9RvSTRiCrtWt+9UVyo6LjQA fgrStqSHGz9A5/7nwte9eD/En4pNrwPLmzrayjLmCzpxjUC/tzg= =QW5d -----END PGP PUBLIC KEY BLOCK----- """ } ] #================================================================== verify = ({sig,key}, T,cb) -> await KeyManager.import_from_armored_pgp { raw : key }, defer err, km T.no_error err await do_message { armored : sig , keyfetch : km }, defer err T.no_error err cb() #-------------------------------- exports.verify = (T,cb) -> for sig in sigs await verify sig, T, defer() cb() #==================================================================
5292
{KeyManager} = require '../../lib/keymanager' {do_message,Processor} = require '../../lib/openpgp/processor' #================================================================== sigs = [ { sig : """ -----BEGIN PGP MESSAGE----- Version: Keybase Go client (OpenPGP version 0.1.0) <KEY> <KEY>CY8JLvFE qFd18S+Phr28d/PT1WcR/wltm8qUlPt2Mk6/LrRjhtI= =H4wc -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK----- """ } ] #================================================================== verify = ({sig,key}, T,cb) -> await KeyManager.import_from_armored_pgp { raw : key }, defer err, km T.no_error err await do_message { armored : sig , keyfetch : km }, defer err T.no_error err cb() #-------------------------------- exports.verify = (T,cb) -> for sig in sigs await verify sig, T, defer() cb() #==================================================================
true
{KeyManager} = require '../../lib/keymanager' {do_message,Processor} = require '../../lib/openpgp/processor' #================================================================== sigs = [ { sig : """ -----BEGIN PGP MESSAGE----- Version: Keybase Go client (OpenPGP version 0.1.0) PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PICY8JLvFE qFd18S+Phr28d/PT1WcR/wltm8qUlPt2Mk6/LrRjhtI= =H4wc -----END PGP MESSAGE----- """, key : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ } ] #================================================================== verify = ({sig,key}, T,cb) -> await KeyManager.import_from_armored_pgp { raw : key }, defer err, km T.no_error err await do_message { armored : sig , keyfetch : km }, defer err T.no_error err cb() #-------------------------------- exports.verify = (T,cb) -> for sig in sigs await verify sig, T, defer() cb() #==================================================================
[ { "context": "p://coffeescript.org/\n\nstrengthReadable = {\n 0: 'Péssimo'\n 1: 'Ruim'\n 2: 'Fraco'\n 3: 'Bom'\n 4: 'Forte'", "end": 246, "score": 0.9945886135101318, "start": 239, "tag": "NAME", "value": "Péssimo" }, { "context": "t.org/\n\nstrengthReadable = {\n 0: 'Péssimo'\...
public/javascripts/user.coffee
GCES-2018-2/core
1
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ strengthReadable = { 0: 'Péssimo' 1: 'Ruim' 2: 'Fraco' 3: 'Bom' 4: 'Forte' } $(document).ready () -> meter = $('#password-strength-meter') text = $('#password-strength-text') $('#user_password').on 'input', () -> strength = zxcvbn(this.value).score meter.val(strength) text.text(strengthReadable[strength])
154406
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ strengthReadable = { 0: '<NAME>' 1: '<NAME>' 2: 'Fr<NAME>' 3: 'Bom' 4: 'Forte' } $(document).ready () -> meter = $('#password-strength-meter') text = $('#password-strength-text') $('#user_password').on 'input', () -> strength = zxcvbn(this.value).score meter.val(strength) text.text(strengthReadable[strength])
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ strengthReadable = { 0: 'PI:NAME:<NAME>END_PI' 1: 'PI:NAME:<NAME>END_PI' 2: 'FrPI:NAME:<NAME>END_PI' 3: 'Bom' 4: 'Forte' } $(document).ready () -> meter = $('#password-strength-meter') text = $('#password-strength-text') $('#user_password').on 'input', () -> strength = zxcvbn(this.value).score meter.val(strength) text.text(strengthReadable[strength])
[ { "context": "\"UserLocator\", ->\n\n\tbeforeEach ->\n\t\t@user = {_id:\"12390i\"}\n\t\t@UserLocator = SandboxedModule.require module", "end": 246, "score": 0.8545112609863281, "start": 240, "tag": "USERNAME", "value": "12390i" }, { "context": ".stub().callsArgWith(1, null, @user)\n\...
test/unit/coffee/User/UserLocatorTests.coffee
dtu-compute/web-sharelatex
0
sinon = require('sinon') chai = require('chai') should = chai.should() modulePath = "../../../../app/js/Features/User/UserLocator.js" SandboxedModule = require('sandboxed-module') describe "UserLocator", -> beforeEach -> @user = {_id:"12390i"} @UserLocator = SandboxedModule.require modulePath, requires: "../../infrastructure/mongojs": db: @db = { users: {} } "metrics-sharelatex": timeAsyncMethod: sinon.stub() 'logger-sharelatex' : { log: sinon.stub() } @db.users = findOne : sinon.stub().callsArgWith(1, null, @user) @email = "bob.oswald@gmail.com" describe "findByEmail", -> it "should try and find a user with that email address", (done)-> @UserLocator.findByEmail @email, (err, user)=> @db.users.findOne.calledWith(email:@email).should.equal true done() it "should trim white space", (done)-> @UserLocator.findByEmail "#{@email} ", (err, user)=> @db.users.findOne.calledWith(email:@email).should.equal true done() it "should return the user if found", (done)-> @UserLocator.findByEmail @email, (err, user)=> user.should.deep.equal @user done()
19456
sinon = require('sinon') chai = require('chai') should = chai.should() modulePath = "../../../../app/js/Features/User/UserLocator.js" SandboxedModule = require('sandboxed-module') describe "UserLocator", -> beforeEach -> @user = {_id:"12390i"} @UserLocator = SandboxedModule.require modulePath, requires: "../../infrastructure/mongojs": db: @db = { users: {} } "metrics-sharelatex": timeAsyncMethod: sinon.stub() 'logger-sharelatex' : { log: sinon.stub() } @db.users = findOne : sinon.stub().callsArgWith(1, null, @user) @email = "<EMAIL>" describe "findByEmail", -> it "should try and find a user with that email address", (done)-> @UserLocator.findByEmail @email, (err, user)=> @db.users.findOne.calledWith(email:@email).should.equal true done() it "should trim white space", (done)-> @UserLocator.findByEmail "#{@email} ", (err, user)=> @db.users.findOne.calledWith(email:@email).should.equal true done() it "should return the user if found", (done)-> @UserLocator.findByEmail @email, (err, user)=> user.should.deep.equal @user done()
true
sinon = require('sinon') chai = require('chai') should = chai.should() modulePath = "../../../../app/js/Features/User/UserLocator.js" SandboxedModule = require('sandboxed-module') describe "UserLocator", -> beforeEach -> @user = {_id:"12390i"} @UserLocator = SandboxedModule.require modulePath, requires: "../../infrastructure/mongojs": db: @db = { users: {} } "metrics-sharelatex": timeAsyncMethod: sinon.stub() 'logger-sharelatex' : { log: sinon.stub() } @db.users = findOne : sinon.stub().callsArgWith(1, null, @user) @email = "PI:EMAIL:<EMAIL>END_PI" describe "findByEmail", -> it "should try and find a user with that email address", (done)-> @UserLocator.findByEmail @email, (err, user)=> @db.users.findOne.calledWith(email:@email).should.equal true done() it "should trim white space", (done)-> @UserLocator.findByEmail "#{@email} ", (err, user)=> @db.users.findOne.calledWith(email:@email).should.equal true done() it "should return the user if found", (done)-> @UserLocator.findByEmail @email, (err, user)=> user.should.deep.equal @user done()
[ { "context": "iguration for tests\n\nmodule.exports =\n thing: 'thing@xmpp.local'\n owner: 'owner@xmpp.local'\n rack: 'rack@xm", "end": 72, "score": 0.9998390674591064, "start": 56, "tag": "EMAIL", "value": "thing@xmpp.local" }, { "context": "ports =\n thing: 'thing@xmpp....
test/helpers/config.coffee
TNO-IoT/testing-xep-0347
0
# Configuration for tests module.exports = thing: 'thing@xmpp.local' owner: 'owner@xmpp.local' rack: 'rack@xmpp.local' registry: 'registry.xmpp.local' password: 'testing' host: process.env.XMPP_HOST port: '5222'
17806
# Configuration for tests module.exports = thing: '<EMAIL>' owner: '<EMAIL>' rack: '<EMAIL>' registry: 'registry.xmpp.local' password: '<PASSWORD>' host: process.env.XMPP_HOST port: '5222'
true
# Configuration for tests module.exports = thing: 'PI:EMAIL:<EMAIL>END_PI' owner: 'PI:EMAIL:<EMAIL>END_PI' rack: 'PI:EMAIL:<EMAIL>END_PI' registry: 'registry.xmpp.local' password: 'PI:PASSWORD:<PASSWORD>END_PI' host: process.env.XMPP_HOST port: '5222'
[ { "context": "corporates code from [markmon](https://github.com/yyjhao/markmon)\n# covered by the following terms:\n#\n# Co", "end": 70, "score": 0.9990246891975403, "start": 64, "tag": "USERNAME", "value": "yyjhao" }, { "context": "ed by the following terms:\n#\n# Copyright (c) 2014...
lib/wrapped-dom-tree.coffee
abejfehr/markdown-preview-katex
20
# This file incorporates code from [markmon](https://github.com/yyjhao/markmon) # covered by the following terms: # # Copyright (c) 2014, Yao Yujian, http://yjyao.com # # 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. "use strict" TwoDimArray = require './two-dim-array' curHash = 0 hashTo = {} module.exports = class WrappedDomTree # @param dom A DOM element object # https://developer.mozilla.org/en-US/docs/Web/API/element # @param clone Boolean flag indicating if this is the DOM tree to modify # @param rep WrappedDomTree of a DOM element node in dom constructor: (dom, clone, rep) -> if clone @shownTree = new WrappedDomTree dom, false, this @dom = dom.cloneNode true else @dom = dom @rep = rep @clone = clone @hash = curHash++ hashTo[@hash] = @ @isText = dom.nodeType is 3 @tagName = dom.tagName @className = dom.className @textData = dom.data @diffHash = {} if @isText @size = 1 else rep = @rep @children = [].map.call @dom.childNodes, (dom, ind) -> new WrappedDomTree(dom, false, if rep then rep.children[ind] else null) @size = if @children.length then @children.reduce ( (prev, cur) -> prev + cur.size ), 0 else 0 if !@size @size = 1 # @param otherTree WrappedDomTree of a DOM element to diff against diffTo: (otherTree) -> if @clone return @shownTree.diffTo otherTree diff = @rep.diff otherTree score = diff.score operations = diff.operations indexShift = 0 inserted = [] # Force variables to leak to diffTo scope last = undefined possibleReplace = undefined r = undefined lastOp = undefined lastElmDeleted = undefined lastElmInserted = undefined if operations if operations instanceof Array for op in operations do (op) => if op.type is "d" possibleLastDeleted = @children[op.tree + indexShift].dom r = @remove op.tree + indexShift @rep.remove op.tree + indexShift if !last or last.nextSibling == r or last == r last = r # Undefined errors can be throw so we add a condition on lastOp # being defined if last and lastOp and op.tree is lastOp.pos lastElmDeleted = possibleLastDeleted else lastElmDeleted = null lastElmInserted = null lastOp = op indexShift-- return else if op.type is "i" @rep.insert op.pos + indexShift, otherTree.children[op.otherTree] r = @insert op.pos + indexShift, otherTree.children[op.otherTree], @rep.children[op.pos + indexShift] inserted.push(r) if !last or last.nextSibling == r last = r lastOp = op lastElmInserted = r indexShift++ return else re = @children[op.tree + indexShift].diffTo otherTree.children[op.otherTree] if !last or (last.nextSibling == @children[op.tree + indexShift].dom and re.last) last = re.last if re.possibleReplace lastElmInserted = re.possibleReplace.cur lastElmDeleted = re.possibleReplace.prev lastOp = op inserted = inserted.concat re.inserted return else console.log operations throw "invalid operations" if lastOp and lastOp.type != 'i' and lastElmInserted and lastElmDeleted possibleReplace = cur: lastElmInserted prev: lastElmDeleted last: last inserted: inserted possibleReplace: possibleReplace insert: (i, tree, rep) -> dom = tree.dom.cloneNode true if i is @dom.childNodes.length @dom.appendChild dom else @dom.insertBefore dom, @dom.childNodes[i] ctree = new WrappedDomTree dom, false, rep @children.splice i, 0, ctree @dom.childNodes[i] remove: (i) -> @dom.removeChild @dom.childNodes[i] @children[i].removeSelf() @children.splice i, 1 @dom.childNodes[i-1] diff: (otherTree, tmax) -> if @equalTo otherTree return score: 0, operations: null if @cannotReplaceWith otherTree return score: 1/0, operations: null key = otherTree.hash if key in @diffHash return @diffHash[key] if tmax == undefined tmax = 100000 if tmax <= 0 return 0 offset = 0 while( offset < @children.length and offset < otherTree.children.length and @children[offset].equalTo otherTree.children[offset] ) offset++ dp = new TwoDimArray @children.length + 1 - offset, otherTree.children.length + 1 - offset p = new TwoDimArray @children.length + 1 - offset, otherTree.children.length + 1 - offset dp.set 0, 0, 0 sum = 0 # Because coffescripts allows biderctional loops we need this condition # gaurd to prevent a decreasing array list if otherTree.children.length - offset > 1 for i in [1..(otherTree.children.length - offset - 1)] dp.set 0, i, sum p.set 0, i, i-1 sum += otherTree.children[i + offset].size if otherTree.children.length - offset > 0 dp.set 0, otherTree.children.length - offset, sum p.set 0, otherTree.children.length - offset, otherTree.children.length - 1 - offset sum = 0 # Because coffescripts allows biderctional loops we need this condition # gaurd to prevent a decreasing array list if @children.length - offset > 1 for i in [1..(@children.length - offset - 1)] dp.set i, 0, sum p.set i, 0, (i-1)*p.col sum += @children[i + offset].size if @children.length - offset dp.set @children.length - offset, 0 ,sum p.set @children.length - offset, 0, (@children.length - 1 - offset)*p.col getScore = (i, j, max) => if dp.get(i,j) isnt undefined return dp.get(i,j) if max is undefined max = 1/0 if max <= 0 return 1/0 val = max bound = max subdiff = @children[i - 1 + offset].diff( otherTree.children[j - 1 + offset], bound).score force = false if subdiff < bound and subdiff + 1 < @children[i - 1 + offset].size + otherTree.children[j - 1 + offset].size force = true val = getScore(i-1, j-1, bound - subdiff) + subdiff prev = p.getInd i-1, j-1 if !force other = getScore(i-1, j, Math.min(val,max) - @children[i-1+offset].size) + @children[i-1+offset].size if other < val prev = p.getInd i-1, j val = other other = getScore(i, j-1, Math.min(val,max) - otherTree.children[j-1+offset].size) + otherTree.children[j-1+offset].size if other < val prev = p.getInd i, j-1 val = other if val >= max val = 1/0 dp.set i, j, val p.set i, j, prev val score = getScore @children.length - offset, otherTree.children.length - offset, tmax operations = [] cur = p.getInd @children.length - offset, otherTree.children.length - offset cr = @children.length - 1 - offset cc = otherTree.children.length - 1 - offset while p.rawGet(cur) isnt undefined prev = p.rawGet cur rc = p.get2DInd prev pr = rc.r - 1 pc = rc.c - 1 if pr is cr operations.unshift type: "i" otherTree: cc + offset pos: cr + 1 + offset else if pc is cc operations.unshift type: "d" tree: cr + offset else op = @children[cr + offset].diff(otherTree.children[cc + offset]).operations if op and op.length operations.unshift type: "r" tree: cr + offset otherTree: cc + offset cur = prev cr = pr cc = pc @diffHash[key] = score: score operations: operations @diffHash[key] equalTo: (otherTree) -> @dom.isEqualNode otherTree.dom cannotReplaceWith: (otherTree) -> @isText or otherTree.isText or @tagName isnt otherTree.tagName or @className isnt otherTree.className or @className is "math" or @tagName is "A" or (@tagName is "IMG" and !@dom.isEqualNode(otherTree.dom)) getContent: () -> if @dom.outerHTML return @dom.outerHTML else return @textData removeSelf: () -> hashTo[@hash] = null @children and @children.forEach (c) -> c.removeSelf() return
80186
# This file incorporates code from [markmon](https://github.com/yyjhao/markmon) # covered by the following terms: # # Copyright (c) 2014, <NAME>, http://yjyao.com # # 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. "use strict" TwoDimArray = require './two-dim-array' curHash = 0 hashTo = {} module.exports = class WrappedDomTree # @param dom A DOM element object # https://developer.mozilla.org/en-US/docs/Web/API/element # @param clone Boolean flag indicating if this is the DOM tree to modify # @param rep WrappedDomTree of a DOM element node in dom constructor: (dom, clone, rep) -> if clone @shownTree = new WrappedDomTree dom, false, this @dom = dom.cloneNode true else @dom = dom @rep = rep @clone = clone @hash = curHash++ hashTo[@hash] = @ @isText = dom.nodeType is 3 @tagName = dom.tagName @className = dom.className @textData = dom.data @diffHash = {} if @isText @size = 1 else rep = @rep @children = [].map.call @dom.childNodes, (dom, ind) -> new WrappedDomTree(dom, false, if rep then rep.children[ind] else null) @size = if @children.length then @children.reduce ( (prev, cur) -> prev + cur.size ), 0 else 0 if !@size @size = 1 # @param otherTree WrappedDomTree of a DOM element to diff against diffTo: (otherTree) -> if @clone return @shownTree.diffTo otherTree diff = @rep.diff otherTree score = diff.score operations = diff.operations indexShift = 0 inserted = [] # Force variables to leak to diffTo scope last = undefined possibleReplace = undefined r = undefined lastOp = undefined lastElmDeleted = undefined lastElmInserted = undefined if operations if operations instanceof Array for op in operations do (op) => if op.type is "d" possibleLastDeleted = @children[op.tree + indexShift].dom r = @remove op.tree + indexShift @rep.remove op.tree + indexShift if !last or last.nextSibling == r or last == r last = r # Undefined errors can be throw so we add a condition on lastOp # being defined if last and lastOp and op.tree is lastOp.pos lastElmDeleted = possibleLastDeleted else lastElmDeleted = null lastElmInserted = null lastOp = op indexShift-- return else if op.type is "i" @rep.insert op.pos + indexShift, otherTree.children[op.otherTree] r = @insert op.pos + indexShift, otherTree.children[op.otherTree], @rep.children[op.pos + indexShift] inserted.push(r) if !last or last.nextSibling == r last = r lastOp = op lastElmInserted = r indexShift++ return else re = @children[op.tree + indexShift].diffTo otherTree.children[op.otherTree] if !last or (last.nextSibling == @children[op.tree + indexShift].dom and re.last) last = re.last if re.possibleReplace lastElmInserted = re.possibleReplace.cur lastElmDeleted = re.possibleReplace.prev lastOp = op inserted = inserted.concat re.inserted return else console.log operations throw "invalid operations" if lastOp and lastOp.type != 'i' and lastElmInserted and lastElmDeleted possibleReplace = cur: lastElmInserted prev: lastElmDeleted last: last inserted: inserted possibleReplace: possibleReplace insert: (i, tree, rep) -> dom = tree.dom.cloneNode true if i is @dom.childNodes.length @dom.appendChild dom else @dom.insertBefore dom, @dom.childNodes[i] ctree = new WrappedDomTree dom, false, rep @children.splice i, 0, ctree @dom.childNodes[i] remove: (i) -> @dom.removeChild @dom.childNodes[i] @children[i].removeSelf() @children.splice i, 1 @dom.childNodes[i-1] diff: (otherTree, tmax) -> if @equalTo otherTree return score: 0, operations: null if @cannotReplaceWith otherTree return score: 1/0, operations: null key = otherTree.hash if key in @diffHash return @diffHash[key] if tmax == undefined tmax = 100000 if tmax <= 0 return 0 offset = 0 while( offset < @children.length and offset < otherTree.children.length and @children[offset].equalTo otherTree.children[offset] ) offset++ dp = new TwoDimArray @children.length + 1 - offset, otherTree.children.length + 1 - offset p = new TwoDimArray @children.length + 1 - offset, otherTree.children.length + 1 - offset dp.set 0, 0, 0 sum = 0 # Because coffescripts allows biderctional loops we need this condition # gaurd to prevent a decreasing array list if otherTree.children.length - offset > 1 for i in [1..(otherTree.children.length - offset - 1)] dp.set 0, i, sum p.set 0, i, i-1 sum += otherTree.children[i + offset].size if otherTree.children.length - offset > 0 dp.set 0, otherTree.children.length - offset, sum p.set 0, otherTree.children.length - offset, otherTree.children.length - 1 - offset sum = 0 # Because coffescripts allows biderctional loops we need this condition # gaurd to prevent a decreasing array list if @children.length - offset > 1 for i in [1..(@children.length - offset - 1)] dp.set i, 0, sum p.set i, 0, (i-1)*p.col sum += @children[i + offset].size if @children.length - offset dp.set @children.length - offset, 0 ,sum p.set @children.length - offset, 0, (@children.length - 1 - offset)*p.col getScore = (i, j, max) => if dp.get(i,j) isnt undefined return dp.get(i,j) if max is undefined max = 1/0 if max <= 0 return 1/0 val = max bound = max subdiff = @children[i - 1 + offset].diff( otherTree.children[j - 1 + offset], bound).score force = false if subdiff < bound and subdiff + 1 < @children[i - 1 + offset].size + otherTree.children[j - 1 + offset].size force = true val = getScore(i-1, j-1, bound - subdiff) + subdiff prev = p.getInd i-1, j-1 if !force other = getScore(i-1, j, Math.min(val,max) - @children[i-1+offset].size) + @children[i-1+offset].size if other < val prev = p.getInd i-1, j val = other other = getScore(i, j-1, Math.min(val,max) - otherTree.children[j-1+offset].size) + otherTree.children[j-1+offset].size if other < val prev = p.getInd i, j-1 val = other if val >= max val = 1/0 dp.set i, j, val p.set i, j, prev val score = getScore @children.length - offset, otherTree.children.length - offset, tmax operations = [] cur = p.getInd @children.length - offset, otherTree.children.length - offset cr = @children.length - 1 - offset cc = otherTree.children.length - 1 - offset while p.rawGet(cur) isnt undefined prev = p.rawGet cur rc = p.get2DInd prev pr = rc.r - 1 pc = rc.c - 1 if pr is cr operations.unshift type: "i" otherTree: cc + offset pos: cr + 1 + offset else if pc is cc operations.unshift type: "d" tree: cr + offset else op = @children[cr + offset].diff(otherTree.children[cc + offset]).operations if op and op.length operations.unshift type: "r" tree: cr + offset otherTree: cc + offset cur = prev cr = pr cc = pc @diffHash[key] = score: score operations: operations @diffHash[key] equalTo: (otherTree) -> @dom.isEqualNode otherTree.dom cannotReplaceWith: (otherTree) -> @isText or otherTree.isText or @tagName isnt otherTree.tagName or @className isnt otherTree.className or @className is "math" or @tagName is "A" or (@tagName is "IMG" and !@dom.isEqualNode(otherTree.dom)) getContent: () -> if @dom.outerHTML return @dom.outerHTML else return @textData removeSelf: () -> hashTo[@hash] = null @children and @children.forEach (c) -> c.removeSelf() return
true
# This file incorporates code from [markmon](https://github.com/yyjhao/markmon) # covered by the following terms: # # Copyright (c) 2014, PI:NAME:<NAME>END_PI, http://yjyao.com # # 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. "use strict" TwoDimArray = require './two-dim-array' curHash = 0 hashTo = {} module.exports = class WrappedDomTree # @param dom A DOM element object # https://developer.mozilla.org/en-US/docs/Web/API/element # @param clone Boolean flag indicating if this is the DOM tree to modify # @param rep WrappedDomTree of a DOM element node in dom constructor: (dom, clone, rep) -> if clone @shownTree = new WrappedDomTree dom, false, this @dom = dom.cloneNode true else @dom = dom @rep = rep @clone = clone @hash = curHash++ hashTo[@hash] = @ @isText = dom.nodeType is 3 @tagName = dom.tagName @className = dom.className @textData = dom.data @diffHash = {} if @isText @size = 1 else rep = @rep @children = [].map.call @dom.childNodes, (dom, ind) -> new WrappedDomTree(dom, false, if rep then rep.children[ind] else null) @size = if @children.length then @children.reduce ( (prev, cur) -> prev + cur.size ), 0 else 0 if !@size @size = 1 # @param otherTree WrappedDomTree of a DOM element to diff against diffTo: (otherTree) -> if @clone return @shownTree.diffTo otherTree diff = @rep.diff otherTree score = diff.score operations = diff.operations indexShift = 0 inserted = [] # Force variables to leak to diffTo scope last = undefined possibleReplace = undefined r = undefined lastOp = undefined lastElmDeleted = undefined lastElmInserted = undefined if operations if operations instanceof Array for op in operations do (op) => if op.type is "d" possibleLastDeleted = @children[op.tree + indexShift].dom r = @remove op.tree + indexShift @rep.remove op.tree + indexShift if !last or last.nextSibling == r or last == r last = r # Undefined errors can be throw so we add a condition on lastOp # being defined if last and lastOp and op.tree is lastOp.pos lastElmDeleted = possibleLastDeleted else lastElmDeleted = null lastElmInserted = null lastOp = op indexShift-- return else if op.type is "i" @rep.insert op.pos + indexShift, otherTree.children[op.otherTree] r = @insert op.pos + indexShift, otherTree.children[op.otherTree], @rep.children[op.pos + indexShift] inserted.push(r) if !last or last.nextSibling == r last = r lastOp = op lastElmInserted = r indexShift++ return else re = @children[op.tree + indexShift].diffTo otherTree.children[op.otherTree] if !last or (last.nextSibling == @children[op.tree + indexShift].dom and re.last) last = re.last if re.possibleReplace lastElmInserted = re.possibleReplace.cur lastElmDeleted = re.possibleReplace.prev lastOp = op inserted = inserted.concat re.inserted return else console.log operations throw "invalid operations" if lastOp and lastOp.type != 'i' and lastElmInserted and lastElmDeleted possibleReplace = cur: lastElmInserted prev: lastElmDeleted last: last inserted: inserted possibleReplace: possibleReplace insert: (i, tree, rep) -> dom = tree.dom.cloneNode true if i is @dom.childNodes.length @dom.appendChild dom else @dom.insertBefore dom, @dom.childNodes[i] ctree = new WrappedDomTree dom, false, rep @children.splice i, 0, ctree @dom.childNodes[i] remove: (i) -> @dom.removeChild @dom.childNodes[i] @children[i].removeSelf() @children.splice i, 1 @dom.childNodes[i-1] diff: (otherTree, tmax) -> if @equalTo otherTree return score: 0, operations: null if @cannotReplaceWith otherTree return score: 1/0, operations: null key = otherTree.hash if key in @diffHash return @diffHash[key] if tmax == undefined tmax = 100000 if tmax <= 0 return 0 offset = 0 while( offset < @children.length and offset < otherTree.children.length and @children[offset].equalTo otherTree.children[offset] ) offset++ dp = new TwoDimArray @children.length + 1 - offset, otherTree.children.length + 1 - offset p = new TwoDimArray @children.length + 1 - offset, otherTree.children.length + 1 - offset dp.set 0, 0, 0 sum = 0 # Because coffescripts allows biderctional loops we need this condition # gaurd to prevent a decreasing array list if otherTree.children.length - offset > 1 for i in [1..(otherTree.children.length - offset - 1)] dp.set 0, i, sum p.set 0, i, i-1 sum += otherTree.children[i + offset].size if otherTree.children.length - offset > 0 dp.set 0, otherTree.children.length - offset, sum p.set 0, otherTree.children.length - offset, otherTree.children.length - 1 - offset sum = 0 # Because coffescripts allows biderctional loops we need this condition # gaurd to prevent a decreasing array list if @children.length - offset > 1 for i in [1..(@children.length - offset - 1)] dp.set i, 0, sum p.set i, 0, (i-1)*p.col sum += @children[i + offset].size if @children.length - offset dp.set @children.length - offset, 0 ,sum p.set @children.length - offset, 0, (@children.length - 1 - offset)*p.col getScore = (i, j, max) => if dp.get(i,j) isnt undefined return dp.get(i,j) if max is undefined max = 1/0 if max <= 0 return 1/0 val = max bound = max subdiff = @children[i - 1 + offset].diff( otherTree.children[j - 1 + offset], bound).score force = false if subdiff < bound and subdiff + 1 < @children[i - 1 + offset].size + otherTree.children[j - 1 + offset].size force = true val = getScore(i-1, j-1, bound - subdiff) + subdiff prev = p.getInd i-1, j-1 if !force other = getScore(i-1, j, Math.min(val,max) - @children[i-1+offset].size) + @children[i-1+offset].size if other < val prev = p.getInd i-1, j val = other other = getScore(i, j-1, Math.min(val,max) - otherTree.children[j-1+offset].size) + otherTree.children[j-1+offset].size if other < val prev = p.getInd i, j-1 val = other if val >= max val = 1/0 dp.set i, j, val p.set i, j, prev val score = getScore @children.length - offset, otherTree.children.length - offset, tmax operations = [] cur = p.getInd @children.length - offset, otherTree.children.length - offset cr = @children.length - 1 - offset cc = otherTree.children.length - 1 - offset while p.rawGet(cur) isnt undefined prev = p.rawGet cur rc = p.get2DInd prev pr = rc.r - 1 pc = rc.c - 1 if pr is cr operations.unshift type: "i" otherTree: cc + offset pos: cr + 1 + offset else if pc is cc operations.unshift type: "d" tree: cr + offset else op = @children[cr + offset].diff(otherTree.children[cc + offset]).operations if op and op.length operations.unshift type: "r" tree: cr + offset otherTree: cc + offset cur = prev cr = pr cc = pc @diffHash[key] = score: score operations: operations @diffHash[key] equalTo: (otherTree) -> @dom.isEqualNode otherTree.dom cannotReplaceWith: (otherTree) -> @isText or otherTree.isText or @tagName isnt otherTree.tagName or @className isnt otherTree.className or @className is "math" or @tagName is "A" or (@tagName is "IMG" and !@dom.isEqualNode(otherTree.dom)) getContent: () -> if @dom.outerHTML return @dom.outerHTML else return @textData removeSelf: () -> hashTo[@hash] = null @children and @children.forEach (c) -> c.removeSelf() return
[ { "context": "egate new_datom '^flowmatic-event', 123\n $key = '°s/^one'\n debug '^8887^', await DB.query [ \"select FM.em", "end": 2628, "score": 0.9993544816970825, "start": 2621, "tag": "KEY", "value": "°s/^one" } ]
src/experiments/demo-intershop-rpc.coffee
loveencounterflow/flowmatic
1
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'INTERSHOP-RPC/DEMO' debug = CND.get_logger 'debug', badge alert = CND.get_logger 'alert', badge whisper = CND.get_logger 'whisper', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge echo = CND.echo.bind CND #........................................................................................................... # FS = require 'fs' # PATH = require 'path' NET = require 'net' #........................................................................................................... SP = require 'steampipes' { $ $async $watch $drain } = SP.export() #........................................................................................................... DATOM = require 'datom' { new_datom select } = DATOM.export() #........................................................................................................... types = require '../types' { isa validate cast type_of } = types #........................................................................................................... { jr } = CND Rpc = require 'intershop-rpc' DB = require '../../intershop/intershop_modules/db' ############################################################################################################ if module is require.main then do => # debug '^7776^', ( k for k of Rpc ) # debug '^7776^', ( k for k of new Rpc 23001 ) rpc = new Rpc 23001 rpc.contract '^flowmatic-event', ( d ) -> help '^5554^ contract', d; return 42 await rpc.start() rpc.listen_to_all ( P... ) -> urge '^66676^ listen_to_all', P rpc.listen_to_unheard ( P... ) -> urge '^66676^ listen_to_unheard', P debug await rpc.emit '^foobar' debug '^7712^', await rpc.delegate '^flowmatic-event', { x: 123, } debug '^7712^', await rpc.delegate '^flowmatic-event', 123 debug '^7712^', await rpc.delegate new_datom '^flowmatic-event', 123 $key = '°s/^one' debug '^8887^', await DB.query [ "select FM.emit( $1 );", $key, ] process.exit 1
211361
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'INTERSHOP-RPC/DEMO' debug = CND.get_logger 'debug', badge alert = CND.get_logger 'alert', badge whisper = CND.get_logger 'whisper', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge echo = CND.echo.bind CND #........................................................................................................... # FS = require 'fs' # PATH = require 'path' NET = require 'net' #........................................................................................................... SP = require 'steampipes' { $ $async $watch $drain } = SP.export() #........................................................................................................... DATOM = require 'datom' { new_datom select } = DATOM.export() #........................................................................................................... types = require '../types' { isa validate cast type_of } = types #........................................................................................................... { jr } = CND Rpc = require 'intershop-rpc' DB = require '../../intershop/intershop_modules/db' ############################################################################################################ if module is require.main then do => # debug '^7776^', ( k for k of Rpc ) # debug '^7776^', ( k for k of new Rpc 23001 ) rpc = new Rpc 23001 rpc.contract '^flowmatic-event', ( d ) -> help '^5554^ contract', d; return 42 await rpc.start() rpc.listen_to_all ( P... ) -> urge '^66676^ listen_to_all', P rpc.listen_to_unheard ( P... ) -> urge '^66676^ listen_to_unheard', P debug await rpc.emit '^foobar' debug '^7712^', await rpc.delegate '^flowmatic-event', { x: 123, } debug '^7712^', await rpc.delegate '^flowmatic-event', 123 debug '^7712^', await rpc.delegate new_datom '^flowmatic-event', 123 $key = '<KEY>' debug '^8887^', await DB.query [ "select FM.emit( $1 );", $key, ] process.exit 1
true
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'INTERSHOP-RPC/DEMO' debug = CND.get_logger 'debug', badge alert = CND.get_logger 'alert', badge whisper = CND.get_logger 'whisper', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge echo = CND.echo.bind CND #........................................................................................................... # FS = require 'fs' # PATH = require 'path' NET = require 'net' #........................................................................................................... SP = require 'steampipes' { $ $async $watch $drain } = SP.export() #........................................................................................................... DATOM = require 'datom' { new_datom select } = DATOM.export() #........................................................................................................... types = require '../types' { isa validate cast type_of } = types #........................................................................................................... { jr } = CND Rpc = require 'intershop-rpc' DB = require '../../intershop/intershop_modules/db' ############################################################################################################ if module is require.main then do => # debug '^7776^', ( k for k of Rpc ) # debug '^7776^', ( k for k of new Rpc 23001 ) rpc = new Rpc 23001 rpc.contract '^flowmatic-event', ( d ) -> help '^5554^ contract', d; return 42 await rpc.start() rpc.listen_to_all ( P... ) -> urge '^66676^ listen_to_all', P rpc.listen_to_unheard ( P... ) -> urge '^66676^ listen_to_unheard', P debug await rpc.emit '^foobar' debug '^7712^', await rpc.delegate '^flowmatic-event', { x: 123, } debug '^7712^', await rpc.delegate '^flowmatic-event', 123 debug '^7712^', await rpc.delegate new_datom '^flowmatic-event', 123 $key = 'PI:KEY:<KEY>END_PI' debug '^8887^', await DB.query [ "select FM.emit( $1 );", $key, ] process.exit 1
[ { "context": "torage = require 'lib/storage'\nGPLUS_TOKEN_KEY = 'gplusToken'\n\n# gplus user object props to\nuserPropsToSave =\n", "end": 164, "score": 0.8899123072624207, "start": 154, "tag": "KEY", "value": "gplusToken" }, { "context": "t props to\nuserPropsToSave =\n 'name.given...
app/lib/GPlusHandler.coffee
Melondonut/codecombat
1
CocoClass = require 'lib/CocoClass' {me} = require 'lib/auth' {backboneFailure} = require 'lib/errors' storage = require 'lib/storage' GPLUS_TOKEN_KEY = 'gplusToken' # gplus user object props to userPropsToSave = 'name.givenName': 'firstName' 'name.familyName': 'lastName' 'gender': 'gender' 'id': 'gplusID' fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id' plusURL = '/plus/v1/people/me?fields='+fieldsToFetch revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' clientID = '800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com' scope = 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' module.exports = GPlusHandler = class GPlusHandler extends CocoClass constructor: -> @accessToken = storage.load GPLUS_TOKEN_KEY super() subscriptions: 'gplus-logged-in':'onGPlusLogin' 'gapi-loaded':'onGPlusLoaded' onGPlusLoaded: -> session_state = null if @accessToken # We need to check the current state, given our access token gapi.auth.setToken 'token', @accessToken session_state = @accessToken.session_state gapi.auth.checkSessionState({client_id: clientID, session_state: session_state}, @onCheckedSessionState) else # If we ran checkSessionState, it might return true, that the user is logged into Google, but has not authorized us @loggedIn = false func = => @trigger 'checked-state' setTimeout func, 1 onCheckedSessionState: (@loggedIn) => @trigger 'checked-state' reauthorize: -> params = 'client_id' : clientID 'scope' : scope gapi.auth.authorize params, @onGPlusLogin onGPlusLogin: (e) => @loggedIn = true storage.save(GPLUS_TOKEN_KEY, e) @accessToken = e @trigger 'logged-in' return if (not me) or me.get 'gplusID' # so only get more data # email and profile data loaded separately @responsesComplete = 0 gapi.client.request(path: plusURL, callback: @onPersonEntityReceived) gapi.client.load('oauth2', 'v2', => gapi.client.oauth2.userinfo.get().execute(@onEmailReceived)) shouldSave: false responsesComplete: 0 onPersonEntityReceived: (r) => for gpProp, userProp of userPropsToSave keys = gpProp.split('.') value = r value = value[key] for key in keys if value and not me.get(userProp) @shouldSave = true me.set(userProp, value) @responsesComplete += 1 @saveIfAllDone() onEmailReceived: (r) => newEmail = r.email and r.email isnt me.get('email') return unless newEmail or me.get('anonymous') me.set('email', r.email) @shouldSave = true @responsesComplete += 1 @saveIfAllDone() saveIfAllDone: => return unless @responsesComplete is 2 return unless me.get('email') and me.get('gplusID') Backbone.Mediator.publish('logging-in-with-gplus') gplusID = me.get('gplusID') window.tracker?.trackEvent 'Google Login' window.tracker?.identify() patch = {} patch[key] = me.get(key) for gplusKey, key of userPropsToSave patch._id = me.id patch.email = me.get('email') wasAnonymous = me.get('anonymous') me.save(patch, { patch: true error: backboneFailure, url: "/db/user?gplusID=#{gplusID}&gplusAccessToken=#{@accessToken.access_token}" success: (model) -> window.location.reload() if wasAnonymous and not model.get('anonymous') }) loadFriends: (friendsCallback) -> return friendsCallback() unless @loggedIn expiresIn = if @accessToken then parseInt(@accessToken.expires_at) - new Date().getTime()/1000 else -1 onReauthorized = => gapi.client.request({path: '/plus/v1/people/me/people/visible', callback: friendsCallback}) if expiresIn < 0 # TODO: this tries to open a popup window, which might not ever finish or work, so the callback may never be called. @reauthorize() @listenToOnce(@, 'logged-in', onReauthorized) else onReauthorized()
213902
CocoClass = require 'lib/CocoClass' {me} = require 'lib/auth' {backboneFailure} = require 'lib/errors' storage = require 'lib/storage' GPLUS_TOKEN_KEY = '<KEY>' # gplus user object props to userPropsToSave = 'name.givenName': '<NAME>' 'name.familyName': '<NAME>' 'gender': 'gender' 'id': 'gplusID' fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id' plusURL = '/plus/v1/people/me?fields='+fieldsToFetch revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' clientID = '800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com' scope = 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' module.exports = GPlusHandler = class GPlusHandler extends CocoClass constructor: -> @accessToken = storage.load GPLUS_TOKEN_KEY super() subscriptions: 'gplus-logged-in':'onGPlusLogin' 'gapi-loaded':'onGPlusLoaded' onGPlusLoaded: -> session_state = null if @accessToken # We need to check the current state, given our access token gapi.auth.setToken 'token', @accessToken session_state = @accessToken.session_state gapi.auth.checkSessionState({client_id: clientID, session_state: session_state}, @onCheckedSessionState) else # If we ran checkSessionState, it might return true, that the user is logged into Google, but has not authorized us @loggedIn = false func = => @trigger 'checked-state' setTimeout func, 1 onCheckedSessionState: (@loggedIn) => @trigger 'checked-state' reauthorize: -> params = 'client_id' : clientID 'scope' : scope gapi.auth.authorize params, @onGPlusLogin onGPlusLogin: (e) => @loggedIn = true storage.save(GPLUS_TOKEN_KEY, e) @accessToken = e @trigger 'logged-in' return if (not me) or me.get 'gplusID' # so only get more data # email and profile data loaded separately @responsesComplete = 0 gapi.client.request(path: plusURL, callback: @onPersonEntityReceived) gapi.client.load('oauth2', 'v2', => gapi.client.oauth2.userinfo.get().execute(@onEmailReceived)) shouldSave: false responsesComplete: 0 onPersonEntityReceived: (r) => for gpProp, userProp of userPropsToSave keys = gp<KEY>('.') value = r value = value[key] for key in keys if value and not me.get(userProp) @shouldSave = true me.set(userProp, value) @responsesComplete += 1 @saveIfAllDone() onEmailReceived: (r) => newEmail = r.email and r.email isnt me.get('email') return unless newEmail or me.get('anonymous') me.set('email', r.email) @shouldSave = true @responsesComplete += 1 @saveIfAllDone() saveIfAllDone: => return unless @responsesComplete is 2 return unless me.get('email') and me.get('gplusID') Backbone.Mediator.publish('logging-in-with-gplus') gplusID = me.get('gplusID') window.tracker?.trackEvent 'Google Login' window.tracker?.identify() patch = {} patch[key] = me.get(key) for gplusKey, key of userPropsToSave patch._id = me.id patch.email = me.get('email') wasAnonymous = me.get('anonymous') me.save(patch, { patch: true error: backboneFailure, url: "/db/user?gplusID=#{gplusID}&gplusAccessToken=#{@accessToken.access_token}" success: (model) -> window.location.reload() if wasAnonymous and not model.get('anonymous') }) loadFriends: (friendsCallback) -> return friendsCallback() unless @loggedIn expiresIn = if @accessToken then parseInt(@accessToken.expires_at) - new Date().getTime()/1000 else -1 onReauthorized = => gapi.client.request({path: '/plus/v1/people/me/people/visible', callback: friendsCallback}) if expiresIn < 0 # TODO: this tries to open a popup window, which might not ever finish or work, so the callback may never be called. @reauthorize() @listenToOnce(@, 'logged-in', onReauthorized) else onReauthorized()
true
CocoClass = require 'lib/CocoClass' {me} = require 'lib/auth' {backboneFailure} = require 'lib/errors' storage = require 'lib/storage' GPLUS_TOKEN_KEY = 'PI:KEY:<KEY>END_PI' # gplus user object props to userPropsToSave = 'name.givenName': 'PI:NAME:<NAME>END_PI' 'name.familyName': 'PI:NAME:<NAME>END_PI' 'gender': 'gender' 'id': 'gplusID' fieldsToFetch = 'displayName,gender,image,name(familyName,givenName),id' plusURL = '/plus/v1/people/me?fields='+fieldsToFetch revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' clientID = '800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com' scope = 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' module.exports = GPlusHandler = class GPlusHandler extends CocoClass constructor: -> @accessToken = storage.load GPLUS_TOKEN_KEY super() subscriptions: 'gplus-logged-in':'onGPlusLogin' 'gapi-loaded':'onGPlusLoaded' onGPlusLoaded: -> session_state = null if @accessToken # We need to check the current state, given our access token gapi.auth.setToken 'token', @accessToken session_state = @accessToken.session_state gapi.auth.checkSessionState({client_id: clientID, session_state: session_state}, @onCheckedSessionState) else # If we ran checkSessionState, it might return true, that the user is logged into Google, but has not authorized us @loggedIn = false func = => @trigger 'checked-state' setTimeout func, 1 onCheckedSessionState: (@loggedIn) => @trigger 'checked-state' reauthorize: -> params = 'client_id' : clientID 'scope' : scope gapi.auth.authorize params, @onGPlusLogin onGPlusLogin: (e) => @loggedIn = true storage.save(GPLUS_TOKEN_KEY, e) @accessToken = e @trigger 'logged-in' return if (not me) or me.get 'gplusID' # so only get more data # email and profile data loaded separately @responsesComplete = 0 gapi.client.request(path: plusURL, callback: @onPersonEntityReceived) gapi.client.load('oauth2', 'v2', => gapi.client.oauth2.userinfo.get().execute(@onEmailReceived)) shouldSave: false responsesComplete: 0 onPersonEntityReceived: (r) => for gpProp, userProp of userPropsToSave keys = gpPI:KEY:<KEY>END_PI('.') value = r value = value[key] for key in keys if value and not me.get(userProp) @shouldSave = true me.set(userProp, value) @responsesComplete += 1 @saveIfAllDone() onEmailReceived: (r) => newEmail = r.email and r.email isnt me.get('email') return unless newEmail or me.get('anonymous') me.set('email', r.email) @shouldSave = true @responsesComplete += 1 @saveIfAllDone() saveIfAllDone: => return unless @responsesComplete is 2 return unless me.get('email') and me.get('gplusID') Backbone.Mediator.publish('logging-in-with-gplus') gplusID = me.get('gplusID') window.tracker?.trackEvent 'Google Login' window.tracker?.identify() patch = {} patch[key] = me.get(key) for gplusKey, key of userPropsToSave patch._id = me.id patch.email = me.get('email') wasAnonymous = me.get('anonymous') me.save(patch, { patch: true error: backboneFailure, url: "/db/user?gplusID=#{gplusID}&gplusAccessToken=#{@accessToken.access_token}" success: (model) -> window.location.reload() if wasAnonymous and not model.get('anonymous') }) loadFriends: (friendsCallback) -> return friendsCallback() unless @loggedIn expiresIn = if @accessToken then parseInt(@accessToken.expires_at) - new Date().getTime()/1000 else -1 onReauthorized = => gapi.client.request({path: '/plus/v1/people/me/people/visible', callback: friendsCallback}) if expiresIn < 0 # TODO: this tries to open a popup window, which might not ever finish or work, so the callback may never be called. @reauthorize() @listenToOnce(@, 'logged-in', onReauthorized) else onReauthorized()
[ { "context": " \n if options.tag\n host = '0.0.0.0'\n port = 80\n opts =\n ", "end": 1899, "score": 0.9996561408042908, "start": 1892, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "entials\n options.user = c...
src/commands.coffee
mobify/mobify-client
4
FS = require 'fs' Path = require 'path' HTTPS = require 'https' program = require 'commander' Async = require 'async' Wrench = require 'wrench' {appSourceDir} = require '../lib/pathUtils' {Project} = require './project.coffee' Injector = require './injector.coffee' Preview = require './preview.coffee' Scaffold = require './scaffold.coffee' Utils = require './utils' Errors = require './errors' exports.init = init = (project_name, options, callback) -> Scaffold.generate(project_name, options.directory, callback) exports.preview = preview = (options) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find your project. Make sure you are inside your project folder." console.log "Visit https://cloud.mobify.com/docs/ for more information.\n" console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error to https://cloud.mobify.com/support/\n" console.log err.stack return environment = project.getEnv() if options.minify environment.production = true key = FS.readFileSync(Path.join appSourceDir, 'vendor', 'certs', 'server.key') cert = FS.readFileSync(Path.join appSourceDir, 'vendor', 'certs', 'server.crt') opts = key: key cert: cert httpServer = Preview.createServer environment httpsServer = Preview.createServer environment, opts httpServer.listen options.port, options.address httpsServer.listen options.sslPort, options.address console.log "Running Preview at address #{options.address} and port #{options.port}/#{options.sslPort}" if options.tag host = '0.0.0.0' port = 80 opts = tag_version: options.tagVersion server = Injector.createServer opts server.listen port, host console.log "Running Tag at http://#{host}:#{port}/" port = 443 opts.port = port opts.key = key opts.cert = cert opts.proxy_module = HTTPS opts.server = Injector.HttpsServer server = Injector.createServer opts server.listen port, host console.log "Running Tag at https://#{host}:#{port}/" console.log "Press <CTRL-C> to terminate." exports.push = push = (options) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find project.json. Ensure you are working inside the project folder." console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error at https://support.mobify.com/\n" console.log err.stack return options.upload = true do_it = (err, credentials) -> if err console.log err return if credentials options.user = credentials.user options.password = credentials.password project.build options, (err, url, body) -> if Utils.pathExistsSync project.build_directory console.log "Removing #{project.build_directory}" Wrench.rmdirSyncRecursive project.build_directory if err console.log err process.exit 1 return console.log "Bundle Uploaded." if body and body.message console.log body.message if options.auth [user, password] = options.auth.split ':' credentials = user: user password: password do_it null, credentials else getCredentials do_it exports.build = build = (options, callback) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find project.json. Ensure you are working inside the project folder." console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error at https://support.mobify.com/\n" console.log err.stack return options.upload = false project.build options, (err, url, body) -> if err console.log err process.exit 1 return console.log "Project built successfully in #{url}/" if callback callback() exports.login = (options, callback) -> save_credentials = (username, api_key) -> Utils.getGlobalSettings (err, settings) -> settings.username = username settings.api_key = api_key Utils.setGlobalSettings settings, (err) -> if err console.log err console.log "Credentials saved to: #{Utils.getGlobalSettingsPath()}" if callback callback() if options.auth [username, api_key] = options.auth.split ':' save_credentials username, api_key else promptCredentials (err, username, api_key) -> if err console.log err return save_credentials username, api_key getCredentials = (callback) -> Utils.getGlobalSettings (err, settings) -> if err callback err else if settings.username and settings.api_key console.log "Using saved credentials: #{settings.username}" callback null, user: settings.username, password: settings.api_key else promptCredentials (err, username, api_key) -> if err callback err return callback null, user: username, password: api_key promptCredentials = (callback) -> promptUsername = (callback) -> program.prompt "Username: ", (input) -> if not input callback new Error("Username must not be blank.") return callback null, input promptKey = (callback) -> program.prompt "API Key: ", (input) -> if not input callback new Error("API Key must not be blank.") return callback null, input Async.series [promptUsername, promptKey], (err, results) -> if err callback err return [username, api_key] = results callback null, username, api_key process.stdin.pause() # Destroy stdin otherwise Node will hang out for ever. # This is fixing in 0.6.12, and we won't have to destroy it explicitly. # Which means we can read from it later, at this time # once it's destroyed, it's gone. process.stdin.destroy()
100690
FS = require 'fs' Path = require 'path' HTTPS = require 'https' program = require 'commander' Async = require 'async' Wrench = require 'wrench' {appSourceDir} = require '../lib/pathUtils' {Project} = require './project.coffee' Injector = require './injector.coffee' Preview = require './preview.coffee' Scaffold = require './scaffold.coffee' Utils = require './utils' Errors = require './errors' exports.init = init = (project_name, options, callback) -> Scaffold.generate(project_name, options.directory, callback) exports.preview = preview = (options) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find your project. Make sure you are inside your project folder." console.log "Visit https://cloud.mobify.com/docs/ for more information.\n" console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error to https://cloud.mobify.com/support/\n" console.log err.stack return environment = project.getEnv() if options.minify environment.production = true key = FS.readFileSync(Path.join appSourceDir, 'vendor', 'certs', 'server.key') cert = FS.readFileSync(Path.join appSourceDir, 'vendor', 'certs', 'server.crt') opts = key: key cert: cert httpServer = Preview.createServer environment httpsServer = Preview.createServer environment, opts httpServer.listen options.port, options.address httpsServer.listen options.sslPort, options.address console.log "Running Preview at address #{options.address} and port #{options.port}/#{options.sslPort}" if options.tag host = '0.0.0.0' port = 80 opts = tag_version: options.tagVersion server = Injector.createServer opts server.listen port, host console.log "Running Tag at http://#{host}:#{port}/" port = 443 opts.port = port opts.key = key opts.cert = cert opts.proxy_module = HTTPS opts.server = Injector.HttpsServer server = Injector.createServer opts server.listen port, host console.log "Running Tag at https://#{host}:#{port}/" console.log "Press <CTRL-C> to terminate." exports.push = push = (options) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find project.json. Ensure you are working inside the project folder." console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error at https://support.mobify.com/\n" console.log err.stack return options.upload = true do_it = (err, credentials) -> if err console.log err return if credentials options.user = credentials.user options.password = <PASSWORD> project.build options, (err, url, body) -> if Utils.pathExistsSync project.build_directory console.log "Removing #{project.build_directory}" Wrench.rmdirSyncRecursive project.build_directory if err console.log err process.exit 1 return console.log "Bundle Uploaded." if body and body.message console.log body.message if options.auth [user, password] = options.auth.split ':' credentials = user: user password: <PASSWORD> do_it null, credentials else getCredentials do_it exports.build = build = (options, callback) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find project.json. Ensure you are working inside the project folder." console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error at https://support.mobify.com/\n" console.log err.stack return options.upload = false project.build options, (err, url, body) -> if err console.log err process.exit 1 return console.log "Project built successfully in #{url}/" if callback callback() exports.login = (options, callback) -> save_credentials = (username, api_key) -> Utils.getGlobalSettings (err, settings) -> settings.username = username settings.api_key = api_key Utils.setGlobalSettings settings, (err) -> if err console.log err console.log "Credentials saved to: #{Utils.getGlobalSettingsPath()}" if callback callback() if options.auth [username, api_key] = options.auth.split ':' save_credentials username, api_key else promptCredentials (err, username, api_key) -> if err console.log err return save_credentials username, api_key getCredentials = (callback) -> Utils.getGlobalSettings (err, settings) -> if err callback err else if settings.username and settings.api_key console.log "Using saved credentials: #{settings.username}" callback null, user: settings.username, password: settings.api_key else promptCredentials (err, username, api_key) -> if err callback err return callback null, user: username, password: api_key promptCredentials = (callback) -> promptUsername = (callback) -> program.prompt "Username: ", (input) -> if not input callback new Error("Username must not be blank.") return callback null, input promptKey = (callback) -> program.prompt "API Key: ", (input) -> if not input callback new Error("API Key must not be blank.") return callback null, input Async.series [promptUsername, promptKey], (err, results) -> if err callback err return [username, api_key] = results callback null, username, api_key process.stdin.pause() # Destroy stdin otherwise Node will hang out for ever. # This is fixing in 0.6.12, and we won't have to destroy it explicitly. # Which means we can read from it later, at this time # once it's destroyed, it's gone. process.stdin.destroy()
true
FS = require 'fs' Path = require 'path' HTTPS = require 'https' program = require 'commander' Async = require 'async' Wrench = require 'wrench' {appSourceDir} = require '../lib/pathUtils' {Project} = require './project.coffee' Injector = require './injector.coffee' Preview = require './preview.coffee' Scaffold = require './scaffold.coffee' Utils = require './utils' Errors = require './errors' exports.init = init = (project_name, options, callback) -> Scaffold.generate(project_name, options.directory, callback) exports.preview = preview = (options) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find your project. Make sure you are inside your project folder." console.log "Visit https://cloud.mobify.com/docs/ for more information.\n" console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error to https://cloud.mobify.com/support/\n" console.log err.stack return environment = project.getEnv() if options.minify environment.production = true key = FS.readFileSync(Path.join appSourceDir, 'vendor', 'certs', 'server.key') cert = FS.readFileSync(Path.join appSourceDir, 'vendor', 'certs', 'server.crt') opts = key: key cert: cert httpServer = Preview.createServer environment httpsServer = Preview.createServer environment, opts httpServer.listen options.port, options.address httpsServer.listen options.sslPort, options.address console.log "Running Preview at address #{options.address} and port #{options.port}/#{options.sslPort}" if options.tag host = '0.0.0.0' port = 80 opts = tag_version: options.tagVersion server = Injector.createServer opts server.listen port, host console.log "Running Tag at http://#{host}:#{port}/" port = 443 opts.port = port opts.key = key opts.cert = cert opts.proxy_module = HTTPS opts.server = Injector.HttpsServer server = Injector.createServer opts server.listen port, host console.log "Running Tag at https://#{host}:#{port}/" console.log "Press <CTRL-C> to terminate." exports.push = push = (options) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find project.json. Ensure you are working inside the project folder." console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error at https://support.mobify.com/\n" console.log err.stack return options.upload = true do_it = (err, credentials) -> if err console.log err return if credentials options.user = credentials.user options.password = PI:PASSWORD:<PASSWORD>END_PI project.build options, (err, url, body) -> if Utils.pathExistsSync project.build_directory console.log "Removing #{project.build_directory}" Wrench.rmdirSyncRecursive project.build_directory if err console.log err process.exit 1 return console.log "Bundle Uploaded." if body and body.message console.log body.message if options.auth [user, password] = options.auth.split ':' credentials = user: user password: PI:PASSWORD:<PASSWORD>END_PI do_it null, credentials else getCredentials do_it exports.build = build = (options, callback) -> try project = Project.load() catch err if err instanceof Errors.ProjectFileNotFound console.log "Could not find project.json. Ensure you are working inside the project folder." console.log err.toString() else console.log "Unexpected Error." console.log "Please report this error at https://support.mobify.com/\n" console.log err.stack return options.upload = false project.build options, (err, url, body) -> if err console.log err process.exit 1 return console.log "Project built successfully in #{url}/" if callback callback() exports.login = (options, callback) -> save_credentials = (username, api_key) -> Utils.getGlobalSettings (err, settings) -> settings.username = username settings.api_key = api_key Utils.setGlobalSettings settings, (err) -> if err console.log err console.log "Credentials saved to: #{Utils.getGlobalSettingsPath()}" if callback callback() if options.auth [username, api_key] = options.auth.split ':' save_credentials username, api_key else promptCredentials (err, username, api_key) -> if err console.log err return save_credentials username, api_key getCredentials = (callback) -> Utils.getGlobalSettings (err, settings) -> if err callback err else if settings.username and settings.api_key console.log "Using saved credentials: #{settings.username}" callback null, user: settings.username, password: settings.api_key else promptCredentials (err, username, api_key) -> if err callback err return callback null, user: username, password: api_key promptCredentials = (callback) -> promptUsername = (callback) -> program.prompt "Username: ", (input) -> if not input callback new Error("Username must not be blank.") return callback null, input promptKey = (callback) -> program.prompt "API Key: ", (input) -> if not input callback new Error("API Key must not be blank.") return callback null, input Async.series [promptUsername, promptKey], (err, results) -> if err callback err return [username, api_key] = results callback null, username, api_key process.stdin.pause() # Destroy stdin otherwise Node will hang out for ever. # This is fixing in 0.6.12, and we won't have to destroy it explicitly. # Which means we can read from it later, at this time # once it's destroyed, it's gone. process.stdin.destroy()
[ { "context": "sable?.dispose()\n commands = {}\n\n allKey = \"window:select-account-0\"\n commands[allKey] = @_focusAccounts.bind(@, a", "end": 638, "score": 0.9987363815307617, "start": 615, "tag": "KEY", "value": "window:select-account-0" }, { "context": "dex - 1]\n r...
app/internal_packages/account-sidebar/lib/account-commands.coffee
immershy/nodemail
0
_ = require 'underscore' {AccountStore, MenuHelpers} = require 'nylas-exports' SidebarActions = require './sidebar-actions' class AccountCommands @_focusAccounts: (accounts) -> SidebarActions.focusAccounts(accounts) NylasEnv.show() unless NylasEnv.isVisible() @_isSelected: (account, focusedAccounts) => if focusedAccounts.length > 1 return account instanceof Array else if focusedAccounts.length is 1 return account?.id is focusedAccounts[0].id else return false @registerCommands: (accounts) -> @_commandsDisposable?.dispose() commands = {} allKey = "window:select-account-0" commands[allKey] = @_focusAccounts.bind(@, accounts) [1..8].forEach (index) => account = accounts[index - 1] return unless account key = "window:select-account-#{index}" commands[key] = @_focusAccounts.bind(@, [account]) @_commandsDisposable = NylasEnv.commands.add(document.body, commands) @registerMenuItems: (accounts, focusedAccounts) -> windowMenu = _.find NylasEnv.menu.template, ({label}) -> MenuHelpers.normalizeLabel(label) is 'Window' return unless windowMenu submenu = _.reject windowMenu.submenu, (item) -> item.account return unless submenu idx = _.findIndex submenu, ({type}) -> type is 'separator' return unless idx > 0 template = @menuTemplate(accounts, focusedAccounts) submenu.splice(idx + 1, 0, template...) windowMenu.submenu = submenu NylasEnv.menu.update() @menuItem: (account, idx, {isSelected, clickHandlers} = {}) => item = { label: account.label ? "All Accounts", command: "window:select-account-#{idx}", account: true } if isSelected item.type = 'checkbox' item.checked = true if clickHandlers accounts = if account instanceof Array then account else [account] item.click = @_focusAccounts.bind(@, accounts) item.accelerator = "CmdOrCtrl+#{idx + 1}" return item @menuTemplate: (accounts, focusedAccounts, {clickHandlers} = {}) => template = [] multiAccount = accounts.length > 1 if multiAccount isSelected = @_isSelected(accounts, focusedAccounts) template = [ @menuItem(accounts, 0, {isSelected, clickHandlers}) ] template = template.concat accounts.map((account, idx) => # If there's only one account, it should be mapped to command+1, not command+2 accIdx = if multiAccount then idx + 1 else idx isSelected = @_isSelected(account, focusedAccounts) return @menuItem(account, accIdx, {isSelected, clickHandlers}) ) return template @register: (accounts, focusedAccounts) -> @registerCommands(accounts) @registerMenuItems(accounts, focusedAccounts) module.exports = AccountCommands
17117
_ = require 'underscore' {AccountStore, MenuHelpers} = require 'nylas-exports' SidebarActions = require './sidebar-actions' class AccountCommands @_focusAccounts: (accounts) -> SidebarActions.focusAccounts(accounts) NylasEnv.show() unless NylasEnv.isVisible() @_isSelected: (account, focusedAccounts) => if focusedAccounts.length > 1 return account instanceof Array else if focusedAccounts.length is 1 return account?.id is focusedAccounts[0].id else return false @registerCommands: (accounts) -> @_commandsDisposable?.dispose() commands = {} allKey = "<KEY>" commands[allKey] = @_focusAccounts.bind(@, accounts) [1..8].forEach (index) => account = accounts[index - 1] return unless account key = "<KEY> commands[key] = @_focusAccounts.bind(@, [account]) @_commandsDisposable = NylasEnv.commands.add(document.body, commands) @registerMenuItems: (accounts, focusedAccounts) -> windowMenu = _.find NylasEnv.menu.template, ({label}) -> MenuHelpers.normalizeLabel(label) is 'Window' return unless windowMenu submenu = _.reject windowMenu.submenu, (item) -> item.account return unless submenu idx = _.findIndex submenu, ({type}) -> type is 'separator' return unless idx > 0 template = @menuTemplate(accounts, focusedAccounts) submenu.splice(idx + 1, 0, template...) windowMenu.submenu = submenu NylasEnv.menu.update() @menuItem: (account, idx, {isSelected, clickHandlers} = {}) => item = { label: account.label ? "All Accounts", command: "window:select-account-#{idx}", account: true } if isSelected item.type = 'checkbox' item.checked = true if clickHandlers accounts = if account instanceof Array then account else [account] item.click = @_focusAccounts.bind(@, accounts) item.accelerator = "CmdOrCtrl+#{idx + 1}" return item @menuTemplate: (accounts, focusedAccounts, {clickHandlers} = {}) => template = [] multiAccount = accounts.length > 1 if multiAccount isSelected = @_isSelected(accounts, focusedAccounts) template = [ @menuItem(accounts, 0, {isSelected, clickHandlers}) ] template = template.concat accounts.map((account, idx) => # If there's only one account, it should be mapped to command+1, not command+2 accIdx = if multiAccount then idx + 1 else idx isSelected = @_isSelected(account, focusedAccounts) return @menuItem(account, accIdx, {isSelected, clickHandlers}) ) return template @register: (accounts, focusedAccounts) -> @registerCommands(accounts) @registerMenuItems(accounts, focusedAccounts) module.exports = AccountCommands
true
_ = require 'underscore' {AccountStore, MenuHelpers} = require 'nylas-exports' SidebarActions = require './sidebar-actions' class AccountCommands @_focusAccounts: (accounts) -> SidebarActions.focusAccounts(accounts) NylasEnv.show() unless NylasEnv.isVisible() @_isSelected: (account, focusedAccounts) => if focusedAccounts.length > 1 return account instanceof Array else if focusedAccounts.length is 1 return account?.id is focusedAccounts[0].id else return false @registerCommands: (accounts) -> @_commandsDisposable?.dispose() commands = {} allKey = "PI:KEY:<KEY>END_PI" commands[allKey] = @_focusAccounts.bind(@, accounts) [1..8].forEach (index) => account = accounts[index - 1] return unless account key = "PI:KEY:<KEY>END_PI commands[key] = @_focusAccounts.bind(@, [account]) @_commandsDisposable = NylasEnv.commands.add(document.body, commands) @registerMenuItems: (accounts, focusedAccounts) -> windowMenu = _.find NylasEnv.menu.template, ({label}) -> MenuHelpers.normalizeLabel(label) is 'Window' return unless windowMenu submenu = _.reject windowMenu.submenu, (item) -> item.account return unless submenu idx = _.findIndex submenu, ({type}) -> type is 'separator' return unless idx > 0 template = @menuTemplate(accounts, focusedAccounts) submenu.splice(idx + 1, 0, template...) windowMenu.submenu = submenu NylasEnv.menu.update() @menuItem: (account, idx, {isSelected, clickHandlers} = {}) => item = { label: account.label ? "All Accounts", command: "window:select-account-#{idx}", account: true } if isSelected item.type = 'checkbox' item.checked = true if clickHandlers accounts = if account instanceof Array then account else [account] item.click = @_focusAccounts.bind(@, accounts) item.accelerator = "CmdOrCtrl+#{idx + 1}" return item @menuTemplate: (accounts, focusedAccounts, {clickHandlers} = {}) => template = [] multiAccount = accounts.length > 1 if multiAccount isSelected = @_isSelected(accounts, focusedAccounts) template = [ @menuItem(accounts, 0, {isSelected, clickHandlers}) ] template = template.concat accounts.map((account, idx) => # If there's only one account, it should be mapped to command+1, not command+2 accIdx = if multiAccount then idx + 1 else idx isSelected = @_isSelected(account, focusedAccounts) return @menuItem(account, accIdx, {isSelected, clickHandlers}) ) return template @register: (accounts, focusedAccounts) -> @registerCommands(accounts) @registerMenuItems(accounts, focusedAccounts) module.exports = AccountCommands
[ { "context": "scribe \"basic redis functioniality\", ->\n\t\tp = \"deltest\"\n\t\td = \"hejejee\"\n\t\tdescribe \"pset\", ->\n\t\t\tit \"sho", "end": 1224, "score": 0.7224403619766235, "start": 1220, "tag": "USERNAME", "value": "test" }, { "context": "\" }\n\t\t\t{ host: \"localhos...
test/RedisPort_test.coffee
viriciti/redis-port
2
_ = require "underscore" async = require "async" assert = require "assert" RedisPort = require "../src/RedisPort" newClient = (p, id, cb) -> p or= "undisclosed#{Math.round Math.random() * 100}" rpc = new RedisPort redisHost: "localhost" redisPort: 6379 host: "localhost" project: p env: "development" , id rpc.start -> cb rpc client = null describe "Unit", -> describe "stop when not started", -> it "should stop anyway", (done) -> client = new RedisPort redisHost: "localhost" # redisPort: 6380 redisPort: 6380 project: "vems" env: "production" host: "localhost" client.stop -> done() describe "not running", -> it "should wait or retry", (done) -> client = new RedisPort redisHost: "localhost" # redisPort: 6380 redisPort: 6380 project: "vems" env: "production" host: "localhost" count = 0 client.on "reconnect", -> if ++count is 3 client.stop() done() client.start() describe "connect to runnning service", -> it "should connect", (done) -> newClient null, null, (c) -> client = c done() describe "basic redis functioniality", -> p = "deltest" d = "hejejee" describe "pset", -> it "should work", (done) -> client.pset p, d, (error) -> throw error if error done() describe "pmset", -> it "should work", (done) -> client.mpset [ ["jo", "ja"] ["je", "ho"] ["li", "lo"] ], (error) -> throw error if error done() describe "list", -> it "should list", (done) -> client.list "", (error, list) -> throw error if error async.each ["li", "je", "jo", "deltest"], ((el, cb) -> assert el in list cb() ), (error) -> throw error if error done() describe "get", -> it "existant get", (done) -> client.get p, (error, data) -> throw error if error assert data, d done() describe "del", -> it "existant", (done) -> client.del p, (error) -> throw error if error done() it "non-existant", (done) -> client.del p, (error) -> throw error if error done() describe "mdel", -> it "should do it", (done) -> client.mdel ["li", "je", "jo", "deltest"], (error) -> throw error if error done() describe "get", -> it "non-existant get", (done) -> client.get p, (error, data) -> throw error if error assert.equal data, null done() describe "recursive delete a list", -> path = "jahah" before (done) -> async.each [ "#{path}/je-vader" "#{path}/je-moeder" "#{path}/je-moeder/hihih" "#{path}/je-moeder/lalala" "#{path}" "#{path}/je-moeder/lalala/jan" "#{path}/hersen" "#{path}/hersen/hans" ], ((p, cb) -> client.pset p, "some data", cb), (error) -> throw error if error done() it "should delete recursively", (done) -> client.del path, (error) -> throw error if error done() describe "recursive delete an awkward list", -> path = "jahah" paths = [ path "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/bla/lalala/jan" "#{path}/sd" "#{path}/adsf" "#{path}/sdas/asdfasdf/asd" "#{path}/jo/mamma/hake" "#{path}/sd/asdf" "#{path}/hehehe/ja-toch/das-gek" "#{path}/hehehe" ] it "do it", (done) -> async.each paths, ((p, cb) -> client.pset p, "some data", cb), (error) -> throw error if error client.del path, (error) -> throw error if error done() describe "ephemeral storage", -> before (done) -> client = new RedisPort redisHost: "localhost" redisPort: 6379 host: "localhost" project: "hmmbob" env: "development" ephemeralExpire: 150 ephemeralRefresh: 100 client.start -> done() describe "set", -> it "should set a key and update the expired flag", (done) -> client.set "some", "data", (error) -> throw error if error done() describe "delete", -> it "should be deleted without an error and delete the timeout", (done) -> setTimeout -> client.del "some", (error) -> throw error if error client.get "some", (error, data) -> throw error if error assert.equal null, data done() , 10 client.get "some", (error, data) -> throw error if error assert data describe "reconnect", -> ephemerals = [ ["someWhere", "a"] ["someHere", "b"] ["someThere", "c"] ] describe "all ephemeral is gone", -> it "set some last ephemerals", (done) -> client.mset ephemerals, (error) -> client.list "", (error, list) -> throw error if error async.each ["someWhere", "someHere", "someThere"], ((el, cb) -> assert el in list cb() ), (error) -> throw error if error done() it "new client", (done) -> client.on "stopped", -> newClient null, null, (c) -> client = c done() client.stop() it "list", (done) -> client.list "", (error, list) -> for e in ephemerals assert e[0] not in list done() describe "services", -> before (done) -> client.on "stopped", -> newClient null, null, (c) -> client = c setTimeout -> done() , 1000 client.stop() services = [ { host: "leo", port: 20000, role: "bla" } { host: "fatima", port: 20000, role: "blaiep" } { host: "localhost", port: 20000, role: "jan" } { host: "localhost", port: 30000, role: "hans" } { host: "localhost", port: 40000, role: "ferry" } ] describe "get ports - filled", -> it "first set some data", (done) -> async.each services, ((s, cb) -> client.set "services/#{s.role}", s, cb ), (error) -> client.list "services", (error, list) -> throw error if error async.each services.map((s) -> s.role), ((role, cb) -> assert "services/#{role}" in list cb() ), (error) -> throw error if error done() it "get services", (done) -> client.getServices (error, list) -> throw error if error async.each services.map((s) -> s.role), ((role, cb) -> assert role in list.map((s) -> s.role) cb() ), (error) -> throw error if error done() it "should get the services ports (filled)", (done) -> client.getPorts (error, ports) -> throw error if error throw error if error async.each [20000, 30000, 40000], ((port, cb) -> assert port in ports cb() ), (error) -> throw error if error done() describe "register a service by role", -> it "should register a service by name", (done) -> client.register "some-unique-service", (error, port) -> throw error if error client.getPorts (error, ports) -> return error if error assert port in ports assert not (port in services.map (s) -> s.port) done() it "should register a service by object twice - no force port", (done) -> client.register role: "queue1" host: "natje", port: 5000 , (error, port) -> throw error if error client.register role: "queue2" host: "natje", port: 5000 , (error, port) -> client.getServices (error, list) -> assert.equal 1, (_.filter list, (s) -> s.port is 5000).length done() it "should register a service by object twice - with force port", (done) -> client.register role: "queue1" host: "natje", port: 5001 , true , (error, port) -> throw error if error client.register role: "queue2" host: "natje", port: 5001 , true , (error, port) -> client.getServices (error, list) -> assert.equal 2, (_.filter list, (s) -> s.port is 5001).length done() it "should be listed with a wildcard", (done) -> client.getServices "some", (error, services) -> throw error if error assert services.length assert.equal "some-unique-service", services[0].role done() describe "Query tests", -> it "Query with a non exsisting role, should not trigger onData", (done) -> count = 0 client.query "GekkeGerrit", (data) -> assert data done() if ++count is 1 client.register "GekkeGerrit", (error, port) -> throw error if error it "Query and free", (done) -> count = 0 client.query "Harry", ((data) -> client.free "Harry", (error, service) -> throw error if error assert.equal "Harry", service.role ), (data) -> done() if ++count is 1 client.register "Harry", (error, port) -> throw error if error it "Query and free - wildcard", (done) -> roles = ["Harry-1", "Harry-2", "Harry-3"] count = 0 client.query "Harry*", ((data) -> client.free "Harry*", (error, service) -> throw error if error ), (role) -> assert role in roles done() if ++count is 3 async.each roles, ((role, cb) -> client.register role, (error, port) -> throw error if error ) it "should trigger onData 4 times after issueing a single query", (done) -> @timeout 100000 role = "web" count = 0 onData = (service) -> assert service.role is "web" assert service.host is "localhost" done() if count++ is 4 client.query role, onData functions = for i in [1..5] (cb) -> client.register role, (error, port) -> return cb error if error setTimeout cb, 100 async.series functions, (error) -> throw error if error it "should trigger a wildcard - existing services", (done) -> services = [ "listener-hy_001-raw" "listener-hy_002-raw" "listener-hy_003-raw" ] async.map services, ((role, cb) -> client.register role, cb), (error, ports) -> throw error if error assert.equal 3, ports.length count = 0 timeout = null client.query "listener*", (service) -> assert (service.role in services) done() if ++count is 3 it "should trigger a wildcard - existing and added services", (done) -> async.map ["1", "2", "3"], ((vid, cb) -> client.register "bladieblaat-#{vid}", cb ), (error, ports) -> throw error if error assert.equal 3, ports.length count = 0 client.query "bladieblaat*", (service) -> assert 0 is service.role.indexOf "bladieblaat" done() if ++count is 6 async.map ["4", "5", "6"], ((vid, cb) -> client.register "bladieblaat-#{vid}", cb ), (error, ports) -> throw error if error assert.equal 3, ports.length describe "2 clients on the same project", -> it "should get notified of each others registerd services", (done) -> newClient "same-project", "client-a", (clientA) -> newClient "same-project", "client-b", (clientB) -> clientA.query "spawner*", (service) -> assert service assert.equal "spawner-hy_001-raw", service.role clientA.stop -> done() clientB.register "spawner-hy_001-raw", (error, port) -> throw error if error describe "2 clients on one redis-port host", -> describe "two seperate clients should not interfere", -> it "create services on client1", (done) -> wildcard = "bladiebap" vids = ["yoy_001", "yoy_002", "yoy_003"] count = 0 onRegister1 = (p) -> done() if ++count is 3 onRegister2 = -> throw new Error "Callback of client 2 was called!" newClient "nice-project-1", "client1", (c) -> client1 = c client1.getServices (error, list) -> throw error if error client1.del "services", (error) -> throw error if error newClient "nice-project-2", "client2", (c) -> client2 = c client1.query "#{wildcard}*", onRegister1 client2.query "#{wildcard}*", onRegister2 async.map vids, ((vid, cb) -> client1.register "#{wildcard}-#{vid}-raw", cb ), (error, ports) -> throw error if error describe 'queues', -> queue = "testlist" rpc = null beforeEach (done) -> newClient "nice-project-1", "client1", (c) -> rpc = c rpc.clearQueue queue, (error) -> throw error if error done() afterEach (done) -> rpc.clearQueue queue, (error) -> throw error if error done() describe "size", -> it 'should return the initial length of the redis enqueue which is zero', (done) -> rpc.queueLength queue, (err, size) -> assert.equal size, 0 done() describe 'enqueue', -> it 'should enqueue 10 items and return length of 10', (done) -> llen = 0 async.eachSeries [1..10], (i, cb) -> rpc.enqueue queue, "sasads", (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal 10, llen done() it 'should enqueue 10 items in expected order', (done) -> async.eachSeries [0..10], ((i, cb) -> rpc.enqueue queue, JSON.stringify({i: i, c: i}), cb ), -> path = rpc._cleanPath "queues/#{queue}" rpc.client.lrange rpc._cleanPath("queues/#{queue}"), 0, 10, (error, arr) -> assert.equal "#{arr.join(",")}", '{"i":10,"c":10},{"i":9,"c":9},{"i":8,"c":8},{"i":7,"c":7},{"i":6,"c":6},{"i":5,"c":5},{"i":4,"c":4},{"i":3,"c":3},{"i":2,"c":2},{"i":1,"c":1},{"i":0,"c":0}' done() it 'should enqueue 10 items and dequeue in expected order', (done) -> async.eachSeries [0..20], ((i, cb) -> rpc.enqueue queue, JSON.stringify({i: i, c: i}), cb ), -> arr = [] async.eachSeries [0..10], ((i, cb) -> rpc.dequeue queue, (error, msg) -> arr.push msg cb() ), -> assert.equal "#{arr.join(",")}", '{"i":0,"c":0},{"i":1,"c":1},{"i":2,"c":2},{"i":3,"c":3},{"i":4,"c":4},{"i":5,"c":5},{"i":6,"c":6},{"i":7,"c":7},{"i":8,"c":8},{"i":9,"c":9},{"i":10,"c":10}' done() describe 'dequeue', -> it 'should enqueue and dequeue 10 items and return length of 0', (done) -> @timeout 10000 llen = 0 amount = 1000 async.eachSeries [1..amount], (i, cb) -> rpc.enqueue queue, JSON.stringify({ha: "sdfsdsdfsdf", d: "sdfsdfsdfsdfsdf", t: 12321321354}), (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal amount, llen async.eachSeries [1..amount], (i, cb) -> rpc.dequeue queue, (err, msg) -> throw err if err llen-- cb() , -> assert.equal llen, 0 done() describe 'maxlength', -> it 'should not go over max length', (done) -> @timeout 10000 rpc.queueMaxLength = 10 llen = 0 async.eachSeries [1..1000], (i, cb) -> rpc.enqueue queue, JSON.stringify({ha: "sdfsdsdfsdf", d: "sdfsdfsdfsdfsdf", t: 1000000 + i}), (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal llen, 10 msg = null async.eachSeries [1..10], (i, cb) -> rpc.dequeue queue, (err, m) -> throw err if err llen-- msg = m cb() , -> assert.equal llen, 0 assert.equal 1001000, JSON.parse(msg).t done() describe "missed", -> rpc = null before (done) -> newClient "hellep", "hellep", (c) -> rpc = c rpc.missedLength = 10 done() it "should emit missed on log", (done) -> rpc.once "missed", (p, info) -> done() rpc.logMissed "boe!" it "should have missed length on log", (done) -> list = rpc._cleanPath "missed" rpc.once "missed", (p, info) -> rpc.client.lpop list, (error, info) -> assert.equal (JSON.parse info)?.path, "boe!" done() rpc.logMissed "boe!" it "should have trim on max length", (done) -> list = rpc._cleanPath "missed" count = 0 handleMissed = (p, info) -> return if ++count isnt 20 rpc.removeListener "missed", handleMissed setTimeout -> rpc.client.llen list, (error, l) -> assert.equal l, 10 rpc.client.lpop list, (error, info) -> assert.equal (JSON.parse info)?.path, rpc._cleanPath "boe!-20" done() , 400 rpc.on "missed", handleMissed async.each [0..20], (i, cb) -> rpc.get "boe!-#{i}", cb
29618
_ = require "underscore" async = require "async" assert = require "assert" RedisPort = require "../src/RedisPort" newClient = (p, id, cb) -> p or= "undisclosed#{Math.round Math.random() * 100}" rpc = new RedisPort redisHost: "localhost" redisPort: 6379 host: "localhost" project: p env: "development" , id rpc.start -> cb rpc client = null describe "Unit", -> describe "stop when not started", -> it "should stop anyway", (done) -> client = new RedisPort redisHost: "localhost" # redisPort: 6380 redisPort: 6380 project: "vems" env: "production" host: "localhost" client.stop -> done() describe "not running", -> it "should wait or retry", (done) -> client = new RedisPort redisHost: "localhost" # redisPort: 6380 redisPort: 6380 project: "vems" env: "production" host: "localhost" count = 0 client.on "reconnect", -> if ++count is 3 client.stop() done() client.start() describe "connect to runnning service", -> it "should connect", (done) -> newClient null, null, (c) -> client = c done() describe "basic redis functioniality", -> p = "deltest" d = "hejejee" describe "pset", -> it "should work", (done) -> client.pset p, d, (error) -> throw error if error done() describe "pmset", -> it "should work", (done) -> client.mpset [ ["jo", "ja"] ["je", "ho"] ["li", "lo"] ], (error) -> throw error if error done() describe "list", -> it "should list", (done) -> client.list "", (error, list) -> throw error if error async.each ["li", "je", "jo", "deltest"], ((el, cb) -> assert el in list cb() ), (error) -> throw error if error done() describe "get", -> it "existant get", (done) -> client.get p, (error, data) -> throw error if error assert data, d done() describe "del", -> it "existant", (done) -> client.del p, (error) -> throw error if error done() it "non-existant", (done) -> client.del p, (error) -> throw error if error done() describe "mdel", -> it "should do it", (done) -> client.mdel ["li", "je", "jo", "deltest"], (error) -> throw error if error done() describe "get", -> it "non-existant get", (done) -> client.get p, (error, data) -> throw error if error assert.equal data, null done() describe "recursive delete a list", -> path = "jahah" before (done) -> async.each [ "#{path}/je-vader" "#{path}/je-moeder" "#{path}/je-moeder/hihih" "#{path}/je-moeder/lalala" "#{path}" "#{path}/je-moeder/lalala/jan" "#{path}/hersen" "#{path}/hersen/hans" ], ((p, cb) -> client.pset p, "some data", cb), (error) -> throw error if error done() it "should delete recursively", (done) -> client.del path, (error) -> throw error if error done() describe "recursive delete an awkward list", -> path = "jahah" paths = [ path "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/bla/lalala/jan" "#{path}/sd" "#{path}/adsf" "#{path}/sdas/asdfasdf/asd" "#{path}/jo/mamma/hake" "#{path}/sd/asdf" "#{path}/hehehe/ja-toch/das-gek" "#{path}/hehehe" ] it "do it", (done) -> async.each paths, ((p, cb) -> client.pset p, "some data", cb), (error) -> throw error if error client.del path, (error) -> throw error if error done() describe "ephemeral storage", -> before (done) -> client = new RedisPort redisHost: "localhost" redisPort: 6379 host: "localhost" project: "hmmbob" env: "development" ephemeralExpire: 150 ephemeralRefresh: 100 client.start -> done() describe "set", -> it "should set a key and update the expired flag", (done) -> client.set "some", "data", (error) -> throw error if error done() describe "delete", -> it "should be deleted without an error and delete the timeout", (done) -> setTimeout -> client.del "some", (error) -> throw error if error client.get "some", (error, data) -> throw error if error assert.equal null, data done() , 10 client.get "some", (error, data) -> throw error if error assert data describe "reconnect", -> ephemerals = [ ["someWhere", "a"] ["someHere", "b"] ["someThere", "c"] ] describe "all ephemeral is gone", -> it "set some last ephemerals", (done) -> client.mset ephemerals, (error) -> client.list "", (error, list) -> throw error if error async.each ["someWhere", "someHere", "someThere"], ((el, cb) -> assert el in list cb() ), (error) -> throw error if error done() it "new client", (done) -> client.on "stopped", -> newClient null, null, (c) -> client = c done() client.stop() it "list", (done) -> client.list "", (error, list) -> for e in ephemerals assert e[0] not in list done() describe "services", -> before (done) -> client.on "stopped", -> newClient null, null, (c) -> client = c setTimeout -> done() , 1000 client.stop() services = [ { host: "leo", port: 20000, role: "bla" } { host: "fatima", port: 20000, role: "blaiep" } { host: "localhost", port: 20000, role: "jan" } { host: "localhost", port: 30000, role: "hans" } { host: "localhost", port: 40000, role: "ferry" } ] describe "get ports - filled", -> it "first set some data", (done) -> async.each services, ((s, cb) -> client.set "services/#{s.role}", s, cb ), (error) -> client.list "services", (error, list) -> throw error if error async.each services.map((s) -> s.role), ((role, cb) -> assert "services/#{role}" in list cb() ), (error) -> throw error if error done() it "get services", (done) -> client.getServices (error, list) -> throw error if error async.each services.map((s) -> s.role), ((role, cb) -> assert role in list.map((s) -> s.role) cb() ), (error) -> throw error if error done() it "should get the services ports (filled)", (done) -> client.getPorts (error, ports) -> throw error if error throw error if error async.each [20000, 30000, 40000], ((port, cb) -> assert port in ports cb() ), (error) -> throw error if error done() describe "register a service by role", -> it "should register a service by name", (done) -> client.register "some-unique-service", (error, port) -> throw error if error client.getPorts (error, ports) -> return error if error assert port in ports assert not (port in services.map (s) -> s.port) done() it "should register a service by object twice - no force port", (done) -> client.register role: "queue1" host: "natje", port: 5000 , (error, port) -> throw error if error client.register role: "queue2" host: "natje", port: 5000 , (error, port) -> client.getServices (error, list) -> assert.equal 1, (_.filter list, (s) -> s.port is 5000).length done() it "should register a service by object twice - with force port", (done) -> client.register role: "queue1" host: "natje", port: 5001 , true , (error, port) -> throw error if error client.register role: "queue2" host: "natje", port: 5001 , true , (error, port) -> client.getServices (error, list) -> assert.equal 2, (_.filter list, (s) -> s.port is 5001).length done() it "should be listed with a wildcard", (done) -> client.getServices "some", (error, services) -> throw error if error assert services.length assert.equal "some-unique-service", services[0].role done() describe "Query tests", -> it "Query with a non exsisting role, should not trigger onData", (done) -> count = 0 client.query "GekkeGerrit", (data) -> assert data done() if ++count is 1 client.register "GekkeGerrit", (error, port) -> throw error if error it "Query and free", (done) -> count = 0 client.query "<NAME>", ((data) -> client.free "<NAME>", (error, service) -> throw error if error assert.equal "<NAME>", service.role ), (data) -> done() if ++count is 1 client.register "<NAME>", (error, port) -> throw error if error it "Query and free - wildcard", (done) -> roles = ["Harry-1", "Harry-2", "Harry-3"] count = 0 client.query "<NAME>*", ((data) -> client.free "H<NAME>*", (error, service) -> throw error if error ), (role) -> assert role in roles done() if ++count is 3 async.each roles, ((role, cb) -> client.register role, (error, port) -> throw error if error ) it "should trigger onData 4 times after issueing a single query", (done) -> @timeout 100000 role = "web" count = 0 onData = (service) -> assert service.role is "web" assert service.host is "localhost" done() if count++ is 4 client.query role, onData functions = for i in [1..5] (cb) -> client.register role, (error, port) -> return cb error if error setTimeout cb, 100 async.series functions, (error) -> throw error if error it "should trigger a wildcard - existing services", (done) -> services = [ "listener-hy_001-raw" "listener-hy_002-raw" "listener-hy_003-raw" ] async.map services, ((role, cb) -> client.register role, cb), (error, ports) -> throw error if error assert.equal 3, ports.length count = 0 timeout = null client.query "listener*", (service) -> assert (service.role in services) done() if ++count is 3 it "should trigger a wildcard - existing and added services", (done) -> async.map ["1", "2", "3"], ((vid, cb) -> client.register "bladieblaat-#{vid}", cb ), (error, ports) -> throw error if error assert.equal 3, ports.length count = 0 client.query "bladieblaat*", (service) -> assert 0 is service.role.indexOf "bladieblaat" done() if ++count is 6 async.map ["4", "5", "6"], ((vid, cb) -> client.register "bladieblaat-#{vid}", cb ), (error, ports) -> throw error if error assert.equal 3, ports.length describe "2 clients on the same project", -> it "should get notified of each others registerd services", (done) -> newClient "same-project", "client-a", (clientA) -> newClient "same-project", "client-b", (clientB) -> clientA.query "spawner*", (service) -> assert service assert.equal "spawner-hy_001-raw", service.role clientA.stop -> done() clientB.register "spawner-hy_001-raw", (error, port) -> throw error if error describe "2 clients on one redis-port host", -> describe "two seperate clients should not interfere", -> it "create services on client1", (done) -> wildcard = "bladiebap" vids = ["yoy_001", "yoy_002", "yoy_003"] count = 0 onRegister1 = (p) -> done() if ++count is 3 onRegister2 = -> throw new Error "Callback of client 2 was called!" newClient "nice-project-1", "client1", (c) -> client1 = c client1.getServices (error, list) -> throw error if error client1.del "services", (error) -> throw error if error newClient "nice-project-2", "client2", (c) -> client2 = c client1.query "#{wildcard}*", onRegister1 client2.query "#{wildcard}*", onRegister2 async.map vids, ((vid, cb) -> client1.register "#{wildcard}-#{vid}-raw", cb ), (error, ports) -> throw error if error describe 'queues', -> queue = "testlist" rpc = null beforeEach (done) -> newClient "nice-project-1", "client1", (c) -> rpc = c rpc.clearQueue queue, (error) -> throw error if error done() afterEach (done) -> rpc.clearQueue queue, (error) -> throw error if error done() describe "size", -> it 'should return the initial length of the redis enqueue which is zero', (done) -> rpc.queueLength queue, (err, size) -> assert.equal size, 0 done() describe 'enqueue', -> it 'should enqueue 10 items and return length of 10', (done) -> llen = 0 async.eachSeries [1..10], (i, cb) -> rpc.enqueue queue, "sasads", (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal 10, llen done() it 'should enqueue 10 items in expected order', (done) -> async.eachSeries [0..10], ((i, cb) -> rpc.enqueue queue, JSON.stringify({i: i, c: i}), cb ), -> path = rpc._cleanPath "queues/#{queue}" rpc.client.lrange rpc._cleanPath("queues/#{queue}"), 0, 10, (error, arr) -> assert.equal "#{arr.join(",")}", '{"i":10,"c":10},{"i":9,"c":9},{"i":8,"c":8},{"i":7,"c":7},{"i":6,"c":6},{"i":5,"c":5},{"i":4,"c":4},{"i":3,"c":3},{"i":2,"c":2},{"i":1,"c":1},{"i":0,"c":0}' done() it 'should enqueue 10 items and dequeue in expected order', (done) -> async.eachSeries [0..20], ((i, cb) -> rpc.enqueue queue, JSON.stringify({i: i, c: i}), cb ), -> arr = [] async.eachSeries [0..10], ((i, cb) -> rpc.dequeue queue, (error, msg) -> arr.push msg cb() ), -> assert.equal "#{arr.join(",")}", '{"i":0,"c":0},{"i":1,"c":1},{"i":2,"c":2},{"i":3,"c":3},{"i":4,"c":4},{"i":5,"c":5},{"i":6,"c":6},{"i":7,"c":7},{"i":8,"c":8},{"i":9,"c":9},{"i":10,"c":10}' done() describe 'dequeue', -> it 'should enqueue and dequeue 10 items and return length of 0', (done) -> @timeout 10000 llen = 0 amount = 1000 async.eachSeries [1..amount], (i, cb) -> rpc.enqueue queue, JSON.stringify({ha: "sdfsdsdfsdf", d: "sdfsdfsdfsdfsdf", t: 12321321354}), (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal amount, llen async.eachSeries [1..amount], (i, cb) -> rpc.dequeue queue, (err, msg) -> throw err if err llen-- cb() , -> assert.equal llen, 0 done() describe 'maxlength', -> it 'should not go over max length', (done) -> @timeout 10000 rpc.queueMaxLength = 10 llen = 0 async.eachSeries [1..1000], (i, cb) -> rpc.enqueue queue, JSON.stringify({ha: "sdfsdsdfsdf", d: "sdfsdfsdfsdfsdf", t: 1000000 + i}), (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal llen, 10 msg = null async.eachSeries [1..10], (i, cb) -> rpc.dequeue queue, (err, m) -> throw err if err llen-- msg = m cb() , -> assert.equal llen, 0 assert.equal 1001000, JSON.parse(msg).t done() describe "missed", -> rpc = null before (done) -> newClient "hellep", "hellep", (c) -> rpc = c rpc.missedLength = 10 done() it "should emit missed on log", (done) -> rpc.once "missed", (p, info) -> done() rpc.logMissed "boe!" it "should have missed length on log", (done) -> list = rpc._cleanPath "missed" rpc.once "missed", (p, info) -> rpc.client.lpop list, (error, info) -> assert.equal (JSON.parse info)?.path, "boe!" done() rpc.logMissed "boe!" it "should have trim on max length", (done) -> list = rpc._cleanPath "missed" count = 0 handleMissed = (p, info) -> return if ++count isnt 20 rpc.removeListener "missed", handleMissed setTimeout -> rpc.client.llen list, (error, l) -> assert.equal l, 10 rpc.client.lpop list, (error, info) -> assert.equal (JSON.parse info)?.path, rpc._cleanPath "boe!-20" done() , 400 rpc.on "missed", handleMissed async.each [0..20], (i, cb) -> rpc.get "boe!-#{i}", cb
true
_ = require "underscore" async = require "async" assert = require "assert" RedisPort = require "../src/RedisPort" newClient = (p, id, cb) -> p or= "undisclosed#{Math.round Math.random() * 100}" rpc = new RedisPort redisHost: "localhost" redisPort: 6379 host: "localhost" project: p env: "development" , id rpc.start -> cb rpc client = null describe "Unit", -> describe "stop when not started", -> it "should stop anyway", (done) -> client = new RedisPort redisHost: "localhost" # redisPort: 6380 redisPort: 6380 project: "vems" env: "production" host: "localhost" client.stop -> done() describe "not running", -> it "should wait or retry", (done) -> client = new RedisPort redisHost: "localhost" # redisPort: 6380 redisPort: 6380 project: "vems" env: "production" host: "localhost" count = 0 client.on "reconnect", -> if ++count is 3 client.stop() done() client.start() describe "connect to runnning service", -> it "should connect", (done) -> newClient null, null, (c) -> client = c done() describe "basic redis functioniality", -> p = "deltest" d = "hejejee" describe "pset", -> it "should work", (done) -> client.pset p, d, (error) -> throw error if error done() describe "pmset", -> it "should work", (done) -> client.mpset [ ["jo", "ja"] ["je", "ho"] ["li", "lo"] ], (error) -> throw error if error done() describe "list", -> it "should list", (done) -> client.list "", (error, list) -> throw error if error async.each ["li", "je", "jo", "deltest"], ((el, cb) -> assert el in list cb() ), (error) -> throw error if error done() describe "get", -> it "existant get", (done) -> client.get p, (error, data) -> throw error if error assert data, d done() describe "del", -> it "existant", (done) -> client.del p, (error) -> throw error if error done() it "non-existant", (done) -> client.del p, (error) -> throw error if error done() describe "mdel", -> it "should do it", (done) -> client.mdel ["li", "je", "jo", "deltest"], (error) -> throw error if error done() describe "get", -> it "non-existant get", (done) -> client.get p, (error, data) -> throw error if error assert.equal data, null done() describe "recursive delete a list", -> path = "jahah" before (done) -> async.each [ "#{path}/je-vader" "#{path}/je-moeder" "#{path}/je-moeder/hihih" "#{path}/je-moeder/lalala" "#{path}" "#{path}/je-moeder/lalala/jan" "#{path}/hersen" "#{path}/hersen/hans" ], ((p, cb) -> client.pset p, "some data", cb), (error) -> throw error if error done() it "should delete recursively", (done) -> client.del path, (error) -> throw error if error done() describe "recursive delete an awkward list", -> path = "jahah" paths = [ path "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/jo/mamma/hake" "#{path}/bla/lalala/jan" "#{path}/sd" "#{path}/adsf" "#{path}/sdas/asdfasdf/asd" "#{path}/jo/mamma/hake" "#{path}/sd/asdf" "#{path}/hehehe/ja-toch/das-gek" "#{path}/hehehe" ] it "do it", (done) -> async.each paths, ((p, cb) -> client.pset p, "some data", cb), (error) -> throw error if error client.del path, (error) -> throw error if error done() describe "ephemeral storage", -> before (done) -> client = new RedisPort redisHost: "localhost" redisPort: 6379 host: "localhost" project: "hmmbob" env: "development" ephemeralExpire: 150 ephemeralRefresh: 100 client.start -> done() describe "set", -> it "should set a key and update the expired flag", (done) -> client.set "some", "data", (error) -> throw error if error done() describe "delete", -> it "should be deleted without an error and delete the timeout", (done) -> setTimeout -> client.del "some", (error) -> throw error if error client.get "some", (error, data) -> throw error if error assert.equal null, data done() , 10 client.get "some", (error, data) -> throw error if error assert data describe "reconnect", -> ephemerals = [ ["someWhere", "a"] ["someHere", "b"] ["someThere", "c"] ] describe "all ephemeral is gone", -> it "set some last ephemerals", (done) -> client.mset ephemerals, (error) -> client.list "", (error, list) -> throw error if error async.each ["someWhere", "someHere", "someThere"], ((el, cb) -> assert el in list cb() ), (error) -> throw error if error done() it "new client", (done) -> client.on "stopped", -> newClient null, null, (c) -> client = c done() client.stop() it "list", (done) -> client.list "", (error, list) -> for e in ephemerals assert e[0] not in list done() describe "services", -> before (done) -> client.on "stopped", -> newClient null, null, (c) -> client = c setTimeout -> done() , 1000 client.stop() services = [ { host: "leo", port: 20000, role: "bla" } { host: "fatima", port: 20000, role: "blaiep" } { host: "localhost", port: 20000, role: "jan" } { host: "localhost", port: 30000, role: "hans" } { host: "localhost", port: 40000, role: "ferry" } ] describe "get ports - filled", -> it "first set some data", (done) -> async.each services, ((s, cb) -> client.set "services/#{s.role}", s, cb ), (error) -> client.list "services", (error, list) -> throw error if error async.each services.map((s) -> s.role), ((role, cb) -> assert "services/#{role}" in list cb() ), (error) -> throw error if error done() it "get services", (done) -> client.getServices (error, list) -> throw error if error async.each services.map((s) -> s.role), ((role, cb) -> assert role in list.map((s) -> s.role) cb() ), (error) -> throw error if error done() it "should get the services ports (filled)", (done) -> client.getPorts (error, ports) -> throw error if error throw error if error async.each [20000, 30000, 40000], ((port, cb) -> assert port in ports cb() ), (error) -> throw error if error done() describe "register a service by role", -> it "should register a service by name", (done) -> client.register "some-unique-service", (error, port) -> throw error if error client.getPorts (error, ports) -> return error if error assert port in ports assert not (port in services.map (s) -> s.port) done() it "should register a service by object twice - no force port", (done) -> client.register role: "queue1" host: "natje", port: 5000 , (error, port) -> throw error if error client.register role: "queue2" host: "natje", port: 5000 , (error, port) -> client.getServices (error, list) -> assert.equal 1, (_.filter list, (s) -> s.port is 5000).length done() it "should register a service by object twice - with force port", (done) -> client.register role: "queue1" host: "natje", port: 5001 , true , (error, port) -> throw error if error client.register role: "queue2" host: "natje", port: 5001 , true , (error, port) -> client.getServices (error, list) -> assert.equal 2, (_.filter list, (s) -> s.port is 5001).length done() it "should be listed with a wildcard", (done) -> client.getServices "some", (error, services) -> throw error if error assert services.length assert.equal "some-unique-service", services[0].role done() describe "Query tests", -> it "Query with a non exsisting role, should not trigger onData", (done) -> count = 0 client.query "GekkeGerrit", (data) -> assert data done() if ++count is 1 client.register "GekkeGerrit", (error, port) -> throw error if error it "Query and free", (done) -> count = 0 client.query "PI:NAME:<NAME>END_PI", ((data) -> client.free "PI:NAME:<NAME>END_PI", (error, service) -> throw error if error assert.equal "PI:NAME:<NAME>END_PI", service.role ), (data) -> done() if ++count is 1 client.register "PI:NAME:<NAME>END_PI", (error, port) -> throw error if error it "Query and free - wildcard", (done) -> roles = ["Harry-1", "Harry-2", "Harry-3"] count = 0 client.query "PI:NAME:<NAME>END_PI*", ((data) -> client.free "HPI:NAME:<NAME>END_PI*", (error, service) -> throw error if error ), (role) -> assert role in roles done() if ++count is 3 async.each roles, ((role, cb) -> client.register role, (error, port) -> throw error if error ) it "should trigger onData 4 times after issueing a single query", (done) -> @timeout 100000 role = "web" count = 0 onData = (service) -> assert service.role is "web" assert service.host is "localhost" done() if count++ is 4 client.query role, onData functions = for i in [1..5] (cb) -> client.register role, (error, port) -> return cb error if error setTimeout cb, 100 async.series functions, (error) -> throw error if error it "should trigger a wildcard - existing services", (done) -> services = [ "listener-hy_001-raw" "listener-hy_002-raw" "listener-hy_003-raw" ] async.map services, ((role, cb) -> client.register role, cb), (error, ports) -> throw error if error assert.equal 3, ports.length count = 0 timeout = null client.query "listener*", (service) -> assert (service.role in services) done() if ++count is 3 it "should trigger a wildcard - existing and added services", (done) -> async.map ["1", "2", "3"], ((vid, cb) -> client.register "bladieblaat-#{vid}", cb ), (error, ports) -> throw error if error assert.equal 3, ports.length count = 0 client.query "bladieblaat*", (service) -> assert 0 is service.role.indexOf "bladieblaat" done() if ++count is 6 async.map ["4", "5", "6"], ((vid, cb) -> client.register "bladieblaat-#{vid}", cb ), (error, ports) -> throw error if error assert.equal 3, ports.length describe "2 clients on the same project", -> it "should get notified of each others registerd services", (done) -> newClient "same-project", "client-a", (clientA) -> newClient "same-project", "client-b", (clientB) -> clientA.query "spawner*", (service) -> assert service assert.equal "spawner-hy_001-raw", service.role clientA.stop -> done() clientB.register "spawner-hy_001-raw", (error, port) -> throw error if error describe "2 clients on one redis-port host", -> describe "two seperate clients should not interfere", -> it "create services on client1", (done) -> wildcard = "bladiebap" vids = ["yoy_001", "yoy_002", "yoy_003"] count = 0 onRegister1 = (p) -> done() if ++count is 3 onRegister2 = -> throw new Error "Callback of client 2 was called!" newClient "nice-project-1", "client1", (c) -> client1 = c client1.getServices (error, list) -> throw error if error client1.del "services", (error) -> throw error if error newClient "nice-project-2", "client2", (c) -> client2 = c client1.query "#{wildcard}*", onRegister1 client2.query "#{wildcard}*", onRegister2 async.map vids, ((vid, cb) -> client1.register "#{wildcard}-#{vid}-raw", cb ), (error, ports) -> throw error if error describe 'queues', -> queue = "testlist" rpc = null beforeEach (done) -> newClient "nice-project-1", "client1", (c) -> rpc = c rpc.clearQueue queue, (error) -> throw error if error done() afterEach (done) -> rpc.clearQueue queue, (error) -> throw error if error done() describe "size", -> it 'should return the initial length of the redis enqueue which is zero', (done) -> rpc.queueLength queue, (err, size) -> assert.equal size, 0 done() describe 'enqueue', -> it 'should enqueue 10 items and return length of 10', (done) -> llen = 0 async.eachSeries [1..10], (i, cb) -> rpc.enqueue queue, "sasads", (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal 10, llen done() it 'should enqueue 10 items in expected order', (done) -> async.eachSeries [0..10], ((i, cb) -> rpc.enqueue queue, JSON.stringify({i: i, c: i}), cb ), -> path = rpc._cleanPath "queues/#{queue}" rpc.client.lrange rpc._cleanPath("queues/#{queue}"), 0, 10, (error, arr) -> assert.equal "#{arr.join(",")}", '{"i":10,"c":10},{"i":9,"c":9},{"i":8,"c":8},{"i":7,"c":7},{"i":6,"c":6},{"i":5,"c":5},{"i":4,"c":4},{"i":3,"c":3},{"i":2,"c":2},{"i":1,"c":1},{"i":0,"c":0}' done() it 'should enqueue 10 items and dequeue in expected order', (done) -> async.eachSeries [0..20], ((i, cb) -> rpc.enqueue queue, JSON.stringify({i: i, c: i}), cb ), -> arr = [] async.eachSeries [0..10], ((i, cb) -> rpc.dequeue queue, (error, msg) -> arr.push msg cb() ), -> assert.equal "#{arr.join(",")}", '{"i":0,"c":0},{"i":1,"c":1},{"i":2,"c":2},{"i":3,"c":3},{"i":4,"c":4},{"i":5,"c":5},{"i":6,"c":6},{"i":7,"c":7},{"i":8,"c":8},{"i":9,"c":9},{"i":10,"c":10}' done() describe 'dequeue', -> it 'should enqueue and dequeue 10 items and return length of 0', (done) -> @timeout 10000 llen = 0 amount = 1000 async.eachSeries [1..amount], (i, cb) -> rpc.enqueue queue, JSON.stringify({ha: "sdfsdsdfsdf", d: "sdfsdfsdfsdfsdf", t: 12321321354}), (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal amount, llen async.eachSeries [1..amount], (i, cb) -> rpc.dequeue queue, (err, msg) -> throw err if err llen-- cb() , -> assert.equal llen, 0 done() describe 'maxlength', -> it 'should not go over max length', (done) -> @timeout 10000 rpc.queueMaxLength = 10 llen = 0 async.eachSeries [1..1000], (i, cb) -> rpc.enqueue queue, JSON.stringify({ha: "sdfsdsdfsdf", d: "sdfsdfsdfsdfsdf", t: 1000000 + i}), (error, l) -> throw error if error llen = l cb() , (error) -> throw error if error assert.equal llen, 10 msg = null async.eachSeries [1..10], (i, cb) -> rpc.dequeue queue, (err, m) -> throw err if err llen-- msg = m cb() , -> assert.equal llen, 0 assert.equal 1001000, JSON.parse(msg).t done() describe "missed", -> rpc = null before (done) -> newClient "hellep", "hellep", (c) -> rpc = c rpc.missedLength = 10 done() it "should emit missed on log", (done) -> rpc.once "missed", (p, info) -> done() rpc.logMissed "boe!" it "should have missed length on log", (done) -> list = rpc._cleanPath "missed" rpc.once "missed", (p, info) -> rpc.client.lpop list, (error, info) -> assert.equal (JSON.parse info)?.path, "boe!" done() rpc.logMissed "boe!" it "should have trim on max length", (done) -> list = rpc._cleanPath "missed" count = 0 handleMissed = (p, info) -> return if ++count isnt 20 rpc.removeListener "missed", handleMissed setTimeout -> rpc.client.llen list, (error, l) -> assert.equal l, 10 rpc.client.lpop list, (error, info) -> assert.equal (JSON.parse info)?.path, rpc._cleanPath "boe!-20" done() , 400 rpc.on "missed", handleMissed async.each [0..20], (i, cb) -> rpc.get "boe!-#{i}", cb
[ { "context": "=\n development:\n basicAuth:\n username : \"dev\"\n password : \"123\"\n\n test:\n basicAuth:\n ", "end": 93, "score": 0.9943020343780518, "start": 90, "tag": "USERNAME", "value": "dev" }, { "context": "sicAuth:\n username : \"dev\"\n passwo...
src/config/config.coffee
yxdh4620/node-ticket-manager-client
0
path = require('path') module.exports = development: basicAuth: username : "dev" password : "123" test: basicAuth: username : "test" password : "123" production: basicAuth: username : "production" password : "123"
179229
path = require('path') module.exports = development: basicAuth: username : "dev" password : "<PASSWORD>" test: basicAuth: username : "test" password : "<PASSWORD>" production: basicAuth: username : "production" password : "<PASSWORD>"
true
path = require('path') module.exports = development: basicAuth: username : "dev" password : "PI:PASSWORD:<PASSWORD>END_PI" test: basicAuth: username : "test" password : "PI:PASSWORD:<PASSWORD>END_PI" production: basicAuth: username : "production" password : "PI:PASSWORD:<PASSWORD>END_PI"
[ { "context": ">\n @view.$('input[name=\"card_name\"]').val 'Foo Bar'\n @view.$('select[name=\"card_expiration_mo", "end": 1401, "score": 0.9457957744598389, "start": 1394, "tag": "NAME", "value": "Foo Bar" } ]
apps/auction_support/test/client/registration_form.coffee
l2succes/force
1
benv = require 'benv' Backbone = require 'backbone' sinon = require 'sinon' { resolve } = require 'path' { fabricate } = require 'antigravity' CurrentUser = require '../../../../models/current_user' Order = require '../../../../models/order' Sale = require '../../../../models/sale' RegistrationForm = require '../../client/registration_form' describe 'RegistrationForm', -> before (done) -> benv.setup => benv.expose $: benv.require('jquery'), Stripe: @Stripe = setPublishableKey: sinon.stub() card: createToken: sinon.stub().yields(200, {}) Backbone.$ = $ done() after -> benv.teardown() beforeEach (done) -> sinon.stub(Backbone, 'sync')#.yieldsTo('success') @order = new Order() @sale = new Sale fabricate 'sale' benv.render resolve(__dirname, '../../templates/registration.jade'), { sd: {} sale: @sale monthRange: @order.getMonthRange() yearRange: @order.getYearRange() asset: -> }, => @view = new RegistrationForm el: $('#auction-registration-page') model: @sale success: sinon.stub() @view.currentUser = new CurrentUser fabricate 'user' done() afterEach -> Backbone.sync.restore() describe '#submit', -> beforeEach -> @submitValidForm = => @view.$('input[name="card_name"]').val 'Foo Bar' @view.$('select[name="card_expiration_month"]').val '1' @view.$('select[name="card_expiration_year"]').val '2024' @view.$('input[name="card_number"]').val '4111111111111111' @view.$('input[name="card_security_code"]').val '123' @view.$('input[name="address[street]"]').val '456 Foo Bar Ln.' @view.$('input[name="address[city]"]').val 'Foobarrington' @view.$('input[name="address[region]"]').val 'FB' @view.$('input[name="address[postal_code]"]').val '90210' @view.$('input[name="telephone"]').val '555-555-5555' @view.$submit.click() it 'still succeeds if the API throws an error for having already created a bidder', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { get: () -> 'pass' } # credit card save success .onCall 2 .yieldsTo 'error', { responseJSON: { message: 'Sale is already taken.' } } # bidder creation failure @submitValidForm() @view.once 'submitted', => done() it 'validates the form and displays errors', (done) -> @view.$submit.length.should.be.ok() @view.$submit.click() @view.once 'submitted', => html = @view.$el.html() html.should.containEql 'Invalid name on card' html.should.containEql 'Invalid card number' html.should.containEql 'Invalid security code' html.should.containEql 'Invalid city' html.should.containEql 'Invalid state' html.should.containEql 'Invalid zip' html.should.containEql 'Invalid telephone' html.should.containEql 'Please review the error(s) above and try again.' @view.$submit.hasClass('is-loading').should.be.false() done() it 'lets the user resubmit a corrected form', -> # Submit a bad form @view.$submit.length.should.be.ok() @view.$submit.click() @view.once "submitted", => html = @view.$el.html() html.should.containEql 'Please review the error(s) above and try again.' # Now submit a good one # Successfully create a stripe token @Stripe.card.createToken.callsArgWith(1, 200, {}) # Successfully save phone number Backbone.sync.onFirstCall().yieldsTo('success') # Successfully save credit card Backbone.sync.onSecondCall().yieldsTo('success') # Successfully create the bidder Backbone.sync.onThirdCall().yieldsTo('success') @submitValidForm() @view.once "submitted", => @Stripe.card.createToken.args[0][1](200, {}) # Saves the phone number Backbone.sync.args[0][1].changed.phone.should.equal '555-555-5555' # Saves the credit card Backbone.sync.args[1][1].url.should.containEql '/api/v1/me/credit_cards' Backbone.sync.args[1][2].success() # Creates the bidder Backbone.sync.args[2][1].attributes.sale_id.should.equal @sale.id Backbone.sync.args[2][2].url.should.containEql '/api/v1/bidder' it 'shows an error when the ZIP check fails', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { address_zip_check: 'fail', cvc_check: 'pass' } # credit card save failure .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => html = @view.$el.html() html.should.containEql "The ZIP code provided did not match your card number." done() it 'shows an error when the CVV check fails', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { address_zip_check: 'pass', cvc_check: 'fail' } # credit card save failure .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => html = @view.$el.html() html.should.containEql "The security code provided did not match your card number." done() it 'submits the form correctly', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { get: () -> 'pass' } # credit card save passes .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => # Saves the phone number Backbone.sync.args[0][1].attributes.phone.should.equal '555-555-5555' # Saves the credit card Backbone.sync.args[1][1].url.should.containEql '/api/v1/me/credit_cards' # Creates the bidder Backbone.sync.args[2][1].attributes.sale_id.should.equal @sale.id Backbone.sync.args[2][2].url.should.containEql '/api/v1/bidder' done()
56450
benv = require 'benv' Backbone = require 'backbone' sinon = require 'sinon' { resolve } = require 'path' { fabricate } = require 'antigravity' CurrentUser = require '../../../../models/current_user' Order = require '../../../../models/order' Sale = require '../../../../models/sale' RegistrationForm = require '../../client/registration_form' describe 'RegistrationForm', -> before (done) -> benv.setup => benv.expose $: benv.require('jquery'), Stripe: @Stripe = setPublishableKey: sinon.stub() card: createToken: sinon.stub().yields(200, {}) Backbone.$ = $ done() after -> benv.teardown() beforeEach (done) -> sinon.stub(Backbone, 'sync')#.yieldsTo('success') @order = new Order() @sale = new Sale fabricate 'sale' benv.render resolve(__dirname, '../../templates/registration.jade'), { sd: {} sale: @sale monthRange: @order.getMonthRange() yearRange: @order.getYearRange() asset: -> }, => @view = new RegistrationForm el: $('#auction-registration-page') model: @sale success: sinon.stub() @view.currentUser = new CurrentUser fabricate 'user' done() afterEach -> Backbone.sync.restore() describe '#submit', -> beforeEach -> @submitValidForm = => @view.$('input[name="card_name"]').val '<NAME>' @view.$('select[name="card_expiration_month"]').val '1' @view.$('select[name="card_expiration_year"]').val '2024' @view.$('input[name="card_number"]').val '4111111111111111' @view.$('input[name="card_security_code"]').val '123' @view.$('input[name="address[street]"]').val '456 Foo Bar Ln.' @view.$('input[name="address[city]"]').val 'Foobarrington' @view.$('input[name="address[region]"]').val 'FB' @view.$('input[name="address[postal_code]"]').val '90210' @view.$('input[name="telephone"]').val '555-555-5555' @view.$submit.click() it 'still succeeds if the API throws an error for having already created a bidder', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { get: () -> 'pass' } # credit card save success .onCall 2 .yieldsTo 'error', { responseJSON: { message: 'Sale is already taken.' } } # bidder creation failure @submitValidForm() @view.once 'submitted', => done() it 'validates the form and displays errors', (done) -> @view.$submit.length.should.be.ok() @view.$submit.click() @view.once 'submitted', => html = @view.$el.html() html.should.containEql 'Invalid name on card' html.should.containEql 'Invalid card number' html.should.containEql 'Invalid security code' html.should.containEql 'Invalid city' html.should.containEql 'Invalid state' html.should.containEql 'Invalid zip' html.should.containEql 'Invalid telephone' html.should.containEql 'Please review the error(s) above and try again.' @view.$submit.hasClass('is-loading').should.be.false() done() it 'lets the user resubmit a corrected form', -> # Submit a bad form @view.$submit.length.should.be.ok() @view.$submit.click() @view.once "submitted", => html = @view.$el.html() html.should.containEql 'Please review the error(s) above and try again.' # Now submit a good one # Successfully create a stripe token @Stripe.card.createToken.callsArgWith(1, 200, {}) # Successfully save phone number Backbone.sync.onFirstCall().yieldsTo('success') # Successfully save credit card Backbone.sync.onSecondCall().yieldsTo('success') # Successfully create the bidder Backbone.sync.onThirdCall().yieldsTo('success') @submitValidForm() @view.once "submitted", => @Stripe.card.createToken.args[0][1](200, {}) # Saves the phone number Backbone.sync.args[0][1].changed.phone.should.equal '555-555-5555' # Saves the credit card Backbone.sync.args[1][1].url.should.containEql '/api/v1/me/credit_cards' Backbone.sync.args[1][2].success() # Creates the bidder Backbone.sync.args[2][1].attributes.sale_id.should.equal @sale.id Backbone.sync.args[2][2].url.should.containEql '/api/v1/bidder' it 'shows an error when the ZIP check fails', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { address_zip_check: 'fail', cvc_check: 'pass' } # credit card save failure .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => html = @view.$el.html() html.should.containEql "The ZIP code provided did not match your card number." done() it 'shows an error when the CVV check fails', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { address_zip_check: 'pass', cvc_check: 'fail' } # credit card save failure .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => html = @view.$el.html() html.should.containEql "The security code provided did not match your card number." done() it 'submits the form correctly', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { get: () -> 'pass' } # credit card save passes .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => # Saves the phone number Backbone.sync.args[0][1].attributes.phone.should.equal '555-555-5555' # Saves the credit card Backbone.sync.args[1][1].url.should.containEql '/api/v1/me/credit_cards' # Creates the bidder Backbone.sync.args[2][1].attributes.sale_id.should.equal @sale.id Backbone.sync.args[2][2].url.should.containEql '/api/v1/bidder' done()
true
benv = require 'benv' Backbone = require 'backbone' sinon = require 'sinon' { resolve } = require 'path' { fabricate } = require 'antigravity' CurrentUser = require '../../../../models/current_user' Order = require '../../../../models/order' Sale = require '../../../../models/sale' RegistrationForm = require '../../client/registration_form' describe 'RegistrationForm', -> before (done) -> benv.setup => benv.expose $: benv.require('jquery'), Stripe: @Stripe = setPublishableKey: sinon.stub() card: createToken: sinon.stub().yields(200, {}) Backbone.$ = $ done() after -> benv.teardown() beforeEach (done) -> sinon.stub(Backbone, 'sync')#.yieldsTo('success') @order = new Order() @sale = new Sale fabricate 'sale' benv.render resolve(__dirname, '../../templates/registration.jade'), { sd: {} sale: @sale monthRange: @order.getMonthRange() yearRange: @order.getYearRange() asset: -> }, => @view = new RegistrationForm el: $('#auction-registration-page') model: @sale success: sinon.stub() @view.currentUser = new CurrentUser fabricate 'user' done() afterEach -> Backbone.sync.restore() describe '#submit', -> beforeEach -> @submitValidForm = => @view.$('input[name="card_name"]').val 'PI:NAME:<NAME>END_PI' @view.$('select[name="card_expiration_month"]').val '1' @view.$('select[name="card_expiration_year"]').val '2024' @view.$('input[name="card_number"]').val '4111111111111111' @view.$('input[name="card_security_code"]').val '123' @view.$('input[name="address[street]"]').val '456 Foo Bar Ln.' @view.$('input[name="address[city]"]').val 'Foobarrington' @view.$('input[name="address[region]"]').val 'FB' @view.$('input[name="address[postal_code]"]').val '90210' @view.$('input[name="telephone"]').val '555-555-5555' @view.$submit.click() it 'still succeeds if the API throws an error for having already created a bidder', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { get: () -> 'pass' } # credit card save success .onCall 2 .yieldsTo 'error', { responseJSON: { message: 'Sale is already taken.' } } # bidder creation failure @submitValidForm() @view.once 'submitted', => done() it 'validates the form and displays errors', (done) -> @view.$submit.length.should.be.ok() @view.$submit.click() @view.once 'submitted', => html = @view.$el.html() html.should.containEql 'Invalid name on card' html.should.containEql 'Invalid card number' html.should.containEql 'Invalid security code' html.should.containEql 'Invalid city' html.should.containEql 'Invalid state' html.should.containEql 'Invalid zip' html.should.containEql 'Invalid telephone' html.should.containEql 'Please review the error(s) above and try again.' @view.$submit.hasClass('is-loading').should.be.false() done() it 'lets the user resubmit a corrected form', -> # Submit a bad form @view.$submit.length.should.be.ok() @view.$submit.click() @view.once "submitted", => html = @view.$el.html() html.should.containEql 'Please review the error(s) above and try again.' # Now submit a good one # Successfully create a stripe token @Stripe.card.createToken.callsArgWith(1, 200, {}) # Successfully save phone number Backbone.sync.onFirstCall().yieldsTo('success') # Successfully save credit card Backbone.sync.onSecondCall().yieldsTo('success') # Successfully create the bidder Backbone.sync.onThirdCall().yieldsTo('success') @submitValidForm() @view.once "submitted", => @Stripe.card.createToken.args[0][1](200, {}) # Saves the phone number Backbone.sync.args[0][1].changed.phone.should.equal '555-555-5555' # Saves the credit card Backbone.sync.args[1][1].url.should.containEql '/api/v1/me/credit_cards' Backbone.sync.args[1][2].success() # Creates the bidder Backbone.sync.args[2][1].attributes.sale_id.should.equal @sale.id Backbone.sync.args[2][2].url.should.containEql '/api/v1/bidder' it 'shows an error when the ZIP check fails', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { address_zip_check: 'fail', cvc_check: 'pass' } # credit card save failure .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => html = @view.$el.html() html.should.containEql "The ZIP code provided did not match your card number." done() it 'shows an error when the CVV check fails', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { address_zip_check: 'pass', cvc_check: 'fail' } # credit card save failure .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => html = @view.$el.html() html.should.containEql "The security code provided did not match your card number." done() it 'submits the form correctly', (done) -> Backbone.sync .yieldsTo 'success', {} # savePhoneNumber success .onCall 1 .yieldsTo 'success', { get: () -> 'pass' } # credit card save passes .onCall 2 .yieldsTo 'success', {} @submitValidForm() @view.once "submitted", => # Saves the phone number Backbone.sync.args[0][1].attributes.phone.should.equal '555-555-5555' # Saves the credit card Backbone.sync.args[1][1].url.should.containEql '/api/v1/me/credit_cards' # Creates the bidder Backbone.sync.args[2][1].attributes.sale_id.should.equal @sale.id Backbone.sync.args[2][2].url.should.containEql '/api/v1/bidder' done()
[ { "context": " getOrElse: (rawKey, val, opts, cb) ->\n key = @applyPrefix rawKey\n\n {cb,opts} = optionalOpts(opts, ", "end": 3901, "score": 0.5426701903343201, "start": 3896, "tag": "KEY", "value": "apply" } ]
src/cache.coffee
Kofia5/node-cached
0
### Copyright (c) 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### {extend} = require 'underscore' Q = require 'q' Backend = require './backend' toPromise = (val) -> # If val is a function, evaluate it first, convert into promise afterwards if 'function' is typeof val Q val() else Q val expiresAt = (seconds) -> if seconds is 0 then 0 else Date.now() + parseInt(seconds, 10) * 1000 isExpired = (expires) -> return false if expires is 0 Date.now() > new Date(expires).getTime() optionalOpts = (opts, cb) -> if not cb? and 'function' is typeof opts { cb: opts, opts: null } else { cb, opts } class Cache constructor: ({backend, defaults, name}) -> @defaults = freshFor: 0 expire: 0 @name = name or 'default' @prefix = "#{@name}:" # stale keys that are loaded right now @staleOrPending = {} @setDefaults defaults @setBackend backend applyPrefix: (key) -> "#{@prefix}#{key}" setDefaults: (defaults) -> @defaults = @prepareOptions defaults setBackend: (backendOptions) -> backendOptions = if 'string' is typeof backendOptions { type: backendOptions } else backendOptions ? {} @end() @backend = Backend.create backendOptions end: -> @backend.end() if @backend?.end? prepareOptions: (options) -> extend {}, @defaults, options set: (key, val, opts, cb) -> {cb,opts} = optionalOpts(opts, cb) key = @applyPrefix key backend = @backend opts = @prepareOptions opts toPromise(val).then( (resolvedValue) -> wrappedValue = b: expiresAt(opts.freshFor) d: resolvedValue Q.npost backend, 'set', [ key, wrappedValue, opts ] ).nodeify cb # Every value we cache is wrapped to enable graceful expire: # { # "d": <data, the actual data that is cached> # "b": <best before, timestamp when the data is considered stale> # } # This allows us to have stale values stored in the cache and fetch a # replacement in the background. getWrapped: (key) -> Q.npost(@backend, 'get', [ key ]) get: (rawKey, cb) -> key = @applyPrefix rawKey @getWrapped(key).then( (wrappedValue) -> # blindly return the wrapped value, ignoring freshness wrappedValue?.d ? null ).nodeify cb # Get from a cache or generate if not present or stale. # A value is stale when it was generated more than `freshFor` seconds ago getOrElse: (rawKey, val, opts, cb) -> key = @applyPrefix rawKey {cb,opts} = optionalOpts(opts, cb) opts = @prepareOptions opts refreshValue = => generatedValue = toPromise(val) @set(rawKey, generatedValue, opts).then( (rawValue) => delete @staleOrPending[key] rawValue?.d ? null (err) => # return generated value instead of error # tracking backend errors should be done with wrapping your backend clients delete @staleOrPending[key] generatedValue ? null ) verifyFreshness = (wrappedValue) => # best before is expired, we have to reload hit = wrappedValue? expired = isExpired wrappedValue?.b loadingNewValue = @staleOrPending[key]? if (!hit or expired) && !loadingNewValue @staleOrPending[key] = refreshValue() # Return the value even if it's stale, we want the result ASAP wrappedValue?.d ? @staleOrPending[key] handleError = (error) -> # we should let the refreshValue method work if getWrapped has problems # tracking backend errors should be done with wrapping your backend clients return null @getWrapped(key).catch(handleError).then(verifyFreshness).nodeify cb module.exports = Cache
62062
### Copyright (c) 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### {extend} = require 'underscore' Q = require 'q' Backend = require './backend' toPromise = (val) -> # If val is a function, evaluate it first, convert into promise afterwards if 'function' is typeof val Q val() else Q val expiresAt = (seconds) -> if seconds is 0 then 0 else Date.now() + parseInt(seconds, 10) * 1000 isExpired = (expires) -> return false if expires is 0 Date.now() > new Date(expires).getTime() optionalOpts = (opts, cb) -> if not cb? and 'function' is typeof opts { cb: opts, opts: null } else { cb, opts } class Cache constructor: ({backend, defaults, name}) -> @defaults = freshFor: 0 expire: 0 @name = name or 'default' @prefix = "#{@name}:" # stale keys that are loaded right now @staleOrPending = {} @setDefaults defaults @setBackend backend applyPrefix: (key) -> "#{@prefix}#{key}" setDefaults: (defaults) -> @defaults = @prepareOptions defaults setBackend: (backendOptions) -> backendOptions = if 'string' is typeof backendOptions { type: backendOptions } else backendOptions ? {} @end() @backend = Backend.create backendOptions end: -> @backend.end() if @backend?.end? prepareOptions: (options) -> extend {}, @defaults, options set: (key, val, opts, cb) -> {cb,opts} = optionalOpts(opts, cb) key = @applyPrefix key backend = @backend opts = @prepareOptions opts toPromise(val).then( (resolvedValue) -> wrappedValue = b: expiresAt(opts.freshFor) d: resolvedValue Q.npost backend, 'set', [ key, wrappedValue, opts ] ).nodeify cb # Every value we cache is wrapped to enable graceful expire: # { # "d": <data, the actual data that is cached> # "b": <best before, timestamp when the data is considered stale> # } # This allows us to have stale values stored in the cache and fetch a # replacement in the background. getWrapped: (key) -> Q.npost(@backend, 'get', [ key ]) get: (rawKey, cb) -> key = @applyPrefix rawKey @getWrapped(key).then( (wrappedValue) -> # blindly return the wrapped value, ignoring freshness wrappedValue?.d ? null ).nodeify cb # Get from a cache or generate if not present or stale. # A value is stale when it was generated more than `freshFor` seconds ago getOrElse: (rawKey, val, opts, cb) -> key = @<KEY>Prefix rawKey {cb,opts} = optionalOpts(opts, cb) opts = @prepareOptions opts refreshValue = => generatedValue = toPromise(val) @set(rawKey, generatedValue, opts).then( (rawValue) => delete @staleOrPending[key] rawValue?.d ? null (err) => # return generated value instead of error # tracking backend errors should be done with wrapping your backend clients delete @staleOrPending[key] generatedValue ? null ) verifyFreshness = (wrappedValue) => # best before is expired, we have to reload hit = wrappedValue? expired = isExpired wrappedValue?.b loadingNewValue = @staleOrPending[key]? if (!hit or expired) && !loadingNewValue @staleOrPending[key] = refreshValue() # Return the value even if it's stale, we want the result ASAP wrappedValue?.d ? @staleOrPending[key] handleError = (error) -> # we should let the refreshValue method work if getWrapped has problems # tracking backend errors should be done with wrapping your backend clients return null @getWrapped(key).catch(handleError).then(verifyFreshness).nodeify cb module.exports = Cache
true
### Copyright (c) 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### {extend} = require 'underscore' Q = require 'q' Backend = require './backend' toPromise = (val) -> # If val is a function, evaluate it first, convert into promise afterwards if 'function' is typeof val Q val() else Q val expiresAt = (seconds) -> if seconds is 0 then 0 else Date.now() + parseInt(seconds, 10) * 1000 isExpired = (expires) -> return false if expires is 0 Date.now() > new Date(expires).getTime() optionalOpts = (opts, cb) -> if not cb? and 'function' is typeof opts { cb: opts, opts: null } else { cb, opts } class Cache constructor: ({backend, defaults, name}) -> @defaults = freshFor: 0 expire: 0 @name = name or 'default' @prefix = "#{@name}:" # stale keys that are loaded right now @staleOrPending = {} @setDefaults defaults @setBackend backend applyPrefix: (key) -> "#{@prefix}#{key}" setDefaults: (defaults) -> @defaults = @prepareOptions defaults setBackend: (backendOptions) -> backendOptions = if 'string' is typeof backendOptions { type: backendOptions } else backendOptions ? {} @end() @backend = Backend.create backendOptions end: -> @backend.end() if @backend?.end? prepareOptions: (options) -> extend {}, @defaults, options set: (key, val, opts, cb) -> {cb,opts} = optionalOpts(opts, cb) key = @applyPrefix key backend = @backend opts = @prepareOptions opts toPromise(val).then( (resolvedValue) -> wrappedValue = b: expiresAt(opts.freshFor) d: resolvedValue Q.npost backend, 'set', [ key, wrappedValue, opts ] ).nodeify cb # Every value we cache is wrapped to enable graceful expire: # { # "d": <data, the actual data that is cached> # "b": <best before, timestamp when the data is considered stale> # } # This allows us to have stale values stored in the cache and fetch a # replacement in the background. getWrapped: (key) -> Q.npost(@backend, 'get', [ key ]) get: (rawKey, cb) -> key = @applyPrefix rawKey @getWrapped(key).then( (wrappedValue) -> # blindly return the wrapped value, ignoring freshness wrappedValue?.d ? null ).nodeify cb # Get from a cache or generate if not present or stale. # A value is stale when it was generated more than `freshFor` seconds ago getOrElse: (rawKey, val, opts, cb) -> key = @PI:KEY:<KEY>END_PIPrefix rawKey {cb,opts} = optionalOpts(opts, cb) opts = @prepareOptions opts refreshValue = => generatedValue = toPromise(val) @set(rawKey, generatedValue, opts).then( (rawValue) => delete @staleOrPending[key] rawValue?.d ? null (err) => # return generated value instead of error # tracking backend errors should be done with wrapping your backend clients delete @staleOrPending[key] generatedValue ? null ) verifyFreshness = (wrappedValue) => # best before is expired, we have to reload hit = wrappedValue? expired = isExpired wrappedValue?.b loadingNewValue = @staleOrPending[key]? if (!hit or expired) && !loadingNewValue @staleOrPending[key] = refreshValue() # Return the value even if it's stale, we want the result ASAP wrappedValue?.d ? @staleOrPending[key] handleError = (error) -> # we should let the refreshValue method work if getWrapped has problems # tracking backend errors should be done with wrapping your backend clients return null @getWrapped(key).catch(handleError).then(verifyFreshness).nodeify cb module.exports = Cache
[ { "context": " http://coffeescript.org\n *\n * Copyright 2011, Jeremy Ashkenas\n * Released under the MIT License\n */\n\"\"\"\n\n# ", "end": 547, "score": 0.9998693466186523, "start": 532, "tag": "NAME", "value": "Jeremy Ashkenas" } ]
Cakefile.coffee
chaosim/coffee-script
1
fs = require 'fs' path = require 'path' CoffeeScript = require './lib/coffee-script' {spawn, exec} = require 'child_process' helpers = require './lib/coffee-script/helpers' # ANSI Terminal Colors. bold = red = green = reset = '' unless process.env.NODE_DISABLE_COLORS bold = '\x1B[0;1m' red = '\x1B[0;31m' green = '\x1B[0;32m' reset = '\x1B[0m' # Built file header. header = """ /** * CoffeeScript Compiler v#{CoffeeScript.VERSION} * http://coffeescript.org * * Copyright 2011, Jeremy Ashkenas * Released under the MIT License */ """ # Build the CoffeeScript language from source. build = (cb) -> files = fs.readdirSync 'src' files = ('src/' + file for file in files when file.match(/\.(lit)?coffee$/)) run ['-c', '-o', 'lib/coffee-script'].concat(files), cb # Run a CoffeeScript through our node/coffee interpreter. run = (args, cb) -> proc = spawn 'node', ['bin/coffee'].concat(args) proc.stderr.on 'data', (buffer) -> console.log buffer.toString() proc.on 'exit', (status) -> process.exit(1) if status != 0 cb() if typeof cb is 'function' # Log a message with a color. log = (message, color, explanation) -> console.log color + message + reset + ' ' + (explanation or '') option '-p', '--prefix [DIR]', 'set the installation prefix for `cake install`' task 'install', 'install CoffeeScript into /usr/local (or --prefix)', (options) -> base = options.prefix or '/usr/local' lib = "#{base}/lib/coffee-script" bin = "#{base}/bin" node = "~/.node_libraries/coffee-script" console.log "Installing CoffeeScript to #{lib}" console.log "Linking to #{node}" console.log "Linking 'coffee' to #{bin}/coffee" exec([ "mkdir -p #{lib} #{bin}" "cp -rf bin lib LICENSE README package.json src #{lib}" "ln -sfn #{lib}/bin/coffee #{bin}/coffee" "ln -sfn #{lib}/bin/cake #{bin}/cake" "mkdir -p ~/.node_libraries" "ln -sfn #{lib}/lib/coffee-script #{node}" ].join(' && '), (err, stdout, stderr) -> if err then console.log stderr.trim() else log 'done', green ) task 'build', 'build the CoffeeScript language from source', build task 'build:full', 'rebuild the source twice, and run the tests', -> build -> build -> csPath = './lib/coffee-script' csDir = path.dirname require.resolve csPath for mod of require.cache when csDir is mod[0 ... csDir.length] delete require.cache[mod] unless runTests require csPath process.exit 1 task 'build:parser', 'rebuild the Jison parser (run build first)', -> helpers.extend global, require('util') require 'jison' parser = require('./lib/coffee-script/grammar').parser fs.writeFile 'lib/coffee-script/parser.js', parser.generate() task 'build:ultraviolet', 'build and install the Ultraviolet syntax highlighter', -> exec 'plist2syntax ../coffee-script-tmbundle/Syntaxes/CoffeeScript.tmLanguage', (err) -> throw err if err exec 'sudo mv coffeescript.yaml /usr/local/lib/ruby/gems/1.8/gems/ultraviolet-0.10.2/syntax/coffeescript.syntax' task 'build:browser', 'rebuild the merged script for inclusion in the browser', -> code = '' for name in ['helpers', 'rewriter', 'lexer', 'parser', 'scope', 'nodes', 'sourcemap', 'coffee-script', 'browser'] code += """ require['./#{name}'] = (function() { var exports = {}, module = {exports: exports}; #{fs.readFileSync "lib/coffee-script/#{name}.js"} return module.exports; })(); """ code = """ (function(root) { var CoffeeScript = function() { function require(path){ return require[path]; } #{code} return require['./coffee-script']; }(); if (typeof define === 'function' && define.amd) { define(function() { return CoffeeScript; }); } else { root.CoffeeScript = CoffeeScript; } }(this)); """ unless process.env.MINIFY is 'false' {code} = require('uglify-js').minify code, fromString: true fs.writeFileSync 'extras/coffee-script.js', header + '\n' + code console.log "built ... running browser tests:" invoke 'test:browser' task 'doc:site', 'watch and continually rebuild the documentation for the website', -> exec 'rake doc', (err) -> throw err if err task 'doc:source', 'rebuild the internal documentation', -> exec 'docco src/*.*coffee && cp -rf docs documentation && rm -r docs', (err) -> throw err if err task 'doc:underscore', 'rebuild the Underscore.coffee documentation page', -> exec 'docco examples/underscore.coffee && cp -rf docs documentation && rm -r docs', (err) -> throw err if err task 'bench', 'quick benchmark of compilation time', -> {Rewriter} = require './lib/coffee-script/rewriter' sources = ['coffee-script', 'grammar', 'helpers', 'lexer', 'nodes', 'rewriter'] coffee = sources.map((name) -> fs.readFileSync "src/#{name}.coffee").join '\n' litcoffee = fs.readFileSync("src/scope.litcoffee").toString() fmt = (ms) -> " #{bold}#{ " #{ms}".slice -4 }#{reset} ms" total = 0 now = Date.now() time = -> total += ms = -(now - now = Date.now()); fmt ms tokens = CoffeeScript.tokens coffee, rewrite: no littokens = CoffeeScript.tokens litcoffee, rewrite: no, literate: yes tokens = tokens.concat(littokens) console.log "Lex #{time()} (#{tokens.length} tokens)" tokens = new Rewriter().rewrite tokens console.log "Rewrite#{time()} (#{tokens.length} tokens)" nodes = CoffeeScript.nodes tokens console.log "Parse #{time()}" js = nodes.compile bare: yes console.log "Compile#{time()} (#{js.length} chars)" console.log "total #{ fmt total }" # Run the CoffeeScript test suite. runTests = (CoffeeScript) -> startTime = Date.now() currentFile = null passedTests = 0 failures = [] global[name] = func for name, func of require 'assert' # Convenience aliases. global.CoffeeScript = CoffeeScript global.Repl = require './lib/coffee-script/repl' # Our test helper function for delimiting different test cases. global.test = (description, fn) -> try fn.test = {description, currentFile} fn.call(fn) ++passedTests catch e failures.push filename: currentFile error: e description: description if description? source: fn.toString() if fn.toString? # See http://wiki.ecmascript.org/doku.php?id=harmony:egal egal = (a, b) -> if a is b a isnt 0 or 1/a is 1/b else a isnt a and b isnt b # A recursive functional equivalence helper; uses egal for testing equivalence. arrayEgal = (a, b) -> if egal a, b then yes else if a instanceof Array and b instanceof Array return no unless a.length is b.length return no for el, idx in a when not arrayEgal el, b[idx] yes global.eq = (a, b, msg) -> ok egal(a, b), msg ? "Expected #{a} to equal #{b}" global.arrayEq = (a, b, msg) -> ok arrayEgal(a,b), msg ? "Expected #{a} to deep equal #{b}" # When all the tests have run, collect and print errors. # If a stacktrace is available, output the compiled function source. process.on 'exit', -> time = ((Date.now() - startTime) / 1000).toFixed(2) message = "passed #{passedTests} tests in #{time} seconds#{reset}" return log(message, green) unless failures.length log "failed #{failures.length} and #{message}", red for fail in failures {error, filename, description, source} = fail console.log '' log " #{description}", red if description log " #{error.stack}", red console.log " #{source}" if source return # Run every test in the `test` folder, recording failures. files = fs.readdirSync 'test' for file in files when helpers.isCoffee file literate = helpers.isLiterate file currentFile = filename = path.join 'test', file code = fs.readFileSync filename try CoffeeScript.run code.toString(), {filename, literate} catch error failures.push {filename, error} return !failures.length task 'test', 'run the CoffeeScript language test suite', -> runTests CoffeeScript task 'test:browser', 'run the test suite against the merged browser script', -> source = fs.readFileSync 'extras/coffee-script.js', 'utf-8' result = {} global.testingBrowser = yes (-> eval source).call result runTests result.CoffeeScript
124548
fs = require 'fs' path = require 'path' CoffeeScript = require './lib/coffee-script' {spawn, exec} = require 'child_process' helpers = require './lib/coffee-script/helpers' # ANSI Terminal Colors. bold = red = green = reset = '' unless process.env.NODE_DISABLE_COLORS bold = '\x1B[0;1m' red = '\x1B[0;31m' green = '\x1B[0;32m' reset = '\x1B[0m' # Built file header. header = """ /** * CoffeeScript Compiler v#{CoffeeScript.VERSION} * http://coffeescript.org * * Copyright 2011, <NAME> * Released under the MIT License */ """ # Build the CoffeeScript language from source. build = (cb) -> files = fs.readdirSync 'src' files = ('src/' + file for file in files when file.match(/\.(lit)?coffee$/)) run ['-c', '-o', 'lib/coffee-script'].concat(files), cb # Run a CoffeeScript through our node/coffee interpreter. run = (args, cb) -> proc = spawn 'node', ['bin/coffee'].concat(args) proc.stderr.on 'data', (buffer) -> console.log buffer.toString() proc.on 'exit', (status) -> process.exit(1) if status != 0 cb() if typeof cb is 'function' # Log a message with a color. log = (message, color, explanation) -> console.log color + message + reset + ' ' + (explanation or '') option '-p', '--prefix [DIR]', 'set the installation prefix for `cake install`' task 'install', 'install CoffeeScript into /usr/local (or --prefix)', (options) -> base = options.prefix or '/usr/local' lib = "#{base}/lib/coffee-script" bin = "#{base}/bin" node = "~/.node_libraries/coffee-script" console.log "Installing CoffeeScript to #{lib}" console.log "Linking to #{node}" console.log "Linking 'coffee' to #{bin}/coffee" exec([ "mkdir -p #{lib} #{bin}" "cp -rf bin lib LICENSE README package.json src #{lib}" "ln -sfn #{lib}/bin/coffee #{bin}/coffee" "ln -sfn #{lib}/bin/cake #{bin}/cake" "mkdir -p ~/.node_libraries" "ln -sfn #{lib}/lib/coffee-script #{node}" ].join(' && '), (err, stdout, stderr) -> if err then console.log stderr.trim() else log 'done', green ) task 'build', 'build the CoffeeScript language from source', build task 'build:full', 'rebuild the source twice, and run the tests', -> build -> build -> csPath = './lib/coffee-script' csDir = path.dirname require.resolve csPath for mod of require.cache when csDir is mod[0 ... csDir.length] delete require.cache[mod] unless runTests require csPath process.exit 1 task 'build:parser', 'rebuild the Jison parser (run build first)', -> helpers.extend global, require('util') require 'jison' parser = require('./lib/coffee-script/grammar').parser fs.writeFile 'lib/coffee-script/parser.js', parser.generate() task 'build:ultraviolet', 'build and install the Ultraviolet syntax highlighter', -> exec 'plist2syntax ../coffee-script-tmbundle/Syntaxes/CoffeeScript.tmLanguage', (err) -> throw err if err exec 'sudo mv coffeescript.yaml /usr/local/lib/ruby/gems/1.8/gems/ultraviolet-0.10.2/syntax/coffeescript.syntax' task 'build:browser', 'rebuild the merged script for inclusion in the browser', -> code = '' for name in ['helpers', 'rewriter', 'lexer', 'parser', 'scope', 'nodes', 'sourcemap', 'coffee-script', 'browser'] code += """ require['./#{name}'] = (function() { var exports = {}, module = {exports: exports}; #{fs.readFileSync "lib/coffee-script/#{name}.js"} return module.exports; })(); """ code = """ (function(root) { var CoffeeScript = function() { function require(path){ return require[path]; } #{code} return require['./coffee-script']; }(); if (typeof define === 'function' && define.amd) { define(function() { return CoffeeScript; }); } else { root.CoffeeScript = CoffeeScript; } }(this)); """ unless process.env.MINIFY is 'false' {code} = require('uglify-js').minify code, fromString: true fs.writeFileSync 'extras/coffee-script.js', header + '\n' + code console.log "built ... running browser tests:" invoke 'test:browser' task 'doc:site', 'watch and continually rebuild the documentation for the website', -> exec 'rake doc', (err) -> throw err if err task 'doc:source', 'rebuild the internal documentation', -> exec 'docco src/*.*coffee && cp -rf docs documentation && rm -r docs', (err) -> throw err if err task 'doc:underscore', 'rebuild the Underscore.coffee documentation page', -> exec 'docco examples/underscore.coffee && cp -rf docs documentation && rm -r docs', (err) -> throw err if err task 'bench', 'quick benchmark of compilation time', -> {Rewriter} = require './lib/coffee-script/rewriter' sources = ['coffee-script', 'grammar', 'helpers', 'lexer', 'nodes', 'rewriter'] coffee = sources.map((name) -> fs.readFileSync "src/#{name}.coffee").join '\n' litcoffee = fs.readFileSync("src/scope.litcoffee").toString() fmt = (ms) -> " #{bold}#{ " #{ms}".slice -4 }#{reset} ms" total = 0 now = Date.now() time = -> total += ms = -(now - now = Date.now()); fmt ms tokens = CoffeeScript.tokens coffee, rewrite: no littokens = CoffeeScript.tokens litcoffee, rewrite: no, literate: yes tokens = tokens.concat(littokens) console.log "Lex #{time()} (#{tokens.length} tokens)" tokens = new Rewriter().rewrite tokens console.log "Rewrite#{time()} (#{tokens.length} tokens)" nodes = CoffeeScript.nodes tokens console.log "Parse #{time()}" js = nodes.compile bare: yes console.log "Compile#{time()} (#{js.length} chars)" console.log "total #{ fmt total }" # Run the CoffeeScript test suite. runTests = (CoffeeScript) -> startTime = Date.now() currentFile = null passedTests = 0 failures = [] global[name] = func for name, func of require 'assert' # Convenience aliases. global.CoffeeScript = CoffeeScript global.Repl = require './lib/coffee-script/repl' # Our test helper function for delimiting different test cases. global.test = (description, fn) -> try fn.test = {description, currentFile} fn.call(fn) ++passedTests catch e failures.push filename: currentFile error: e description: description if description? source: fn.toString() if fn.toString? # See http://wiki.ecmascript.org/doku.php?id=harmony:egal egal = (a, b) -> if a is b a isnt 0 or 1/a is 1/b else a isnt a and b isnt b # A recursive functional equivalence helper; uses egal for testing equivalence. arrayEgal = (a, b) -> if egal a, b then yes else if a instanceof Array and b instanceof Array return no unless a.length is b.length return no for el, idx in a when not arrayEgal el, b[idx] yes global.eq = (a, b, msg) -> ok egal(a, b), msg ? "Expected #{a} to equal #{b}" global.arrayEq = (a, b, msg) -> ok arrayEgal(a,b), msg ? "Expected #{a} to deep equal #{b}" # When all the tests have run, collect and print errors. # If a stacktrace is available, output the compiled function source. process.on 'exit', -> time = ((Date.now() - startTime) / 1000).toFixed(2) message = "passed #{passedTests} tests in #{time} seconds#{reset}" return log(message, green) unless failures.length log "failed #{failures.length} and #{message}", red for fail in failures {error, filename, description, source} = fail console.log '' log " #{description}", red if description log " #{error.stack}", red console.log " #{source}" if source return # Run every test in the `test` folder, recording failures. files = fs.readdirSync 'test' for file in files when helpers.isCoffee file literate = helpers.isLiterate file currentFile = filename = path.join 'test', file code = fs.readFileSync filename try CoffeeScript.run code.toString(), {filename, literate} catch error failures.push {filename, error} return !failures.length task 'test', 'run the CoffeeScript language test suite', -> runTests CoffeeScript task 'test:browser', 'run the test suite against the merged browser script', -> source = fs.readFileSync 'extras/coffee-script.js', 'utf-8' result = {} global.testingBrowser = yes (-> eval source).call result runTests result.CoffeeScript
true
fs = require 'fs' path = require 'path' CoffeeScript = require './lib/coffee-script' {spawn, exec} = require 'child_process' helpers = require './lib/coffee-script/helpers' # ANSI Terminal Colors. bold = red = green = reset = '' unless process.env.NODE_DISABLE_COLORS bold = '\x1B[0;1m' red = '\x1B[0;31m' green = '\x1B[0;32m' reset = '\x1B[0m' # Built file header. header = """ /** * CoffeeScript Compiler v#{CoffeeScript.VERSION} * http://coffeescript.org * * Copyright 2011, PI:NAME:<NAME>END_PI * Released under the MIT License */ """ # Build the CoffeeScript language from source. build = (cb) -> files = fs.readdirSync 'src' files = ('src/' + file for file in files when file.match(/\.(lit)?coffee$/)) run ['-c', '-o', 'lib/coffee-script'].concat(files), cb # Run a CoffeeScript through our node/coffee interpreter. run = (args, cb) -> proc = spawn 'node', ['bin/coffee'].concat(args) proc.stderr.on 'data', (buffer) -> console.log buffer.toString() proc.on 'exit', (status) -> process.exit(1) if status != 0 cb() if typeof cb is 'function' # Log a message with a color. log = (message, color, explanation) -> console.log color + message + reset + ' ' + (explanation or '') option '-p', '--prefix [DIR]', 'set the installation prefix for `cake install`' task 'install', 'install CoffeeScript into /usr/local (or --prefix)', (options) -> base = options.prefix or '/usr/local' lib = "#{base}/lib/coffee-script" bin = "#{base}/bin" node = "~/.node_libraries/coffee-script" console.log "Installing CoffeeScript to #{lib}" console.log "Linking to #{node}" console.log "Linking 'coffee' to #{bin}/coffee" exec([ "mkdir -p #{lib} #{bin}" "cp -rf bin lib LICENSE README package.json src #{lib}" "ln -sfn #{lib}/bin/coffee #{bin}/coffee" "ln -sfn #{lib}/bin/cake #{bin}/cake" "mkdir -p ~/.node_libraries" "ln -sfn #{lib}/lib/coffee-script #{node}" ].join(' && '), (err, stdout, stderr) -> if err then console.log stderr.trim() else log 'done', green ) task 'build', 'build the CoffeeScript language from source', build task 'build:full', 'rebuild the source twice, and run the tests', -> build -> build -> csPath = './lib/coffee-script' csDir = path.dirname require.resolve csPath for mod of require.cache when csDir is mod[0 ... csDir.length] delete require.cache[mod] unless runTests require csPath process.exit 1 task 'build:parser', 'rebuild the Jison parser (run build first)', -> helpers.extend global, require('util') require 'jison' parser = require('./lib/coffee-script/grammar').parser fs.writeFile 'lib/coffee-script/parser.js', parser.generate() task 'build:ultraviolet', 'build and install the Ultraviolet syntax highlighter', -> exec 'plist2syntax ../coffee-script-tmbundle/Syntaxes/CoffeeScript.tmLanguage', (err) -> throw err if err exec 'sudo mv coffeescript.yaml /usr/local/lib/ruby/gems/1.8/gems/ultraviolet-0.10.2/syntax/coffeescript.syntax' task 'build:browser', 'rebuild the merged script for inclusion in the browser', -> code = '' for name in ['helpers', 'rewriter', 'lexer', 'parser', 'scope', 'nodes', 'sourcemap', 'coffee-script', 'browser'] code += """ require['./#{name}'] = (function() { var exports = {}, module = {exports: exports}; #{fs.readFileSync "lib/coffee-script/#{name}.js"} return module.exports; })(); """ code = """ (function(root) { var CoffeeScript = function() { function require(path){ return require[path]; } #{code} return require['./coffee-script']; }(); if (typeof define === 'function' && define.amd) { define(function() { return CoffeeScript; }); } else { root.CoffeeScript = CoffeeScript; } }(this)); """ unless process.env.MINIFY is 'false' {code} = require('uglify-js').minify code, fromString: true fs.writeFileSync 'extras/coffee-script.js', header + '\n' + code console.log "built ... running browser tests:" invoke 'test:browser' task 'doc:site', 'watch and continually rebuild the documentation for the website', -> exec 'rake doc', (err) -> throw err if err task 'doc:source', 'rebuild the internal documentation', -> exec 'docco src/*.*coffee && cp -rf docs documentation && rm -r docs', (err) -> throw err if err task 'doc:underscore', 'rebuild the Underscore.coffee documentation page', -> exec 'docco examples/underscore.coffee && cp -rf docs documentation && rm -r docs', (err) -> throw err if err task 'bench', 'quick benchmark of compilation time', -> {Rewriter} = require './lib/coffee-script/rewriter' sources = ['coffee-script', 'grammar', 'helpers', 'lexer', 'nodes', 'rewriter'] coffee = sources.map((name) -> fs.readFileSync "src/#{name}.coffee").join '\n' litcoffee = fs.readFileSync("src/scope.litcoffee").toString() fmt = (ms) -> " #{bold}#{ " #{ms}".slice -4 }#{reset} ms" total = 0 now = Date.now() time = -> total += ms = -(now - now = Date.now()); fmt ms tokens = CoffeeScript.tokens coffee, rewrite: no littokens = CoffeeScript.tokens litcoffee, rewrite: no, literate: yes tokens = tokens.concat(littokens) console.log "Lex #{time()} (#{tokens.length} tokens)" tokens = new Rewriter().rewrite tokens console.log "Rewrite#{time()} (#{tokens.length} tokens)" nodes = CoffeeScript.nodes tokens console.log "Parse #{time()}" js = nodes.compile bare: yes console.log "Compile#{time()} (#{js.length} chars)" console.log "total #{ fmt total }" # Run the CoffeeScript test suite. runTests = (CoffeeScript) -> startTime = Date.now() currentFile = null passedTests = 0 failures = [] global[name] = func for name, func of require 'assert' # Convenience aliases. global.CoffeeScript = CoffeeScript global.Repl = require './lib/coffee-script/repl' # Our test helper function for delimiting different test cases. global.test = (description, fn) -> try fn.test = {description, currentFile} fn.call(fn) ++passedTests catch e failures.push filename: currentFile error: e description: description if description? source: fn.toString() if fn.toString? # See http://wiki.ecmascript.org/doku.php?id=harmony:egal egal = (a, b) -> if a is b a isnt 0 or 1/a is 1/b else a isnt a and b isnt b # A recursive functional equivalence helper; uses egal for testing equivalence. arrayEgal = (a, b) -> if egal a, b then yes else if a instanceof Array and b instanceof Array return no unless a.length is b.length return no for el, idx in a when not arrayEgal el, b[idx] yes global.eq = (a, b, msg) -> ok egal(a, b), msg ? "Expected #{a} to equal #{b}" global.arrayEq = (a, b, msg) -> ok arrayEgal(a,b), msg ? "Expected #{a} to deep equal #{b}" # When all the tests have run, collect and print errors. # If a stacktrace is available, output the compiled function source. process.on 'exit', -> time = ((Date.now() - startTime) / 1000).toFixed(2) message = "passed #{passedTests} tests in #{time} seconds#{reset}" return log(message, green) unless failures.length log "failed #{failures.length} and #{message}", red for fail in failures {error, filename, description, source} = fail console.log '' log " #{description}", red if description log " #{error.stack}", red console.log " #{source}" if source return # Run every test in the `test` folder, recording failures. files = fs.readdirSync 'test' for file in files when helpers.isCoffee file literate = helpers.isLiterate file currentFile = filename = path.join 'test', file code = fs.readFileSync filename try CoffeeScript.run code.toString(), {filename, literate} catch error failures.push {filename, error} return !failures.length task 'test', 'run the CoffeeScript language test suite', -> runTests CoffeeScript task 'test:browser', 'run the test suite against the merged browser script', -> source = fs.readFileSync 'extras/coffee-script.js', 'utf-8' result = {} global.testingBrowser = yes (-> eval source).call result runTests result.CoffeeScript
[ { "context": " step.push \"\"\"\n cat #{files} | coffee -cbs > Cin7Menu@darkoverlordofdata.com/applet.js\n \"\"\"\n \n return step\n \n ", "end": 988, "score": 0.976520299911499, "start": 957, "tag": "EMAIL", "value": "Cin7Menu@darkoverlordofdata.com" }, { "cont...
package.scripts.coffee
darkoverlordofdata/Cin7Menu
1
### #+--------------------------------------------------------------------+ #| package.scripts.coffee #+--------------------------------------------------------------------+ #| Copyright DarkOverlordOfData (c) 2014-2015 #+--------------------------------------------------------------------+ #| #| Generate package.script #| #| ash.coffee is free software; you can copy, modify, and distribute #| it under the terms of the MIT License #| #+--------------------------------------------------------------------+ ### fs = require('fs') # paths: LIB_NAME = "Cin7Menu" CSCONFIG = "./csconfig.json" ### # Generate package.script ### module.exports = (project, options = {}) -> ### build the project ### build: do -> step = [].concat(project.config.build) ### # Build after recompiling all coffeescript together ### files = require(CSCONFIG).files.join(" LF ") step.push """ cat #{files} | coffee -cbs > Cin7Menu@darkoverlordofdata.com/applet.js """ return step ### delete the prior build items ### clean: """ rm -rf build/* """ ### prepare for build ### prebuild: """ npm run clean -s """ postbuild: """ cp -f ./Cin7Menu@darkoverlordofdata.com/applet.js ~/.local/share/cinnamon/applets/Cin7Menu@darkoverlordofdata.com/applet.js """
62536
### #+--------------------------------------------------------------------+ #| package.scripts.coffee #+--------------------------------------------------------------------+ #| Copyright DarkOverlordOfData (c) 2014-2015 #+--------------------------------------------------------------------+ #| #| Generate package.script #| #| ash.coffee is free software; you can copy, modify, and distribute #| it under the terms of the MIT License #| #+--------------------------------------------------------------------+ ### fs = require('fs') # paths: LIB_NAME = "Cin7Menu" CSCONFIG = "./csconfig.json" ### # Generate package.script ### module.exports = (project, options = {}) -> ### build the project ### build: do -> step = [].concat(project.config.build) ### # Build after recompiling all coffeescript together ### files = require(CSCONFIG).files.join(" LF ") step.push """ cat #{files} | coffee -cbs > <EMAIL>/applet.js """ return step ### delete the prior build items ### clean: """ rm -rf build/* """ ### prepare for build ### prebuild: """ npm run clean -s """ postbuild: """ cp -f ./<EMAIL>/applet.js ~/.local/share/cinnamon/applets/C<EMAIL>/applet.js """
true
### #+--------------------------------------------------------------------+ #| package.scripts.coffee #+--------------------------------------------------------------------+ #| Copyright DarkOverlordOfData (c) 2014-2015 #+--------------------------------------------------------------------+ #| #| Generate package.script #| #| ash.coffee is free software; you can copy, modify, and distribute #| it under the terms of the MIT License #| #+--------------------------------------------------------------------+ ### fs = require('fs') # paths: LIB_NAME = "Cin7Menu" CSCONFIG = "./csconfig.json" ### # Generate package.script ### module.exports = (project, options = {}) -> ### build the project ### build: do -> step = [].concat(project.config.build) ### # Build after recompiling all coffeescript together ### files = require(CSCONFIG).files.join(" LF ") step.push """ cat #{files} | coffee -cbs > PI:EMAIL:<EMAIL>END_PI/applet.js """ return step ### delete the prior build items ### clean: """ rm -rf build/* """ ### prepare for build ### prebuild: """ npm run clean -s """ postbuild: """ cp -f ./PI:EMAIL:<EMAIL>END_PI/applet.js ~/.local/share/cinnamon/applets/CPI:EMAIL:<EMAIL>END_PI/applet.js """
[ { "context": "\"))\n\ndescribe 'source helper', ->\n cloud_name = 'test123'\n public_id = \"sample\"\n image_format = \"jpg\"\n ", "end": 515, "score": 0.9084383249282837, "start": 508, "tag": "USERNAME", "value": "test123" }, { "context": "(true) # Reset\n cloudinary.config(c...
test/source_tag_spec.coffee
optune/cloudinary
0
expect = require('expect.js') cloudinary = require('../cloudinary') utils = cloudinary.utils helper = require("./spechelper") sharedContext = helper.sharedContext sharedExamples = helper.sharedExamples includeContext = helper.includeContext extend = require('lodash/extend') BREAKPOINTS = [5,3,7,5] UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload" srcRegExp = (name, path)-> RegExp("#{name}=[\"']#{UPLOAD_PATH}/#{path}[\"']".replace("/", "\/")) describe 'source helper', -> cloud_name = 'test123' public_id = "sample" image_format = "jpg" FULL_PUBLIC_ID = "#{public_id}.#{image_format}" commonTrans = null commonTransformationStr = null customAttributes = null min_width = null max_width = null breakpoint_list = null common_srcset = null fill_transformation = null fill_transformation_str = null beforeEach -> commonTrans = effect: 'sepia', cloud_name: 'test123', client_hints: false commonTransformationStr = 'e_sepia' customAttributes = custom_attr1: 'custom_value1', custom_attr2: 'custom_value2' min_width = 100 max_width = 399 breakpoint_list = [min_width, 200, 300, max_width] common_srcset = {"breakpoints": breakpoint_list} fill_transformation = {"width": max_width, "height": max_width, "crop": "fill"} fill_transformation_str = "c_fill,h_#{max_width},w_#{max_width}" cloudinary.config(true) # Reset cloudinary.config(cloud_name: "test123", api_secret: "1234") it "should generate a source tag", -> expect(cloudinary.source("sample.jpg")).to.eql("<source srcset='#{UPLOAD_PATH}/sample.jpg'>") it "should generate source tag with media query", -> media = {min_width, max_width} tag = cloudinary.source(FULL_PUBLIC_ID, media: media) expectedMedia = "(min-width: #{min_width}px) and (max-width: #{max_width}px)" expectedTag = "<source media='#{expectedMedia}' srcset='#{UPLOAD_PATH}/sample.jpg'>" expect(tag).to.eql(expectedTag) it "should generate source tag with responsive srcset", -> tag = cloudinary.source(FULL_PUBLIC_ID, srcset: common_srcset) expect(tag).to.eql( "<source srcset='" + "http://res.cloudinary.com/test123/image/upload/c_scale,w_100/sample.jpg 100w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_200/sample.jpg 200w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_300/sample.jpg 300w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_399/sample.jpg 399w" + "'>") it "should generate picture tag", -> tag = cloudinary.picture(FULL_PUBLIC_ID, cloudinary.utils.extend({sources: [ {"max_width": min_width, "transformation": {"effect": "sepia", "angle": 17, "width": min_width}}, {"min_width": min_width, "max_width": max_width, "transformation": {"effect": "colorize", "angle": 18, "width": max_width}}, {"min_width": max_width, "transformation": {"effect": "blur", "angle": 19, "width": max_width}} ]}, fill_transformation)) exp_tag = "<picture>" + "<source media='(max-width: 100px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_17,e_sepia,w_100/sample.jpg'>" + "<source media='(min-width: 100px) and (max-width: 399px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_18,e_colorize,w_399/sample.jpg'>" + "<source media='(min-width: 399px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_19,e_blur,w_399/sample.jpg'>" + "<img src='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/sample.jpg' height='399' width='399'/>" + "</picture>" expect(tag).to.eql(exp_tag) getExpectedSrcsetTag = (publicId, commonTrans, customTrans, breakpoints, attributes = {})-> if(!customTrans) customTrans = commonTrans if(!utils.isEmpty(breakpoints)) attributes.srcset = breakpoints.map((width)-> "#{UPLOAD_PATH}/#{customTrans}/c_scale,w_#{width}/#{publicId} #{width}w").join(', '); tag = "<img src='#{UPLOAD_PATH}/#{commonTrans}/#{publicId}'" attrs = Object.entries(attributes).map(([key, value])-> "#{key}='#{value}'").join(' ') if(attrs) tag += ' ' + attrs tag += "/>"
203455
expect = require('expect.js') cloudinary = require('../cloudinary') utils = cloudinary.utils helper = require("./spechelper") sharedContext = helper.sharedContext sharedExamples = helper.sharedExamples includeContext = helper.includeContext extend = require('lodash/extend') BREAKPOINTS = [5,3,7,5] UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload" srcRegExp = (name, path)-> RegExp("#{name}=[\"']#{UPLOAD_PATH}/#{path}[\"']".replace("/", "\/")) describe 'source helper', -> cloud_name = 'test123' public_id = "sample" image_format = "jpg" FULL_PUBLIC_ID = "#{public_id}.#{image_format}" commonTrans = null commonTransformationStr = null customAttributes = null min_width = null max_width = null breakpoint_list = null common_srcset = null fill_transformation = null fill_transformation_str = null beforeEach -> commonTrans = effect: 'sepia', cloud_name: 'test123', client_hints: false commonTransformationStr = 'e_sepia' customAttributes = custom_attr1: 'custom_value1', custom_attr2: 'custom_value2' min_width = 100 max_width = 399 breakpoint_list = [min_width, 200, 300, max_width] common_srcset = {"breakpoints": breakpoint_list} fill_transformation = {"width": max_width, "height": max_width, "crop": "fill"} fill_transformation_str = "c_fill,h_#{max_width},w_#{max_width}" cloudinary.config(true) # Reset cloudinary.config(cloud_name: "test123", api_secret: "<KEY>") it "should generate a source tag", -> expect(cloudinary.source("sample.jpg")).to.eql("<source srcset='#{UPLOAD_PATH}/sample.jpg'>") it "should generate source tag with media query", -> media = {min_width, max_width} tag = cloudinary.source(FULL_PUBLIC_ID, media: media) expectedMedia = "(min-width: #{min_width}px) and (max-width: #{max_width}px)" expectedTag = "<source media='#{expectedMedia}' srcset='#{UPLOAD_PATH}/sample.jpg'>" expect(tag).to.eql(expectedTag) it "should generate source tag with responsive srcset", -> tag = cloudinary.source(FULL_PUBLIC_ID, srcset: common_srcset) expect(tag).to.eql( "<source srcset='" + "http://res.cloudinary.com/test123/image/upload/c_scale,w_100/sample.jpg 100w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_200/sample.jpg 200w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_300/sample.jpg 300w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_399/sample.jpg 399w" + "'>") it "should generate picture tag", -> tag = cloudinary.picture(FULL_PUBLIC_ID, cloudinary.utils.extend({sources: [ {"max_width": min_width, "transformation": {"effect": "sepia", "angle": 17, "width": min_width}}, {"min_width": min_width, "max_width": max_width, "transformation": {"effect": "colorize", "angle": 18, "width": max_width}}, {"min_width": max_width, "transformation": {"effect": "blur", "angle": 19, "width": max_width}} ]}, fill_transformation)) exp_tag = "<picture>" + "<source media='(max-width: 100px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_17,e_sepia,w_100/sample.jpg'>" + "<source media='(min-width: 100px) and (max-width: 399px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_18,e_colorize,w_399/sample.jpg'>" + "<source media='(min-width: 399px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_19,e_blur,w_399/sample.jpg'>" + "<img src='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/sample.jpg' height='399' width='399'/>" + "</picture>" expect(tag).to.eql(exp_tag) getExpectedSrcsetTag = (publicId, commonTrans, customTrans, breakpoints, attributes = {})-> if(!customTrans) customTrans = commonTrans if(!utils.isEmpty(breakpoints)) attributes.srcset = breakpoints.map((width)-> "#{UPLOAD_PATH}/#{customTrans}/c_scale,w_#{width}/#{publicId} #{width}w").join(', '); tag = "<img src='#{UPLOAD_PATH}/#{commonTrans}/#{publicId}'" attrs = Object.entries(attributes).map(([key, value])-> "#{key}='#{value}'").join(' ') if(attrs) tag += ' ' + attrs tag += "/>"
true
expect = require('expect.js') cloudinary = require('../cloudinary') utils = cloudinary.utils helper = require("./spechelper") sharedContext = helper.sharedContext sharedExamples = helper.sharedExamples includeContext = helper.includeContext extend = require('lodash/extend') BREAKPOINTS = [5,3,7,5] UPLOAD_PATH = "http://res.cloudinary.com/test123/image/upload" srcRegExp = (name, path)-> RegExp("#{name}=[\"']#{UPLOAD_PATH}/#{path}[\"']".replace("/", "\/")) describe 'source helper', -> cloud_name = 'test123' public_id = "sample" image_format = "jpg" FULL_PUBLIC_ID = "#{public_id}.#{image_format}" commonTrans = null commonTransformationStr = null customAttributes = null min_width = null max_width = null breakpoint_list = null common_srcset = null fill_transformation = null fill_transformation_str = null beforeEach -> commonTrans = effect: 'sepia', cloud_name: 'test123', client_hints: false commonTransformationStr = 'e_sepia' customAttributes = custom_attr1: 'custom_value1', custom_attr2: 'custom_value2' min_width = 100 max_width = 399 breakpoint_list = [min_width, 200, 300, max_width] common_srcset = {"breakpoints": breakpoint_list} fill_transformation = {"width": max_width, "height": max_width, "crop": "fill"} fill_transformation_str = "c_fill,h_#{max_width},w_#{max_width}" cloudinary.config(true) # Reset cloudinary.config(cloud_name: "test123", api_secret: "PI:KEY:<KEY>END_PI") it "should generate a source tag", -> expect(cloudinary.source("sample.jpg")).to.eql("<source srcset='#{UPLOAD_PATH}/sample.jpg'>") it "should generate source tag with media query", -> media = {min_width, max_width} tag = cloudinary.source(FULL_PUBLIC_ID, media: media) expectedMedia = "(min-width: #{min_width}px) and (max-width: #{max_width}px)" expectedTag = "<source media='#{expectedMedia}' srcset='#{UPLOAD_PATH}/sample.jpg'>" expect(tag).to.eql(expectedTag) it "should generate source tag with responsive srcset", -> tag = cloudinary.source(FULL_PUBLIC_ID, srcset: common_srcset) expect(tag).to.eql( "<source srcset='" + "http://res.cloudinary.com/test123/image/upload/c_scale,w_100/sample.jpg 100w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_200/sample.jpg 200w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_300/sample.jpg 300w, " + "http://res.cloudinary.com/test123/image/upload/c_scale,w_399/sample.jpg 399w" + "'>") it "should generate picture tag", -> tag = cloudinary.picture(FULL_PUBLIC_ID, cloudinary.utils.extend({sources: [ {"max_width": min_width, "transformation": {"effect": "sepia", "angle": 17, "width": min_width}}, {"min_width": min_width, "max_width": max_width, "transformation": {"effect": "colorize", "angle": 18, "width": max_width}}, {"min_width": max_width, "transformation": {"effect": "blur", "angle": 19, "width": max_width}} ]}, fill_transformation)) exp_tag = "<picture>" + "<source media='(max-width: 100px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_17,e_sepia,w_100/sample.jpg'>" + "<source media='(min-width: 100px) and (max-width: 399px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_18,e_colorize,w_399/sample.jpg'>" + "<source media='(min-width: 399px)' srcset='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/a_19,e_blur,w_399/sample.jpg'>" + "<img src='http://res.cloudinary.com/test123/image/upload/c_fill,h_399,w_399/sample.jpg' height='399' width='399'/>" + "</picture>" expect(tag).to.eql(exp_tag) getExpectedSrcsetTag = (publicId, commonTrans, customTrans, breakpoints, attributes = {})-> if(!customTrans) customTrans = commonTrans if(!utils.isEmpty(breakpoints)) attributes.srcset = breakpoints.map((width)-> "#{UPLOAD_PATH}/#{customTrans}/c_scale,w_#{width}/#{publicId} #{width}w").join(', '); tag = "<img src='#{UPLOAD_PATH}/#{commonTrans}/#{publicId}'" attrs = Object.entries(attributes).map(([key, value])-> "#{key}='#{value}'").join(' ') if(attrs) tag += ' ' + attrs tag += "/>"
[ { "context": "\n\t\tdoi: [\"jaes/savva001\"]\n\t\ttitle: \"Replication of Grier, Henry, Olekalns and Shields (2004)--The Asym", "end": 878, "score": 0.581762969493866, "start": 877, "tag": "NAME", "value": "G" }, { "context": " [\"jaes/savva001\"]\n\t\ttitle: \"Replication of Grier, ...
data.cson
infolis/infolis-button
2
# vim: ft=coffee : # :nnoremap <buffer> <F5> :!cson2json % > %:t:r.json<cr> uri2doi: 'http://www.igi-global.com/article/a-prescriptive-stock-market-investment-strategy-for-the-restaurant-industry-using-an-artificial-neural-network-methodology/142778': '10.4018/IJBAN.2016010101' 'http://indexes.nikkei.co.jp/en/nkave/index/profile?idx=nk225': 'nk225' 'https://ideas.repec.org/h/eee/finchp/2-13.html': 'RePEc:eee:finchp:2-13' datasets: # http://ec.europa.eu/eurostat/statistics-explained/index.php/Labour_markets_at_regional_level/de#Ver.C3.B6ffentlichungen 'eurostat:tgs00054(2004)': doi:['eurostat:tgs00054'] url: 'http://ec.europa.eu/eurostat/tgm/table.do?tab=table&plugin=1&language=de&pcode=tgs00054' title: 'Erwerbstätigenquote der Altersgruppe 55-64, nach NUTS-2-Regionen, Stand 31.12.2004' "jaes/savva001": doi: ["jaes/savva001"] title: "Replication of Grier, Henry, Olekalns and Shields (2004)--The Asymmetric Effects of Uncertainty on Inflation and Output Growth" url: "http://qed.econ.queensu.ca/jae/datasets/savva001/" "10.4232/1.12209": title: "ALLBUS/GGSS 2014" doi: ["10.4232/1.12209"] "10.4232/1.12288": title: "ALLBUS/GGSS 2015" doi: ["10.4232/1.12209"] "10.5281/zenodo.13293": title: 'Researcher Data Publication Perceptions' doi: ["10.5281/zenodo.13293"] github: ['JEK-III/ResearcherDataPubPerceptions'] '10.6084/m9.figshare.c.2011262.v1': title: 'Stock Return Predictability: A Factor-Augmented Predictive Regression System with Shrinkage Method' doi: ['10.6084/m9.figshare.c.2011262.v1'] figshare: 'https://figshare.com/collections/Stock_Return_Predictability_A_Factor_Augmented_Predictive_Regression_System_with_Shrinkage_Method/2011262' "1902.1/UQRPVVDBHI": title: "Replication data for: Consumption-Based Asset Pricing" doi: ["1902.1/UQRPVVDBHI"] citation_ris: """ Provider: Harvard Dataverse Content: text/plain; charset="us-ascii" TY - DBASE T1 - Replication data for: Consumption-Based Asset Pricing AU - John Y. Campbell DO - hdl/1902.1/UQRPVVDBHI PY - 2013 UR - http://hdl.handle.net/1902.1/UQRPVVDBHI PB - Harvard Dataverse ER - """ citation_endnote: """ <?xml version='1.0' encoding='UTF-8'?> <xml> <records> <record> <ref-type name="Online Database">45</ref-type> <contributors> <authors> <author>John Y. Campbell</author> </authors> </contributors> <titles> <title>Replication data for: Consumption-Based Asset Pricing</title> </titles> <section>2007-12-03</section> <dates> <year>2013</year> </dates> <publisher>Harvard Dataverse</publisher> <urls> <related-urls> <url>http://hdl.handle.net/1902.1/UQRPVVDBHI</url> </related-urls> </urls> <electronic-resource-num>hdl/1902.1/UQRPVVDBHI</electronic-resource-num> </record> </records> </xml> """ databases: eulfs: name: 'Eurostat LFS' url: 'http://ec.europa.eu/eurostat/web/lfs/data/main-tables' toyo_keizai: name: 'Toyo Keizai' url: 'http://dbs.toyokeizai.net/en/' topix: name: 'Tokyo Stock Price Index' url: 'http://www.bloomberg.com/quote/TPX:IND' dax30: name: 'Deutscher Aktienindex DAX' url: 'http://www.bloomberg.com/quote/DAX:IND' nasdaq: name: 'NASDAQ' url: 'http://www.bloomberg.com/quote/NASDAQ:IND' ftse100: name: 'FTSE 100 Index (UKX)' url: 'http://www.bloomberg.com/quote/UKX:IND' sp500: name: "Standard and Poor's 500" url: 'http://www.bloomberg.com/quote/SPX:IND' sensex: name: 'BME SENSEX' url: 'http://www.bloomberg.com/quote/SENSEX:IND' shshazr: name: 'Shenzhen A-Share' url: 'http://www.bloomberg.com/quote/SZASHR:IND' csmar: name: 'China Stock Market Accounting Research' url: 'http://csmar.gtadata.com/' yahoo_finance: name: "Yahoo Finance" url: "https://in.finance.yahoo.com" bist100: name: "Borsa Istanbul 100 Index" url: "http://www.bloomberg.com/quote/XU100:IND" gfd: name: 'Global Finance Data' url: 'https://www.globalfinancialdata.com' csi100: name: 'CSI 100 Index' url: 'http://www.bloomberg.com/quote/SHCSI100:IND' nikkei225: name: 'Nikkei Index' url: 'http://indexes.nikkei.co.jp/en/nkave/index/profile?idx=nk225' eia_monthly: url: 'http://www.eia.gov/totalenergy/data/monthly/' name: 'Monthly Energy Review' eia_steo: name: 'Short-term Energy Outlook' url: 'http://www.eia.gov/forecasts/steo/' amadeus: name: 'Amadeus' url: 'https://amadeus.bvdinfo.com' osiris: name: "Osiris" url: "http://www.bvdinfo.com/en-gb/our-products/company-information/international-products/osiris" bloomberg: name: "Bloomberg" url: "http://www.bloomberg.com/professional/" worldscope: name: "Worldscope" url: "http://extranet.datastream.com/Data/Worldscope/index.htm" datastream: name: "DataStream" url: "http://financial.thomsonreuters.com/en/products/tools-applications/trading-investment-tools/datastream-macroeconomic-analysis.html" trna: name: "TRNA" url: "http://financial.thomsonreuters.com/en/products/data-analytics/financial-news-feed.html" sdc: name: "SDC" url: "http://thomsonreuters.com/en/products-services/financial/market-data/sdc-platinum.html" crsp: name: "CRSP" url: "http://www.crsp.com/" ctbs: name: "CTBS" url: "http://www.nelson.com/assessment/classroom-CTBS.html" publications: "10.1093/rfs/hht068": doi: ["10.1093/rfs/hht068"] databases: ["bloomberg"] "10.1207/s15327035ex1302_2": doi: ["10.1207/s15327035ex1302_2"] databases: ["ctbs"] "10.1093/rfs/hht044": doi: ["10.1093/rfs/hht044"] databases: ["osiris", "worldscope", "datastream"] "10.1093/rfs/hhu032": doi: ["10.1093/rfs/hhu032"] databases: ["trna", "bloomberg"] "10.1093/rfs/hht082": doi: ["10.1093/rfs/hht082"] databases: ["sdc", "crsp"] "10.1080/095372897235398": doi: ["10.1080/095372897235398"] title: "An algorithm to dynamically adjust the number of kanbans in stochastic processing times and variable demand environment" databases: ["sdc","crsp"] datasets: ['10.4232/1.12209'] "10.1093/rfs/6.2.327": doi: ["10.1093/rfs/6.2.327"] title: "A Closed-Form Solution for Options with Stochastic Volatility with Applications to Bond and Currency Options" authors: "Steven L. Heston " databases: ['crsp'] datasets: ['10.4232/1.12209'] "10.1093/rfs/5.4.553": doi: ["10.1093/rfs/5.4.553"] databases: ['amadeus'] # # Google Scholar: Search 'stock market prediction' # "10.1016/j.chaos.2016.01.004": doi: ["10.1016/j.chaos.2016.01.004"] title: "Application of artificial neural network for the prediction of stock market returns: The case of the Japanese stock market" databases: ['nikkei225'] "10.1111/jofi.12364": doi: ["10.1111/jofi.12364"] title: "Stock Market Volatility and Learning" datasets: ["1902.1/UQRPVVDBHI"] databases: ['gfd'] "10.1016/j.eswa.2015.09.029": doi: ["10.1016/j.eswa.2015.09.029"] title: "Integrating metaheuristics and Artificial Neural Networks for improved stock price prediction" databases: ['bloomberg', 'bist100'] "10.1007/978-3-319-23258-4_24": doi: ['10.1007/978-3-319-23258-4_24'] title: 'An Effective Stock Price Prediction Technique Using Hybrid Adaptive Neuro Fuzzy Inference System Based on Grid Partitioning' databases: ['yahoo_finance'] "10.1002/jae.2500": doi:['10.1002/jae.2500'] title: 'Anticipation, Tax Avoidance, and the Price Elasticity of Gasoline Demand' datasets: ['jaes/savva001'] databases: ['eia_steo', 'eia_monthly'] "10.1145/2838731": doi: ['10.1145/2838731'] title: 'A Tensor-Based Information Framework for Predicting the Stock Market' databases: ['csmar', 'csi100', 'sensex'] "10.1016/j.eswa.2016.01.016": doi:['10.1016/j.eswa.2016.01.016'] title: 'Efficient stock price prediction using a Self Evolving Recurrent Neuro-Fuzzy Inference System optimized through a Modified technique' databases: ['bloomberg', 'sensex', 'sp500'] "10.4018/IJBAN.2016010101": doi: ['10.4018/IJBAN.2016010101'] title: 'A Prescriptive Stock Market Investment Strategy for the Restaurant Industry using an Artificial Neural Network Methodology' databases: ['yahoo_finance'] # # Primo -> 'Stock price prediction' # "10.1016/j.eswa.2010.08.076": doi: ["10.1016/j.eswa.2010.08.076"] title: 'Translation Invariant Morphological Time-lag Added Evolutionary Forecasting method for stock market prediction' databases: ['bloomberg'] # # Primo -> 'Stock price prediction', newest, peer-reviewd journal # '10.1016/j.eswa.2015.01.035': doi: ['10.1016/j.eswa.2015.01.035'] title: 'Stock market trend prediction using dynamical Bayesian factor graph' databases: ['shshazr', 'sp500'] '10.1016/j.eswa.2015.04.056': doi:['10.1016/j.eswa.2015.04.056'] title: 'Boosting Trading Strategies performance using VIX indicator together with a dual-objective Evolutionary Computation optimizer' databases: ['nasdaq', 'nikkei225', 'sp500', 'ftse100', 'dax30'] # http://www.tandfonline.com/doi/full/10.1080/07474938.2014.977086 '10.1080/07474938.2014.977086': doi:['10.1080/07474938.2014.977086'] title:'Stock Return Predictability: A Factor-Augmented Predictive Regression System with Shrinkage Method' datasets: ['10.6084/m9.figshare.c.2011262.v1'] databases: ['toyo_keizai', 'topix'] # https://ideas.repec.org/h/eee/finchp/2-13.html "RePEc:eee:finchp:2-13": doi:["RePEc:eee:finchp:2-13"] title: 'Consumption-based asset pricing' datasets: ['1902.1/UQRPVVDBHI'] '10.1371/journal.pone.0117619': doi:['10.1371/journal.pone.0117619'] title: 'Researcher Perspectives on Publication and Peer Review of Data' datasets: ['10.5281/zenodo.13293'] 'ZAAA2005110027513181411142812171': doi:['10.17877/DE290R-1856'] url: 'http://dx.doi.org/10.17877/DE290R-1856' title: 'Die Beschäftigung Älterer in Europa zwischen Vorruhestand und "Work-Line"' datasets: ['eurostat:tgs00054(2004)'] databases: ['eulfs']
132054
# vim: ft=coffee : # :nnoremap <buffer> <F5> :!cson2json % > %:t:r.json<cr> uri2doi: 'http://www.igi-global.com/article/a-prescriptive-stock-market-investment-strategy-for-the-restaurant-industry-using-an-artificial-neural-network-methodology/142778': '10.4018/IJBAN.2016010101' 'http://indexes.nikkei.co.jp/en/nkave/index/profile?idx=nk225': 'nk225' 'https://ideas.repec.org/h/eee/finchp/2-13.html': 'RePEc:eee:finchp:2-13' datasets: # http://ec.europa.eu/eurostat/statistics-explained/index.php/Labour_markets_at_regional_level/de#Ver.C3.B6ffentlichungen 'eurostat:tgs00054(2004)': doi:['eurostat:tgs00054'] url: 'http://ec.europa.eu/eurostat/tgm/table.do?tab=table&plugin=1&language=de&pcode=tgs00054' title: 'Erwerbstätigenquote der Altersgruppe 55-64, nach NUTS-2-Regionen, Stand 31.12.2004' "jaes/savva001": doi: ["jaes/savva001"] title: "Replication of <NAME>rier, <NAME>, Ole<NAME>ns and Shields (2004)--The Asymmetric Effects of Uncertainty on Inflation and Output Growth" url: "http://qed.econ.queensu.ca/jae/datasets/savva001/" "10.4232/1.12209": title: "ALLBUS/GGSS 2014" doi: ["10.4232/1.12209"] "10.4232/1.12288": title: "ALLBUS/GGSS 2015" doi: ["10.4232/1.12209"] "10.5281/zenodo.13293": title: 'Researcher Data Publication Perceptions' doi: ["10.5281/zenodo.13293"] github: ['JEK-III/ResearcherDataPubPerceptions'] '10.6084/m9.figshare.c.2011262.v1': title: 'Stock Return Predictability: A Factor-Augmented Predictive Regression System with Shrinkage Method' doi: ['10.6084/m9.figshare.c.2011262.v1'] figshare: 'https://figshare.com/collections/Stock_Return_Predictability_A_Factor_Augmented_Predictive_Regression_System_with_Shrinkage_Method/2011262' "1902.1/UQRPVVDBHI": title: "Replication data for: Consumption-Based Asset Pricing" doi: ["1902.1/UQRPVVDBHI"] citation_ris: """ Provider: Harvard Dataverse Content: text/plain; charset="us-ascii" TY - DBASE T1 - Replication data for: Consumption-Based Asset Pricing AU - <NAME> DO - hdl/1902.1/UQRPVVDBHI PY - 2013 UR - http://hdl.handle.net/1902.1/UQRPVVDBHI PB - Harvard Dataverse ER - """ citation_endnote: """ <?xml version='1.0' encoding='UTF-8'?> <xml> <records> <record> <ref-type name="Online Database">45</ref-type> <contributors> <authors> <author><NAME></author> </authors> </contributors> <titles> <title>Replication data for: Consumption-Based Asset Pricing</title> </titles> <section>2007-12-03</section> <dates> <year>2013</year> </dates> <publisher>Harvard Dataverse</publisher> <urls> <related-urls> <url>http://hdl.handle.net/1902.1/UQRPVVDBHI</url> </related-urls> </urls> <electronic-resource-num>hdl/1902.1/UQRPVVDBHI</electronic-resource-num> </record> </records> </xml> """ databases: eulfs: name: 'Eurostat LFS' url: 'http://ec.europa.eu/eurostat/web/lfs/data/main-tables' toyo_keizai: name: 'Toyo Keizai' url: 'http://dbs.toyokeizai.net/en/' topix: name: 'Tokyo Stock Price Index' url: 'http://www.bloomberg.com/quote/TPX:IND' dax30: name: 'Deutscher Aktienindex DAX' url: 'http://www.bloomberg.com/quote/DAX:IND' nasdaq: name: 'NASDAQ' url: 'http://www.bloomberg.com/quote/NASDAQ:IND' ftse100: name: 'FTSE 100 Index (UKX)' url: 'http://www.bloomberg.com/quote/UKX:IND' sp500: name: "Standard and Poor's 500" url: 'http://www.bloomberg.com/quote/SPX:IND' sensex: name: 'BME SENSEX' url: 'http://www.bloomberg.com/quote/SENSEX:IND' shshazr: name: 'Shenzhen A-Share' url: 'http://www.bloomberg.com/quote/SZASHR:IND' csmar: name: 'China Stock Market Accounting Research' url: 'http://csmar.gtadata.com/' yahoo_finance: name: "Yahoo Finance" url: "https://in.finance.yahoo.com" bist100: name: "Borsa Istanbul 100 Index" url: "http://www.bloomberg.com/quote/XU100:IND" gfd: name: 'Global Finance Data' url: 'https://www.globalfinancialdata.com' csi100: name: 'CSI 100 Index' url: 'http://www.bloomberg.com/quote/SHCSI100:IND' nikkei225: name: 'Nikkei Index' url: 'http://indexes.nikkei.co.jp/en/nkave/index/profile?idx=nk225' eia_monthly: url: 'http://www.eia.gov/totalenergy/data/monthly/' name: 'Monthly Energy Review' eia_steo: name: 'Short-term Energy Outlook' url: 'http://www.eia.gov/forecasts/steo/' amadeus: name: 'Amadeus' url: 'https://amadeus.bvdinfo.com' osiris: name: "Osiris" url: "http://www.bvdinfo.com/en-gb/our-products/company-information/international-products/osiris" bloomberg: name: "Bloomberg" url: "http://www.bloomberg.com/professional/" worldscope: name: "Worldscope" url: "http://extranet.datastream.com/Data/Worldscope/index.htm" datastream: name: "DataStream" url: "http://financial.thomsonreuters.com/en/products/tools-applications/trading-investment-tools/datastream-macroeconomic-analysis.html" trna: name: "TRNA" url: "http://financial.thomsonreuters.com/en/products/data-analytics/financial-news-feed.html" sdc: name: "SDC" url: "http://thomsonreuters.com/en/products-services/financial/market-data/sdc-platinum.html" crsp: name: "CRSP" url: "http://www.crsp.com/" ctbs: name: "CTBS" url: "http://www.nelson.com/assessment/classroom-CTBS.html" publications: "10.1093/rfs/hht068": doi: ["10.1093/rfs/hht068"] databases: ["bloomberg"] "10.1207/s15327035ex1302_2": doi: ["10.1207/s15327035ex1302_2"] databases: ["ctbs"] "10.1093/rfs/hht044": doi: ["10.1093/rfs/hht044"] databases: ["osiris", "worldscope", "datastream"] "10.1093/rfs/hhu032": doi: ["10.1093/rfs/hhu032"] databases: ["trna", "bloomberg"] "10.1093/rfs/hht082": doi: ["10.1093/rfs/hht082"] databases: ["sdc", "crsp"] "10.1080/095372897235398": doi: ["10.1080/095372897235398"] title: "An algorithm to dynamically adjust the number of kanbans in stochastic processing times and variable demand environment" databases: ["sdc","crsp"] datasets: ['10.4232/1.12209'] "10.1093/rfs/6.2.327": doi: ["10.1093/rfs/6.2.327"] title: "A Closed-Form Solution for Options with Stochastic Volatility with Applications to Bond and Currency Options" authors: "<NAME> " databases: ['crsp'] datasets: ['10.4232/1.12209'] "10.1093/rfs/5.4.553": doi: ["10.1093/rfs/5.4.553"] databases: ['amadeus'] # # Google Scholar: Search 'stock market prediction' # "10.1016/j.chaos.2016.01.004": doi: ["10.1016/j.chaos.2016.01.004"] title: "Application of artificial neural network for the prediction of stock market returns: The case of the Japanese stock market" databases: ['nikkei225'] "10.1111/jofi.12364": doi: ["10.1111/jofi.12364"] title: "Stock Market Volatility and Learning" datasets: ["1902.1/UQRPVVDBHI"] databases: ['gfd'] "10.1016/j.eswa.2015.09.029": doi: ["10.1016/j.eswa.2015.09.029"] title: "Integrating metaheuristics and Artificial Neural Networks for improved stock price prediction" databases: ['bloomberg', 'bist100'] "10.1007/978-3-319-23258-4_24": doi: ['10.1007/978-3-319-23258-4_24'] title: 'An Effective Stock Price Prediction Technique Using Hybrid Adaptive Neuro Fuzzy Inference System Based on Grid Partitioning' databases: ['yahoo_finance'] "10.1002/jae.2500": doi:['10.1002/jae.2500'] title: 'Anticipation, Tax Avoidance, and the Price Elasticity of Gasoline Demand' datasets: ['jaes/savva001'] databases: ['eia_steo', 'eia_monthly'] "10.1145/2838731": doi: ['10.1145/2838731'] title: 'A Tensor-Based Information Framework for Predicting the Stock Market' databases: ['csmar', 'csi100', 'sensex'] "10.1016/j.eswa.2016.01.016": doi:['10.1016/j.eswa.2016.01.016'] title: 'Efficient stock price prediction using a Self Evolving Recurrent Neuro-Fuzzy Inference System optimized through a Modified technique' databases: ['bloomberg', 'sensex', 'sp500'] "10.4018/IJBAN.2016010101": doi: ['10.4018/IJBAN.2016010101'] title: 'A Prescriptive Stock Market Investment Strategy for the Restaurant Industry using an Artificial Neural Network Methodology' databases: ['yahoo_finance'] # # Primo -> 'Stock price prediction' # "10.1016/j.eswa.2010.08.076": doi: ["10.1016/j.eswa.2010.08.076"] title: 'Translation Invariant Morphological Time-lag Added Evolutionary Forecasting method for stock market prediction' databases: ['bloomberg'] # # Primo -> 'Stock price prediction', newest, peer-reviewd journal # '10.1016/j.eswa.2015.01.035': doi: ['10.1016/j.eswa.2015.01.035'] title: 'Stock market trend prediction using dynamical Bayesian factor graph' databases: ['shshazr', 'sp500'] '10.1016/j.eswa.2015.04.056': doi:['10.1016/j.eswa.2015.04.056'] title: 'Boosting Trading Strategies performance using VIX indicator together with a dual-objective Evolutionary Computation optimizer' databases: ['nasdaq', 'nikkei225', 'sp500', 'ftse100', 'dax30'] # http://www.tandfonline.com/doi/full/10.1080/07474938.2014.977086 '10.1080/07474938.2014.977086': doi:['10.1080/07474938.2014.977086'] title:'Stock Return Predictability: A Factor-Augmented Predictive Regression System with Shrinkage Method' datasets: ['10.6084/m9.figshare.c.2011262.v1'] databases: ['toyo_keizai', 'topix'] # https://ideas.repec.org/h/eee/finchp/2-13.html "RePEc:eee:finchp:2-13": doi:["RePEc:eee:finchp:2-13"] title: 'Consumption-based asset pricing' datasets: ['1902.1/UQRPVVDBHI'] '10.1371/journal.pone.0117619': doi:['10.1371/journal.pone.0117619'] title: 'Researcher Perspectives on Publication and Peer Review of Data' datasets: ['10.5281/zenodo.13293'] 'ZAAA2005110027513181411142812171': doi:['10.17877/DE290R-1856'] url: 'http://dx.doi.org/10.17877/DE290R-1856' title: 'Die Beschäftigung Älterer in Europa zwischen Vorruhestand und "Work-Line"' datasets: ['eurostat:tgs00054(2004)'] databases: ['eulfs']
true
# vim: ft=coffee : # :nnoremap <buffer> <F5> :!cson2json % > %:t:r.json<cr> uri2doi: 'http://www.igi-global.com/article/a-prescriptive-stock-market-investment-strategy-for-the-restaurant-industry-using-an-artificial-neural-network-methodology/142778': '10.4018/IJBAN.2016010101' 'http://indexes.nikkei.co.jp/en/nkave/index/profile?idx=nk225': 'nk225' 'https://ideas.repec.org/h/eee/finchp/2-13.html': 'RePEc:eee:finchp:2-13' datasets: # http://ec.europa.eu/eurostat/statistics-explained/index.php/Labour_markets_at_regional_level/de#Ver.C3.B6ffentlichungen 'eurostat:tgs00054(2004)': doi:['eurostat:tgs00054'] url: 'http://ec.europa.eu/eurostat/tgm/table.do?tab=table&plugin=1&language=de&pcode=tgs00054' title: 'Erwerbstätigenquote der Altersgruppe 55-64, nach NUTS-2-Regionen, Stand 31.12.2004' "jaes/savva001": doi: ["jaes/savva001"] title: "Replication of PI:NAME:<NAME>END_PIrier, PI:NAME:<NAME>END_PI, OlePI:NAME:<NAME>END_PIns and Shields (2004)--The Asymmetric Effects of Uncertainty on Inflation and Output Growth" url: "http://qed.econ.queensu.ca/jae/datasets/savva001/" "10.4232/1.12209": title: "ALLBUS/GGSS 2014" doi: ["10.4232/1.12209"] "10.4232/1.12288": title: "ALLBUS/GGSS 2015" doi: ["10.4232/1.12209"] "10.5281/zenodo.13293": title: 'Researcher Data Publication Perceptions' doi: ["10.5281/zenodo.13293"] github: ['JEK-III/ResearcherDataPubPerceptions'] '10.6084/m9.figshare.c.2011262.v1': title: 'Stock Return Predictability: A Factor-Augmented Predictive Regression System with Shrinkage Method' doi: ['10.6084/m9.figshare.c.2011262.v1'] figshare: 'https://figshare.com/collections/Stock_Return_Predictability_A_Factor_Augmented_Predictive_Regression_System_with_Shrinkage_Method/2011262' "1902.1/UQRPVVDBHI": title: "Replication data for: Consumption-Based Asset Pricing" doi: ["1902.1/UQRPVVDBHI"] citation_ris: """ Provider: Harvard Dataverse Content: text/plain; charset="us-ascii" TY - DBASE T1 - Replication data for: Consumption-Based Asset Pricing AU - PI:NAME:<NAME>END_PI DO - hdl/1902.1/UQRPVVDBHI PY - 2013 UR - http://hdl.handle.net/1902.1/UQRPVVDBHI PB - Harvard Dataverse ER - """ citation_endnote: """ <?xml version='1.0' encoding='UTF-8'?> <xml> <records> <record> <ref-type name="Online Database">45</ref-type> <contributors> <authors> <author>PI:NAME:<NAME>END_PI</author> </authors> </contributors> <titles> <title>Replication data for: Consumption-Based Asset Pricing</title> </titles> <section>2007-12-03</section> <dates> <year>2013</year> </dates> <publisher>Harvard Dataverse</publisher> <urls> <related-urls> <url>http://hdl.handle.net/1902.1/UQRPVVDBHI</url> </related-urls> </urls> <electronic-resource-num>hdl/1902.1/UQRPVVDBHI</electronic-resource-num> </record> </records> </xml> """ databases: eulfs: name: 'Eurostat LFS' url: 'http://ec.europa.eu/eurostat/web/lfs/data/main-tables' toyo_keizai: name: 'Toyo Keizai' url: 'http://dbs.toyokeizai.net/en/' topix: name: 'Tokyo Stock Price Index' url: 'http://www.bloomberg.com/quote/TPX:IND' dax30: name: 'Deutscher Aktienindex DAX' url: 'http://www.bloomberg.com/quote/DAX:IND' nasdaq: name: 'NASDAQ' url: 'http://www.bloomberg.com/quote/NASDAQ:IND' ftse100: name: 'FTSE 100 Index (UKX)' url: 'http://www.bloomberg.com/quote/UKX:IND' sp500: name: "Standard and Poor's 500" url: 'http://www.bloomberg.com/quote/SPX:IND' sensex: name: 'BME SENSEX' url: 'http://www.bloomberg.com/quote/SENSEX:IND' shshazr: name: 'Shenzhen A-Share' url: 'http://www.bloomberg.com/quote/SZASHR:IND' csmar: name: 'China Stock Market Accounting Research' url: 'http://csmar.gtadata.com/' yahoo_finance: name: "Yahoo Finance" url: "https://in.finance.yahoo.com" bist100: name: "Borsa Istanbul 100 Index" url: "http://www.bloomberg.com/quote/XU100:IND" gfd: name: 'Global Finance Data' url: 'https://www.globalfinancialdata.com' csi100: name: 'CSI 100 Index' url: 'http://www.bloomberg.com/quote/SHCSI100:IND' nikkei225: name: 'Nikkei Index' url: 'http://indexes.nikkei.co.jp/en/nkave/index/profile?idx=nk225' eia_monthly: url: 'http://www.eia.gov/totalenergy/data/monthly/' name: 'Monthly Energy Review' eia_steo: name: 'Short-term Energy Outlook' url: 'http://www.eia.gov/forecasts/steo/' amadeus: name: 'Amadeus' url: 'https://amadeus.bvdinfo.com' osiris: name: "Osiris" url: "http://www.bvdinfo.com/en-gb/our-products/company-information/international-products/osiris" bloomberg: name: "Bloomberg" url: "http://www.bloomberg.com/professional/" worldscope: name: "Worldscope" url: "http://extranet.datastream.com/Data/Worldscope/index.htm" datastream: name: "DataStream" url: "http://financial.thomsonreuters.com/en/products/tools-applications/trading-investment-tools/datastream-macroeconomic-analysis.html" trna: name: "TRNA" url: "http://financial.thomsonreuters.com/en/products/data-analytics/financial-news-feed.html" sdc: name: "SDC" url: "http://thomsonreuters.com/en/products-services/financial/market-data/sdc-platinum.html" crsp: name: "CRSP" url: "http://www.crsp.com/" ctbs: name: "CTBS" url: "http://www.nelson.com/assessment/classroom-CTBS.html" publications: "10.1093/rfs/hht068": doi: ["10.1093/rfs/hht068"] databases: ["bloomberg"] "10.1207/s15327035ex1302_2": doi: ["10.1207/s15327035ex1302_2"] databases: ["ctbs"] "10.1093/rfs/hht044": doi: ["10.1093/rfs/hht044"] databases: ["osiris", "worldscope", "datastream"] "10.1093/rfs/hhu032": doi: ["10.1093/rfs/hhu032"] databases: ["trna", "bloomberg"] "10.1093/rfs/hht082": doi: ["10.1093/rfs/hht082"] databases: ["sdc", "crsp"] "10.1080/095372897235398": doi: ["10.1080/095372897235398"] title: "An algorithm to dynamically adjust the number of kanbans in stochastic processing times and variable demand environment" databases: ["sdc","crsp"] datasets: ['10.4232/1.12209'] "10.1093/rfs/6.2.327": doi: ["10.1093/rfs/6.2.327"] title: "A Closed-Form Solution for Options with Stochastic Volatility with Applications to Bond and Currency Options" authors: "PI:NAME:<NAME>END_PI " databases: ['crsp'] datasets: ['10.4232/1.12209'] "10.1093/rfs/5.4.553": doi: ["10.1093/rfs/5.4.553"] databases: ['amadeus'] # # Google Scholar: Search 'stock market prediction' # "10.1016/j.chaos.2016.01.004": doi: ["10.1016/j.chaos.2016.01.004"] title: "Application of artificial neural network for the prediction of stock market returns: The case of the Japanese stock market" databases: ['nikkei225'] "10.1111/jofi.12364": doi: ["10.1111/jofi.12364"] title: "Stock Market Volatility and Learning" datasets: ["1902.1/UQRPVVDBHI"] databases: ['gfd'] "10.1016/j.eswa.2015.09.029": doi: ["10.1016/j.eswa.2015.09.029"] title: "Integrating metaheuristics and Artificial Neural Networks for improved stock price prediction" databases: ['bloomberg', 'bist100'] "10.1007/978-3-319-23258-4_24": doi: ['10.1007/978-3-319-23258-4_24'] title: 'An Effective Stock Price Prediction Technique Using Hybrid Adaptive Neuro Fuzzy Inference System Based on Grid Partitioning' databases: ['yahoo_finance'] "10.1002/jae.2500": doi:['10.1002/jae.2500'] title: 'Anticipation, Tax Avoidance, and the Price Elasticity of Gasoline Demand' datasets: ['jaes/savva001'] databases: ['eia_steo', 'eia_monthly'] "10.1145/2838731": doi: ['10.1145/2838731'] title: 'A Tensor-Based Information Framework for Predicting the Stock Market' databases: ['csmar', 'csi100', 'sensex'] "10.1016/j.eswa.2016.01.016": doi:['10.1016/j.eswa.2016.01.016'] title: 'Efficient stock price prediction using a Self Evolving Recurrent Neuro-Fuzzy Inference System optimized through a Modified technique' databases: ['bloomberg', 'sensex', 'sp500'] "10.4018/IJBAN.2016010101": doi: ['10.4018/IJBAN.2016010101'] title: 'A Prescriptive Stock Market Investment Strategy for the Restaurant Industry using an Artificial Neural Network Methodology' databases: ['yahoo_finance'] # # Primo -> 'Stock price prediction' # "10.1016/j.eswa.2010.08.076": doi: ["10.1016/j.eswa.2010.08.076"] title: 'Translation Invariant Morphological Time-lag Added Evolutionary Forecasting method for stock market prediction' databases: ['bloomberg'] # # Primo -> 'Stock price prediction', newest, peer-reviewd journal # '10.1016/j.eswa.2015.01.035': doi: ['10.1016/j.eswa.2015.01.035'] title: 'Stock market trend prediction using dynamical Bayesian factor graph' databases: ['shshazr', 'sp500'] '10.1016/j.eswa.2015.04.056': doi:['10.1016/j.eswa.2015.04.056'] title: 'Boosting Trading Strategies performance using VIX indicator together with a dual-objective Evolutionary Computation optimizer' databases: ['nasdaq', 'nikkei225', 'sp500', 'ftse100', 'dax30'] # http://www.tandfonline.com/doi/full/10.1080/07474938.2014.977086 '10.1080/07474938.2014.977086': doi:['10.1080/07474938.2014.977086'] title:'Stock Return Predictability: A Factor-Augmented Predictive Regression System with Shrinkage Method' datasets: ['10.6084/m9.figshare.c.2011262.v1'] databases: ['toyo_keizai', 'topix'] # https://ideas.repec.org/h/eee/finchp/2-13.html "RePEc:eee:finchp:2-13": doi:["RePEc:eee:finchp:2-13"] title: 'Consumption-based asset pricing' datasets: ['1902.1/UQRPVVDBHI'] '10.1371/journal.pone.0117619': doi:['10.1371/journal.pone.0117619'] title: 'Researcher Perspectives on Publication and Peer Review of Data' datasets: ['10.5281/zenodo.13293'] 'ZAAA2005110027513181411142812171': doi:['10.17877/DE290R-1856'] url: 'http://dx.doi.org/10.17877/DE290R-1856' title: 'Die Beschäftigung Älterer in Europa zwischen Vorruhestand und "Work-Line"' datasets: ['eurostat:tgs00054(2004)'] databases: ['eulfs']
[ { "context": "#\n ScrollHandler\n Copyright(c) 2014 SHIFTBRAIN - Tsukasa Tokura\n This software is released under the MIT License", "end": 116, "score": 0.9998566508293152, "start": 102, "tag": "NAME", "value": "Tsukasa Tokura" } ]
scrollHandler.coffee
tsukasa-web/myFuncs_coffee
2
$ = require('jquery') _ = require('underscore') ### ScrollHandler Copyright(c) 2014 SHIFTBRAIN - Tsukasa Tokura This software is released under the MIT License. http://opensource.org/licenses/mit-license.php ### # require()で返されるオブジェクト module.exports = class ScrollHandler constructor : ($scrollTarget, throttletime = 50) -> @scrollTarget = $scrollTarget @throttletime = throttletime @$window = $(window) setShowEvent : ($target, func, margin=0, id=null, index=null) -> contextObj = target: $target height: $target.height() method: func id: id index: index margin: margin throttled = _.throttle (=>@showscrollEvent(contextObj)), @throttletime @scrollTarget.on 'scroll.'+id+'show', throttled showscrollEvent: (contextObj) => nowTargetTop = contextObj.target.position().top windowHeight = @$window.height() if nowTargetTop > -contextObj.height + contextObj.margin and nowTargetTop < windowHeight - contextObj.margin contextObj.method() removeShowEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'show' setHideEvent : ($target, func, margin=0, id=null, index=null) -> contextObj = target: $target height: $target.height() position: $target.position().top method: func id: id index: index margin: margin throttled = _.throttle (=> @hidescrollEvent(contextObj)), @throttletime @scrollTarget.on 'scroll.'+id+'hide', throttled hidescrollEvent: (contextObj)=> nowTargetTop = contextObj.target.position().top windowHeight = @$window.height() if nowTargetTop < -contextObj.height - contextObj.margin or nowTargetTop > windowHeight + contextObj.margin contextObj.method() removeHideEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'hide' removeAllEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'hide' @scrollTarget.off 'scroll.'+id+'show'
120389
$ = require('jquery') _ = require('underscore') ### ScrollHandler Copyright(c) 2014 SHIFTBRAIN - <NAME> This software is released under the MIT License. http://opensource.org/licenses/mit-license.php ### # require()で返されるオブジェクト module.exports = class ScrollHandler constructor : ($scrollTarget, throttletime = 50) -> @scrollTarget = $scrollTarget @throttletime = throttletime @$window = $(window) setShowEvent : ($target, func, margin=0, id=null, index=null) -> contextObj = target: $target height: $target.height() method: func id: id index: index margin: margin throttled = _.throttle (=>@showscrollEvent(contextObj)), @throttletime @scrollTarget.on 'scroll.'+id+'show', throttled showscrollEvent: (contextObj) => nowTargetTop = contextObj.target.position().top windowHeight = @$window.height() if nowTargetTop > -contextObj.height + contextObj.margin and nowTargetTop < windowHeight - contextObj.margin contextObj.method() removeShowEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'show' setHideEvent : ($target, func, margin=0, id=null, index=null) -> contextObj = target: $target height: $target.height() position: $target.position().top method: func id: id index: index margin: margin throttled = _.throttle (=> @hidescrollEvent(contextObj)), @throttletime @scrollTarget.on 'scroll.'+id+'hide', throttled hidescrollEvent: (contextObj)=> nowTargetTop = contextObj.target.position().top windowHeight = @$window.height() if nowTargetTop < -contextObj.height - contextObj.margin or nowTargetTop > windowHeight + contextObj.margin contextObj.method() removeHideEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'hide' removeAllEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'hide' @scrollTarget.off 'scroll.'+id+'show'
true
$ = require('jquery') _ = require('underscore') ### ScrollHandler Copyright(c) 2014 SHIFTBRAIN - PI:NAME:<NAME>END_PI This software is released under the MIT License. http://opensource.org/licenses/mit-license.php ### # require()で返されるオブジェクト module.exports = class ScrollHandler constructor : ($scrollTarget, throttletime = 50) -> @scrollTarget = $scrollTarget @throttletime = throttletime @$window = $(window) setShowEvent : ($target, func, margin=0, id=null, index=null) -> contextObj = target: $target height: $target.height() method: func id: id index: index margin: margin throttled = _.throttle (=>@showscrollEvent(contextObj)), @throttletime @scrollTarget.on 'scroll.'+id+'show', throttled showscrollEvent: (contextObj) => nowTargetTop = contextObj.target.position().top windowHeight = @$window.height() if nowTargetTop > -contextObj.height + contextObj.margin and nowTargetTop < windowHeight - contextObj.margin contextObj.method() removeShowEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'show' setHideEvent : ($target, func, margin=0, id=null, index=null) -> contextObj = target: $target height: $target.height() position: $target.position().top method: func id: id index: index margin: margin throttled = _.throttle (=> @hidescrollEvent(contextObj)), @throttletime @scrollTarget.on 'scroll.'+id+'hide', throttled hidescrollEvent: (contextObj)=> nowTargetTop = contextObj.target.position().top windowHeight = @$window.height() if nowTargetTop < -contextObj.height - contextObj.margin or nowTargetTop > windowHeight + contextObj.margin contextObj.method() removeHideEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'hide' removeAllEvent : (id=null) -> @scrollTarget.off 'scroll.'+id+'hide' @scrollTarget.off 'scroll.'+id+'show'
[ { "context": "WithTarget = (name, actual, target) ->\n key = example.i.toString()\n expected = expectedSwatches[target][key][na", "end": 351, "score": 0.9992281794548035, "start": 331, "tag": "KEY", "value": "example.i.toString()" } ]
test/vibrant.browser-spec.coffee
Kronuz/node-vibrant
0
examples = [1..4].map (i) -> e = i: i fileName: "#{i}.jpg" fileUrl: "base/examples/#{i}.jpg" expectedSwatches = {} TARGETS = ['chrome', 'firefox', 'ie'] paletteCallback = (example, done) -> (err, palette) -> if err? then throw err failCount = 0 testWithTarget = (name, actual, target) -> key = example.i.toString() expected = expectedSwatches[target][key][name] result = target: target expected: expected ? "null" status: "N/A" diff: -1 if actual == null expect(expected, "#{name} color from '#{target}' was expected").to.be.null if expected == null expect(actual, "#{name} color form '#{target}' was not expected").to.be.null else actualHex = actual.getHex() diff = Vibrant.Util.hexDiff(actualHex, expected) result.diff = diff result.status = Vibrant.Util.getColorDiffStatus(diff) if diff > Vibrant.Util.DELTAE94_DIFF_STATUS.SIMILAR then failCount++ result expect(palette, "Palette should not be null").not.to.be.null colorSummary = {} for name, actual of palette for target in TARGETS if not colorSummary[target]? colorSummary[target] = {} r = testWithTarget(name, actual, target) if not colorSummary[target][r.status]? colorSummary[target][r.status] = 0 colorSummary[target][r.status] += 1 console.log "File #{example.fileName} palette color score" for target, summary of colorSummary s = "#{target}>\t\t" for status, count of summary s += "#{status}: #{count}\t\t" console.log s console.log "" expect(failCount, "#{failCount} colors are too diffrent from reference palettes") .to.equal(0) done() testVibrant = (example, done) -> Vibrant.from example.fileUrl .quality(1) .clearFilters() .getPalette paletteCallback(example, done) describe "Vibrant", -> it "exports to window", -> expect(Vibrant).not.to.be.null expect(Vibrant.Util).not.to.be.null expect(Vibrant.Quantizer).not.to.be.null expect(Vibrant.Generator).not.to.be.null expect(Vibrant.Filter).not.to.be.null describe "Palette Extraction", -> before -> expectedSwatches['chrome'] = __json__['test/data/chrome-exec-ref'] expectedSwatches['firefox'] = __json__['test/data/firefox-exec-ref'] expectedSwatches['ie'] = __json__['test/data/ie11-exec-ref'] examples.forEach (example) -> it example.fileName, (done) -> testVibrant example, done describe "Browser Image", -> loc = window.location BrowserImage = Vibrant.DefaultOpts.Image CROS_URL = "http://example.com/foo.jpg" RELATIVE_URL = "foo/bar.jpg" SAME_ORIGIN_URL = "#{loc.protocol}//#{loc.host}/foo/bar.jpg" it "should set crossOrigin flag for images form foreign origin", -> m = new BrowserImage(CROS_URL) expect(m.img.crossOrigin, "#{CROS_URL} should have crossOrigin === 'anonymous'") .to.equal("anonymous") it "should not set crossOrigin flag for images from same origin", -> m1 = new BrowserImage(RELATIVE_URL) expect(m1.img.crossOrigin, "#{RELATIVE_URL} should not have crossOrigin set") .not.to.equal("anonymous") m2 = new BrowserImage(SAME_ORIGIN_URL) expect(m1.img.crossOrigin, "#{SAME_ORIGIN_URL} should not have crossOrigin set") .not.to.equal("anonymous") it "should accept HTMLImageElement as input", (done) -> img = document.createElement('img') img.src = examples[0].fileUrl m1 = new BrowserImage img, (err, m) => if err then throw err done() it "should accept HTMLImageElement that is already loaded as input", (done) -> img = document.createElement('img') img.src = examples[0].fileUrl img.onload = => m1 = new BrowserImage img, (err, m) => if err then throw err done()
26658
examples = [1..4].map (i) -> e = i: i fileName: "#{i}.jpg" fileUrl: "base/examples/#{i}.jpg" expectedSwatches = {} TARGETS = ['chrome', 'firefox', 'ie'] paletteCallback = (example, done) -> (err, palette) -> if err? then throw err failCount = 0 testWithTarget = (name, actual, target) -> key = <KEY> expected = expectedSwatches[target][key][name] result = target: target expected: expected ? "null" status: "N/A" diff: -1 if actual == null expect(expected, "#{name} color from '#{target}' was expected").to.be.null if expected == null expect(actual, "#{name} color form '#{target}' was not expected").to.be.null else actualHex = actual.getHex() diff = Vibrant.Util.hexDiff(actualHex, expected) result.diff = diff result.status = Vibrant.Util.getColorDiffStatus(diff) if diff > Vibrant.Util.DELTAE94_DIFF_STATUS.SIMILAR then failCount++ result expect(palette, "Palette should not be null").not.to.be.null colorSummary = {} for name, actual of palette for target in TARGETS if not colorSummary[target]? colorSummary[target] = {} r = testWithTarget(name, actual, target) if not colorSummary[target][r.status]? colorSummary[target][r.status] = 0 colorSummary[target][r.status] += 1 console.log "File #{example.fileName} palette color score" for target, summary of colorSummary s = "#{target}>\t\t" for status, count of summary s += "#{status}: #{count}\t\t" console.log s console.log "" expect(failCount, "#{failCount} colors are too diffrent from reference palettes") .to.equal(0) done() testVibrant = (example, done) -> Vibrant.from example.fileUrl .quality(1) .clearFilters() .getPalette paletteCallback(example, done) describe "Vibrant", -> it "exports to window", -> expect(Vibrant).not.to.be.null expect(Vibrant.Util).not.to.be.null expect(Vibrant.Quantizer).not.to.be.null expect(Vibrant.Generator).not.to.be.null expect(Vibrant.Filter).not.to.be.null describe "Palette Extraction", -> before -> expectedSwatches['chrome'] = __json__['test/data/chrome-exec-ref'] expectedSwatches['firefox'] = __json__['test/data/firefox-exec-ref'] expectedSwatches['ie'] = __json__['test/data/ie11-exec-ref'] examples.forEach (example) -> it example.fileName, (done) -> testVibrant example, done describe "Browser Image", -> loc = window.location BrowserImage = Vibrant.DefaultOpts.Image CROS_URL = "http://example.com/foo.jpg" RELATIVE_URL = "foo/bar.jpg" SAME_ORIGIN_URL = "#{loc.protocol}//#{loc.host}/foo/bar.jpg" it "should set crossOrigin flag for images form foreign origin", -> m = new BrowserImage(CROS_URL) expect(m.img.crossOrigin, "#{CROS_URL} should have crossOrigin === 'anonymous'") .to.equal("anonymous") it "should not set crossOrigin flag for images from same origin", -> m1 = new BrowserImage(RELATIVE_URL) expect(m1.img.crossOrigin, "#{RELATIVE_URL} should not have crossOrigin set") .not.to.equal("anonymous") m2 = new BrowserImage(SAME_ORIGIN_URL) expect(m1.img.crossOrigin, "#{SAME_ORIGIN_URL} should not have crossOrigin set") .not.to.equal("anonymous") it "should accept HTMLImageElement as input", (done) -> img = document.createElement('img') img.src = examples[0].fileUrl m1 = new BrowserImage img, (err, m) => if err then throw err done() it "should accept HTMLImageElement that is already loaded as input", (done) -> img = document.createElement('img') img.src = examples[0].fileUrl img.onload = => m1 = new BrowserImage img, (err, m) => if err then throw err done()
true
examples = [1..4].map (i) -> e = i: i fileName: "#{i}.jpg" fileUrl: "base/examples/#{i}.jpg" expectedSwatches = {} TARGETS = ['chrome', 'firefox', 'ie'] paletteCallback = (example, done) -> (err, palette) -> if err? then throw err failCount = 0 testWithTarget = (name, actual, target) -> key = PI:KEY:<KEY>END_PI expected = expectedSwatches[target][key][name] result = target: target expected: expected ? "null" status: "N/A" diff: -1 if actual == null expect(expected, "#{name} color from '#{target}' was expected").to.be.null if expected == null expect(actual, "#{name} color form '#{target}' was not expected").to.be.null else actualHex = actual.getHex() diff = Vibrant.Util.hexDiff(actualHex, expected) result.diff = diff result.status = Vibrant.Util.getColorDiffStatus(diff) if diff > Vibrant.Util.DELTAE94_DIFF_STATUS.SIMILAR then failCount++ result expect(palette, "Palette should not be null").not.to.be.null colorSummary = {} for name, actual of palette for target in TARGETS if not colorSummary[target]? colorSummary[target] = {} r = testWithTarget(name, actual, target) if not colorSummary[target][r.status]? colorSummary[target][r.status] = 0 colorSummary[target][r.status] += 1 console.log "File #{example.fileName} palette color score" for target, summary of colorSummary s = "#{target}>\t\t" for status, count of summary s += "#{status}: #{count}\t\t" console.log s console.log "" expect(failCount, "#{failCount} colors are too diffrent from reference palettes") .to.equal(0) done() testVibrant = (example, done) -> Vibrant.from example.fileUrl .quality(1) .clearFilters() .getPalette paletteCallback(example, done) describe "Vibrant", -> it "exports to window", -> expect(Vibrant).not.to.be.null expect(Vibrant.Util).not.to.be.null expect(Vibrant.Quantizer).not.to.be.null expect(Vibrant.Generator).not.to.be.null expect(Vibrant.Filter).not.to.be.null describe "Palette Extraction", -> before -> expectedSwatches['chrome'] = __json__['test/data/chrome-exec-ref'] expectedSwatches['firefox'] = __json__['test/data/firefox-exec-ref'] expectedSwatches['ie'] = __json__['test/data/ie11-exec-ref'] examples.forEach (example) -> it example.fileName, (done) -> testVibrant example, done describe "Browser Image", -> loc = window.location BrowserImage = Vibrant.DefaultOpts.Image CROS_URL = "http://example.com/foo.jpg" RELATIVE_URL = "foo/bar.jpg" SAME_ORIGIN_URL = "#{loc.protocol}//#{loc.host}/foo/bar.jpg" it "should set crossOrigin flag for images form foreign origin", -> m = new BrowserImage(CROS_URL) expect(m.img.crossOrigin, "#{CROS_URL} should have crossOrigin === 'anonymous'") .to.equal("anonymous") it "should not set crossOrigin flag for images from same origin", -> m1 = new BrowserImage(RELATIVE_URL) expect(m1.img.crossOrigin, "#{RELATIVE_URL} should not have crossOrigin set") .not.to.equal("anonymous") m2 = new BrowserImage(SAME_ORIGIN_URL) expect(m1.img.crossOrigin, "#{SAME_ORIGIN_URL} should not have crossOrigin set") .not.to.equal("anonymous") it "should accept HTMLImageElement as input", (done) -> img = document.createElement('img') img.src = examples[0].fileUrl m1 = new BrowserImage img, (err, m) => if err then throw err done() it "should accept HTMLImageElement that is already loaded as input", (done) -> img = document.createElement('img') img.src = examples[0].fileUrl img.onload = => m1 = new BrowserImage img, (err, m) => if err then throw err done()
[ { "context": "\"title\": \"Costa Azul Digital\"\n\n\"api\":\n \"baseUrl\": \"http://costazuldigital.c", "end": 28, "score": 0.8384086489677429, "start": 10, "tag": "NAME", "value": "Costa Azul Digital" } ]
config/config.cson
MariusMez/CADMobile
1
"title": "Costa Azul Digital" "api": "baseUrl": "http://costazuldigital.com/wp-json" "timeout": 15000 "maxAttempt": 3 "translation": "displayed" : ["es", "en", "fr"] "prefered": "es" # CACHE "cache": "img": "localCacheFolder": "imgcache" "useDataURI": false "chromeQuota": 10485760 "usePersistentCache": true "cacheClearSize": 0 "headers": {} "skipURIencoding": false "data": "capacity": 100 "maxAge": 360000 "deleteOnExpire": "aggressive" "recycleFreq": 1000 "cacheFlushInterval": null "storageMode": "localStorage" # BOOKMARK PAGE "bookmark": "cache": "capacity": 10 # POST PAGES "post": "comments": "enabled": true "depth": 2 "per_page": 50 "cache": "maxAge": 360000 "capacity": 10 # SYNTAX HIGHLIGHTER FOR TECH BLOG "syntaxHighlighter": "enabled": false "classPrefix": "hljs-" "tabReplace": " " "useBR": false "languages": ["javascript", "html", "coffeescript", "html", "css", "scss", "json", "apache", "bash", "markdown", "less", "php", "apache", "typescript"] # TAXONOMIES "taxonomies": "query": "per_page": 10 "orderby": "count" "order": "desc" "cache": "maxAge": 10800000 # AUTHOR "authors": "query": "per_page": 10 "cache": "capacity": 15 "maxAge": 10800000 # PAGES PAGE "pages": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "cache": "capacity": 10 "maxAge": 10800000 # SEARCH PAGE "search": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "filter[post_status]": "publish" "cache": "capacity": 25 "maxAge": 360000 # POSTS PAGE "posts": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "filter[post_status]": "publish" "cache": "capacity": 25 "maxAge": 360000 # ANALYTICS (GOOGLE ANALYTICS) "analytics": "enabled": true "trackingId": "UA-45984258-1" "userId": "45984258" "virtualPageTracking": true # CORDOVA "cordova": "nativeTransitions": "enabled": false "defaultOptions": null "defaultTransition" : null "defaultBackTransition" : null "appRate": "enabled": true "language": "es" "appName": "Costa Azul Digital" "openStoreInApp": true "usesUntilPrompt": 3 "promptForNewVersion": true "useCustomRateDialog": "" "iosURL": "1107263009" "androidURL": "https://play.google.com/store/apps/details?id=com.costazuldigital" "windowsURL": "" "pushNotifications": "enabled": true "baseUrl": "http://costazuldigital.com/pnfw" "android": "senderID": "817819662481" "ios": "badge": true "sound": true "alert": true
23398
"title": "<NAME>" "api": "baseUrl": "http://costazuldigital.com/wp-json" "timeout": 15000 "maxAttempt": 3 "translation": "displayed" : ["es", "en", "fr"] "prefered": "es" # CACHE "cache": "img": "localCacheFolder": "imgcache" "useDataURI": false "chromeQuota": 10485760 "usePersistentCache": true "cacheClearSize": 0 "headers": {} "skipURIencoding": false "data": "capacity": 100 "maxAge": 360000 "deleteOnExpire": "aggressive" "recycleFreq": 1000 "cacheFlushInterval": null "storageMode": "localStorage" # BOOKMARK PAGE "bookmark": "cache": "capacity": 10 # POST PAGES "post": "comments": "enabled": true "depth": 2 "per_page": 50 "cache": "maxAge": 360000 "capacity": 10 # SYNTAX HIGHLIGHTER FOR TECH BLOG "syntaxHighlighter": "enabled": false "classPrefix": "hljs-" "tabReplace": " " "useBR": false "languages": ["javascript", "html", "coffeescript", "html", "css", "scss", "json", "apache", "bash", "markdown", "less", "php", "apache", "typescript"] # TAXONOMIES "taxonomies": "query": "per_page": 10 "orderby": "count" "order": "desc" "cache": "maxAge": 10800000 # AUTHOR "authors": "query": "per_page": 10 "cache": "capacity": 15 "maxAge": 10800000 # PAGES PAGE "pages": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "cache": "capacity": 10 "maxAge": 10800000 # SEARCH PAGE "search": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "filter[post_status]": "publish" "cache": "capacity": 25 "maxAge": 360000 # POSTS PAGE "posts": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "filter[post_status]": "publish" "cache": "capacity": 25 "maxAge": 360000 # ANALYTICS (GOOGLE ANALYTICS) "analytics": "enabled": true "trackingId": "UA-45984258-1" "userId": "45984258" "virtualPageTracking": true # CORDOVA "cordova": "nativeTransitions": "enabled": false "defaultOptions": null "defaultTransition" : null "defaultBackTransition" : null "appRate": "enabled": true "language": "es" "appName": "Costa Azul Digital" "openStoreInApp": true "usesUntilPrompt": 3 "promptForNewVersion": true "useCustomRateDialog": "" "iosURL": "1107263009" "androidURL": "https://play.google.com/store/apps/details?id=com.costazuldigital" "windowsURL": "" "pushNotifications": "enabled": true "baseUrl": "http://costazuldigital.com/pnfw" "android": "senderID": "817819662481" "ios": "badge": true "sound": true "alert": true
true
"title": "PI:NAME:<NAME>END_PI" "api": "baseUrl": "http://costazuldigital.com/wp-json" "timeout": 15000 "maxAttempt": 3 "translation": "displayed" : ["es", "en", "fr"] "prefered": "es" # CACHE "cache": "img": "localCacheFolder": "imgcache" "useDataURI": false "chromeQuota": 10485760 "usePersistentCache": true "cacheClearSize": 0 "headers": {} "skipURIencoding": false "data": "capacity": 100 "maxAge": 360000 "deleteOnExpire": "aggressive" "recycleFreq": 1000 "cacheFlushInterval": null "storageMode": "localStorage" # BOOKMARK PAGE "bookmark": "cache": "capacity": 10 # POST PAGES "post": "comments": "enabled": true "depth": 2 "per_page": 50 "cache": "maxAge": 360000 "capacity": 10 # SYNTAX HIGHLIGHTER FOR TECH BLOG "syntaxHighlighter": "enabled": false "classPrefix": "hljs-" "tabReplace": " " "useBR": false "languages": ["javascript", "html", "coffeescript", "html", "css", "scss", "json", "apache", "bash", "markdown", "less", "php", "apache", "typescript"] # TAXONOMIES "taxonomies": "query": "per_page": 10 "orderby": "count" "order": "desc" "cache": "maxAge": 10800000 # AUTHOR "authors": "query": "per_page": 10 "cache": "capacity": 15 "maxAge": 10800000 # PAGES PAGE "pages": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "cache": "capacity": 10 "maxAge": 10800000 # SEARCH PAGE "search": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "filter[post_status]": "publish" "cache": "capacity": 25 "maxAge": 360000 # POSTS PAGE "posts": "query": "per_page": 5 "filter[orderby]": "date" "filter[order]": "desc" "filter[post_status]": "publish" "cache": "capacity": 25 "maxAge": 360000 # ANALYTICS (GOOGLE ANALYTICS) "analytics": "enabled": true "trackingId": "UA-45984258-1" "userId": "45984258" "virtualPageTracking": true # CORDOVA "cordova": "nativeTransitions": "enabled": false "defaultOptions": null "defaultTransition" : null "defaultBackTransition" : null "appRate": "enabled": true "language": "es" "appName": "Costa Azul Digital" "openStoreInApp": true "usesUntilPrompt": 3 "promptForNewVersion": true "useCustomRateDialog": "" "iosURL": "1107263009" "androidURL": "https://play.google.com/store/apps/details?id=com.costazuldigital" "windowsURL": "" "pushNotifications": "enabled": true "baseUrl": "http://costazuldigital.com/pnfw" "android": "senderID": "817819662481" "ios": "badge": true "sound": true "alert": true
[ { "context": "foreEach ->\n struct = new TestStruct(hello: 'guys', whats: 'up', nada: 'much')\n\n it \"gives all t", "end": 618, "score": 0.993899941444397, "start": 614, "tag": "NAME", "value": "guys" }, { "context": " expect( struct.attrs() )\n .to.eql(hello: 'guys',...
public/js/plugins/onionjs-master/test/struct_spec.coffee
kemiedon/android_project
6
Struct = requirejs('onion/struct') describe "Struct", -> describe "attributes", -> class TestStruct extends Struct @attributes 'brucy' struct = null beforeEach -> struct = new TestStruct(brucy: 'bonus') it "sets provided attributes", -> expect( struct.attrs() ).to.eql(brucy: 'bonus') it "returns the class's attribute names", -> expect( TestStruct.attributeNames ).to.eql(['brucy']) describe "#attrs", -> class TestStruct extends Struct @attributes 'hello', 'whats', 'nada' struct = null beforeEach -> struct = new TestStruct(hello: 'guys', whats: 'up', nada: 'much') it "gives all the attrs", -> expect( struct.attrs() ) .to.eql(hello: 'guys', whats: 'up', nada: 'much') it "allows specifying specific attrs", -> expect( struct.attrs('hello', 'whats') ) .to.eql(hello: 'guys', whats: 'up') describe "setting", -> class TestStruct extends Struct @attributes 'gold', 'silver' struct = null beforeEach -> struct = new TestStruct() it "sets and emits the `change` event", -> expect -> struct.setGold('lots') .toEmitOn(struct, 'change') expect( struct.gold() ) .to.eql('lots') it "sets and emits the `change:gold` event", -> expect -> struct.setGold('lots') .toEmitOn(struct, 'change:gold', {from: undefined, to: 'lots'}) expect( struct.gold() ).to.eql('lots') it "sets and emits a set event when a value is first set", -> struct.setGold(null) expect -> struct.setGold('lots') .toEmitOn(struct, 'set:gold', 'lots') expect( struct.gold() ).to.eql('lots') it "doesn't trigger if not changed", -> struct.setGold('lots') expect -> struct.setGold('lots') .not.toEmitOn(struct, 'change') expect -> struct.setGold('lots') .not.toEmitOn(struct, 'change:gold') describe "setting many", -> it "allows setting multiple at once", -> struct.setAttrs(gold: 'lots', silver: 'not so much') expect( struct.gold() ).to.eql('lots') expect( struct.silver() ).to.eql('not so much') it "doesn't allow setting attributes it doesn't know about", -> expect -> struct.setAttrs(what: 'the') .to.throw("unknown attribute what for TestStruct") it "emits `change:XXX` for each attribute", -> changeGoldEvents = changeSilverEvents = 0 struct.on 'change:gold', -> changeGoldEvents++ struct.on 'change:silver', -> changeSilverEvents++ struct.setAttrs(gold: 'lots', silver: 'not so much') expect( changeGoldEvents ).to.eql( 1 ) expect( changeSilverEvents ).to.eql( 1 ) struct.setAttrs(gold: 'less now', silver: 'not so much') expect( changeGoldEvents ).to.eql( 2 ) expect( changeSilverEvents ).to.eql( 1 ) it "emits `change` only once, and only if there are changes", -> changeEvents = 0 struct.on 'change', (changes) -> changeEvents++ struct.setAttrs(gold: 'lots', silver: 'not so much') expect( changeEvents ).to.eql( 1 ) struct.setAttrs(silver: 'not so much') expect( changeEvents ).to.eql( 1 ) describe "decorateWriter", -> class TestStruct extends Struct @attributes 'thing' @decorateWriter 'thing', (value) -> value.toUpperCase() it "decorates a writer with a function", -> struct = new TestStruct() struct.setThing('blob') expect( struct.thing() ).to.eql('BLOB') it "ignores the decorator if set to null", -> struct = new TestStruct() struct.setThing(null) expect( struct.thing() ).to.eql(null) it "works on null if the flag is set", -> TestStruct.attributes 'array' TestStruct.decorateWriter 'array', ((value) -> [value]), includeNull: true struct = new TestStruct() struct.setArray(null) expect( struct.array() ).to.eql([null]) it "works with setAttrs", -> struct = new TestStruct() struct.setAttrs(thing: 'blob') expect( struct.thing() ).to.eql('BLOB') describe "setDefaults", -> class TestStruct extends Struct @attributes 'colour' struct = null beforeEach -> struct = new TestStruct() it "sets if not already set", -> struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('blue') it "doesn't overwrite", -> struct.setColour('red') struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('red') it "doesn't overwrite falsy but already set", -> struct.setColour('') struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('') describe "relatedAttributes", -> struct = null TestStruct = null beforeEach -> TestStruct = class TestStruct extends Struct @attributes 'number', 'doubleNumber', 'tripleNumber' @relateAttributes 'doubleNumber', ['number'], (number) -> number * 2 struct = new TestStruct() it "updates when the other is updated", -> struct.setNumber(3) expect( struct.doubleNumber() ).to.equal(6) it "emits both change events", -> expect(-> struct.setNumber(3) ).toEmitOn(struct, 'change:number') expect(-> struct.setNumber(4) ).toEmitOn(struct, 'change:doubleNumber') it "doesn't run in reverse", -> struct.setDoubleNumber(6) expect( struct.number() ).to.be.undefined it "doesn't run the function if it isn't affected by changes", -> spy = sinon.spy() TestStruct = class TestStruct extends Struct @attributes 'a', 'b', 'c' @relateAttributes 'a', ['b'], spy struct = new TestStruct() struct.setC('stuff') expect( spy.called ).to.be.false it "sanity check with more complex example", -> TestStruct = class TestStruct extends Struct @attributes 'firstName', 'lastName', 'fullName' @relateAttributes 'fullName', ['firstName', 'lastName'], (first, last) -> "#{first} #{last}" @relateAttributes 'firstName', ['fullName'], (fullName) -> fullName.split(' ')[0] @relateAttributes 'lastName', ['fullName'], (fullName) -> fullName.split(' ')[1] struct = new TestStruct() struct.setAttrs(firstName: 'John', lastName: 'Barnes') expect( struct.fullName() ).to.equal("John Barnes") struct.setAttrs(fullName: 'Mary Egg') expect( struct.firstName() ).to.equal("Mary") expect( struct.lastName() ).to.equal("Egg") describe "newFromAttributes", -> it "creates a new struct, ignoring attributes it doesn't know about", -> class TestStruct extends Struct @attributes 'sound' struct = TestStruct.newFromAttributes(sound: 'hollow', colour: 'eh?') expect( struct.sound() ).to.equal('hollow')
1417
Struct = requirejs('onion/struct') describe "Struct", -> describe "attributes", -> class TestStruct extends Struct @attributes 'brucy' struct = null beforeEach -> struct = new TestStruct(brucy: 'bonus') it "sets provided attributes", -> expect( struct.attrs() ).to.eql(brucy: 'bonus') it "returns the class's attribute names", -> expect( TestStruct.attributeNames ).to.eql(['brucy']) describe "#attrs", -> class TestStruct extends Struct @attributes 'hello', 'whats', 'nada' struct = null beforeEach -> struct = new TestStruct(hello: '<NAME>', whats: 'up', nada: 'much') it "gives all the attrs", -> expect( struct.attrs() ) .to.eql(hello: '<NAME>', whats: 'up', nada: 'much') it "allows specifying specific attrs", -> expect( struct.attrs('hello', 'whats') ) .to.eql(hello: '<NAME>', whats: 'up') describe "setting", -> class TestStruct extends Struct @attributes 'gold', 'silver' struct = null beforeEach -> struct = new TestStruct() it "sets and emits the `change` event", -> expect -> struct.setGold('lots') .toEmitOn(struct, 'change') expect( struct.gold() ) .to.eql('lots') it "sets and emits the `change:gold` event", -> expect -> struct.setGold('lots') .toEmitOn(struct, 'change:gold', {from: undefined, to: 'lots'}) expect( struct.gold() ).to.eql('lots') it "sets and emits a set event when a value is first set", -> struct.setGold(null) expect -> struct.setGold('lots') .toEmitOn(struct, 'set:gold', 'lots') expect( struct.gold() ).to.eql('lots') it "doesn't trigger if not changed", -> struct.setGold('lots') expect -> struct.setGold('lots') .not.toEmitOn(struct, 'change') expect -> struct.setGold('lots') .not.toEmitOn(struct, 'change:gold') describe "setting many", -> it "allows setting multiple at once", -> struct.setAttrs(gold: 'lots', silver: 'not so much') expect( struct.gold() ).to.eql('lots') expect( struct.silver() ).to.eql('not so much') it "doesn't allow setting attributes it doesn't know about", -> expect -> struct.setAttrs(what: 'the') .to.throw("unknown attribute what for TestStruct") it "emits `change:XXX` for each attribute", -> changeGoldEvents = changeSilverEvents = 0 struct.on 'change:gold', -> changeGoldEvents++ struct.on 'change:silver', -> changeSilverEvents++ struct.setAttrs(gold: 'lots', silver: 'not so much') expect( changeGoldEvents ).to.eql( 1 ) expect( changeSilverEvents ).to.eql( 1 ) struct.setAttrs(gold: 'less now', silver: 'not so much') expect( changeGoldEvents ).to.eql( 2 ) expect( changeSilverEvents ).to.eql( 1 ) it "emits `change` only once, and only if there are changes", -> changeEvents = 0 struct.on 'change', (changes) -> changeEvents++ struct.setAttrs(gold: 'lots', silver: 'not so much') expect( changeEvents ).to.eql( 1 ) struct.setAttrs(silver: 'not so much') expect( changeEvents ).to.eql( 1 ) describe "decorateWriter", -> class TestStruct extends Struct @attributes 'thing' @decorateWriter 'thing', (value) -> value.toUpperCase() it "decorates a writer with a function", -> struct = new TestStruct() struct.setThing('blob') expect( struct.thing() ).to.eql('BLOB') it "ignores the decorator if set to null", -> struct = new TestStruct() struct.setThing(null) expect( struct.thing() ).to.eql(null) it "works on null if the flag is set", -> TestStruct.attributes 'array' TestStruct.decorateWriter 'array', ((value) -> [value]), includeNull: true struct = new TestStruct() struct.setArray(null) expect( struct.array() ).to.eql([null]) it "works with setAttrs", -> struct = new TestStruct() struct.setAttrs(thing: 'blob') expect( struct.thing() ).to.eql('BLOB') describe "setDefaults", -> class TestStruct extends Struct @attributes 'colour' struct = null beforeEach -> struct = new TestStruct() it "sets if not already set", -> struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('blue') it "doesn't overwrite", -> struct.setColour('red') struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('red') it "doesn't overwrite falsy but already set", -> struct.setColour('') struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('') describe "relatedAttributes", -> struct = null TestStruct = null beforeEach -> TestStruct = class TestStruct extends Struct @attributes 'number', 'doubleNumber', 'tripleNumber' @relateAttributes 'doubleNumber', ['number'], (number) -> number * 2 struct = new TestStruct() it "updates when the other is updated", -> struct.setNumber(3) expect( struct.doubleNumber() ).to.equal(6) it "emits both change events", -> expect(-> struct.setNumber(3) ).toEmitOn(struct, 'change:number') expect(-> struct.setNumber(4) ).toEmitOn(struct, 'change:doubleNumber') it "doesn't run in reverse", -> struct.setDoubleNumber(6) expect( struct.number() ).to.be.undefined it "doesn't run the function if it isn't affected by changes", -> spy = sinon.spy() TestStruct = class TestStruct extends Struct @attributes 'a', 'b', 'c' @relateAttributes 'a', ['b'], spy struct = new TestStruct() struct.setC('stuff') expect( spy.called ).to.be.false it "sanity check with more complex example", -> TestStruct = class TestStruct extends Struct @attributes 'firstName', '<NAME>', 'fullName' @relateAttributes 'fullName', ['firstName', 'lastName'], (first, last) -> "#{first} #{last}" @relateAttributes 'firstName', ['fullName'], (fullName) -> fullName.split(' ')[0] @relateAttributes 'lastName', ['fullName'], (fullName) -> fullName.split(' ')[1] struct = new TestStruct() struct.setAttrs(firstName: '<NAME>', lastName: '<NAME>') expect( struct.fullName() ).to.equal("<NAME>") struct.setAttrs(fullName: '<NAME>') expect( struct.firstName() ).to.equal("<NAME>") expect( struct.lastName() ).to.equal("Egg") describe "newFromAttributes", -> it "creates a new struct, ignoring attributes it doesn't know about", -> class TestStruct extends Struct @attributes 'sound' struct = TestStruct.newFromAttributes(sound: 'hollow', colour: 'eh?') expect( struct.sound() ).to.equal('hollow')
true
Struct = requirejs('onion/struct') describe "Struct", -> describe "attributes", -> class TestStruct extends Struct @attributes 'brucy' struct = null beforeEach -> struct = new TestStruct(brucy: 'bonus') it "sets provided attributes", -> expect( struct.attrs() ).to.eql(brucy: 'bonus') it "returns the class's attribute names", -> expect( TestStruct.attributeNames ).to.eql(['brucy']) describe "#attrs", -> class TestStruct extends Struct @attributes 'hello', 'whats', 'nada' struct = null beforeEach -> struct = new TestStruct(hello: 'PI:NAME:<NAME>END_PI', whats: 'up', nada: 'much') it "gives all the attrs", -> expect( struct.attrs() ) .to.eql(hello: 'PI:NAME:<NAME>END_PI', whats: 'up', nada: 'much') it "allows specifying specific attrs", -> expect( struct.attrs('hello', 'whats') ) .to.eql(hello: 'PI:NAME:<NAME>END_PI', whats: 'up') describe "setting", -> class TestStruct extends Struct @attributes 'gold', 'silver' struct = null beforeEach -> struct = new TestStruct() it "sets and emits the `change` event", -> expect -> struct.setGold('lots') .toEmitOn(struct, 'change') expect( struct.gold() ) .to.eql('lots') it "sets and emits the `change:gold` event", -> expect -> struct.setGold('lots') .toEmitOn(struct, 'change:gold', {from: undefined, to: 'lots'}) expect( struct.gold() ).to.eql('lots') it "sets and emits a set event when a value is first set", -> struct.setGold(null) expect -> struct.setGold('lots') .toEmitOn(struct, 'set:gold', 'lots') expect( struct.gold() ).to.eql('lots') it "doesn't trigger if not changed", -> struct.setGold('lots') expect -> struct.setGold('lots') .not.toEmitOn(struct, 'change') expect -> struct.setGold('lots') .not.toEmitOn(struct, 'change:gold') describe "setting many", -> it "allows setting multiple at once", -> struct.setAttrs(gold: 'lots', silver: 'not so much') expect( struct.gold() ).to.eql('lots') expect( struct.silver() ).to.eql('not so much') it "doesn't allow setting attributes it doesn't know about", -> expect -> struct.setAttrs(what: 'the') .to.throw("unknown attribute what for TestStruct") it "emits `change:XXX` for each attribute", -> changeGoldEvents = changeSilverEvents = 0 struct.on 'change:gold', -> changeGoldEvents++ struct.on 'change:silver', -> changeSilverEvents++ struct.setAttrs(gold: 'lots', silver: 'not so much') expect( changeGoldEvents ).to.eql( 1 ) expect( changeSilverEvents ).to.eql( 1 ) struct.setAttrs(gold: 'less now', silver: 'not so much') expect( changeGoldEvents ).to.eql( 2 ) expect( changeSilverEvents ).to.eql( 1 ) it "emits `change` only once, and only if there are changes", -> changeEvents = 0 struct.on 'change', (changes) -> changeEvents++ struct.setAttrs(gold: 'lots', silver: 'not so much') expect( changeEvents ).to.eql( 1 ) struct.setAttrs(silver: 'not so much') expect( changeEvents ).to.eql( 1 ) describe "decorateWriter", -> class TestStruct extends Struct @attributes 'thing' @decorateWriter 'thing', (value) -> value.toUpperCase() it "decorates a writer with a function", -> struct = new TestStruct() struct.setThing('blob') expect( struct.thing() ).to.eql('BLOB') it "ignores the decorator if set to null", -> struct = new TestStruct() struct.setThing(null) expect( struct.thing() ).to.eql(null) it "works on null if the flag is set", -> TestStruct.attributes 'array' TestStruct.decorateWriter 'array', ((value) -> [value]), includeNull: true struct = new TestStruct() struct.setArray(null) expect( struct.array() ).to.eql([null]) it "works with setAttrs", -> struct = new TestStruct() struct.setAttrs(thing: 'blob') expect( struct.thing() ).to.eql('BLOB') describe "setDefaults", -> class TestStruct extends Struct @attributes 'colour' struct = null beforeEach -> struct = new TestStruct() it "sets if not already set", -> struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('blue') it "doesn't overwrite", -> struct.setColour('red') struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('red') it "doesn't overwrite falsy but already set", -> struct.setColour('') struct.setDefaults(colour: 'blue') expect( struct.colour() ).to.eql('') describe "relatedAttributes", -> struct = null TestStruct = null beforeEach -> TestStruct = class TestStruct extends Struct @attributes 'number', 'doubleNumber', 'tripleNumber' @relateAttributes 'doubleNumber', ['number'], (number) -> number * 2 struct = new TestStruct() it "updates when the other is updated", -> struct.setNumber(3) expect( struct.doubleNumber() ).to.equal(6) it "emits both change events", -> expect(-> struct.setNumber(3) ).toEmitOn(struct, 'change:number') expect(-> struct.setNumber(4) ).toEmitOn(struct, 'change:doubleNumber') it "doesn't run in reverse", -> struct.setDoubleNumber(6) expect( struct.number() ).to.be.undefined it "doesn't run the function if it isn't affected by changes", -> spy = sinon.spy() TestStruct = class TestStruct extends Struct @attributes 'a', 'b', 'c' @relateAttributes 'a', ['b'], spy struct = new TestStruct() struct.setC('stuff') expect( spy.called ).to.be.false it "sanity check with more complex example", -> TestStruct = class TestStruct extends Struct @attributes 'firstName', 'PI:NAME:<NAME>END_PI', 'fullName' @relateAttributes 'fullName', ['firstName', 'lastName'], (first, last) -> "#{first} #{last}" @relateAttributes 'firstName', ['fullName'], (fullName) -> fullName.split(' ')[0] @relateAttributes 'lastName', ['fullName'], (fullName) -> fullName.split(' ')[1] struct = new TestStruct() struct.setAttrs(firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI') expect( struct.fullName() ).to.equal("PI:NAME:<NAME>END_PI") struct.setAttrs(fullName: 'PI:NAME:<NAME>END_PI') expect( struct.firstName() ).to.equal("PI:NAME:<NAME>END_PI") expect( struct.lastName() ).to.equal("Egg") describe "newFromAttributes", -> it "creates a new struct, ignoring attributes it doesn't know about", -> class TestStruct extends Struct @attributes 'sound' struct = TestStruct.newFromAttributes(sound: 'hollow', colour: 'eh?') expect( struct.sound() ).to.equal('hollow')
[ { "context": " name: User.schema.properties.name\n password: User.schema.properties.password\n required: switch @signupState.get('path')\n ", "end": 6380, "score": 0.9927536845207214, "start": 6349, "tag": "PASSWORD", "value": "User.schema.properties.password" }, { "context...
app/views/core/CreateAccountModal/BasicInfoView.coffee
robertkachniarz/codecombat
1
require('app/styles/modal/create-account-modal/basic-info-view.sass') CocoView = require 'views/core/CocoView' AuthModal = require 'views/core/AuthModal' template = require 'templates/core/create-account-modal/basic-info-view' forms = require 'core/forms' errors = require 'core/errors' User = require 'models/User' State = require 'models/State' ### This view handles the primary form for user details — name, email, password, etc, and the AJAX that actually creates the user. It also handles facebook/g+ login, which if used, open one of two other screens: sso-already-exists: If the facebook/g+ connection is already associated with a user, they're given a log in button sso-confirm: If this is a new facebook/g+ connection, ask for a username, then allow creation of a user The sso-confirm view *inherits from this view* in order to share its account-creation logic and events. This means the selectors used in these events must work in both templates. This view currently uses the old form API instead of stateful render. It needs some work to make error UX and rendering better, but is functional. ### module.exports = class BasicInfoView extends CocoView id: 'basic-info-view' template: template events: 'change input[name="email"]': 'onChangeEmail' 'change input[name="name"]': 'onChangeName' 'change input[name="password"]': 'onChangePassword' 'click .back-button': 'onClickBackButton' 'submit form': 'onSubmitForm' 'click .use-suggested-name-link': 'onClickUseSuggestedNameLink' 'click #facebook-signup-btn': 'onClickSsoSignupButton' 'click #gplus-signup-btn': 'onClickSsoSignupButton' initialize: ({ @signupState } = {}) -> @state = new State { suggestedNameText: '...' checkEmailState: 'standby' # 'checking', 'exists', 'available' checkEmailValue: null checkEmailPromise: null checkNameState: 'standby' # same checkNameValue: null checkNamePromise: null error: '' } @listenTo @state, 'change:checkEmailState', -> @renderSelectors('.email-check') @listenTo @state, 'change:checkNameState', -> @renderSelectors('.name-check') @listenTo @state, 'change:error', -> @renderSelectors('.error-area') @listenTo @signupState, 'change:facebookEnabled', -> @renderSelectors('.auth-network-logins') @listenTo @signupState, 'change:gplusEnabled', -> @renderSelectors('.auth-network-logins') afterRender: -> @$el.find('#first-name-input').focus() super() # These values are passed along to AuthModal if the user clicks "Sign In" (handled by CreateAccountModal) updateAuthModalInitialValues: (values) -> @signupState.set { authModalInitialValues: _.merge @signupState.get('authModalInitialValues'), values }, { silent: true } onChangeEmail: (e) -> @updateAuthModalInitialValues { email: @$(e.currentTarget).val() } @checkEmail() checkEmail: -> email = @$('[name="email"]').val() if @signupState.get('path') isnt 'student' and (not _.isEmpty(email) and email is @state.get('checkEmailValue')) return @state.get('checkEmailPromise') if not (email and forms.validateEmail(email)) @state.set({ checkEmailState: 'standby' checkEmailValue: email checkEmailPromise: null }) return Promise.resolve() @state.set({ checkEmailState: 'checking' checkEmailValue: email checkEmailPromise: (User.checkEmailExists(email) .then ({exists}) => return unless email is @$('[name="email"]').val() if exists @state.set('checkEmailState', 'exists') else @state.set('checkEmailState', 'available') .catch (e) => @state.set('checkEmailState', 'standby') throw e ) }) return @state.get('checkEmailPromise') onChangeName: (e) -> @updateAuthModalInitialValues { name: @$(e.currentTarget).val() } # Go through the form library so this follows the same trimming rules name = forms.formToObject(@$el.find('#basic-info-form')).name # Carefully remove the error for just this field @$el.find('[for="username-input"] ~ .help-block.error-help-block').remove() @$el.find('[for="username-input"]').closest('.form-group').removeClass('has-error') if name and forms.validateEmail(name) forms.setErrorToProperty(@$el, 'name', $.i18n.t('signup.name_is_email')) return @checkName() checkName: -> return Promise.resolve() if @signupState.get('path') is 'teacher' name = @$('input[name="name"]').val() if name is @state.get('checkNameValue') return @state.get('checkNamePromise') if not name @state.set({ checkNameState: 'standby' checkNameValue: name checkNamePromise: null }) return Promise.resolve() @state.set({ checkNameState: 'checking' checkNameValue: name checkNamePromise: (User.checkNameConflicts(name) .then ({ suggestedName, conflicts }) => return unless name is @$('input[name="name"]').val() if conflicts suggestedNameText = $.i18n.t('signup.name_taken').replace('{{suggestedName}}', suggestedName) @state.set({ checkNameState: 'exists', suggestedNameText }) else @state.set { checkNameState: 'available' } .catch (error) => @state.set('checkNameState', 'standby') throw error ) }) return @state.get('checkNamePromise') onChangePassword: (e) -> @updateAuthModalInitialValues { password: @$(e.currentTarget).val() } checkBasicInfo: (data) -> # TODO: Move this to somewhere appropriate tv4.addFormat({ 'email': (email) -> if forms.validateEmail(email) return null else return {code: tv4.errorCodes.FORMAT_CUSTOM, message: "Please enter a valid email address."} }) forms.clearFormAlerts(@$el) if data.name and forms.validateEmail(data.name) forms.setErrorToProperty(@$el, 'name', $.i18n.t('signup.name_is_email')) return false res = tv4.validateMultiple data, @formSchema() forms.applyErrorsToForm(@$('form'), res.errors) unless res.valid return res.valid formSchema: -> type: 'object' properties: email: User.schema.properties.email name: User.schema.properties.name password: User.schema.properties.password required: switch @signupState.get('path') when 'student' then ['name', 'password', 'firstName', 'lastName'] when 'teacher' then ['password', 'email', 'firstName', 'lastName'] else ['name', 'password', 'email'] onClickBackButton: -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Back Clicked', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Back Clicked', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Back Clicked', category: 'Individuals' @trigger 'nav-back' onClickUseSuggestedNameLink: (e) -> @$('input[name="name"]').val(@state.get('suggestedName')) forms.clearFormAlerts(@$el.find('input[name="name"]').closest('.form-group').parent()) onSubmitForm: (e) -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Submit Clicked', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Submit Clicked', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Submit Clicked', category: 'Individuals' @state.unset('error') e.preventDefault() data = forms.formToObject(e.currentTarget) valid = @checkBasicInfo(data) return unless valid @displayFormSubmitting() AbortError = new Error() @checkEmail() .then @checkName() .then => if not (@state.get('checkEmailState') in ['available', 'standby'] and (@state.get('checkNameState') is 'available' or @signupState.get('path') is 'teacher')) throw AbortError # update User emails = _.assign({}, me.get('emails')) emails.generalNews ?= {} if me.inEU() emails.generalNews.enabled = false me.set('unsubscribedFromMarketingEmails', true) else emails.generalNews.enabled = not _.isEmpty(@state.get('checkEmailValue')) me.set('emails', emails) me.set(_.pick(data, 'firstName', 'lastName')) unless _.isNaN(@signupState.get('birthday').getTime()) me.set('birthday', @signupState.get('birthday').toISOString().slice(0,7)) me.set(_.omit(@signupState.get('ssoAttrs') or {}, 'email', 'facebookID', 'gplusID')) jqxhr = me.save() if not jqxhr console.error(me.validationError) throw new Error('Could not save user') return new Promise(jqxhr.then) .then => # Don't sign up, kick to TeacherComponent instead if @signupState.get('path') is 'teacher' @signupState.set({ signupForm: _.pick(forms.formToObject(@$el), 'firstName', 'lastName', 'email', 'password', 'subscribe') }) @trigger 'signup' return # Use signup method window.tracker?.identify() unless User.isSmokeTestUser({ email: @signupState.get('signupForm').email }) switch @signupState.get('ssoUsed') when 'gplus' { email, gplusID } = @signupState.get('ssoAttrs') { name } = forms.formToObject(@$el) jqxhr = me.signupWithGPlus(name, email, gplusID) when 'facebook' { email, facebookID } = @signupState.get('ssoAttrs') { name } = forms.formToObject(@$el) jqxhr = me.signupWithFacebook(name, email, facebookID) else { name, email, password } = forms.formToObject(@$el) jqxhr = me.signupWithPassword(name, email, password) return new Promise(jqxhr.then) .then => { classCode, classroom } = @signupState.attributes if classCode and classroom return new Promise(classroom.joinWithCode(classCode).then) .then => @finishSignup() .catch (e) => @displayFormStandingBy() if e is AbortError return else console.error 'BasicInfoView form submission Promise error:', e @state.set('error', e.responseJSON?.message or 'Unknown Error') finishSignup: -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Submit Success', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Submit Success', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Submit Success', category: 'Individuals', wantInSchool: @$('#want-in-school-checkbox').is(':checked') if @$('#want-in-school-checkbox').is(':checked') @signupState.set 'wantInSchool', true @trigger 'signup' displayFormSubmitting: -> @$('#create-account-btn').text($.i18n.t('signup.creating')).attr('disabled', true) @$('input').attr('disabled', true) displayFormStandingBy: -> @$('#create-account-btn').text($.i18n.t('login.sign_up')).attr('disabled', false) @$('input').attr('disabled', false) onClickSsoSignupButton: (e) -> e.preventDefault() ssoUsed = $(e.currentTarget).data('sso-used') handler = if ssoUsed is 'facebook' then application.facebookHandler else application.gplusHandler handler.connect({ context: @ success: -> handler.loadPerson({ context: @ success: (ssoAttrs) -> @signupState.set { ssoAttrs } { email } = ssoAttrs User.checkEmailExists(email).then ({exists}) => @signupState.set { ssoUsed email: ssoAttrs.email } if exists @trigger 'sso-connect:already-in-use' else @trigger 'sso-connect:new-user' }) })
153664
require('app/styles/modal/create-account-modal/basic-info-view.sass') CocoView = require 'views/core/CocoView' AuthModal = require 'views/core/AuthModal' template = require 'templates/core/create-account-modal/basic-info-view' forms = require 'core/forms' errors = require 'core/errors' User = require 'models/User' State = require 'models/State' ### This view handles the primary form for user details — name, email, password, etc, and the AJAX that actually creates the user. It also handles facebook/g+ login, which if used, open one of two other screens: sso-already-exists: If the facebook/g+ connection is already associated with a user, they're given a log in button sso-confirm: If this is a new facebook/g+ connection, ask for a username, then allow creation of a user The sso-confirm view *inherits from this view* in order to share its account-creation logic and events. This means the selectors used in these events must work in both templates. This view currently uses the old form API instead of stateful render. It needs some work to make error UX and rendering better, but is functional. ### module.exports = class BasicInfoView extends CocoView id: 'basic-info-view' template: template events: 'change input[name="email"]': 'onChangeEmail' 'change input[name="name"]': 'onChangeName' 'change input[name="password"]': 'onChangePassword' 'click .back-button': 'onClickBackButton' 'submit form': 'onSubmitForm' 'click .use-suggested-name-link': 'onClickUseSuggestedNameLink' 'click #facebook-signup-btn': 'onClickSsoSignupButton' 'click #gplus-signup-btn': 'onClickSsoSignupButton' initialize: ({ @signupState } = {}) -> @state = new State { suggestedNameText: '...' checkEmailState: 'standby' # 'checking', 'exists', 'available' checkEmailValue: null checkEmailPromise: null checkNameState: 'standby' # same checkNameValue: null checkNamePromise: null error: '' } @listenTo @state, 'change:checkEmailState', -> @renderSelectors('.email-check') @listenTo @state, 'change:checkNameState', -> @renderSelectors('.name-check') @listenTo @state, 'change:error', -> @renderSelectors('.error-area') @listenTo @signupState, 'change:facebookEnabled', -> @renderSelectors('.auth-network-logins') @listenTo @signupState, 'change:gplusEnabled', -> @renderSelectors('.auth-network-logins') afterRender: -> @$el.find('#first-name-input').focus() super() # These values are passed along to AuthModal if the user clicks "Sign In" (handled by CreateAccountModal) updateAuthModalInitialValues: (values) -> @signupState.set { authModalInitialValues: _.merge @signupState.get('authModalInitialValues'), values }, { silent: true } onChangeEmail: (e) -> @updateAuthModalInitialValues { email: @$(e.currentTarget).val() } @checkEmail() checkEmail: -> email = @$('[name="email"]').val() if @signupState.get('path') isnt 'student' and (not _.isEmpty(email) and email is @state.get('checkEmailValue')) return @state.get('checkEmailPromise') if not (email and forms.validateEmail(email)) @state.set({ checkEmailState: 'standby' checkEmailValue: email checkEmailPromise: null }) return Promise.resolve() @state.set({ checkEmailState: 'checking' checkEmailValue: email checkEmailPromise: (User.checkEmailExists(email) .then ({exists}) => return unless email is @$('[name="email"]').val() if exists @state.set('checkEmailState', 'exists') else @state.set('checkEmailState', 'available') .catch (e) => @state.set('checkEmailState', 'standby') throw e ) }) return @state.get('checkEmailPromise') onChangeName: (e) -> @updateAuthModalInitialValues { name: @$(e.currentTarget).val() } # Go through the form library so this follows the same trimming rules name = forms.formToObject(@$el.find('#basic-info-form')).name # Carefully remove the error for just this field @$el.find('[for="username-input"] ~ .help-block.error-help-block').remove() @$el.find('[for="username-input"]').closest('.form-group').removeClass('has-error') if name and forms.validateEmail(name) forms.setErrorToProperty(@$el, 'name', $.i18n.t('signup.name_is_email')) return @checkName() checkName: -> return Promise.resolve() if @signupState.get('path') is 'teacher' name = @$('input[name="name"]').val() if name is @state.get('checkNameValue') return @state.get('checkNamePromise') if not name @state.set({ checkNameState: 'standby' checkNameValue: name checkNamePromise: null }) return Promise.resolve() @state.set({ checkNameState: 'checking' checkNameValue: name checkNamePromise: (User.checkNameConflicts(name) .then ({ suggestedName, conflicts }) => return unless name is @$('input[name="name"]').val() if conflicts suggestedNameText = $.i18n.t('signup.name_taken').replace('{{suggestedName}}', suggestedName) @state.set({ checkNameState: 'exists', suggestedNameText }) else @state.set { checkNameState: 'available' } .catch (error) => @state.set('checkNameState', 'standby') throw error ) }) return @state.get('checkNamePromise') onChangePassword: (e) -> @updateAuthModalInitialValues { password: @$(e.currentTarget).val() } checkBasicInfo: (data) -> # TODO: Move this to somewhere appropriate tv4.addFormat({ 'email': (email) -> if forms.validateEmail(email) return null else return {code: tv4.errorCodes.FORMAT_CUSTOM, message: "Please enter a valid email address."} }) forms.clearFormAlerts(@$el) if data.name and forms.validateEmail(data.name) forms.setErrorToProperty(@$el, 'name', $.i18n.t('signup.name_is_email')) return false res = tv4.validateMultiple data, @formSchema() forms.applyErrorsToForm(@$('form'), res.errors) unless res.valid return res.valid formSchema: -> type: 'object' properties: email: User.schema.properties.email name: User.schema.properties.name password: <PASSWORD> required: switch @signupState.get('path') when 'student' then ['name', 'password', 'firstName', 'lastName'] when 'teacher' then ['password', 'email', 'firstName', 'lastName'] else ['name', 'password', 'email'] onClickBackButton: -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Back Clicked', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Back Clicked', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Back Clicked', category: 'Individuals' @trigger 'nav-back' onClickUseSuggestedNameLink: (e) -> @$('input[name="name"]').val(@state.get('suggestedName')) forms.clearFormAlerts(@$el.find('input[name="name"]').closest('.form-group').parent()) onSubmitForm: (e) -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Submit Clicked', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Submit Clicked', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Submit Clicked', category: 'Individuals' @state.unset('error') e.preventDefault() data = forms.formToObject(e.currentTarget) valid = @checkBasicInfo(data) return unless valid @displayFormSubmitting() AbortError = new Error() @checkEmail() .then @checkName() .then => if not (@state.get('checkEmailState') in ['available', 'standby'] and (@state.get('checkNameState') is 'available' or @signupState.get('path') is 'teacher')) throw AbortError # update User emails = _.assign({}, me.get('emails')) emails.generalNews ?= {} if me.inEU() emails.generalNews.enabled = false me.set('unsubscribedFromMarketingEmails', true) else emails.generalNews.enabled = not _.isEmpty(@state.get('checkEmailValue')) me.set('emails', emails) me.set(_.pick(data, 'firstName', 'lastName')) unless _.isNaN(@signupState.get('birthday').getTime()) me.set('birthday', @signupState.get('birthday').toISOString().slice(0,7)) me.set(_.omit(@signupState.get('ssoAttrs') or {}, 'email', 'facebookID', 'gplusID')) jqxhr = me.save() if not jqxhr console.error(me.validationError) throw new Error('Could not save user') return new Promise(jqxhr.then) .then => # Don't sign up, kick to TeacherComponent instead if @signupState.get('path') is 'teacher' @signupState.set({ signupForm: _.pick(forms.formToObject(@$el), 'firstName', '<NAME>', 'email', 'password', 'subscribe') }) @trigger 'signup' return # Use signup method window.tracker?.identify() unless User.isSmokeTestUser({ email: @signupState.get('signupForm').email }) switch @signupState.get('ssoUsed') when 'gplus' { email, gplusID } = @signupState.get('ssoAttrs') { name } = forms.formToObject(@$el) jqxhr = me.signupWithGPlus(name, email, gplusID) when 'facebook' { email, facebookID } = @signupState.get('ssoAttrs') { name } = forms.formToObject(@$el) jqxhr = me.signupWithFacebook(name, email, facebookID) else { name, email, password } = forms.formToObject(@$el) jqxhr = me.signupWithPassword(name, email, password) return new Promise(jqxhr.then) .then => { classCode, classroom } = @signupState.attributes if classCode and classroom return new Promise(classroom.joinWithCode(classCode).then) .then => @finishSignup() .catch (e) => @displayFormStandingBy() if e is AbortError return else console.error 'BasicInfoView form submission Promise error:', e @state.set('error', e.responseJSON?.message or 'Unknown Error') finishSignup: -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Submit Success', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Submit Success', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Submit Success', category: 'Individuals', wantInSchool: @$('#want-in-school-checkbox').is(':checked') if @$('#want-in-school-checkbox').is(':checked') @signupState.set 'wantInSchool', true @trigger 'signup' displayFormSubmitting: -> @$('#create-account-btn').text($.i18n.t('signup.creating')).attr('disabled', true) @$('input').attr('disabled', true) displayFormStandingBy: -> @$('#create-account-btn').text($.i18n.t('login.sign_up')).attr('disabled', false) @$('input').attr('disabled', false) onClickSsoSignupButton: (e) -> e.preventDefault() ssoUsed = $(e.currentTarget).data('sso-used') handler = if ssoUsed is 'facebook' then application.facebookHandler else application.gplusHandler handler.connect({ context: @ success: -> handler.loadPerson({ context: @ success: (ssoAttrs) -> @signupState.set { ssoAttrs } { email } = ssoAttrs User.checkEmailExists(email).then ({exists}) => @signupState.set { ssoUsed email: ssoAttrs.email } if exists @trigger 'sso-connect:already-in-use' else @trigger 'sso-connect:new-user' }) })
true
require('app/styles/modal/create-account-modal/basic-info-view.sass') CocoView = require 'views/core/CocoView' AuthModal = require 'views/core/AuthModal' template = require 'templates/core/create-account-modal/basic-info-view' forms = require 'core/forms' errors = require 'core/errors' User = require 'models/User' State = require 'models/State' ### This view handles the primary form for user details — name, email, password, etc, and the AJAX that actually creates the user. It also handles facebook/g+ login, which if used, open one of two other screens: sso-already-exists: If the facebook/g+ connection is already associated with a user, they're given a log in button sso-confirm: If this is a new facebook/g+ connection, ask for a username, then allow creation of a user The sso-confirm view *inherits from this view* in order to share its account-creation logic and events. This means the selectors used in these events must work in both templates. This view currently uses the old form API instead of stateful render. It needs some work to make error UX and rendering better, but is functional. ### module.exports = class BasicInfoView extends CocoView id: 'basic-info-view' template: template events: 'change input[name="email"]': 'onChangeEmail' 'change input[name="name"]': 'onChangeName' 'change input[name="password"]': 'onChangePassword' 'click .back-button': 'onClickBackButton' 'submit form': 'onSubmitForm' 'click .use-suggested-name-link': 'onClickUseSuggestedNameLink' 'click #facebook-signup-btn': 'onClickSsoSignupButton' 'click #gplus-signup-btn': 'onClickSsoSignupButton' initialize: ({ @signupState } = {}) -> @state = new State { suggestedNameText: '...' checkEmailState: 'standby' # 'checking', 'exists', 'available' checkEmailValue: null checkEmailPromise: null checkNameState: 'standby' # same checkNameValue: null checkNamePromise: null error: '' } @listenTo @state, 'change:checkEmailState', -> @renderSelectors('.email-check') @listenTo @state, 'change:checkNameState', -> @renderSelectors('.name-check') @listenTo @state, 'change:error', -> @renderSelectors('.error-area') @listenTo @signupState, 'change:facebookEnabled', -> @renderSelectors('.auth-network-logins') @listenTo @signupState, 'change:gplusEnabled', -> @renderSelectors('.auth-network-logins') afterRender: -> @$el.find('#first-name-input').focus() super() # These values are passed along to AuthModal if the user clicks "Sign In" (handled by CreateAccountModal) updateAuthModalInitialValues: (values) -> @signupState.set { authModalInitialValues: _.merge @signupState.get('authModalInitialValues'), values }, { silent: true } onChangeEmail: (e) -> @updateAuthModalInitialValues { email: @$(e.currentTarget).val() } @checkEmail() checkEmail: -> email = @$('[name="email"]').val() if @signupState.get('path') isnt 'student' and (not _.isEmpty(email) and email is @state.get('checkEmailValue')) return @state.get('checkEmailPromise') if not (email and forms.validateEmail(email)) @state.set({ checkEmailState: 'standby' checkEmailValue: email checkEmailPromise: null }) return Promise.resolve() @state.set({ checkEmailState: 'checking' checkEmailValue: email checkEmailPromise: (User.checkEmailExists(email) .then ({exists}) => return unless email is @$('[name="email"]').val() if exists @state.set('checkEmailState', 'exists') else @state.set('checkEmailState', 'available') .catch (e) => @state.set('checkEmailState', 'standby') throw e ) }) return @state.get('checkEmailPromise') onChangeName: (e) -> @updateAuthModalInitialValues { name: @$(e.currentTarget).val() } # Go through the form library so this follows the same trimming rules name = forms.formToObject(@$el.find('#basic-info-form')).name # Carefully remove the error for just this field @$el.find('[for="username-input"] ~ .help-block.error-help-block').remove() @$el.find('[for="username-input"]').closest('.form-group').removeClass('has-error') if name and forms.validateEmail(name) forms.setErrorToProperty(@$el, 'name', $.i18n.t('signup.name_is_email')) return @checkName() checkName: -> return Promise.resolve() if @signupState.get('path') is 'teacher' name = @$('input[name="name"]').val() if name is @state.get('checkNameValue') return @state.get('checkNamePromise') if not name @state.set({ checkNameState: 'standby' checkNameValue: name checkNamePromise: null }) return Promise.resolve() @state.set({ checkNameState: 'checking' checkNameValue: name checkNamePromise: (User.checkNameConflicts(name) .then ({ suggestedName, conflicts }) => return unless name is @$('input[name="name"]').val() if conflicts suggestedNameText = $.i18n.t('signup.name_taken').replace('{{suggestedName}}', suggestedName) @state.set({ checkNameState: 'exists', suggestedNameText }) else @state.set { checkNameState: 'available' } .catch (error) => @state.set('checkNameState', 'standby') throw error ) }) return @state.get('checkNamePromise') onChangePassword: (e) -> @updateAuthModalInitialValues { password: @$(e.currentTarget).val() } checkBasicInfo: (data) -> # TODO: Move this to somewhere appropriate tv4.addFormat({ 'email': (email) -> if forms.validateEmail(email) return null else return {code: tv4.errorCodes.FORMAT_CUSTOM, message: "Please enter a valid email address."} }) forms.clearFormAlerts(@$el) if data.name and forms.validateEmail(data.name) forms.setErrorToProperty(@$el, 'name', $.i18n.t('signup.name_is_email')) return false res = tv4.validateMultiple data, @formSchema() forms.applyErrorsToForm(@$('form'), res.errors) unless res.valid return res.valid formSchema: -> type: 'object' properties: email: User.schema.properties.email name: User.schema.properties.name password: PI:PASSWORD:<PASSWORD>END_PI required: switch @signupState.get('path') when 'student' then ['name', 'password', 'firstName', 'lastName'] when 'teacher' then ['password', 'email', 'firstName', 'lastName'] else ['name', 'password', 'email'] onClickBackButton: -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Back Clicked', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Back Clicked', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Back Clicked', category: 'Individuals' @trigger 'nav-back' onClickUseSuggestedNameLink: (e) -> @$('input[name="name"]').val(@state.get('suggestedName')) forms.clearFormAlerts(@$el.find('input[name="name"]').closest('.form-group').parent()) onSubmitForm: (e) -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Submit Clicked', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Submit Clicked', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Submit Clicked', category: 'Individuals' @state.unset('error') e.preventDefault() data = forms.formToObject(e.currentTarget) valid = @checkBasicInfo(data) return unless valid @displayFormSubmitting() AbortError = new Error() @checkEmail() .then @checkName() .then => if not (@state.get('checkEmailState') in ['available', 'standby'] and (@state.get('checkNameState') is 'available' or @signupState.get('path') is 'teacher')) throw AbortError # update User emails = _.assign({}, me.get('emails')) emails.generalNews ?= {} if me.inEU() emails.generalNews.enabled = false me.set('unsubscribedFromMarketingEmails', true) else emails.generalNews.enabled = not _.isEmpty(@state.get('checkEmailValue')) me.set('emails', emails) me.set(_.pick(data, 'firstName', 'lastName')) unless _.isNaN(@signupState.get('birthday').getTime()) me.set('birthday', @signupState.get('birthday').toISOString().slice(0,7)) me.set(_.omit(@signupState.get('ssoAttrs') or {}, 'email', 'facebookID', 'gplusID')) jqxhr = me.save() if not jqxhr console.error(me.validationError) throw new Error('Could not save user') return new Promise(jqxhr.then) .then => # Don't sign up, kick to TeacherComponent instead if @signupState.get('path') is 'teacher' @signupState.set({ signupForm: _.pick(forms.formToObject(@$el), 'firstName', 'PI:NAME:<NAME>END_PI', 'email', 'password', 'subscribe') }) @trigger 'signup' return # Use signup method window.tracker?.identify() unless User.isSmokeTestUser({ email: @signupState.get('signupForm').email }) switch @signupState.get('ssoUsed') when 'gplus' { email, gplusID } = @signupState.get('ssoAttrs') { name } = forms.formToObject(@$el) jqxhr = me.signupWithGPlus(name, email, gplusID) when 'facebook' { email, facebookID } = @signupState.get('ssoAttrs') { name } = forms.formToObject(@$el) jqxhr = me.signupWithFacebook(name, email, facebookID) else { name, email, password } = forms.formToObject(@$el) jqxhr = me.signupWithPassword(name, email, password) return new Promise(jqxhr.then) .then => { classCode, classroom } = @signupState.attributes if classCode and classroom return new Promise(classroom.joinWithCode(classCode).then) .then => @finishSignup() .catch (e) => @displayFormStandingBy() if e is AbortError return else console.error 'BasicInfoView form submission Promise error:', e @state.set('error', e.responseJSON?.message or 'Unknown Error') finishSignup: -> if @signupState.get('path') is 'teacher' window.tracker?.trackEvent 'CreateAccountModal Teacher BasicInfoView Submit Success', category: 'Teachers' if @signupState.get('path') is 'student' window.tracker?.trackEvent 'CreateAccountModal Student BasicInfoView Submit Success', category: 'Students' if @signupState.get('path') is 'individual' window.tracker?.trackEvent 'CreateAccountModal Individual BasicInfoView Submit Success', category: 'Individuals', wantInSchool: @$('#want-in-school-checkbox').is(':checked') if @$('#want-in-school-checkbox').is(':checked') @signupState.set 'wantInSchool', true @trigger 'signup' displayFormSubmitting: -> @$('#create-account-btn').text($.i18n.t('signup.creating')).attr('disabled', true) @$('input').attr('disabled', true) displayFormStandingBy: -> @$('#create-account-btn').text($.i18n.t('login.sign_up')).attr('disabled', false) @$('input').attr('disabled', false) onClickSsoSignupButton: (e) -> e.preventDefault() ssoUsed = $(e.currentTarget).data('sso-used') handler = if ssoUsed is 'facebook' then application.facebookHandler else application.gplusHandler handler.connect({ context: @ success: -> handler.loadPerson({ context: @ success: (ssoAttrs) -> @signupState.set { ssoAttrs } { email } = ssoAttrs User.checkEmailExists(email).then ({exists}) => @signupState.set { ssoUsed email: ssoAttrs.email } if exists @trigger 'sso-connect:already-in-use' else @trigger 'sso-connect:new-user' }) })
[ { "context": "re_auth = null\r\n credentials = \r\n email: \"testing@tedchef.com\"\r\n password: \"testing\"\r\n\r\n beforeEach ->\r", "end": 403, "score": 0.999922513961792, "start": 384, "tag": "EMAIL", "value": "testing@tedchef.com" }, { "context": " email: \"tes...
test/specs/fire_auth.spec.coffee
CurtisHumphrey/knockout-firebase-users
0
define (require) -> ko = require 'knockout' _ = require 'lodash' window.ko = ko MockFirebase = require('mockfirebase').MockFirebase Fire_Auth_Class = require 'fire_auth_class' Fire_Auth = require 'fire_auth' describe 'Fire Auth', -> fire_ref = null fire_auth = null credentials = email: "testing@tedchef.com" password: "testing" beforeEach -> fire_ref = new MockFirebase('testing://') fire_ref.autoFlush() fire_ref.set users: defaults: public: picture: "me.png" private: awaiting_approvial: true resets: null public: u001: picture: "user.png" display_name: "user" u002: display_name: "user" private: u001: awaiting_approvial: true email: credentials.email u002: is_admin: true email: credentials.email describe 'Exports', -> beforeEach -> fire_auth = Fire_Auth it 'Should have a Setup function', -> expect _.isFunction fire_auth.Setup .toBeTruthy() it 'Should have a Login function', -> expect _.isFunction fire_auth.Login .toBeTruthy() it 'Should have a Logout function', -> expect _.isFunction fire_auth.Logout .toBeTruthy() it 'Should have a Recover_Password function', -> expect _.isFunction fire_auth.Recover_Password .toBeTruthy() it 'Should have a Create_User function', -> expect _.isFunction fire_auth.Create_User .toBeTruthy() it 'Should have a user object', -> expect _.isObject fire_auth.user .toBeTruthy() it 'Should have a user_id observable', -> expect fire_auth.user_id .toBeDefined() it 'Should have a valid observable', -> expect ko.isObservable(fire_auth.valid) .toBeTruthy() it 'Should have a checking observable', -> expect ko.isObservable(fire_auth.checking) .toBeTruthy() it 'Should have a reset_requested observable', -> expect fire_auth.reset_requested .toBeDefined() describe 'User Login', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref public: picture: null display_name: null private: email: null awaiting_approvial: null is_admin: null fire_auth.Login credentials it 'Should be able to login a user', -> expect(fire_auth.valid()).toBeFalsy() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.valid()).toBeTruthy() expect(fire_auth.user_id()).toEqual('u001') it 'Should be report "checking" as true until login is complete', -> expect(fire_auth.checking()).toBeTruthy() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.checking()).toBeFalsy() it 'Should load the user\'s data from both public and private locations', -> fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect( fire_auth.user.picture()).toEqual "user.png" expect( fire_auth.user.awaiting_approvial()).toEqual true expect( fire_auth.user.display_name()).toEqual "user" expect( fire_auth.user.email()).toEqual credentials.email it 'If the user\'s data does not have some of the default values it should add them', -> fire_ref.changeAuthState uid: 'u002' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} #has expect( fire_auth.user.display_name()).toEqual "user" expect( fire_auth.user.is_admin()).toEqual true expect( fire_auth.user.email()).toEqual credentials.email #added expect( fire_auth.user.picture()).toEqual "me.png" expect( fire_auth.user.awaiting_approvial()).toEqual true expect( fire_ref.child('users/public').child('u002').getData().picture).toEqual "me.png" expect( fire_ref.child('users/private').child('u002').getData().awaiting_approvial).toEqual true describe 'Log out', -> public_data = null private_data = null beforeEach -> public_data = fire_ref.child('users/public/u001').getData() private_data = fire_ref.child('users/private/u001').getData() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} fire_auth.Logout() it 'Should be able to logout a user', -> expect(fire_auth.valid()).toBeFalsy() expect(fire_auth.user_id()).toBeFalsy() it 'Should clear the user\'s data', -> expect( fire_auth.user.picture()).toEqual null expect( fire_auth.user.awaiting_approvial()).toEqual null expect( fire_auth.user.display_name()).toEqual null expect( fire_auth.user.email()).toEqual null it 'Should not clear the DB values', -> expect( fire_ref.child('users/public/u001').getData()).toBeDefined() expect fire_ref.child('users/public/u001').getData() .toEqual public_data expect fire_ref.child('users/private/u001').getData() .toEqual private_data describe 'Recover Password', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref fire_auth.Create_User email: credentials.email password: credentials.password it 'Should flag that reset happened in firebase', -> fire_auth.Recover_Password credentials.email expect(fire_ref.child('users/resets/'+credentials.email.replace('.','')).getData()).toBeTruthy() it 'Should flag that a reset happened once they login again', -> fire_auth.Recover_Password credentials.email fire_auth.Login credentials fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.reset_requested()).toBeTruthy() describe 'Creating a User', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref fire_auth.Create_User email: credentials.email password: credentials.password new_private: email: credentials.email new_public: display_name: 'user' it 'Should create a new user', -> expect( fire_ref.getEmailUser(credentials.email)).not.toBeNull() it 'Should add entries into public list', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData()).not.toBeNull() it 'Should add entries into private list', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData()).not.toBeNull() it 'Should copy the private defaults into the private', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData().awaiting_approvial).toEqual true it 'Should copy the public defaults into the public', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData().picture).toEqual "me.png" it 'Should add to the public profile values passed under the "new_public" object', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData().display_name).toEqual "user" it 'Should add to the private profile values passed under the "new_private" object', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData().email).toEqual credentials.email return
193869
define (require) -> ko = require 'knockout' _ = require 'lodash' window.ko = ko MockFirebase = require('mockfirebase').MockFirebase Fire_Auth_Class = require 'fire_auth_class' Fire_Auth = require 'fire_auth' describe 'Fire Auth', -> fire_ref = null fire_auth = null credentials = email: "<EMAIL>" password: "<PASSWORD>" beforeEach -> fire_ref = new MockFirebase('testing://') fire_ref.autoFlush() fire_ref.set users: defaults: public: picture: "me.png" private: awaiting_approvial: true resets: null public: u001: picture: "user.png" display_name: "<NAME>" u002: display_name: "<NAME>" private: u001: awaiting_approvial: true email: credentials.email u002: is_admin: true email: credentials.email describe 'Exports', -> beforeEach -> fire_auth = Fire_Auth it 'Should have a Setup function', -> expect _.isFunction fire_auth.Setup .toBeTruthy() it 'Should have a Login function', -> expect _.isFunction fire_auth.Login .toBeTruthy() it 'Should have a Logout function', -> expect _.isFunction fire_auth.Logout .toBeTruthy() it 'Should have a Recover_Password function', -> expect _.isFunction fire_auth.Recover_Password .toBeTruthy() it 'Should have a Create_User function', -> expect _.isFunction fire_auth.Create_User .toBeTruthy() it 'Should have a user object', -> expect _.isObject fire_auth.user .toBeTruthy() it 'Should have a user_id observable', -> expect fire_auth.user_id .toBeDefined() it 'Should have a valid observable', -> expect ko.isObservable(fire_auth.valid) .toBeTruthy() it 'Should have a checking observable', -> expect ko.isObservable(fire_auth.checking) .toBeTruthy() it 'Should have a reset_requested observable', -> expect fire_auth.reset_requested .toBeDefined() describe 'User Login', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref public: picture: null display_name: null private: email: null awaiting_approvial: null is_admin: null fire_auth.Login credentials it 'Should be able to login a user', -> expect(fire_auth.valid()).toBeFalsy() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.valid()).toBeTruthy() expect(fire_auth.user_id()).toEqual('u001') it 'Should be report "checking" as true until login is complete', -> expect(fire_auth.checking()).toBeTruthy() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.checking()).toBeFalsy() it 'Should load the user\'s data from both public and private locations', -> fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect( fire_auth.user.picture()).toEqual "user.png" expect( fire_auth.user.awaiting_approvial()).toEqual true expect( fire_auth.user.display_name()).toEqual "user" expect( fire_auth.user.email()).toEqual credentials.email it 'If the user\'s data does not have some of the default values it should add them', -> fire_ref.changeAuthState uid: 'u002' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} #has expect( fire_auth.user.display_name()).toEqual "user" expect( fire_auth.user.is_admin()).toEqual true expect( fire_auth.user.email()).toEqual credentials.email #added expect( fire_auth.user.picture()).toEqual "me.png" expect( fire_auth.user.awaiting_approvial()).toEqual true expect( fire_ref.child('users/public').child('u002').getData().picture).toEqual "me.png" expect( fire_ref.child('users/private').child('u002').getData().awaiting_approvial).toEqual true describe 'Log out', -> public_data = null private_data = null beforeEach -> public_data = fire_ref.child('users/public/u001').getData() private_data = fire_ref.child('users/private/u001').getData() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} fire_auth.Logout() it 'Should be able to logout a user', -> expect(fire_auth.valid()).toBeFalsy() expect(fire_auth.user_id()).toBeFalsy() it 'Should clear the user\'s data', -> expect( fire_auth.user.picture()).toEqual null expect( fire_auth.user.awaiting_approvial()).toEqual null expect( fire_auth.user.display_name()).toEqual null expect( fire_auth.user.email()).toEqual null it 'Should not clear the DB values', -> expect( fire_ref.child('users/public/u001').getData()).toBeDefined() expect fire_ref.child('users/public/u001').getData() .toEqual public_data expect fire_ref.child('users/private/u001').getData() .toEqual private_data describe 'Recover Password', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref fire_auth.Create_User email: credentials.email password: <PASSWORD> it 'Should flag that reset happened in firebase', -> fire_auth.Recover_Password credentials.email expect(fire_ref.child('users/resets/'+credentials.email.replace('.','')).getData()).toBeTruthy() it 'Should flag that a reset happened once they login again', -> fire_auth.Recover_Password credentials.email fire_auth.Login credentials fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.reset_requested()).toBeTruthy() describe 'Creating a User', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref fire_auth.Create_User email: credentials.email password: <PASSWORD> new_private: email: credentials.email new_public: display_name: 'user' it 'Should create a new user', -> expect( fire_ref.getEmailUser(credentials.email)).not.toBeNull() it 'Should add entries into public list', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData()).not.toBeNull() it 'Should add entries into private list', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData()).not.toBeNull() it 'Should copy the private defaults into the private', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData().awaiting_approvial).toEqual true it 'Should copy the public defaults into the public', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData().picture).toEqual "me.png" it 'Should add to the public profile values passed under the "new_public" object', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData().display_name).toEqual "user" it 'Should add to the private profile values passed under the "new_private" object', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData().email).toEqual credentials.email return
true
define (require) -> ko = require 'knockout' _ = require 'lodash' window.ko = ko MockFirebase = require('mockfirebase').MockFirebase Fire_Auth_Class = require 'fire_auth_class' Fire_Auth = require 'fire_auth' describe 'Fire Auth', -> fire_ref = null fire_auth = null credentials = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" beforeEach -> fire_ref = new MockFirebase('testing://') fire_ref.autoFlush() fire_ref.set users: defaults: public: picture: "me.png" private: awaiting_approvial: true resets: null public: u001: picture: "user.png" display_name: "PI:NAME:<NAME>END_PI" u002: display_name: "PI:NAME:<NAME>END_PI" private: u001: awaiting_approvial: true email: credentials.email u002: is_admin: true email: credentials.email describe 'Exports', -> beforeEach -> fire_auth = Fire_Auth it 'Should have a Setup function', -> expect _.isFunction fire_auth.Setup .toBeTruthy() it 'Should have a Login function', -> expect _.isFunction fire_auth.Login .toBeTruthy() it 'Should have a Logout function', -> expect _.isFunction fire_auth.Logout .toBeTruthy() it 'Should have a Recover_Password function', -> expect _.isFunction fire_auth.Recover_Password .toBeTruthy() it 'Should have a Create_User function', -> expect _.isFunction fire_auth.Create_User .toBeTruthy() it 'Should have a user object', -> expect _.isObject fire_auth.user .toBeTruthy() it 'Should have a user_id observable', -> expect fire_auth.user_id .toBeDefined() it 'Should have a valid observable', -> expect ko.isObservable(fire_auth.valid) .toBeTruthy() it 'Should have a checking observable', -> expect ko.isObservable(fire_auth.checking) .toBeTruthy() it 'Should have a reset_requested observable', -> expect fire_auth.reset_requested .toBeDefined() describe 'User Login', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref public: picture: null display_name: null private: email: null awaiting_approvial: null is_admin: null fire_auth.Login credentials it 'Should be able to login a user', -> expect(fire_auth.valid()).toBeFalsy() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.valid()).toBeTruthy() expect(fire_auth.user_id()).toEqual('u001') it 'Should be report "checking" as true until login is complete', -> expect(fire_auth.checking()).toBeTruthy() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.checking()).toBeFalsy() it 'Should load the user\'s data from both public and private locations', -> fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect( fire_auth.user.picture()).toEqual "user.png" expect( fire_auth.user.awaiting_approvial()).toEqual true expect( fire_auth.user.display_name()).toEqual "user" expect( fire_auth.user.email()).toEqual credentials.email it 'If the user\'s data does not have some of the default values it should add them', -> fire_ref.changeAuthState uid: 'u002' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} #has expect( fire_auth.user.display_name()).toEqual "user" expect( fire_auth.user.is_admin()).toEqual true expect( fire_auth.user.email()).toEqual credentials.email #added expect( fire_auth.user.picture()).toEqual "me.png" expect( fire_auth.user.awaiting_approvial()).toEqual true expect( fire_ref.child('users/public').child('u002').getData().picture).toEqual "me.png" expect( fire_ref.child('users/private').child('u002').getData().awaiting_approvial).toEqual true describe 'Log out', -> public_data = null private_data = null beforeEach -> public_data = fire_ref.child('users/public/u001').getData() private_data = fire_ref.child('users/private/u001').getData() fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} fire_auth.Logout() it 'Should be able to logout a user', -> expect(fire_auth.valid()).toBeFalsy() expect(fire_auth.user_id()).toBeFalsy() it 'Should clear the user\'s data', -> expect( fire_auth.user.picture()).toEqual null expect( fire_auth.user.awaiting_approvial()).toEqual null expect( fire_auth.user.display_name()).toEqual null expect( fire_auth.user.email()).toEqual null it 'Should not clear the DB values', -> expect( fire_ref.child('users/public/u001').getData()).toBeDefined() expect fire_ref.child('users/public/u001').getData() .toEqual public_data expect fire_ref.child('users/private/u001').getData() .toEqual private_data describe 'Recover Password', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref fire_auth.Create_User email: credentials.email password: PI:PASSWORD:<PASSWORD>END_PI it 'Should flag that reset happened in firebase', -> fire_auth.Recover_Password credentials.email expect(fire_ref.child('users/resets/'+credentials.email.replace('.','')).getData()).toBeTruthy() it 'Should flag that a reset happened once they login again', -> fire_auth.Recover_Password credentials.email fire_auth.Login credentials fire_ref.changeAuthState uid: 'u001' provider: 'password' token: 'token' expires: Math.floor(new Date() / 1000) + 24 * 60 * 60 auth: {} expect(fire_auth.reset_requested()).toBeTruthy() describe 'Creating a User', -> beforeEach -> fire_auth = new Fire_Auth_Class() fire_auth.Setup fire_ref: fire_ref fire_auth.Create_User email: credentials.email password: PI:PASSWORD:<PASSWORD>END_PI new_private: email: credentials.email new_public: display_name: 'user' it 'Should create a new user', -> expect( fire_ref.getEmailUser(credentials.email)).not.toBeNull() it 'Should add entries into public list', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData()).not.toBeNull() it 'Should add entries into private list', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData()).not.toBeNull() it 'Should copy the private defaults into the private', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData().awaiting_approvial).toEqual true it 'Should copy the public defaults into the public', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData().picture).toEqual "me.png" it 'Should add to the public profile values passed under the "new_public" object', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/public').child(uid).getData().display_name).toEqual "user" it 'Should add to the private profile values passed under the "new_private" object', -> uid = fire_ref.getEmailUser(credentials.email).uid expect( fire_ref.child('users/private').child(uid).getData().email).toEqual credentials.email return
[ { "context": " desc: '预约,体检,诊疗业务操作演示'\r\n key: 'guahao'\r\n href: 'guide.html'\r\n }\r\n ", "end": 820, "score": 0.9711430668830872, "start": 814, "tag": "KEY", "value": "guahao" }, { "context": "ml'\r\n }\r\n {\r\n ...
src/base/coffee/demo-index-page.coffee
ben7th/zdmockup
0
@DemoIndexPage = React.createClass render: -> <div className='demo-index-page'> <div className='ui vertical segment page-title'> <div className='ui container'> <DemoIndexPage.Header /> </div> </div> <div className='ui vertical segment'> <div className='ui container'> <HorizontalChineseScroll> <DemoIndexPage.Cards /> </HorizontalChineseScroll> </div> </div> </div> statics: Header: React.createClass render: -> <h1 className='ui header lishu'> <span>正道中医系统演示</span> </h1> Cards: React.createClass render: -> data = [ { name: '挂号' desc: '预约,体检,诊疗业务操作演示' key: 'guahao' href: 'guide.html' } { name: '医师' desc: '医师操作演示' key: 'doctor' href: 'doctor.html' } { name: '体检' desc: '综合规范化诊断记录系统' key: 'tijian' # href: 'diagnosis.html' href: 'tijian.html' } { name: '管理' desc: '后台管理,维护,信息查看等功能' href: 'clinic.html' key: 'guanli' } ] <div className="ui cards four doubling"> { for item, idx in data href = item.href || 'javascript:;' <a key={idx} className="card" href={href}> <div className="content"> <div className='yunwen' /> <div className="header lishu #{item.key}"><span>{item.name}</span></div> <div className="description">{item.desc}</div> </div> </a> } </div>
171582
@DemoIndexPage = React.createClass render: -> <div className='demo-index-page'> <div className='ui vertical segment page-title'> <div className='ui container'> <DemoIndexPage.Header /> </div> </div> <div className='ui vertical segment'> <div className='ui container'> <HorizontalChineseScroll> <DemoIndexPage.Cards /> </HorizontalChineseScroll> </div> </div> </div> statics: Header: React.createClass render: -> <h1 className='ui header lishu'> <span>正道中医系统演示</span> </h1> Cards: React.createClass render: -> data = [ { name: '挂号' desc: '预约,体检,诊疗业务操作演示' key: '<KEY>' href: 'guide.html' } { name: '<NAME>师' desc: '医师操作演示' key: 'doctor' href: 'doctor.html' } { name: '<NAME>检' desc: '综合规范化诊断记录系统' key: '<KEY>' # href: 'diagnosis.html' href: 'tijian.html' } { name: '管理' desc: '后台管理,维护,信息查看等功能' href: 'clinic.html' key: 'guanli' } ] <div className="ui cards four doubling"> { for item, idx in data href = item.href || 'javascript:;' <a key={idx} className="card" href={href}> <div className="content"> <div className='yunwen' /> <div className="header lishu #{item.key}"><span>{item.name}</span></div> <div className="description">{item.desc}</div> </div> </a> } </div>
true
@DemoIndexPage = React.createClass render: -> <div className='demo-index-page'> <div className='ui vertical segment page-title'> <div className='ui container'> <DemoIndexPage.Header /> </div> </div> <div className='ui vertical segment'> <div className='ui container'> <HorizontalChineseScroll> <DemoIndexPage.Cards /> </HorizontalChineseScroll> </div> </div> </div> statics: Header: React.createClass render: -> <h1 className='ui header lishu'> <span>正道中医系统演示</span> </h1> Cards: React.createClass render: -> data = [ { name: '挂号' desc: '预约,体检,诊疗业务操作演示' key: 'PI:KEY:<KEY>END_PI' href: 'guide.html' } { name: 'PI:NAME:<NAME>END_PI师' desc: '医师操作演示' key: 'doctor' href: 'doctor.html' } { name: 'PI:NAME:<NAME>END_PI检' desc: '综合规范化诊断记录系统' key: 'PI:KEY:<KEY>END_PI' # href: 'diagnosis.html' href: 'tijian.html' } { name: '管理' desc: '后台管理,维护,信息查看等功能' href: 'clinic.html' key: 'guanli' } ] <div className="ui cards four doubling"> { for item, idx in data href = item.href || 'javascript:;' <a key={idx} className="card" href={href}> <div className="content"> <div className='yunwen' /> <div className="header lishu #{item.key}"><span>{item.name}</span></div> <div className="description">{item.desc}</div> </div> </a> } </div>
[ { "context": "ss.env.SLURRY_SPREADER_NAMESPACE\n privateKey: process.env.MESHBLU_PRIVATE_KEY\n\n jobsPath = path.join __d", "end": 2155, "score": 0.764738142490387, "start": 2144, "tag": "KEY", "value": "process.env" }, { "context": "_SPREADER_NAMESPACE\n privateKey: pro...
command.coffee
octoblu/slurry-exchange
0
_ = require 'lodash' MeshbluConfig = require 'meshblu-config' path = require 'path' Slurry = require 'slurry-core' OctobluStrategy = require 'slurry-core/octoblu-strategy' MessageHandler = require 'slurry-core/message-handler' ConfigureHandler = require 'slurry-core/configure-handler' SlurrySpreader = require 'slurry-spreader' SigtermHandler = require 'sigterm-handler' ApiStrategy = require './src/api-strategy' MISSING_SERVICE_URL = 'Missing required environment variable: SLURRY_EXCHANGE_SERVICE_URL' MISSING_MANAGER_URL = 'Missing required environment variable: SLURRY_EXCHANGE_MANAGER_URL' MISSING_APP_OCTOBLU_HOST = 'Missing required environment variable: APP_OCTOBLU_HOST' MISSING_SPREADER_REDIS_URI = 'Missing required environment variable: SLURRY_SPREADER_REDIS_URI' MISSING_SPREADER_NAMESPACE = 'Missing required environment variable: SLURRY_SPREADER_NAMESPACE' MISSING_MESHBLU_PRIVATE_KEY = 'Missing required environment variable: MESHBLU_PRIVATE_KEY' class Command getOptions: => throw new Error MISSING_SPREADER_REDIS_URI if _.isEmpty process.env.SLURRY_SPREADER_REDIS_URI throw new Error MISSING_SPREADER_NAMESPACE if _.isEmpty process.env.SLURRY_SPREADER_NAMESPACE throw new Error MISSING_SERVICE_URL if _.isEmpty process.env.SLURRY_EXCHANGE_SERVICE_URL throw new Error MISSING_MANAGER_URL if _.isEmpty process.env.SLURRY_EXCHANGE_MANAGER_URL throw new Error MISSING_APP_OCTOBLU_HOST if _.isEmpty process.env.APP_OCTOBLU_HOST throw new Error MISSING_MESHBLU_PRIVATE_KEY if _.isEmpty process.env.MESHBLU_PRIVATE_KEY meshbluConfig = new MeshbluConfig().toJSON() apiStrategy = new ApiStrategy process.env octobluStrategy = new OctobluStrategy process.env, meshbluConfig meshbluConfig = new MeshbluConfig().toJSON() apiStrategy = new ApiStrategy process.env octobluStrategy = new OctobluStrategy process.env, meshbluConfig @slurrySpreader = new SlurrySpreader redisUri: process.env.SLURRY_SPREADER_REDIS_URI namespace: process.env.SLURRY_SPREADER_NAMESPACE privateKey: process.env.MESHBLU_PRIVATE_KEY jobsPath = path.join __dirname, 'src/jobs' configurationsPath = path.join __dirname, 'src/configurations' return { apiStrategy: apiStrategy deviceType: 'slurry:exchange' disableLogging: process.env.DISABLE_LOGGING == "true" meshbluConfig: meshbluConfig messageHandler: new MessageHandler {jobsPath} configureHandler: new ConfigureHandler {@slurrySpreader, configurationsPath, meshbluConfig} octobluStrategy: octobluStrategy port: process.env.PORT || 80 appOctobluHost: process.env.APP_OCTOBLU_HOST serviceUrl: process.env.SLURRY_EXCHANGE_SERVICE_URL userDeviceManagerUrl: process.env.SLURRY_EXCHANGE_MANAGER_URL staticSchemasPath: process.env.SLURRY_EXCHANGE_STATIC_SCHEMAS_PATH skipRedirectAfterApiAuth: true } run: => server = new Slurry @getOptions() @slurrySpreader.start (error) => console.error "SlurrySpreader Error", error.stack if error? throw error if error? server.run (error) => console.error "Server.run Error", error.stack if error? throw error if error? {address,port} = server.address() console.log "Server listening on #{address}:#{port}" sigtermHandler = new SigtermHandler { events: ['SIGTERM', 'SIGINT'] } sigtermHandler.register @slurrySpreader?.stop sigtermHandler.register server?.stop command = new Command() command.run()
79044
_ = require 'lodash' MeshbluConfig = require 'meshblu-config' path = require 'path' Slurry = require 'slurry-core' OctobluStrategy = require 'slurry-core/octoblu-strategy' MessageHandler = require 'slurry-core/message-handler' ConfigureHandler = require 'slurry-core/configure-handler' SlurrySpreader = require 'slurry-spreader' SigtermHandler = require 'sigterm-handler' ApiStrategy = require './src/api-strategy' MISSING_SERVICE_URL = 'Missing required environment variable: SLURRY_EXCHANGE_SERVICE_URL' MISSING_MANAGER_URL = 'Missing required environment variable: SLURRY_EXCHANGE_MANAGER_URL' MISSING_APP_OCTOBLU_HOST = 'Missing required environment variable: APP_OCTOBLU_HOST' MISSING_SPREADER_REDIS_URI = 'Missing required environment variable: SLURRY_SPREADER_REDIS_URI' MISSING_SPREADER_NAMESPACE = 'Missing required environment variable: SLURRY_SPREADER_NAMESPACE' MISSING_MESHBLU_PRIVATE_KEY = 'Missing required environment variable: MESHBLU_PRIVATE_KEY' class Command getOptions: => throw new Error MISSING_SPREADER_REDIS_URI if _.isEmpty process.env.SLURRY_SPREADER_REDIS_URI throw new Error MISSING_SPREADER_NAMESPACE if _.isEmpty process.env.SLURRY_SPREADER_NAMESPACE throw new Error MISSING_SERVICE_URL if _.isEmpty process.env.SLURRY_EXCHANGE_SERVICE_URL throw new Error MISSING_MANAGER_URL if _.isEmpty process.env.SLURRY_EXCHANGE_MANAGER_URL throw new Error MISSING_APP_OCTOBLU_HOST if _.isEmpty process.env.APP_OCTOBLU_HOST throw new Error MISSING_MESHBLU_PRIVATE_KEY if _.isEmpty process.env.MESHBLU_PRIVATE_KEY meshbluConfig = new MeshbluConfig().toJSON() apiStrategy = new ApiStrategy process.env octobluStrategy = new OctobluStrategy process.env, meshbluConfig meshbluConfig = new MeshbluConfig().toJSON() apiStrategy = new ApiStrategy process.env octobluStrategy = new OctobluStrategy process.env, meshbluConfig @slurrySpreader = new SlurrySpreader redisUri: process.env.SLURRY_SPREADER_REDIS_URI namespace: process.env.SLURRY_SPREADER_NAMESPACE privateKey: <KEY>.<KEY>_PRIVATE_KEY jobsPath = path.join __dirname, 'src/jobs' configurationsPath = path.join __dirname, 'src/configurations' return { apiStrategy: apiStrategy deviceType: 'slurry:exchange' disableLogging: process.env.DISABLE_LOGGING == "true" meshbluConfig: meshbluConfig messageHandler: new MessageHandler {jobsPath} configureHandler: new ConfigureHandler {@slurrySpreader, configurationsPath, meshbluConfig} octobluStrategy: octobluStrategy port: process.env.PORT || 80 appOctobluHost: process.env.APP_OCTOBLU_HOST serviceUrl: process.env.SLURRY_EXCHANGE_SERVICE_URL userDeviceManagerUrl: process.env.SLURRY_EXCHANGE_MANAGER_URL staticSchemasPath: process.env.SLURRY_EXCHANGE_STATIC_SCHEMAS_PATH skipRedirectAfterApiAuth: true } run: => server = new Slurry @getOptions() @slurrySpreader.start (error) => console.error "SlurrySpreader Error", error.stack if error? throw error if error? server.run (error) => console.error "Server.run Error", error.stack if error? throw error if error? {address,port} = server.address() console.log "Server listening on #{address}:#{port}" sigtermHandler = new SigtermHandler { events: ['SIGTERM', 'SIGINT'] } sigtermHandler.register @slurrySpreader?.stop sigtermHandler.register server?.stop command = new Command() command.run()
true
_ = require 'lodash' MeshbluConfig = require 'meshblu-config' path = require 'path' Slurry = require 'slurry-core' OctobluStrategy = require 'slurry-core/octoblu-strategy' MessageHandler = require 'slurry-core/message-handler' ConfigureHandler = require 'slurry-core/configure-handler' SlurrySpreader = require 'slurry-spreader' SigtermHandler = require 'sigterm-handler' ApiStrategy = require './src/api-strategy' MISSING_SERVICE_URL = 'Missing required environment variable: SLURRY_EXCHANGE_SERVICE_URL' MISSING_MANAGER_URL = 'Missing required environment variable: SLURRY_EXCHANGE_MANAGER_URL' MISSING_APP_OCTOBLU_HOST = 'Missing required environment variable: APP_OCTOBLU_HOST' MISSING_SPREADER_REDIS_URI = 'Missing required environment variable: SLURRY_SPREADER_REDIS_URI' MISSING_SPREADER_NAMESPACE = 'Missing required environment variable: SLURRY_SPREADER_NAMESPACE' MISSING_MESHBLU_PRIVATE_KEY = 'Missing required environment variable: MESHBLU_PRIVATE_KEY' class Command getOptions: => throw new Error MISSING_SPREADER_REDIS_URI if _.isEmpty process.env.SLURRY_SPREADER_REDIS_URI throw new Error MISSING_SPREADER_NAMESPACE if _.isEmpty process.env.SLURRY_SPREADER_NAMESPACE throw new Error MISSING_SERVICE_URL if _.isEmpty process.env.SLURRY_EXCHANGE_SERVICE_URL throw new Error MISSING_MANAGER_URL if _.isEmpty process.env.SLURRY_EXCHANGE_MANAGER_URL throw new Error MISSING_APP_OCTOBLU_HOST if _.isEmpty process.env.APP_OCTOBLU_HOST throw new Error MISSING_MESHBLU_PRIVATE_KEY if _.isEmpty process.env.MESHBLU_PRIVATE_KEY meshbluConfig = new MeshbluConfig().toJSON() apiStrategy = new ApiStrategy process.env octobluStrategy = new OctobluStrategy process.env, meshbluConfig meshbluConfig = new MeshbluConfig().toJSON() apiStrategy = new ApiStrategy process.env octobluStrategy = new OctobluStrategy process.env, meshbluConfig @slurrySpreader = new SlurrySpreader redisUri: process.env.SLURRY_SPREADER_REDIS_URI namespace: process.env.SLURRY_SPREADER_NAMESPACE privateKey: PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI_PRIVATE_KEY jobsPath = path.join __dirname, 'src/jobs' configurationsPath = path.join __dirname, 'src/configurations' return { apiStrategy: apiStrategy deviceType: 'slurry:exchange' disableLogging: process.env.DISABLE_LOGGING == "true" meshbluConfig: meshbluConfig messageHandler: new MessageHandler {jobsPath} configureHandler: new ConfigureHandler {@slurrySpreader, configurationsPath, meshbluConfig} octobluStrategy: octobluStrategy port: process.env.PORT || 80 appOctobluHost: process.env.APP_OCTOBLU_HOST serviceUrl: process.env.SLURRY_EXCHANGE_SERVICE_URL userDeviceManagerUrl: process.env.SLURRY_EXCHANGE_MANAGER_URL staticSchemasPath: process.env.SLURRY_EXCHANGE_STATIC_SCHEMAS_PATH skipRedirectAfterApiAuth: true } run: => server = new Slurry @getOptions() @slurrySpreader.start (error) => console.error "SlurrySpreader Error", error.stack if error? throw error if error? server.run (error) => console.error "Server.run Error", error.stack if error? throw error if error? {address,port} = server.address() console.log "Server listening on #{address}:#{port}" sigtermHandler = new SigtermHandler { events: ['SIGTERM', 'SIGINT'] } sigtermHandler.register @slurrySpreader?.stop sigtermHandler.register server?.stop command = new Command() command.run()
[ { "context": "emachine.com/talk1/17b.html\n# http://mrl.nyu.edu/~perlin/noise/\n# generate permutation\n\nclass PerlinNoise\n", "end": 14937, "score": 0.9837049245834351, "start": 14931, "tag": "USERNAME", "value": "perlin" }, { "context": "the\nstandard random() function. It was inv...
coffee/globals/math.coffee
xinaesthete/livecodelab
1
# Functions adapted from processing.js #////////////////////////////////////////////////////////////////////////// # Math functions #////////////////////////////////////////////////////////////////////////// # Calculation ### Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. @param {int|float} value int or float @returns {int|float} ### abs = Math.abs ### Calculates the closest int value that is greater than or equal to the value of the parameter. For example, ceil(9.03) returns the value 10. @param {float} value float @returns {int} @see floor @see round ### ceil = Math.ceil ### Constrains a value to not exceed a maximum and minimum value. @param {int|float} value the value to constrain @param {int|float} value minimum limit @param {int|float} value maximum limit @returns {int|float} @see max @see min ### constrain = (aNumber, aMin, aMax) -> (if aNumber > aMax then aMax else (if aNumber < aMin then aMin else aNumber)) ### Calculates the distance between two points. @param {int|float} x1 int or float: x-coordinate of the first point @param {int|float} y1 int or float: y-coordinate of the first point @param {int|float} z1 int or float: z-coordinate of the first point @param {int|float} x2 int or float: x-coordinate of the second point @param {int|float} y2 int or float: y-coordinate of the second point @param {int|float} z2 int or float: z-coordinate of the second point @returns {float} ### dist = -> dx = undefined dy = undefined dz = undefined if arguments.length is 4 dx = arguments[0] - arguments[2] dy = arguments[1] - arguments[3] return Math.sqrt(dx * dx + dy * dy) if arguments.length is 6 dx = arguments[0] - arguments[3] dy = arguments[1] - arguments[4] dz = arguments[2] - arguments[5] Math.sqrt dx * dx + dy * dy + dz * dz ### Returns Euler's number e (2.71828...) raised to the power of the value parameter. @param {int|float} value int or float: the exponent to raise e to @returns {float} ### exp = Math.exp ### Calculates the closest int value that is less than or equal to the value of the parameter. Note that casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative. @param {int|float} value the value to floor @returns {int|float} @see ceil @see round @see int ### floor = Math.floor ### Casting to an int. Will truncate toward zero. (floor() will truncate toward negative infinite). This will give you different values if bar were negative. @param {int|float} value the value to cast to integer @returns {int|float} @see ceil @see round ### int = parseInt ### Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines. @param {int|float} value1 float or int: first value @param {int|float} value2 float or int: second value @param {int|float} amt float: between 0.0 and 1.0 @returns {float} @see curvePoint @see bezierPoint ### lerp = (value1, value2, amt) -> ((value2 - value1) * amt) + value1 ### Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the values greater than 0.0. @param {int|float} value int or float: number must be greater then 0.0 @returns {float} ### log = Math.log ### Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". @param {int|float} a float or int: first value @param {int|float} b float or int: second value @param {int|float} c float or int: third value @returns {float} @see dist ### mag = (a, b, c) -> return Math.sqrt(a * a + b * b + c * c) if c Math.sqrt a * a + b * b ### Re-maps a number from one range to another. In the example above, the number '25' is converted from a value in the range 0..100 into a value that ranges from the left edge (0) to the right edge (width) of the screen. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. @param {float} value The incoming value to be converted @param {float} istart Lower bound of the value's current range @param {float} istop Upper bound of the value's current range @param {float} ostart Lower bound of the value's target range @param {float} ostop Upper bound of the value's target range @returns {float} @see norm @see lerp ### map = (value, istart, istop, ostart, ostop) -> ostart + (ostop - ostart) * ((value - istart) / (istop - istart)) ### Determines the largest value in a sequence of numbers. @param {int|float} value1 int or float @param {int|float} value2 int or float @param {int|float} value3 int or float @param {int|float} array int or float array @returns {int|float} @see min ### max = -> return ( if arguments[0] < arguments[1] then arguments[1] else arguments[0] ) if arguments.length is 2 # if single argument, array is used numbers = (if arguments.length is 1 then arguments[0] else arguments) throw new Error("Non-empty array is expected") unless( "length" of numbers and numbers.length ) max = numbers[0] count = numbers.length i = 1 while i < count max = numbers[i] if max < numbers[i] ++i max ### Determines the smallest value in a sequence of numbers. @param {int|float} value1 int or float @param {int|float} value2 int or float @param {int|float} value3 int or float @param {int|float} array int or float array @returns {int|float} @see max ### min = -> return ( if arguments[0] < arguments[1] then arguments[0] else arguments[1] ) if arguments.length is 2 # if single argument, array is used numbers = (if arguments.length is 1 then arguments[0] else arguments) throw new Error("Non-empty array is expected") unless( "length" of numbers and numbers.length ) min = numbers[0] count = numbers.length i = 1 while i < count min = numbers[i] if min > numbers[i] ++i min ### Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1); Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. @param {float} aNumber The incoming value to be converted @param {float} low Lower bound of the value's current range @param {float} high Upper bound of the value's current range @returns {float} @see map @see lerp ### norm = (aNumber, low, high) -> (aNumber - low) / (high - low) ### Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocal) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. @param {int|float} num base of the exponential expression @param {int|float} exponent power of which to raise the base @returns {float} @see sqrt ### pow = Math.pow ### Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9. @param {float} value number to round @returns {int} @see floor @see ceil ### round = Math.round ### Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1. @param {float} value int or float @returns {float} @see sqrt ### sq = (aNumber) -> aNumber * aNumber ### Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. @param {float} value int or float, non negative @returns {float} @see pow @see sq ### sqrt = Math.sqrt # Trigonometry ### The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927). @param {float} value the value whose arc cosine is to be returned @returns {float} @see cos @see asin @see atan ### acos = Math.acos ### The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2. @param {float} value the value whose arc sine is to be returned @returns {float} @see sin @see acos @see atan ### asin = Math.asin ### The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 . @param {float} value -Infinity to Infinity (exclusive) @returns {float} @see tan @see asin @see acos ### atan = Math.atan ### Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent. @param {float} y y-coordinate of the point @param {float} x x-coordinate of the point @returns {float} @see tan ### atan2 = Math.atan2 ### Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range -1 to 1. @param {float} value an angle in radians @returns {float} @see tan @see sin ### cos = Math.cos ### Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. @param {int|float} value an angle in radians @returns {float} @see radians ### degrees = (aAngle) -> (aAngle * 180) / Math.PI ### Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. @param {int|float} value an angle in radians @returns {float} @see degrees ### radians = (aAngle) -> (aAngle / 180) * Math.PI ### Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to 6.28). Values are returned in the range -1 to 1. @param {float} value an angle in radians @returns {float} @see cos @see radians ### sin = Math.sin ### Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity. @param {float} value an angle in radians @returns {float} @see cos @see sin @see radians ### tan = Math.tan currentRandom = Math.random ### Generates random numbers. Each time the random() function is called, it returns an unexpected value within the specified range. If one parameter is passed to the function it will return a float between zero and the value of the high parameter. The function call random(5) returns values between 0 and 5 (starting at zero, up to but not including 5). If two parameters are passed, it will return a float with a value between the parameters. The function call random(-5, 10.2) returns values starting at -5 up to (but not including) 10.2. To convert a floating-point random number to an integer, use the int() function. @param {int|float} value1 if one parameter is used, the top end to random from, if two params the low end @param {int|float} value2 the top end of the random range @returns {float} @see randomSeed @see noise ### random = -> return currentRandom() if !arguments.length return currentRandom() * arguments[0] if arguments.length is 1 aMin = arguments[0] aMax = arguments[1] currentRandom() * (aMax - aMin) + aMin # Pseudo-random generator class Marsaglia z:0 w:0 constructor:(i1, i2) -> # from http://www.math.uni-bielefeld.de/~sillke/ALGORITHMS/random/marsaglia-c @z = i1 or 362436069 @w = i2 or 521288629 @createRandomized: -> now = new Date() new Marsaglia((now / 60000) & 0xFFFFFFFF, now & 0xFFFFFFFF) nextInt: -> @z = (36969 * (@z & 65535) + (@z >>> 16)) & 0xFFFFFFFF @w = (18000 * (@w & 65535) + (@w >>> 16)) & 0xFFFFFFFF (((@z & 0xFFFF) << 16) | (@w & 0xFFFF)) & 0xFFFFFFFF nextDouble: -> i = @nextInt() / 4294967296 (if i < 0 then 1 + i else i) ### Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run. @param {int|float} seed int @see random @see noise @see noiseSeed ### randomSeed = (seed) -> mrand = new Marsaglia(seed) currentRandom = ()->mrand.nextDouble() # Random # We have two random()'s in the code... what does this do ? and which one is current ? Random = (seed) -> haveNextNextGaussian = false nextNextGaussian = undefined random = undefined @nextGaussian = -> if haveNextNextGaussian haveNextNextGaussian = false return nextNextGaussian v1 = undefined v2 = undefined s = undefined loop v1 = 2 * random() - 1 # between -1.0 and 1.0 v2 = 2 * random() - 1 # between -1.0 and 1.0 s = v1 * v1 + v2 * v2 break unless s >= 1 or s is 0 multiplier = Math.sqrt(-2 * Math.log(s) / s) nextNextGaussian = v2 * multiplier haveNextNextGaussian = true v1 * multiplier # by default use standard random, otherwise seeded random = (if (seed is undefined) then Math.random else (new Marsaglia(seed)).nextDouble) # Noise functions and helpers # http://www.noisemachine.com/talk1/17b.html # http://mrl.nyu.edu/~perlin/noise/ # generate permutation class PerlinNoise seed:0 perm: null constructor:(@seed) -> rnd = (if @seed isnt undefined then new Marsaglia(@seed) else Marsaglia.createRandomized()) i = undefined j = undefined @perm = new Uint8Array(512) i = 0 while i < 256 @perm[i] = i ++i i = 0 while i < 256 t = @perm[j = rnd.nextInt() & 0xFF] @perm[j] = @perm[i] @perm[i] = t ++i i = 0 while i < 256 @perm[i + 256] = @perm[i] ++i # copy to avoid taking mod in @perm[0]; grad3d: (i, x, y, z) -> h = i & 15 # convert into 12 gradient directions u = (if h < 8 then x else y) v = (if h < 4 then y else (if h is 12 or h is 14 then x else z)) ((if (h & 1) is 0 then u else -u)) + ((if (h & 2) is 0 then v else -v)) grad2d: (i, x, y) -> v = (if (i & 1) is 0 then x else y) (if (i & 2) is 0 then -v else v) grad1d: (i, x) -> (if (i & 1) is 0 then -x else x) # there is a lerp defined already, with same # behaviour, but I guess it makes sense to have # one here to make things self-contained. lerp: (t, a, b) -> a + t * (b - a) noise3d: (x, y, z) -> X = Math.floor(x) & 255 Y = Math.floor(y) & 255 Z = Math.floor(z) & 255 x -= Math.floor(x) y -= Math.floor(y) z -= Math.floor(z) fx = (3 - 2 * x) * x * x fy = (3 - 2 * y) * y * y fz = (3 - 2 * z) * z * z p0 = @perm[X] + Y p00 = @perm[p0] + Z p01 = @perm[p0 + 1] + Z p1 = @perm[X + 1] + Y p10 = @perm[p1] + Z p11 = @perm[p1 + 1] + Z @lerp fz, @lerp(fy, @lerp(fx, @grad3d(@perm[p00], x, y, z), @grad3d(@perm[p10], x - 1, y, z)), @lerp(fx, @grad3d(@perm[p01], x, y - 1, z), @grad3d(@perm[p11], x - 1, y - 1, z))), @lerp(fy, @lerp(fx, @grad3d(@perm[p00 + 1], x, y, z - 1), @grad3d(@perm[p10 + 1], x - 1, y, z - 1)), @lerp(fx, @grad3d(@perm[p01 + 1], x, y - 1, z - 1), @grad3d(@perm[p11 + 1], x - 1, y - 1, z - 1))) noise2d: (x, y) -> X = Math.floor(x) & 255 Y = Math.floor(y) & 255 x -= Math.floor(x) y -= Math.floor(y) fx = (3 - 2 * x) * x * x fy = (3 - 2 * y) * y * y p0 = @perm[X] + Y p1 = @perm[X + 1] + Y @lerp fy, @lerp(fx, @grad2d(@perm[p0], x, y), @grad2d(@perm[p1], x - 1, y)), @lerp(fx, @grad2d(@perm[p0 + 1], x, y - 1), @grad2d(@perm[p1 + 1], x - 1, y - 1)) noise1d: (x) -> X = Math.floor(x) & 255 x -= Math.floor(x) fx = (3 - 2 * x) * x * x @lerp fx, @grad1d(@perm[X], x), @grad1d(@perm[X + 1], x - 1) # processing defaults noiseProfile = generator: undefined octaves: 4 fallout: 0.5 seed: undefined ### Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by Ken Perlin in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program). The resulting value will always be between 0.0 and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time. The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result. Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use. @param {float} x x coordinate in noise space @param {float} y y coordinate in noise space @param {float} z z coordinate in noise space @returns {float} @see random @see noiseDetail ### noise = (x, y, z) -> # caching noiseProfile.generator = new PerlinNoise(noiseProfile.seed) if noiseProfile.generator is undefined generator = noiseProfile.generator effect = 1 k = 1 sum = 0 i = 0 while i < noiseProfile.octaves effect *= noiseProfile.fallout switch arguments.length when 1 sum += effect * (1 + generator.noise1d(k * x)) / 2 when 2 sum += effect * (1 + generator.noise2d(k * x, k * y)) / 2 when 3 sum += effect * (1 + generator.noise3d(k * x, k * y, k * z)) / 2 k *= 2 ++i sum ### Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overal intensity of the noise, whereas higher octaves create finer grained details in the noise sequence. By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise(). By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics. @param {int} octaves number of octaves to be used by the noise() function @param {float} falloff falloff factor for each octave @see noise ### noiseDetail = (octaves, fallout) -> noiseProfile.octaves = octaves noiseProfile.fallout = fallout if fallout isnt undefined ### Sets the seed value for noise(). By default, noise() produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run. @param {int} seed int @returns {float} @see random @see radomSeed @see noise @see noiseDetail ### noiseSeed = (seed) -> noiseProfile.seed = seed noiseProfile.generator = undefined
27814
# Functions adapted from processing.js #////////////////////////////////////////////////////////////////////////// # Math functions #////////////////////////////////////////////////////////////////////////// # Calculation ### Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. @param {int|float} value int or float @returns {int|float} ### abs = Math.abs ### Calculates the closest int value that is greater than or equal to the value of the parameter. For example, ceil(9.03) returns the value 10. @param {float} value float @returns {int} @see floor @see round ### ceil = Math.ceil ### Constrains a value to not exceed a maximum and minimum value. @param {int|float} value the value to constrain @param {int|float} value minimum limit @param {int|float} value maximum limit @returns {int|float} @see max @see min ### constrain = (aNumber, aMin, aMax) -> (if aNumber > aMax then aMax else (if aNumber < aMin then aMin else aNumber)) ### Calculates the distance between two points. @param {int|float} x1 int or float: x-coordinate of the first point @param {int|float} y1 int or float: y-coordinate of the first point @param {int|float} z1 int or float: z-coordinate of the first point @param {int|float} x2 int or float: x-coordinate of the second point @param {int|float} y2 int or float: y-coordinate of the second point @param {int|float} z2 int or float: z-coordinate of the second point @returns {float} ### dist = -> dx = undefined dy = undefined dz = undefined if arguments.length is 4 dx = arguments[0] - arguments[2] dy = arguments[1] - arguments[3] return Math.sqrt(dx * dx + dy * dy) if arguments.length is 6 dx = arguments[0] - arguments[3] dy = arguments[1] - arguments[4] dz = arguments[2] - arguments[5] Math.sqrt dx * dx + dy * dy + dz * dz ### Returns Euler's number e (2.71828...) raised to the power of the value parameter. @param {int|float} value int or float: the exponent to raise e to @returns {float} ### exp = Math.exp ### Calculates the closest int value that is less than or equal to the value of the parameter. Note that casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative. @param {int|float} value the value to floor @returns {int|float} @see ceil @see round @see int ### floor = Math.floor ### Casting to an int. Will truncate toward zero. (floor() will truncate toward negative infinite). This will give you different values if bar were negative. @param {int|float} value the value to cast to integer @returns {int|float} @see ceil @see round ### int = parseInt ### Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines. @param {int|float} value1 float or int: first value @param {int|float} value2 float or int: second value @param {int|float} amt float: between 0.0 and 1.0 @returns {float} @see curvePoint @see bezierPoint ### lerp = (value1, value2, amt) -> ((value2 - value1) * amt) + value1 ### Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the values greater than 0.0. @param {int|float} value int or float: number must be greater then 0.0 @returns {float} ### log = Math.log ### Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". @param {int|float} a float or int: first value @param {int|float} b float or int: second value @param {int|float} c float or int: third value @returns {float} @see dist ### mag = (a, b, c) -> return Math.sqrt(a * a + b * b + c * c) if c Math.sqrt a * a + b * b ### Re-maps a number from one range to another. In the example above, the number '25' is converted from a value in the range 0..100 into a value that ranges from the left edge (0) to the right edge (width) of the screen. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. @param {float} value The incoming value to be converted @param {float} istart Lower bound of the value's current range @param {float} istop Upper bound of the value's current range @param {float} ostart Lower bound of the value's target range @param {float} ostop Upper bound of the value's target range @returns {float} @see norm @see lerp ### map = (value, istart, istop, ostart, ostop) -> ostart + (ostop - ostart) * ((value - istart) / (istop - istart)) ### Determines the largest value in a sequence of numbers. @param {int|float} value1 int or float @param {int|float} value2 int or float @param {int|float} value3 int or float @param {int|float} array int or float array @returns {int|float} @see min ### max = -> return ( if arguments[0] < arguments[1] then arguments[1] else arguments[0] ) if arguments.length is 2 # if single argument, array is used numbers = (if arguments.length is 1 then arguments[0] else arguments) throw new Error("Non-empty array is expected") unless( "length" of numbers and numbers.length ) max = numbers[0] count = numbers.length i = 1 while i < count max = numbers[i] if max < numbers[i] ++i max ### Determines the smallest value in a sequence of numbers. @param {int|float} value1 int or float @param {int|float} value2 int or float @param {int|float} value3 int or float @param {int|float} array int or float array @returns {int|float} @see max ### min = -> return ( if arguments[0] < arguments[1] then arguments[0] else arguments[1] ) if arguments.length is 2 # if single argument, array is used numbers = (if arguments.length is 1 then arguments[0] else arguments) throw new Error("Non-empty array is expected") unless( "length" of numbers and numbers.length ) min = numbers[0] count = numbers.length i = 1 while i < count min = numbers[i] if min > numbers[i] ++i min ### Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1); Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. @param {float} aNumber The incoming value to be converted @param {float} low Lower bound of the value's current range @param {float} high Upper bound of the value's current range @returns {float} @see map @see lerp ### norm = (aNumber, low, high) -> (aNumber - low) / (high - low) ### Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocal) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. @param {int|float} num base of the exponential expression @param {int|float} exponent power of which to raise the base @returns {float} @see sqrt ### pow = Math.pow ### Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9. @param {float} value number to round @returns {int} @see floor @see ceil ### round = Math.round ### Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1. @param {float} value int or float @returns {float} @see sqrt ### sq = (aNumber) -> aNumber * aNumber ### Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. @param {float} value int or float, non negative @returns {float} @see pow @see sq ### sqrt = Math.sqrt # Trigonometry ### The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927). @param {float} value the value whose arc cosine is to be returned @returns {float} @see cos @see asin @see atan ### acos = Math.acos ### The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2. @param {float} value the value whose arc sine is to be returned @returns {float} @see sin @see acos @see atan ### asin = Math.asin ### The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 . @param {float} value -Infinity to Infinity (exclusive) @returns {float} @see tan @see asin @see acos ### atan = Math.atan ### Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent. @param {float} y y-coordinate of the point @param {float} x x-coordinate of the point @returns {float} @see tan ### atan2 = Math.atan2 ### Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range -1 to 1. @param {float} value an angle in radians @returns {float} @see tan @see sin ### cos = Math.cos ### Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. @param {int|float} value an angle in radians @returns {float} @see radians ### degrees = (aAngle) -> (aAngle * 180) / Math.PI ### Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. @param {int|float} value an angle in radians @returns {float} @see degrees ### radians = (aAngle) -> (aAngle / 180) * Math.PI ### Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to 6.28). Values are returned in the range -1 to 1. @param {float} value an angle in radians @returns {float} @see cos @see radians ### sin = Math.sin ### Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity. @param {float} value an angle in radians @returns {float} @see cos @see sin @see radians ### tan = Math.tan currentRandom = Math.random ### Generates random numbers. Each time the random() function is called, it returns an unexpected value within the specified range. If one parameter is passed to the function it will return a float between zero and the value of the high parameter. The function call random(5) returns values between 0 and 5 (starting at zero, up to but not including 5). If two parameters are passed, it will return a float with a value between the parameters. The function call random(-5, 10.2) returns values starting at -5 up to (but not including) 10.2. To convert a floating-point random number to an integer, use the int() function. @param {int|float} value1 if one parameter is used, the top end to random from, if two params the low end @param {int|float} value2 the top end of the random range @returns {float} @see randomSeed @see noise ### random = -> return currentRandom() if !arguments.length return currentRandom() * arguments[0] if arguments.length is 1 aMin = arguments[0] aMax = arguments[1] currentRandom() * (aMax - aMin) + aMin # Pseudo-random generator class Marsaglia z:0 w:0 constructor:(i1, i2) -> # from http://www.math.uni-bielefeld.de/~sillke/ALGORITHMS/random/marsaglia-c @z = i1 or 362436069 @w = i2 or 521288629 @createRandomized: -> now = new Date() new Marsaglia((now / 60000) & 0xFFFFFFFF, now & 0xFFFFFFFF) nextInt: -> @z = (36969 * (@z & 65535) + (@z >>> 16)) & 0xFFFFFFFF @w = (18000 * (@w & 65535) + (@w >>> 16)) & 0xFFFFFFFF (((@z & 0xFFFF) << 16) | (@w & 0xFFFF)) & 0xFFFFFFFF nextDouble: -> i = @nextInt() / 4294967296 (if i < 0 then 1 + i else i) ### Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run. @param {int|float} seed int @see random @see noise @see noiseSeed ### randomSeed = (seed) -> mrand = new Marsaglia(seed) currentRandom = ()->mrand.nextDouble() # Random # We have two random()'s in the code... what does this do ? and which one is current ? Random = (seed) -> haveNextNextGaussian = false nextNextGaussian = undefined random = undefined @nextGaussian = -> if haveNextNextGaussian haveNextNextGaussian = false return nextNextGaussian v1 = undefined v2 = undefined s = undefined loop v1 = 2 * random() - 1 # between -1.0 and 1.0 v2 = 2 * random() - 1 # between -1.0 and 1.0 s = v1 * v1 + v2 * v2 break unless s >= 1 or s is 0 multiplier = Math.sqrt(-2 * Math.log(s) / s) nextNextGaussian = v2 * multiplier haveNextNextGaussian = true v1 * multiplier # by default use standard random, otherwise seeded random = (if (seed is undefined) then Math.random else (new Marsaglia(seed)).nextDouble) # Noise functions and helpers # http://www.noisemachine.com/talk1/17b.html # http://mrl.nyu.edu/~perlin/noise/ # generate permutation class PerlinNoise seed:0 perm: null constructor:(@seed) -> rnd = (if @seed isnt undefined then new Marsaglia(@seed) else Marsaglia.createRandomized()) i = undefined j = undefined @perm = new Uint8Array(512) i = 0 while i < 256 @perm[i] = i ++i i = 0 while i < 256 t = @perm[j = rnd.nextInt() & 0xFF] @perm[j] = @perm[i] @perm[i] = t ++i i = 0 while i < 256 @perm[i + 256] = @perm[i] ++i # copy to avoid taking mod in @perm[0]; grad3d: (i, x, y, z) -> h = i & 15 # convert into 12 gradient directions u = (if h < 8 then x else y) v = (if h < 4 then y else (if h is 12 or h is 14 then x else z)) ((if (h & 1) is 0 then u else -u)) + ((if (h & 2) is 0 then v else -v)) grad2d: (i, x, y) -> v = (if (i & 1) is 0 then x else y) (if (i & 2) is 0 then -v else v) grad1d: (i, x) -> (if (i & 1) is 0 then -x else x) # there is a lerp defined already, with same # behaviour, but I guess it makes sense to have # one here to make things self-contained. lerp: (t, a, b) -> a + t * (b - a) noise3d: (x, y, z) -> X = Math.floor(x) & 255 Y = Math.floor(y) & 255 Z = Math.floor(z) & 255 x -= Math.floor(x) y -= Math.floor(y) z -= Math.floor(z) fx = (3 - 2 * x) * x * x fy = (3 - 2 * y) * y * y fz = (3 - 2 * z) * z * z p0 = @perm[X] + Y p00 = @perm[p0] + Z p01 = @perm[p0 + 1] + Z p1 = @perm[X + 1] + Y p10 = @perm[p1] + Z p11 = @perm[p1 + 1] + Z @lerp fz, @lerp(fy, @lerp(fx, @grad3d(@perm[p00], x, y, z), @grad3d(@perm[p10], x - 1, y, z)), @lerp(fx, @grad3d(@perm[p01], x, y - 1, z), @grad3d(@perm[p11], x - 1, y - 1, z))), @lerp(fy, @lerp(fx, @grad3d(@perm[p00 + 1], x, y, z - 1), @grad3d(@perm[p10 + 1], x - 1, y, z - 1)), @lerp(fx, @grad3d(@perm[p01 + 1], x, y - 1, z - 1), @grad3d(@perm[p11 + 1], x - 1, y - 1, z - 1))) noise2d: (x, y) -> X = Math.floor(x) & 255 Y = Math.floor(y) & 255 x -= Math.floor(x) y -= Math.floor(y) fx = (3 - 2 * x) * x * x fy = (3 - 2 * y) * y * y p0 = @perm[X] + Y p1 = @perm[X + 1] + Y @lerp fy, @lerp(fx, @grad2d(@perm[p0], x, y), @grad2d(@perm[p1], x - 1, y)), @lerp(fx, @grad2d(@perm[p0 + 1], x, y - 1), @grad2d(@perm[p1 + 1], x - 1, y - 1)) noise1d: (x) -> X = Math.floor(x) & 255 x -= Math.floor(x) fx = (3 - 2 * x) * x * x @lerp fx, @grad1d(@perm[X], x), @grad1d(@perm[X + 1], x - 1) # processing defaults noiseProfile = generator: undefined octaves: 4 fallout: 0.5 seed: undefined ### Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by <NAME> in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program). The resulting value will always be between 0.0 and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time. The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result. Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use. @param {float} x x coordinate in noise space @param {float} y y coordinate in noise space @param {float} z z coordinate in noise space @returns {float} @see random @see noiseDetail ### noise = (x, y, z) -> # caching noiseProfile.generator = new PerlinNoise(noiseProfile.seed) if noiseProfile.generator is undefined generator = noiseProfile.generator effect = 1 k = 1 sum = 0 i = 0 while i < noiseProfile.octaves effect *= noiseProfile.fallout switch arguments.length when 1 sum += effect * (1 + generator.noise1d(k * x)) / 2 when 2 sum += effect * (1 + generator.noise2d(k * x, k * y)) / 2 when 3 sum += effect * (1 + generator.noise3d(k * x, k * y, k * z)) / 2 k *= 2 ++i sum ### Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overal intensity of the noise, whereas higher octaves create finer grained details in the noise sequence. By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise(). By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics. @param {int} octaves number of octaves to be used by the noise() function @param {float} falloff falloff factor for each octave @see noise ### noiseDetail = (octaves, fallout) -> noiseProfile.octaves = octaves noiseProfile.fallout = fallout if fallout isnt undefined ### Sets the seed value for noise(). By default, noise() produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run. @param {int} seed int @returns {float} @see random @see radomSeed @see noise @see noiseDetail ### noiseSeed = (seed) -> noiseProfile.seed = seed noiseProfile.generator = undefined
true
# Functions adapted from processing.js #////////////////////////////////////////////////////////////////////////// # Math functions #////////////////////////////////////////////////////////////////////////// # Calculation ### Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. @param {int|float} value int or float @returns {int|float} ### abs = Math.abs ### Calculates the closest int value that is greater than or equal to the value of the parameter. For example, ceil(9.03) returns the value 10. @param {float} value float @returns {int} @see floor @see round ### ceil = Math.ceil ### Constrains a value to not exceed a maximum and minimum value. @param {int|float} value the value to constrain @param {int|float} value minimum limit @param {int|float} value maximum limit @returns {int|float} @see max @see min ### constrain = (aNumber, aMin, aMax) -> (if aNumber > aMax then aMax else (if aNumber < aMin then aMin else aNumber)) ### Calculates the distance between two points. @param {int|float} x1 int or float: x-coordinate of the first point @param {int|float} y1 int or float: y-coordinate of the first point @param {int|float} z1 int or float: z-coordinate of the first point @param {int|float} x2 int or float: x-coordinate of the second point @param {int|float} y2 int or float: y-coordinate of the second point @param {int|float} z2 int or float: z-coordinate of the second point @returns {float} ### dist = -> dx = undefined dy = undefined dz = undefined if arguments.length is 4 dx = arguments[0] - arguments[2] dy = arguments[1] - arguments[3] return Math.sqrt(dx * dx + dy * dy) if arguments.length is 6 dx = arguments[0] - arguments[3] dy = arguments[1] - arguments[4] dz = arguments[2] - arguments[5] Math.sqrt dx * dx + dy * dy + dz * dz ### Returns Euler's number e (2.71828...) raised to the power of the value parameter. @param {int|float} value int or float: the exponent to raise e to @returns {float} ### exp = Math.exp ### Calculates the closest int value that is less than or equal to the value of the parameter. Note that casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative. @param {int|float} value the value to floor @returns {int|float} @see ceil @see round @see int ### floor = Math.floor ### Casting to an int. Will truncate toward zero. (floor() will truncate toward negative infinite). This will give you different values if bar were negative. @param {int|float} value the value to cast to integer @returns {int|float} @see ceil @see round ### int = parseInt ### Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines. @param {int|float} value1 float or int: first value @param {int|float} value2 float or int: second value @param {int|float} amt float: between 0.0 and 1.0 @returns {float} @see curvePoint @see bezierPoint ### lerp = (value1, value2, amt) -> ((value2 - value1) * amt) + value1 ### Calculates the natural logarithm (the base-e logarithm) of a number. This function expects the values greater than 0.0. @param {int|float} value int or float: number must be greater then 0.0 @returns {float} ### log = Math.log ### Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly used in computer graphics and linear algebra. Because it has no "start" position, the magnitude of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". @param {int|float} a float or int: first value @param {int|float} b float or int: second value @param {int|float} c float or int: third value @returns {float} @see dist ### mag = (a, b, c) -> return Math.sqrt(a * a + b * b + c * c) if c Math.sqrt a * a + b * b ### Re-maps a number from one range to another. In the example above, the number '25' is converted from a value in the range 0..100 into a value that ranges from the left edge (0) to the right edge (width) of the screen. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. @param {float} value The incoming value to be converted @param {float} istart Lower bound of the value's current range @param {float} istop Upper bound of the value's current range @param {float} ostart Lower bound of the value's target range @param {float} ostop Upper bound of the value's target range @returns {float} @see norm @see lerp ### map = (value, istart, istop, ostart, ostop) -> ostart + (ostop - ostart) * ((value - istart) / (istop - istart)) ### Determines the largest value in a sequence of numbers. @param {int|float} value1 int or float @param {int|float} value2 int or float @param {int|float} value3 int or float @param {int|float} array int or float array @returns {int|float} @see min ### max = -> return ( if arguments[0] < arguments[1] then arguments[1] else arguments[0] ) if arguments.length is 2 # if single argument, array is used numbers = (if arguments.length is 1 then arguments[0] else arguments) throw new Error("Non-empty array is expected") unless( "length" of numbers and numbers.length ) max = numbers[0] count = numbers.length i = 1 while i < count max = numbers[i] if max < numbers[i] ++i max ### Determines the smallest value in a sequence of numbers. @param {int|float} value1 int or float @param {int|float} value2 int or float @param {int|float} value3 int or float @param {int|float} array int or float array @returns {int|float} @see max ### min = -> return ( if arguments[0] < arguments[1] then arguments[0] else arguments[1] ) if arguments.length is 2 # if single argument, array is used numbers = (if arguments.length is 1 then arguments[0] else arguments) throw new Error("Non-empty array is expected") unless( "length" of numbers and numbers.length ) min = numbers[0] count = numbers.length i = 1 while i < count min = numbers[i] if min > numbers[i] ++i min ### Normalizes a number from another range into a value between 0 and 1. Identical to map(value, low, high, 0, 1); Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. @param {float} aNumber The incoming value to be converted @param {float} low Lower bound of the value's current range @param {float} high Upper bound of the value's current range @returns {float} @see map @see lerp ### norm = (aNumber, low, high) -> (aNumber - low) / (high - low) ### Facilitates exponential expressions. The pow() function is an efficient way of multiplying numbers by themselves (or their reciprocal) in large quantities. For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. @param {int|float} num base of the exponential expression @param {int|float} exponent power of which to raise the base @returns {float} @see sqrt ### pow = Math.pow ### Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9. @param {float} value number to round @returns {int} @see floor @see ceil ### round = Math.round ### Squares a number (multiplies a number by itself). The result is always a positive number, as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1. @param {float} value int or float @returns {float} @see sqrt ### sq = (aNumber) -> aNumber * aNumber ### Calculates the square root of a number. The square root of a number is always positive, even though there may be a valid negative root. The square root s of number a is such that s*s = a. It is the opposite of squaring. @param {float} value int or float, non negative @returns {float} @see pow @see sq ### sqrt = Math.sqrt # Trigonometry ### The inverse of cos(), returns the arc cosine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927). @param {float} value the value whose arc cosine is to be returned @returns {float} @see cos @see asin @see atan ### acos = Math.acos ### The inverse of sin(), returns the arc sine of a value. This function expects the values in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2. @param {float} value the value whose arc sine is to be returned @returns {float} @see sin @see acos @see atan ### asin = Math.asin ### The inverse of tan(), returns the arc tangent of a value. This function expects the values in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 . @param {float} value -Infinity to Infinity (exclusive) @returns {float} @see tan @see asin @see acos ### atan = Math.atan ### Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent. @param {float} y y-coordinate of the point @param {float} x x-coordinate of the point @returns {float} @see tan ### atan2 = Math.atan2 ### Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range -1 to 1. @param {float} value an angle in radians @returns {float} @see tan @see sin ### cos = Math.cos ### Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. @param {int|float} value an angle in radians @returns {float} @see radians ### degrees = (aAngle) -> (aAngle * 180) / Math.PI ### Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. @param {int|float} value an angle in radians @returns {float} @see degrees ### radians = (aAngle) -> (aAngle / 180) * Math.PI ### Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to 6.28). Values are returned in the range -1 to 1. @param {float} value an angle in radians @returns {float} @see cos @see radians ### sin = Math.sin ### Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity. @param {float} value an angle in radians @returns {float} @see cos @see sin @see radians ### tan = Math.tan currentRandom = Math.random ### Generates random numbers. Each time the random() function is called, it returns an unexpected value within the specified range. If one parameter is passed to the function it will return a float between zero and the value of the high parameter. The function call random(5) returns values between 0 and 5 (starting at zero, up to but not including 5). If two parameters are passed, it will return a float with a value between the parameters. The function call random(-5, 10.2) returns values starting at -5 up to (but not including) 10.2. To convert a floating-point random number to an integer, use the int() function. @param {int|float} value1 if one parameter is used, the top end to random from, if two params the low end @param {int|float} value2 the top end of the random range @returns {float} @see randomSeed @see noise ### random = -> return currentRandom() if !arguments.length return currentRandom() * arguments[0] if arguments.length is 1 aMin = arguments[0] aMax = arguments[1] currentRandom() * (aMax - aMin) + aMin # Pseudo-random generator class Marsaglia z:0 w:0 constructor:(i1, i2) -> # from http://www.math.uni-bielefeld.de/~sillke/ALGORITHMS/random/marsaglia-c @z = i1 or 362436069 @w = i2 or 521288629 @createRandomized: -> now = new Date() new Marsaglia((now / 60000) & 0xFFFFFFFF, now & 0xFFFFFFFF) nextInt: -> @z = (36969 * (@z & 65535) + (@z >>> 16)) & 0xFFFFFFFF @w = (18000 * (@w & 65535) + (@w >>> 16)) & 0xFFFFFFFF (((@z & 0xFFFF) << 16) | (@w & 0xFFFF)) & 0xFFFFFFFF nextDouble: -> i = @nextInt() / 4294967296 (if i < 0 then 1 + i else i) ### Sets the seed value for random(). By default, random() produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run. @param {int|float} seed int @see random @see noise @see noiseSeed ### randomSeed = (seed) -> mrand = new Marsaglia(seed) currentRandom = ()->mrand.nextDouble() # Random # We have two random()'s in the code... what does this do ? and which one is current ? Random = (seed) -> haveNextNextGaussian = false nextNextGaussian = undefined random = undefined @nextGaussian = -> if haveNextNextGaussian haveNextNextGaussian = false return nextNextGaussian v1 = undefined v2 = undefined s = undefined loop v1 = 2 * random() - 1 # between -1.0 and 1.0 v2 = 2 * random() - 1 # between -1.0 and 1.0 s = v1 * v1 + v2 * v2 break unless s >= 1 or s is 0 multiplier = Math.sqrt(-2 * Math.log(s) / s) nextNextGaussian = v2 * multiplier haveNextNextGaussian = true v1 * multiplier # by default use standard random, otherwise seeded random = (if (seed is undefined) then Math.random else (new Marsaglia(seed)).nextDouble) # Noise functions and helpers # http://www.noisemachine.com/talk1/17b.html # http://mrl.nyu.edu/~perlin/noise/ # generate permutation class PerlinNoise seed:0 perm: null constructor:(@seed) -> rnd = (if @seed isnt undefined then new Marsaglia(@seed) else Marsaglia.createRandomized()) i = undefined j = undefined @perm = new Uint8Array(512) i = 0 while i < 256 @perm[i] = i ++i i = 0 while i < 256 t = @perm[j = rnd.nextInt() & 0xFF] @perm[j] = @perm[i] @perm[i] = t ++i i = 0 while i < 256 @perm[i + 256] = @perm[i] ++i # copy to avoid taking mod in @perm[0]; grad3d: (i, x, y, z) -> h = i & 15 # convert into 12 gradient directions u = (if h < 8 then x else y) v = (if h < 4 then y else (if h is 12 or h is 14 then x else z)) ((if (h & 1) is 0 then u else -u)) + ((if (h & 2) is 0 then v else -v)) grad2d: (i, x, y) -> v = (if (i & 1) is 0 then x else y) (if (i & 2) is 0 then -v else v) grad1d: (i, x) -> (if (i & 1) is 0 then -x else x) # there is a lerp defined already, with same # behaviour, but I guess it makes sense to have # one here to make things self-contained. lerp: (t, a, b) -> a + t * (b - a) noise3d: (x, y, z) -> X = Math.floor(x) & 255 Y = Math.floor(y) & 255 Z = Math.floor(z) & 255 x -= Math.floor(x) y -= Math.floor(y) z -= Math.floor(z) fx = (3 - 2 * x) * x * x fy = (3 - 2 * y) * y * y fz = (3 - 2 * z) * z * z p0 = @perm[X] + Y p00 = @perm[p0] + Z p01 = @perm[p0 + 1] + Z p1 = @perm[X + 1] + Y p10 = @perm[p1] + Z p11 = @perm[p1 + 1] + Z @lerp fz, @lerp(fy, @lerp(fx, @grad3d(@perm[p00], x, y, z), @grad3d(@perm[p10], x - 1, y, z)), @lerp(fx, @grad3d(@perm[p01], x, y - 1, z), @grad3d(@perm[p11], x - 1, y - 1, z))), @lerp(fy, @lerp(fx, @grad3d(@perm[p00 + 1], x, y, z - 1), @grad3d(@perm[p10 + 1], x - 1, y, z - 1)), @lerp(fx, @grad3d(@perm[p01 + 1], x, y - 1, z - 1), @grad3d(@perm[p11 + 1], x - 1, y - 1, z - 1))) noise2d: (x, y) -> X = Math.floor(x) & 255 Y = Math.floor(y) & 255 x -= Math.floor(x) y -= Math.floor(y) fx = (3 - 2 * x) * x * x fy = (3 - 2 * y) * y * y p0 = @perm[X] + Y p1 = @perm[X + 1] + Y @lerp fy, @lerp(fx, @grad2d(@perm[p0], x, y), @grad2d(@perm[p1], x - 1, y)), @lerp(fx, @grad2d(@perm[p0 + 1], x, y - 1), @grad2d(@perm[p1 + 1], x - 1, y - 1)) noise1d: (x) -> X = Math.floor(x) & 255 x -= Math.floor(x) fx = (3 - 2 * x) * x * x @lerp fx, @grad1d(@perm[X], x), @grad1d(@perm[X + 1], x - 1) # processing defaults noiseProfile = generator: undefined octaves: 4 fallout: 0.5 seed: undefined ### Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence generator producing a more natural ordered, harmonic succession of numbers compared to the standard random() function. It was invented by PI:NAME:<NAME>END_PI in the 1980s and been used since in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. The main difference to the random() function is that Perlin noise is defined in an infinite n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value (fixed only for the lifespan of the program). The resulting value will always be between 0.0 and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates given. The noise value can be animated by moving through the noise space as demonstrated in the example above. The 2nd and 3rd dimension can also be interpreted as time. The actual noise is structured similar to an audio signal, in respect to the function's use of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over several octaves which are added together for the final result. Another way to adjust the character of the resulting sequence is the scale of the input coordinates. As the function works within an infinite space the value of the coordinates doesn't matter as such, only the distance between successive coordinates does (eg. when using noise() within a loop). As a general rule the smaller the difference between coordinates, the smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, but this will differ depending on use. @param {float} x x coordinate in noise space @param {float} y y coordinate in noise space @param {float} z z coordinate in noise space @returns {float} @see random @see noiseDetail ### noise = (x, y, z) -> # caching noiseProfile.generator = new PerlinNoise(noiseProfile.seed) if noiseProfile.generator is undefined generator = noiseProfile.generator effect = 1 k = 1 sum = 0 i = 0 while i < noiseProfile.octaves effect *= noiseProfile.fallout switch arguments.length when 1 sum += effect * (1 + generator.noise1d(k * x)) / 2 when 2 sum += effect * (1 + generator.noise2d(k * x, k * y)) / 2 when 3 sum += effect * (1 + generator.noise3d(k * x, k * y, k * z)) / 2 k *= 2 ++i sum ### Adjusts the character and level of detail produced by the Perlin noise function. Similar to harmonics in physics, noise is computed over several octaves. Lower octaves contribute more to the output signal and as such define the overal intensity of the noise, whereas higher octaves create finer grained details in the noise sequence. By default, noise is computed over 4 octaves with each octave contributing exactly half than its predecessor, starting at 50% strength for the 1st octave. This falloff amount can be changed by adding an additional function parameter. Eg. a falloff factor of 0.75 means each octave will now have 75% impact (25% less) of the previous lower octave. Any value between 0.0 and 1.0 is valid, however note that values greater than 0.5 might result in greater than 1.0 values returned by noise(). By changing these parameters, the signal created by the noise() function can be adapted to fit very specific needs and characteristics. @param {int} octaves number of octaves to be used by the noise() function @param {float} falloff falloff factor for each octave @see noise ### noiseDetail = (octaves, fallout) -> noiseProfile.octaves = octaves noiseProfile.fallout = fallout if fallout isnt undefined ### Sets the seed value for noise(). By default, noise() produces different results each time the program is run. Set the value parameter to a constant to return the same pseudo-random numbers each time the software is run. @param {int} seed int @returns {float} @see random @see radomSeed @see noise @see noiseDetail ### noiseSeed = (seed) -> noiseProfile.seed = seed noiseProfile.generator = undefined
[ { "context": "Version: FORMAT_VERSION, noteData: []}\n\nLS_KEY = \"chiptool song data\"\n\n@state_changed = ->\n\t# TODO: update playback he", "end": 426, "score": 0.9932982325553894, "start": 408, "tag": "KEY", "value": "chiptool song data" }, { "context": "ok through the source his...
src/app.coffee
1j01/chiptool
3
scale = teoria.note("c#4").scale("lydian") scale_notes = scale.notes() scale_note_midis = (note.midi() for note in scale_notes) midi_to_freq = (midi)-> teoria.note.fromMIDI(midi).fq() audioContext = new AudioContext() #master = audioContext.createGain() #master.gain.value = 0 #master.connect audioContext.destination FORMAT_VERSION = 0 @song = {formatVersion: FORMAT_VERSION, noteData: []} LS_KEY = "chiptool song data" @state_changed = -> # TODO: update playback here try save() catch err console.warn err # TODO: warn user @get_state = -> JSON.stringify(song) @set_state = (song_json)-> # Performance: could do without JSON parsing and document validation for undo/redo try if song_json data = JSON.parse(song_json) if data if not Number.isInteger(data.formatVersion) console.error "In the JSON data, expected a top level property `formatVersion` to hold an integer; is this a Chiptool song?", data return if data.formatVersion > FORMAT_VERSION console.error "The song file appears to have been created with a later version of Chiptool; try refreshing to get the latest version." return if data.formatVersion < FORMAT_VERSION # upgrades can be done like so: # if data.formatVersion is 0 # console.log "Upgrading song file from format version #{data.formatVersion} to #{data.formatVersion + 1}" # data.formatVersion += 1 # data.foo = data.bar # delete data.bar # return # they could also be moved into an array/map of format upgrades # for backwards compatible changes, the version number can simply be incremented # also, in Wavey, I've included undos and redos in the saved state and done this: # upgrade = (fn)-> # fn doc.state # fn state for state in doc.undos # fn state for state in doc.redos if data.formatVersion isnt FORMAT_VERSION # this message is really verbose, but also not nearly as helpful as it could be # this isn't even shown to the user yet # and this app is very much pre-alpha; it's an experiment # but this shows what kind of help could be given for this sort of scenario console.error "The song file appears to have been created with an earlier version of Chiptool, but there's no upgrade path from #{data.formatVersion} to #{FORMAT_VERSION}. You could try refreshing the page in case an upgrade path has been established since whenever, or you could look through the source history (https://github.com/1j01/chiptool) to find a version capable of loading the file and maybe use RawGit to get a URL for that version of the app" return if not Array.isArray(data.noteData) console.error "In JSON data, expected a top level property `noteData` to hold an array.", data return # TODO: recover from validation errors? for position, index in data when position? for note_prop in ["n1", "n2"] if not Number.isInteger(position[note_prop]) console.error "At index #{index} in song, expected an integer for property `#{note_prop}`", position return # TODO: check for unhandled keys? # maybe have a more robust system with schemas? @song = data catch err console.warn err # TODO: warn user state_changed() load = -> set_state(localStorage.getItem(LS_KEY)) save = -> localStorage.setItem(LS_KEY, get_state()) playing = no x_scale = 30 # pixels note_length = 0.5 # seconds glide_length = 0.2 # seconds pointers = {} # used for display pressed = {} # used for interaction document.body.setAttribute "touch-action", "none" document.body.addEventListener "pointermove", (e)-> x = e.clientX y = e.clientY pointer = pointers[e.pointerId] if pointer pointer.x = x pointer.y = y time = audioContext.currentTime pointer = pressed[e.pointerId] if pointer pointer.x = x pointer.y = y {gain, osc} = pointer note_midi_at_pointer_y = note_midi_at y if note_midi_at_pointer_y new_freq = midi_to_freq(note_midi_at_pointer_y) xi = x // x_scale last_xi = pointer.last_x // x_scale if xi isnt last_xi for _xi_ in [xi...last_xi] song.noteData[_xi_] = n1: pointer.last_note_midi n2: pointer.last_note_midi if new_freq isnt pointer.last_freq pointer.last_freq = new_freq osc.frequency.value = new_freq if song.noteData[xi] song.noteData[xi].n2 = note_midi_at_pointer_y state_changed() pointer.last_note_midi = note_midi_at_pointer_y pointer.last_x = x document.body.addEventListener "pointerdown", (e)-> pointers[e.pointerId]?.down = yes return if pressed[e.pointerId] x = e.clientX y = e.clientY note_midi_at_pointer_y = note_midi_at y if note_midi_at_pointer_y undoable => song.noteData[x // x_scale] = n1: note_midi_at_pointer_y n2: note_midi_at_pointer_y osc = audioContext.createOscillator() gain = audioContext.createGain() osc.type = "triangle" osc.connect gain gain.connect audioContext.destination freq = last_freq = midi_to_freq(note_midi_at_pointer_y) pointer = pressed[e.pointerId] = {x, y, gain, osc, last_freq, last_x: x, last_note: note_midi_at_pointer_y} time = audioContext.currentTime osc.frequency.value = freq osc.start 0 gain.gain.cancelScheduledValues time gain.gain.linearRampToValueAtTime 0.001, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.01 e.preventDefault() document.body.tabIndex = 1 document.body.focus() pointerstop = (e)-> pointers[e.pointerId]?.down = no pointer = pressed[e.pointerId] delete pressed[e.pointerId] if pointer {gain, osc} = pointer time = audioContext.currentTime gain.gain.setValueAtTime 0.1, time gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 setTimeout -> osc.stop 0 , 1500 window.addEventListener "pointerup", pointerstop window.addEventListener "pointercancel", pointerstop # TODO: cancel edit document.body.addEventListener "pointerout", (e)-> delete pointers[e.pointerId] document.body.addEventListener "pointerover", (e)-> x = e.clientX y = e.clientY pointers[e.pointerId] = { x, y hover_y_lagged: undefined hover_y: undefined hover_r: 0 hover_r_lagged: 0 } playback = [] playback_start_time = undefined play = -> stop() playing = yes time = playback_start_time = audioContext.currentTime playback = [] for position, i in song.noteData if position {n1, n2} = position prev_position = song.noteData[i - 1] # TODO: allow explicit reactuation if prev_position and prev_position.n2 is n1 {osc, gain} = playback[playback.length - 1] # cancel the note fading out gain.gain.cancelScheduledValues time - 0.2 #gain.gain.setValueAtTime 0.1, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.5 # fade it out later gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 else osc = audioContext.createOscillator() gain = audioContext.createGain() osc.type = "triangle" osc.connect gain gain.connect audioContext.destination osc.start time gain.gain.cancelScheduledValues time gain.gain.linearRampToValueAtTime 0.001, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.01 gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 osc.frequency.setValueAtTime midi_to_freq(n1), time osc.frequency.exponentialRampToValueAtTime midi_to_freq(n2), time + glide_length playback.push {osc, gain} time += note_length stop = -> time = audioContext.currentTime for {osc, gain} in playback #gain.gain.cancelScheduledValues time #gain.gain.exponentialRampToValueAtTime 0.01, time + 0.1 #gain.gain.linearRampToValueAtTime 0.0001, time + 0.19 #osc.stop time + 1 osc.stop() playback = [] playback_start_time = undefined playing = no window.addEventListener "keydown", (e)-> key = (e.key ? String.fromCharCode(e.keyCode)).toUpperCase() if e.ctrlKey switch key when "Z" if e.shiftKey then redo() else undo() when "Y" redo() #when "A" #select_all() else return # don't prevent default else switch e.keyCode when 32 # Space if playing stop() else play() #when 27 # Escape #deselect() if selection #when 13 # Enter #deselect() if selection when 115 # F4 redo() #when 46 # Delete #delete_selected() else return # don't prevent default e.preventDefault() note_midi_at = (y)-> scale_note_midis[~~((1 - y / canvas.height) * scale_note_midis.length)] y_for_note_i = (i)-> (i + 0.5) / scale_notes.length * canvas.height y_for_note_midi = (note_midi)-> y_for_note_i(scale_note_midis.length - 1 - (scale_note_midis.indexOf(note_midi))) lerp = (v1, v2, x)-> v1 + (v2 - v1) * x animate -> ctx.fillStyle = "black" ctx.fillRect 0, 0, canvas.width, canvas.height ctx.save() ctx.beginPath() for note, i in scale_notes y = y_for_note_i i ctx.moveTo 0, y ctx.lineTo canvas.width, y ctx.strokeStyle = "rgba(255, 255, 255, 0.2)" ctx.lineWidth = 1 ctx.stroke() ctx.beginPath() for position, i in song.noteData when position i1 = i + 0 i2 = i + 1 x1 = x_scale * i1 x2 = x_scale * i2 y1 = y_for_note_midi position.n1 y2 = y_for_note_midi position.n2 ctx.moveTo x1, y1 #ctx.bezierCurveTo lerp(x1, x2, 0.5), y1, lerp(x1, x2, 0.5), y2, x2, y2 ctx.lineTo x1 + x_scale * glide_length, y2 ctx.lineTo x2, y2 #ctx.bezierCurveTo lerp(x1, x2, 0.3), y1, lerp(x1, x2, 0.4), y2, x2, y2 #ctx.bezierCurveTo lerp(x1, x2, 0.2), y1, lerp(x1, x2, 0.4), y2, x2, y2 ctx.strokeStyle = "rgba(0, 255, 0, 1)" ctx.lineCap = "round" ctx.lineWidth = 3 ctx.stroke() if playing ctx.beginPath() playback_position = (audioContext.currentTime - playback_start_time) / note_length playback_position_x = playback_position * x_scale ctx.moveTo playback_position_x, 0 ctx.lineTo playback_position_x, canvas.height ctx.strokeStyle = "rgba(0, 255, 0, 1)" ctx.lineWidth = 1 ctx.stroke() for pointerId, pointer of pointers note_midi_at_pointer_y = note_midi_at pointer.y if note_midi_at_pointer_y pointer.hover_y = y_for_note_midi note_midi_at_pointer_y pointer.hover_r = if pointer.down then 20 else 30 pointer.hover_y_lagged ?= pointer.hover_y pointer.hover_y_lagged += (pointer.hover_y - pointer.hover_y_lagged) * 0.6 pointer.hover_r_lagged += (pointer.hover_r - pointer.hover_r_lagged) * 0.5 ctx.beginPath() ctx.arc pointer.x, pointer.hover_y_lagged, pointer.hover_r_lagged, 0, TAU ctx.fillStyle = "rgba(0, 255, 0, 0.3)" ctx.fill() ctx.restore() load()
80444
scale = teoria.note("c#4").scale("lydian") scale_notes = scale.notes() scale_note_midis = (note.midi() for note in scale_notes) midi_to_freq = (midi)-> teoria.note.fromMIDI(midi).fq() audioContext = new AudioContext() #master = audioContext.createGain() #master.gain.value = 0 #master.connect audioContext.destination FORMAT_VERSION = 0 @song = {formatVersion: FORMAT_VERSION, noteData: []} LS_KEY = "<KEY>" @state_changed = -> # TODO: update playback here try save() catch err console.warn err # TODO: warn user @get_state = -> JSON.stringify(song) @set_state = (song_json)-> # Performance: could do without JSON parsing and document validation for undo/redo try if song_json data = JSON.parse(song_json) if data if not Number.isInteger(data.formatVersion) console.error "In the JSON data, expected a top level property `formatVersion` to hold an integer; is this a Chiptool song?", data return if data.formatVersion > FORMAT_VERSION console.error "The song file appears to have been created with a later version of Chiptool; try refreshing to get the latest version." return if data.formatVersion < FORMAT_VERSION # upgrades can be done like so: # if data.formatVersion is 0 # console.log "Upgrading song file from format version #{data.formatVersion} to #{data.formatVersion + 1}" # data.formatVersion += 1 # data.foo = data.bar # delete data.bar # return # they could also be moved into an array/map of format upgrades # for backwards compatible changes, the version number can simply be incremented # also, in Wavey, I've included undos and redos in the saved state and done this: # upgrade = (fn)-> # fn doc.state # fn state for state in doc.undos # fn state for state in doc.redos if data.formatVersion isnt FORMAT_VERSION # this message is really verbose, but also not nearly as helpful as it could be # this isn't even shown to the user yet # and this app is very much pre-alpha; it's an experiment # but this shows what kind of help could be given for this sort of scenario console.error "The song file appears to have been created with an earlier version of Chiptool, but there's no upgrade path from #{data.formatVersion} to #{FORMAT_VERSION}. You could try refreshing the page in case an upgrade path has been established since whenever, or you could look through the source history (https://github.com/1j01/chiptool) to find a version capable of loading the file and maybe use RawGit to get a URL for that version of the app" return if not Array.isArray(data.noteData) console.error "In JSON data, expected a top level property `noteData` to hold an array.", data return # TODO: recover from validation errors? for position, index in data when position? for note_prop in ["n1", "n2"] if not Number.isInteger(position[note_prop]) console.error "At index #{index} in song, expected an integer for property `#{note_prop}`", position return # TODO: check for unhandled keys? # maybe have a more robust system with schemas? @song = data catch err console.warn err # TODO: warn user state_changed() load = -> set_state(localStorage.getItem(LS_KEY)) save = -> localStorage.setItem(LS_KEY, get_state()) playing = no x_scale = 30 # pixels note_length = 0.5 # seconds glide_length = 0.2 # seconds pointers = {} # used for display pressed = {} # used for interaction document.body.setAttribute "touch-action", "none" document.body.addEventListener "pointermove", (e)-> x = e.clientX y = e.clientY pointer = pointers[e.pointerId] if pointer pointer.x = x pointer.y = y time = audioContext.currentTime pointer = pressed[e.pointerId] if pointer pointer.x = x pointer.y = y {gain, osc} = pointer note_midi_at_pointer_y = note_midi_at y if note_midi_at_pointer_y new_freq = midi_to_freq(note_midi_at_pointer_y) xi = x // x_scale last_xi = pointer.last_x // x_scale if xi isnt last_xi for _xi_ in [xi...last_xi] song.noteData[_xi_] = n1: pointer.last_note_midi n2: pointer.last_note_midi if new_freq isnt pointer.last_freq pointer.last_freq = new_freq osc.frequency.value = new_freq if song.noteData[xi] song.noteData[xi].n2 = note_midi_at_pointer_y state_changed() pointer.last_note_midi = note_midi_at_pointer_y pointer.last_x = x document.body.addEventListener "pointerdown", (e)-> pointers[e.pointerId]?.down = yes return if pressed[e.pointerId] x = e.clientX y = e.clientY note_midi_at_pointer_y = note_midi_at y if note_midi_at_pointer_y undoable => song.noteData[x // x_scale] = n1: note_midi_at_pointer_y n2: note_midi_at_pointer_y osc = audioContext.createOscillator() gain = audioContext.createGain() osc.type = "triangle" osc.connect gain gain.connect audioContext.destination freq = last_freq = midi_to_freq(note_midi_at_pointer_y) pointer = pressed[e.pointerId] = {x, y, gain, osc, last_freq, last_x: x, last_note: note_midi_at_pointer_y} time = audioContext.currentTime osc.frequency.value = freq osc.start 0 gain.gain.cancelScheduledValues time gain.gain.linearRampToValueAtTime 0.001, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.01 e.preventDefault() document.body.tabIndex = 1 document.body.focus() pointerstop = (e)-> pointers[e.pointerId]?.down = no pointer = pressed[e.pointerId] delete pressed[e.pointerId] if pointer {gain, osc} = pointer time = audioContext.currentTime gain.gain.setValueAtTime 0.1, time gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 setTimeout -> osc.stop 0 , 1500 window.addEventListener "pointerup", pointerstop window.addEventListener "pointercancel", pointerstop # TODO: cancel edit document.body.addEventListener "pointerout", (e)-> delete pointers[e.pointerId] document.body.addEventListener "pointerover", (e)-> x = e.clientX y = e.clientY pointers[e.pointerId] = { x, y hover_y_lagged: undefined hover_y: undefined hover_r: 0 hover_r_lagged: 0 } playback = [] playback_start_time = undefined play = -> stop() playing = yes time = playback_start_time = audioContext.currentTime playback = [] for position, i in song.noteData if position {n1, n2} = position prev_position = song.noteData[i - 1] # TODO: allow explicit reactuation if prev_position and prev_position.n2 is n1 {osc, gain} = playback[playback.length - 1] # cancel the note fading out gain.gain.cancelScheduledValues time - 0.2 #gain.gain.setValueAtTime 0.1, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.5 # fade it out later gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 else osc = audioContext.createOscillator() gain = audioContext.createGain() osc.type = "triangle" osc.connect gain gain.connect audioContext.destination osc.start time gain.gain.cancelScheduledValues time gain.gain.linearRampToValueAtTime 0.001, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.01 gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 osc.frequency.setValueAtTime midi_to_freq(n1), time osc.frequency.exponentialRampToValueAtTime midi_to_freq(n2), time + glide_length playback.push {osc, gain} time += note_length stop = -> time = audioContext.currentTime for {osc, gain} in playback #gain.gain.cancelScheduledValues time #gain.gain.exponentialRampToValueAtTime 0.01, time + 0.1 #gain.gain.linearRampToValueAtTime 0.0001, time + 0.19 #osc.stop time + 1 osc.stop() playback = [] playback_start_time = undefined playing = no window.addEventListener "keydown", (e)-> key = (e.key ? String.fromCharCode(e.keyCode)).toUpperCase() if e.ctrlKey switch key when "Z" if e.shiftKey then redo() else undo() when "Y" redo() #when "A" #select_all() else return # don't prevent default else switch e.keyCode when 32 # Space if playing stop() else play() #when 27 # Escape #deselect() if selection #when 13 # Enter #deselect() if selection when 115 # F4 redo() #when 46 # Delete #delete_selected() else return # don't prevent default e.preventDefault() note_midi_at = (y)-> scale_note_midis[~~((1 - y / canvas.height) * scale_note_midis.length)] y_for_note_i = (i)-> (i + 0.5) / scale_notes.length * canvas.height y_for_note_midi = (note_midi)-> y_for_note_i(scale_note_midis.length - 1 - (scale_note_midis.indexOf(note_midi))) lerp = (v1, v2, x)-> v1 + (v2 - v1) * x animate -> ctx.fillStyle = "black" ctx.fillRect 0, 0, canvas.width, canvas.height ctx.save() ctx.beginPath() for note, i in scale_notes y = y_for_note_i i ctx.moveTo 0, y ctx.lineTo canvas.width, y ctx.strokeStyle = "rgba(255, 255, 255, 0.2)" ctx.lineWidth = 1 ctx.stroke() ctx.beginPath() for position, i in song.noteData when position i1 = i + 0 i2 = i + 1 x1 = x_scale * i1 x2 = x_scale * i2 y1 = y_for_note_midi position.n1 y2 = y_for_note_midi position.n2 ctx.moveTo x1, y1 #ctx.bezierCurveTo lerp(x1, x2, 0.5), y1, lerp(x1, x2, 0.5), y2, x2, y2 ctx.lineTo x1 + x_scale * glide_length, y2 ctx.lineTo x2, y2 #ctx.bezierCurveTo lerp(x1, x2, 0.3), y1, lerp(x1, x2, 0.4), y2, x2, y2 #ctx.bezierCurveTo lerp(x1, x2, 0.2), y1, lerp(x1, x2, 0.4), y2, x2, y2 ctx.strokeStyle = "rgba(0, 255, 0, 1)" ctx.lineCap = "round" ctx.lineWidth = 3 ctx.stroke() if playing ctx.beginPath() playback_position = (audioContext.currentTime - playback_start_time) / note_length playback_position_x = playback_position * x_scale ctx.moveTo playback_position_x, 0 ctx.lineTo playback_position_x, canvas.height ctx.strokeStyle = "rgba(0, 255, 0, 1)" ctx.lineWidth = 1 ctx.stroke() for pointerId, pointer of pointers note_midi_at_pointer_y = note_midi_at pointer.y if note_midi_at_pointer_y pointer.hover_y = y_for_note_midi note_midi_at_pointer_y pointer.hover_r = if pointer.down then 20 else 30 pointer.hover_y_lagged ?= pointer.hover_y pointer.hover_y_lagged += (pointer.hover_y - pointer.hover_y_lagged) * 0.6 pointer.hover_r_lagged += (pointer.hover_r - pointer.hover_r_lagged) * 0.5 ctx.beginPath() ctx.arc pointer.x, pointer.hover_y_lagged, pointer.hover_r_lagged, 0, TAU ctx.fillStyle = "rgba(0, 255, 0, 0.3)" ctx.fill() ctx.restore() load()
true
scale = teoria.note("c#4").scale("lydian") scale_notes = scale.notes() scale_note_midis = (note.midi() for note in scale_notes) midi_to_freq = (midi)-> teoria.note.fromMIDI(midi).fq() audioContext = new AudioContext() #master = audioContext.createGain() #master.gain.value = 0 #master.connect audioContext.destination FORMAT_VERSION = 0 @song = {formatVersion: FORMAT_VERSION, noteData: []} LS_KEY = "PI:KEY:<KEY>END_PI" @state_changed = -> # TODO: update playback here try save() catch err console.warn err # TODO: warn user @get_state = -> JSON.stringify(song) @set_state = (song_json)-> # Performance: could do without JSON parsing and document validation for undo/redo try if song_json data = JSON.parse(song_json) if data if not Number.isInteger(data.formatVersion) console.error "In the JSON data, expected a top level property `formatVersion` to hold an integer; is this a Chiptool song?", data return if data.formatVersion > FORMAT_VERSION console.error "The song file appears to have been created with a later version of Chiptool; try refreshing to get the latest version." return if data.formatVersion < FORMAT_VERSION # upgrades can be done like so: # if data.formatVersion is 0 # console.log "Upgrading song file from format version #{data.formatVersion} to #{data.formatVersion + 1}" # data.formatVersion += 1 # data.foo = data.bar # delete data.bar # return # they could also be moved into an array/map of format upgrades # for backwards compatible changes, the version number can simply be incremented # also, in Wavey, I've included undos and redos in the saved state and done this: # upgrade = (fn)-> # fn doc.state # fn state for state in doc.undos # fn state for state in doc.redos if data.formatVersion isnt FORMAT_VERSION # this message is really verbose, but also not nearly as helpful as it could be # this isn't even shown to the user yet # and this app is very much pre-alpha; it's an experiment # but this shows what kind of help could be given for this sort of scenario console.error "The song file appears to have been created with an earlier version of Chiptool, but there's no upgrade path from #{data.formatVersion} to #{FORMAT_VERSION}. You could try refreshing the page in case an upgrade path has been established since whenever, or you could look through the source history (https://github.com/1j01/chiptool) to find a version capable of loading the file and maybe use RawGit to get a URL for that version of the app" return if not Array.isArray(data.noteData) console.error "In JSON data, expected a top level property `noteData` to hold an array.", data return # TODO: recover from validation errors? for position, index in data when position? for note_prop in ["n1", "n2"] if not Number.isInteger(position[note_prop]) console.error "At index #{index} in song, expected an integer for property `#{note_prop}`", position return # TODO: check for unhandled keys? # maybe have a more robust system with schemas? @song = data catch err console.warn err # TODO: warn user state_changed() load = -> set_state(localStorage.getItem(LS_KEY)) save = -> localStorage.setItem(LS_KEY, get_state()) playing = no x_scale = 30 # pixels note_length = 0.5 # seconds glide_length = 0.2 # seconds pointers = {} # used for display pressed = {} # used for interaction document.body.setAttribute "touch-action", "none" document.body.addEventListener "pointermove", (e)-> x = e.clientX y = e.clientY pointer = pointers[e.pointerId] if pointer pointer.x = x pointer.y = y time = audioContext.currentTime pointer = pressed[e.pointerId] if pointer pointer.x = x pointer.y = y {gain, osc} = pointer note_midi_at_pointer_y = note_midi_at y if note_midi_at_pointer_y new_freq = midi_to_freq(note_midi_at_pointer_y) xi = x // x_scale last_xi = pointer.last_x // x_scale if xi isnt last_xi for _xi_ in [xi...last_xi] song.noteData[_xi_] = n1: pointer.last_note_midi n2: pointer.last_note_midi if new_freq isnt pointer.last_freq pointer.last_freq = new_freq osc.frequency.value = new_freq if song.noteData[xi] song.noteData[xi].n2 = note_midi_at_pointer_y state_changed() pointer.last_note_midi = note_midi_at_pointer_y pointer.last_x = x document.body.addEventListener "pointerdown", (e)-> pointers[e.pointerId]?.down = yes return if pressed[e.pointerId] x = e.clientX y = e.clientY note_midi_at_pointer_y = note_midi_at y if note_midi_at_pointer_y undoable => song.noteData[x // x_scale] = n1: note_midi_at_pointer_y n2: note_midi_at_pointer_y osc = audioContext.createOscillator() gain = audioContext.createGain() osc.type = "triangle" osc.connect gain gain.connect audioContext.destination freq = last_freq = midi_to_freq(note_midi_at_pointer_y) pointer = pressed[e.pointerId] = {x, y, gain, osc, last_freq, last_x: x, last_note: note_midi_at_pointer_y} time = audioContext.currentTime osc.frequency.value = freq osc.start 0 gain.gain.cancelScheduledValues time gain.gain.linearRampToValueAtTime 0.001, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.01 e.preventDefault() document.body.tabIndex = 1 document.body.focus() pointerstop = (e)-> pointers[e.pointerId]?.down = no pointer = pressed[e.pointerId] delete pressed[e.pointerId] if pointer {gain, osc} = pointer time = audioContext.currentTime gain.gain.setValueAtTime 0.1, time gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 setTimeout -> osc.stop 0 , 1500 window.addEventListener "pointerup", pointerstop window.addEventListener "pointercancel", pointerstop # TODO: cancel edit document.body.addEventListener "pointerout", (e)-> delete pointers[e.pointerId] document.body.addEventListener "pointerover", (e)-> x = e.clientX y = e.clientY pointers[e.pointerId] = { x, y hover_y_lagged: undefined hover_y: undefined hover_r: 0 hover_r_lagged: 0 } playback = [] playback_start_time = undefined play = -> stop() playing = yes time = playback_start_time = audioContext.currentTime playback = [] for position, i in song.noteData if position {n1, n2} = position prev_position = song.noteData[i - 1] # TODO: allow explicit reactuation if prev_position and prev_position.n2 is n1 {osc, gain} = playback[playback.length - 1] # cancel the note fading out gain.gain.cancelScheduledValues time - 0.2 #gain.gain.setValueAtTime 0.1, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.5 # fade it out later gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 else osc = audioContext.createOscillator() gain = audioContext.createGain() osc.type = "triangle" osc.connect gain gain.connect audioContext.destination osc.start time gain.gain.cancelScheduledValues time gain.gain.linearRampToValueAtTime 0.001, time gain.gain.exponentialRampToValueAtTime 0.1, time + 0.01 gain.gain.exponentialRampToValueAtTime 0.01, time + 0.9 gain.gain.linearRampToValueAtTime 0.0001, time + 0.99 osc.frequency.setValueAtTime midi_to_freq(n1), time osc.frequency.exponentialRampToValueAtTime midi_to_freq(n2), time + glide_length playback.push {osc, gain} time += note_length stop = -> time = audioContext.currentTime for {osc, gain} in playback #gain.gain.cancelScheduledValues time #gain.gain.exponentialRampToValueAtTime 0.01, time + 0.1 #gain.gain.linearRampToValueAtTime 0.0001, time + 0.19 #osc.stop time + 1 osc.stop() playback = [] playback_start_time = undefined playing = no window.addEventListener "keydown", (e)-> key = (e.key ? String.fromCharCode(e.keyCode)).toUpperCase() if e.ctrlKey switch key when "Z" if e.shiftKey then redo() else undo() when "Y" redo() #when "A" #select_all() else return # don't prevent default else switch e.keyCode when 32 # Space if playing stop() else play() #when 27 # Escape #deselect() if selection #when 13 # Enter #deselect() if selection when 115 # F4 redo() #when 46 # Delete #delete_selected() else return # don't prevent default e.preventDefault() note_midi_at = (y)-> scale_note_midis[~~((1 - y / canvas.height) * scale_note_midis.length)] y_for_note_i = (i)-> (i + 0.5) / scale_notes.length * canvas.height y_for_note_midi = (note_midi)-> y_for_note_i(scale_note_midis.length - 1 - (scale_note_midis.indexOf(note_midi))) lerp = (v1, v2, x)-> v1 + (v2 - v1) * x animate -> ctx.fillStyle = "black" ctx.fillRect 0, 0, canvas.width, canvas.height ctx.save() ctx.beginPath() for note, i in scale_notes y = y_for_note_i i ctx.moveTo 0, y ctx.lineTo canvas.width, y ctx.strokeStyle = "rgba(255, 255, 255, 0.2)" ctx.lineWidth = 1 ctx.stroke() ctx.beginPath() for position, i in song.noteData when position i1 = i + 0 i2 = i + 1 x1 = x_scale * i1 x2 = x_scale * i2 y1 = y_for_note_midi position.n1 y2 = y_for_note_midi position.n2 ctx.moveTo x1, y1 #ctx.bezierCurveTo lerp(x1, x2, 0.5), y1, lerp(x1, x2, 0.5), y2, x2, y2 ctx.lineTo x1 + x_scale * glide_length, y2 ctx.lineTo x2, y2 #ctx.bezierCurveTo lerp(x1, x2, 0.3), y1, lerp(x1, x2, 0.4), y2, x2, y2 #ctx.bezierCurveTo lerp(x1, x2, 0.2), y1, lerp(x1, x2, 0.4), y2, x2, y2 ctx.strokeStyle = "rgba(0, 255, 0, 1)" ctx.lineCap = "round" ctx.lineWidth = 3 ctx.stroke() if playing ctx.beginPath() playback_position = (audioContext.currentTime - playback_start_time) / note_length playback_position_x = playback_position * x_scale ctx.moveTo playback_position_x, 0 ctx.lineTo playback_position_x, canvas.height ctx.strokeStyle = "rgba(0, 255, 0, 1)" ctx.lineWidth = 1 ctx.stroke() for pointerId, pointer of pointers note_midi_at_pointer_y = note_midi_at pointer.y if note_midi_at_pointer_y pointer.hover_y = y_for_note_midi note_midi_at_pointer_y pointer.hover_r = if pointer.down then 20 else 30 pointer.hover_y_lagged ?= pointer.hover_y pointer.hover_y_lagged += (pointer.hover_y - pointer.hover_y_lagged) * 0.6 pointer.hover_r_lagged += (pointer.hover_r - pointer.hover_r_lagged) * 0.5 ctx.beginPath() ctx.arc pointer.x, pointer.hover_y_lagged, pointer.hover_r_lagged, 0, TAU ctx.fillStyle = "rgba(0, 255, 0, 0.3)" ctx.fill() ctx.restore() load()
[ { "context": ".stringify(@getLog()))\n\n logKey: =>\n key = [ @id, PokeBattle.username ]\n key.sort()\n key.joi", "end": 1146, "score": 0.8687909841537476, "start": 1144, "tag": "KEY", "value": "id" } ]
client/app/js/models/chats/private_message.coffee
sarenji/pokebattle-sim
5
MAX_LOG_LENGTH = 50 class @PrivateMessage extends Backbone.Model initialize: => @loadLog() @set('notifications', 0) add: (username, message, opts = {}) => @set('notifications', @get('notifications') + 1) if username == @id @trigger("receive", this, @id, username, message, opts) log = @get('log') log.push({username, message, opts}) # Trim the log size. Use 2x log length to reduce how often this happens if log.length > (2 * MAX_LOG_LENGTH) log.splice(0, log.length - MAX_LOG_LENGTH) @saveLog() openChallenge: (args...) => @trigger("openChallenge", args...) cancelChallenge: (args...) => @trigger("cancelChallenge", args...) closeChallenge: (args...) => @trigger("closeChallenge", args...) getLog: => log = @get('log') if log.length > 50 log.splice(0, log.length - 50) return log loadLog: => try log = JSON.parse(window.localStorage.getItem(@logKey())) || [] @set('log', log) catch @set('log', []) saveLog: => try window.localStorage.setItem(@logKey(), JSON.stringify(@getLog())) logKey: => key = [ @id, PokeBattle.username ] key.sort() key.join(':')
125172
MAX_LOG_LENGTH = 50 class @PrivateMessage extends Backbone.Model initialize: => @loadLog() @set('notifications', 0) add: (username, message, opts = {}) => @set('notifications', @get('notifications') + 1) if username == @id @trigger("receive", this, @id, username, message, opts) log = @get('log') log.push({username, message, opts}) # Trim the log size. Use 2x log length to reduce how often this happens if log.length > (2 * MAX_LOG_LENGTH) log.splice(0, log.length - MAX_LOG_LENGTH) @saveLog() openChallenge: (args...) => @trigger("openChallenge", args...) cancelChallenge: (args...) => @trigger("cancelChallenge", args...) closeChallenge: (args...) => @trigger("closeChallenge", args...) getLog: => log = @get('log') if log.length > 50 log.splice(0, log.length - 50) return log loadLog: => try log = JSON.parse(window.localStorage.getItem(@logKey())) || [] @set('log', log) catch @set('log', []) saveLog: => try window.localStorage.setItem(@logKey(), JSON.stringify(@getLog())) logKey: => key = [ @<KEY>, PokeBattle.username ] key.sort() key.join(':')
true
MAX_LOG_LENGTH = 50 class @PrivateMessage extends Backbone.Model initialize: => @loadLog() @set('notifications', 0) add: (username, message, opts = {}) => @set('notifications', @get('notifications') + 1) if username == @id @trigger("receive", this, @id, username, message, opts) log = @get('log') log.push({username, message, opts}) # Trim the log size. Use 2x log length to reduce how often this happens if log.length > (2 * MAX_LOG_LENGTH) log.splice(0, log.length - MAX_LOG_LENGTH) @saveLog() openChallenge: (args...) => @trigger("openChallenge", args...) cancelChallenge: (args...) => @trigger("cancelChallenge", args...) closeChallenge: (args...) => @trigger("closeChallenge", args...) getLog: => log = @get('log') if log.length > 50 log.splice(0, log.length - 50) return log loadLog: => try log = JSON.parse(window.localStorage.getItem(@logKey())) || [] @set('log', log) catch @set('log', []) saveLog: => try window.localStorage.setItem(@logKey(), JSON.stringify(@getLog())) logKey: => key = [ @PI:KEY:<KEY>END_PI, PokeBattle.username ] key.sort() key.join(':')
[ { "context": "#####\nrouteDetect = /^[a-z0-9]+/i\n\nrouteKey = \"### /\"\nrequestKey = \"#### request\"\nresponseKey = \"#### ", "end": 907, "score": 0.9654139280319214, "start": 906, "tag": "KEY", "value": "/" }, { "context": "= /^[a-z0-9]+/i\n\nrouteKey = \"### /\"\nrequestKey = \"...
source/definitionfilemodule/definitionfilemodule.coffee
JhonnyJason/interface-gen-sources
0
definitionfilemodule = {name: "definitionfilemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["definitionfilemodule"]? then console.log "[definitionfilemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region modulesFromEnvironment fs = require("fs") HJSON = require("hjson") ############################################################ p = null ############################################################ file = "" slices = [] ############################################################ interfaceObject = {routes:[]} ############################################################ routeDetect = /^[a-z0-9]+/i routeKey = "### /" requestKey = "#### request" responseKey = "#### response" definitionStartKey = "```json" definitionEndKey = "```" #endregion ############################################################ definitionfilemodule.initialize = () -> log "definitionfilemodule.initialize" p = allModules.pathmodule return ############################################################ #region internalFunctions sliceFile = -> index = file.indexOf(routeKey) while index >= 0 index += routeKey.length nextIndex = file.indexOf(routeKey, index) if nextIndex < 0 then slices.push(file.slice(index)) else slices.push(file.slice(index, nextIndex)) index = nextIndex return ############################################################ extractInterface = -> extractFromSlice(slice) for slice in slices return extractFromSlice = (slice) -> route = routeDetect.exec(slice) requestIndex = slice.indexOf(requestKey) if requestIndex < 0 then throw new Error("File Corrupt! Expected '#### request' in route slice!") requestIndex += requestKey.length requestDefinitionStart = slice.indexOf(definitionStartKey, requestIndex) if requestDefinitionStart < 0 then throw new Error("File Corrupt! Expected '```json' to start request definition!") requestDefinitionStart += definitionStartKey.length requestDefinitionEnd = slice.indexOf(definitionEndKey, requestDefinitionStart) if requestDefinitionEnd < 0 then throw new Error("File Corrupt! Expected '```' to end request definition!") responseIndex = slice.indexOf(responseKey, requestDefinitionEnd) if responseIndex < 0 then throw new Error("File Corrupt! Expected '#### response' definition in route slice!") responseIndex += responseKey.length responseDefinitionStart = slice.indexOf(definitionStartKey, responseIndex) if responseDefinitionStart < 0 then throw new Error("File Corrupt! Expected '```json' to start response definition!") responseDefinitionStart += definitionStartKey.length responseDefinitionEnd = slice.indexOf(definitionEndKey, responseDefinitionStart) if responseDefinitionEnd < 0 then throw new Error("File Corrupt! Expected '```' to end response definition!") requestDefinitionString = slice.slice(requestDefinitionStart, requestDefinitionEnd) requestDefinition = HJSON.parse(requestDefinitionString) responseDefinitionString = slice.slice(responseDefinitionStart, responseDefinitionEnd) addRoute(route, Object.keys(requestDefinition), responseDefinitionString) return ############################################################ addRoute = (routeName, requestArgs, sampleResponse) -> routeObject = route: routeName args: requestArgs.join(", ") requestBlock: "\""+requestArgs.join("\": \"...\", \n\"")+"\": \"...\"" argsBlock: createArgsBlock(requestArgs) response: sampleResponse interfaceObject.routes.push(routeObject) return ############################################################ createArgsBlock = (argsArray) -> return argsArray.map( (el) -> "req.body."+el ).join(", ") #endregion ############################################################ #region exposedFunctions definitionfilemodule.digestFile = (source) -> p.digestPath(source) file = fs.readFileSync(p.absolutePath, 'utf8') sliceFile() extractInterface() return ############################################################ definitionfilemodule.interfaceObject = interfaceObject #endregion module.exports = definitionfilemodule
47286
definitionfilemodule = {name: "definitionfilemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["definitionfilemodule"]? then console.log "[definitionfilemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region modulesFromEnvironment fs = require("fs") HJSON = require("hjson") ############################################################ p = null ############################################################ file = "" slices = [] ############################################################ interfaceObject = {routes:[]} ############################################################ routeDetect = /^[a-z0-9]+/i routeKey = "### <KEY>" requestKey = "<KEY>" responseKey = "<KEY>" definitionStartKey = "```<KEY>" definitionEndKey = "```" #endregion ############################################################ definitionfilemodule.initialize = () -> log "definitionfilemodule.initialize" p = allModules.pathmodule return ############################################################ #region internalFunctions sliceFile = -> index = file.indexOf(routeKey) while index >= 0 index += routeKey.length nextIndex = file.indexOf(routeKey, index) if nextIndex < 0 then slices.push(file.slice(index)) else slices.push(file.slice(index, nextIndex)) index = nextIndex return ############################################################ extractInterface = -> extractFromSlice(slice) for slice in slices return extractFromSlice = (slice) -> route = routeDetect.exec(slice) requestIndex = slice.indexOf(requestKey) if requestIndex < 0 then throw new Error("File Corrupt! Expected '#### request' in route slice!") requestIndex += requestKey.length requestDefinitionStart = slice.indexOf(definitionStartKey, requestIndex) if requestDefinitionStart < 0 then throw new Error("File Corrupt! Expected '```json' to start request definition!") requestDefinitionStart += definitionStartKey.length requestDefinitionEnd = slice.indexOf(definitionEndKey, requestDefinitionStart) if requestDefinitionEnd < 0 then throw new Error("File Corrupt! Expected '```' to end request definition!") responseIndex = slice.indexOf(responseKey, requestDefinitionEnd) if responseIndex < 0 then throw new Error("File Corrupt! Expected '#### response' definition in route slice!") responseIndex += responseKey.length responseDefinitionStart = slice.indexOf(definitionStartKey, responseIndex) if responseDefinitionStart < 0 then throw new Error("File Corrupt! Expected '```json' to start response definition!") responseDefinitionStart += definitionStartKey.length responseDefinitionEnd = slice.indexOf(definitionEndKey, responseDefinitionStart) if responseDefinitionEnd < 0 then throw new Error("File Corrupt! Expected '```' to end response definition!") requestDefinitionString = slice.slice(requestDefinitionStart, requestDefinitionEnd) requestDefinition = HJSON.parse(requestDefinitionString) responseDefinitionString = slice.slice(responseDefinitionStart, responseDefinitionEnd) addRoute(route, Object.keys(requestDefinition), responseDefinitionString) return ############################################################ addRoute = (routeName, requestArgs, sampleResponse) -> routeObject = route: routeName args: requestArgs.join(", ") requestBlock: "\""+requestArgs.join("\": \"...\", \n\"")+"\": \"...\"" argsBlock: createArgsBlock(requestArgs) response: sampleResponse interfaceObject.routes.push(routeObject) return ############################################################ createArgsBlock = (argsArray) -> return argsArray.map( (el) -> "req.body."+el ).join(", ") #endregion ############################################################ #region exposedFunctions definitionfilemodule.digestFile = (source) -> p.digestPath(source) file = fs.readFileSync(p.absolutePath, 'utf8') sliceFile() extractInterface() return ############################################################ definitionfilemodule.interfaceObject = interfaceObject #endregion module.exports = definitionfilemodule
true
definitionfilemodule = {name: "definitionfilemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["definitionfilemodule"]? then console.log "[definitionfilemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region modulesFromEnvironment fs = require("fs") HJSON = require("hjson") ############################################################ p = null ############################################################ file = "" slices = [] ############################################################ interfaceObject = {routes:[]} ############################################################ routeDetect = /^[a-z0-9]+/i routeKey = "### PI:KEY:<KEY>END_PI" requestKey = "PI:KEY:<KEY>END_PI" responseKey = "PI:KEY:<KEY>END_PI" definitionStartKey = "```PI:KEY:<KEY>END_PI" definitionEndKey = "```" #endregion ############################################################ definitionfilemodule.initialize = () -> log "definitionfilemodule.initialize" p = allModules.pathmodule return ############################################################ #region internalFunctions sliceFile = -> index = file.indexOf(routeKey) while index >= 0 index += routeKey.length nextIndex = file.indexOf(routeKey, index) if nextIndex < 0 then slices.push(file.slice(index)) else slices.push(file.slice(index, nextIndex)) index = nextIndex return ############################################################ extractInterface = -> extractFromSlice(slice) for slice in slices return extractFromSlice = (slice) -> route = routeDetect.exec(slice) requestIndex = slice.indexOf(requestKey) if requestIndex < 0 then throw new Error("File Corrupt! Expected '#### request' in route slice!") requestIndex += requestKey.length requestDefinitionStart = slice.indexOf(definitionStartKey, requestIndex) if requestDefinitionStart < 0 then throw new Error("File Corrupt! Expected '```json' to start request definition!") requestDefinitionStart += definitionStartKey.length requestDefinitionEnd = slice.indexOf(definitionEndKey, requestDefinitionStart) if requestDefinitionEnd < 0 then throw new Error("File Corrupt! Expected '```' to end request definition!") responseIndex = slice.indexOf(responseKey, requestDefinitionEnd) if responseIndex < 0 then throw new Error("File Corrupt! Expected '#### response' definition in route slice!") responseIndex += responseKey.length responseDefinitionStart = slice.indexOf(definitionStartKey, responseIndex) if responseDefinitionStart < 0 then throw new Error("File Corrupt! Expected '```json' to start response definition!") responseDefinitionStart += definitionStartKey.length responseDefinitionEnd = slice.indexOf(definitionEndKey, responseDefinitionStart) if responseDefinitionEnd < 0 then throw new Error("File Corrupt! Expected '```' to end response definition!") requestDefinitionString = slice.slice(requestDefinitionStart, requestDefinitionEnd) requestDefinition = HJSON.parse(requestDefinitionString) responseDefinitionString = slice.slice(responseDefinitionStart, responseDefinitionEnd) addRoute(route, Object.keys(requestDefinition), responseDefinitionString) return ############################################################ addRoute = (routeName, requestArgs, sampleResponse) -> routeObject = route: routeName args: requestArgs.join(", ") requestBlock: "\""+requestArgs.join("\": \"...\", \n\"")+"\": \"...\"" argsBlock: createArgsBlock(requestArgs) response: sampleResponse interfaceObject.routes.push(routeObject) return ############################################################ createArgsBlock = (argsArray) -> return argsArray.map( (el) -> "req.body."+el ).join(", ") #endregion ############################################################ #region exposedFunctions definitionfilemodule.digestFile = (source) -> p.digestPath(source) file = fs.readFileSync(p.absolutePath, 'utf8') sliceFile() extractInterface() return ############################################################ definitionfilemodule.interfaceObject = interfaceObject #endregion module.exports = definitionfilemodule
[ { "context": "# Made by Viktor Strate\n# Based on SmoothAnalogClock by N00bySumairu\n# ht", "end": 23, "score": 0.9998958706855774, "start": 10, "tag": "NAME", "value": "Viktor Strate" }, { "context": "e by Viktor Strate\n# Based on SmoothAnalogClock by N00bySumairu\n# https://github...
simple-analog-clock.widget/index.coffee
viktorstrate/simple-analog-clock
2
# Made by Viktor Strate # Based on SmoothAnalogClock by N00bySumairu # https://github.com/N00bySumairu/SmoothAnalogClock.widget # Begin of styling options options = pos: x: "left: 50px" y: "top: 40px" size: 192 # width of the clock in px scale: 1 # for retina displays set to 2 fontSize: 48 # in px secPtr: color: "rgb(209,97,143)" # css color string width: 1 # in px length: 72 # in px minPtr: color: "rgb(40,40,40)" # css color string width: 1 # in px length: 68 # in px hrPtr: color: "rgb(40,40,40)" # css color string width: 1 # in px length: 44 # in px markerOffset: 4 # offset from the border of the clock in px majorMarker: width: 0.8 # in px length: 24 # in px minorMarker: width: 0.8 # in px length: 16 # in px intervalLength: 30 # interval between the transition triggers in seconds backgroundBlur: false refreshFrequency: "30s" # change this as well when changing the intervalLength # End of styling options render: (_) -> """ <div class="clock"> <div class="markers"></div> <div class="secPtr"></div> <div class="hrPtr"></div> <div class="minPtr"></div> </div> """ afterRender: (domEl) -> # Initialize the markers (I just wanted to keep the render function small and tidy) markers = $(domEl).find('.markers') for i in [0...12] for j in [0...5] id = "" cls = "" if j is 0 id = i+1 cls = "major" else id = (i+1)+"_"+j cls = "minor" rotation = -60 + 6 * (i * 5 + j) markers.append('<div id="'+id+'" class="'+cls+'" style="transform: rotate('+rotation+'deg);"></div>') # Prevent blocking of the clock for the refresh duration after widget refresh setTimeout(@refresh) update: (_, domEl) -> # Use the time elapsed (in ms) since 0:00 of the current day time = Date.now() - (new Date()).setHours(0,0,0,0) div = $(domEl) pointers = div.find('.secPtr, .minPtr, .hrPtr') # Set the rotation of the pointers to what they should be at the current time # (without transition, to prevent the pointer from rotating backwards around the beginning of the day) # Disable transition pointers.removeClass('pointer') div.find('.secPtr').css('transform', 'rotate('+(-90+time/60000*360)+'deg)') div.find('.minPtr').css('transform', 'rotate('+(-90+time/3600000*360)+'deg)') div.find('.hrPtr').css('transform', 'rotate('+(-90+time/43200000*360)+'deg)') # Trigger a reflow, flushing the CSS changes (see http://stackoverflow.com/questions/11131875/what-is-the-cleanest-way-to-disable-css-transition-effects-temporarily) div[0].offsetHeight # Enable transition again pointers.addClass('pointer') # Trigger transition to the rotation of the pointers in 10s time += options.intervalLength * 1000 div.find('.secPtr').css('transform', 'rotate('+(-90+time/60000*360)+'deg)') div.find('.minPtr').css('transform', 'rotate('+(-90+time/3600000*360)+'deg)') div.find('.hrPtr').css('transform', 'rotate('+(-90+time/43200000*360)+'deg)') style: """ #{options.pos.x} #{options.pos.y} .clock width: #{options.size * options.scale}px height: #{options.size * options.scale}px border-radius: 50% background-color: rgba(255,255,255,0.8) box-shadow: 0 0 8px rgba(0,0,0,0.1) if #{options.backgroundBlur} -webkit-backdrop-filter: blur(5px) overflow: hidden .pointer transition: transform #{options.intervalLength}s linear .secPtr position: absolute top: #{options.size * options.scale / 2 - options.secPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.secPtr.width / 2 * options.scale}px width: #{options.secPtr.length * options.scale}px height: #{options.secPtr.width * options.scale}px background-color: #{options.secPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.secPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.secPtr.width / 2 * options.scale}px transform-origin: #{options.secPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .minPtr position: absolute top: #{options.size * options.scale / 2 - options.minPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.minPtr.width / 2 * options.scale}px width: #{options.minPtr.length * options.scale}px height: #{options.minPtr.width * options.scale}px background-color: #{options.minPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.minPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.minPtr.width / 2 * options.scale}px transform-origin: #{options.minPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .hrPtr position: absolute top: #{options.size * options.scale / 2 - options.hrPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.hrPtr.width / 2 * options.scale}px width: #{options.hrPtr.length * options.scale}px height: #{options.hrPtr.width * options.scale}px background-color: #{options.hrPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.hrPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.hrPtr.width / 2 * options.scale}px transform-origin: #{options.minPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .markers > .major position: absolute top: #{options.size * options.scale / 2 - options.majorMarker.width * options.scale / 2}px left: #{options.size * options.scale / 2 - (-options.size / 2 + options.majorMarker.length + options.markerOffset) * options.scale}px width: #{options.majorMarker.length * options.scale}px height: #{options.majorMarker.width * options.scale}px background-color: rgba(0,0,0,0.3) transform-origin: #{(-options.size / 2 + options.majorMarker.length + options.markerOffset) * options.scale}px 50% .markers > .minor position: absolute top: #{options.size * options.scale / 2 - options.minorMarker.width * options.scale / 2}px left: #{options.size * options.scale / 2 - (-options.size / 2 + options.minorMarker.length + options.markerOffset) * options.scale}px width: #{options.minorMarker.length * options.scale}px height: #{options.minorMarker.width * options.scale}px background-color: rgba(0,0,0,0.1) transform-origin: #{(-options.size / 2 + options.minorMarker.length + options.markerOffset) * options.scale}px 50% """
115741
# Made by <NAME> # Based on SmoothAnalogClock by N00bySumairu # https://github.com/N00bySumairu/SmoothAnalogClock.widget # Begin of styling options options = pos: x: "left: 50px" y: "top: 40px" size: 192 # width of the clock in px scale: 1 # for retina displays set to 2 fontSize: 48 # in px secPtr: color: "rgb(209,97,143)" # css color string width: 1 # in px length: 72 # in px minPtr: color: "rgb(40,40,40)" # css color string width: 1 # in px length: 68 # in px hrPtr: color: "rgb(40,40,40)" # css color string width: 1 # in px length: 44 # in px markerOffset: 4 # offset from the border of the clock in px majorMarker: width: 0.8 # in px length: 24 # in px minorMarker: width: 0.8 # in px length: 16 # in px intervalLength: 30 # interval between the transition triggers in seconds backgroundBlur: false refreshFrequency: "30s" # change this as well when changing the intervalLength # End of styling options render: (_) -> """ <div class="clock"> <div class="markers"></div> <div class="secPtr"></div> <div class="hrPtr"></div> <div class="minPtr"></div> </div> """ afterRender: (domEl) -> # Initialize the markers (I just wanted to keep the render function small and tidy) markers = $(domEl).find('.markers') for i in [0...12] for j in [0...5] id = "" cls = "" if j is 0 id = i+1 cls = "major" else id = (i+1)+"_"+j cls = "minor" rotation = -60 + 6 * (i * 5 + j) markers.append('<div id="'+id+'" class="'+cls+'" style="transform: rotate('+rotation+'deg);"></div>') # Prevent blocking of the clock for the refresh duration after widget refresh setTimeout(@refresh) update: (_, domEl) -> # Use the time elapsed (in ms) since 0:00 of the current day time = Date.now() - (new Date()).setHours(0,0,0,0) div = $(domEl) pointers = div.find('.secPtr, .minPtr, .hrPtr') # Set the rotation of the pointers to what they should be at the current time # (without transition, to prevent the pointer from rotating backwards around the beginning of the day) # Disable transition pointers.removeClass('pointer') div.find('.secPtr').css('transform', 'rotate('+(-90+time/60000*360)+'deg)') div.find('.minPtr').css('transform', 'rotate('+(-90+time/3600000*360)+'deg)') div.find('.hrPtr').css('transform', 'rotate('+(-90+time/43200000*360)+'deg)') # Trigger a reflow, flushing the CSS changes (see http://stackoverflow.com/questions/11131875/what-is-the-cleanest-way-to-disable-css-transition-effects-temporarily) div[0].offsetHeight # Enable transition again pointers.addClass('pointer') # Trigger transition to the rotation of the pointers in 10s time += options.intervalLength * 1000 div.find('.secPtr').css('transform', 'rotate('+(-90+time/60000*360)+'deg)') div.find('.minPtr').css('transform', 'rotate('+(-90+time/3600000*360)+'deg)') div.find('.hrPtr').css('transform', 'rotate('+(-90+time/43200000*360)+'deg)') style: """ #{options.pos.x} #{options.pos.y} .clock width: #{options.size * options.scale}px height: #{options.size * options.scale}px border-radius: 50% background-color: rgba(255,255,255,0.8) box-shadow: 0 0 8px rgba(0,0,0,0.1) if #{options.backgroundBlur} -webkit-backdrop-filter: blur(5px) overflow: hidden .pointer transition: transform #{options.intervalLength}s linear .secPtr position: absolute top: #{options.size * options.scale / 2 - options.secPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.secPtr.width / 2 * options.scale}px width: #{options.secPtr.length * options.scale}px height: #{options.secPtr.width * options.scale}px background-color: #{options.secPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.secPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.secPtr.width / 2 * options.scale}px transform-origin: #{options.secPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .minPtr position: absolute top: #{options.size * options.scale / 2 - options.minPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.minPtr.width / 2 * options.scale}px width: #{options.minPtr.length * options.scale}px height: #{options.minPtr.width * options.scale}px background-color: #{options.minPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.minPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.minPtr.width / 2 * options.scale}px transform-origin: #{options.minPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .hrPtr position: absolute top: #{options.size * options.scale / 2 - options.hrPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.hrPtr.width / 2 * options.scale}px width: #{options.hrPtr.length * options.scale}px height: #{options.hrPtr.width * options.scale}px background-color: #{options.hrPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.hrPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.hrPtr.width / 2 * options.scale}px transform-origin: #{options.minPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .markers > .major position: absolute top: #{options.size * options.scale / 2 - options.majorMarker.width * options.scale / 2}px left: #{options.size * options.scale / 2 - (-options.size / 2 + options.majorMarker.length + options.markerOffset) * options.scale}px width: #{options.majorMarker.length * options.scale}px height: #{options.majorMarker.width * options.scale}px background-color: rgba(0,0,0,0.3) transform-origin: #{(-options.size / 2 + options.majorMarker.length + options.markerOffset) * options.scale}px 50% .markers > .minor position: absolute top: #{options.size * options.scale / 2 - options.minorMarker.width * options.scale / 2}px left: #{options.size * options.scale / 2 - (-options.size / 2 + options.minorMarker.length + options.markerOffset) * options.scale}px width: #{options.minorMarker.length * options.scale}px height: #{options.minorMarker.width * options.scale}px background-color: rgba(0,0,0,0.1) transform-origin: #{(-options.size / 2 + options.minorMarker.length + options.markerOffset) * options.scale}px 50% """
true
# Made by PI:NAME:<NAME>END_PI # Based on SmoothAnalogClock by N00bySumairu # https://github.com/N00bySumairu/SmoothAnalogClock.widget # Begin of styling options options = pos: x: "left: 50px" y: "top: 40px" size: 192 # width of the clock in px scale: 1 # for retina displays set to 2 fontSize: 48 # in px secPtr: color: "rgb(209,97,143)" # css color string width: 1 # in px length: 72 # in px minPtr: color: "rgb(40,40,40)" # css color string width: 1 # in px length: 68 # in px hrPtr: color: "rgb(40,40,40)" # css color string width: 1 # in px length: 44 # in px markerOffset: 4 # offset from the border of the clock in px majorMarker: width: 0.8 # in px length: 24 # in px minorMarker: width: 0.8 # in px length: 16 # in px intervalLength: 30 # interval between the transition triggers in seconds backgroundBlur: false refreshFrequency: "30s" # change this as well when changing the intervalLength # End of styling options render: (_) -> """ <div class="clock"> <div class="markers"></div> <div class="secPtr"></div> <div class="hrPtr"></div> <div class="minPtr"></div> </div> """ afterRender: (domEl) -> # Initialize the markers (I just wanted to keep the render function small and tidy) markers = $(domEl).find('.markers') for i in [0...12] for j in [0...5] id = "" cls = "" if j is 0 id = i+1 cls = "major" else id = (i+1)+"_"+j cls = "minor" rotation = -60 + 6 * (i * 5 + j) markers.append('<div id="'+id+'" class="'+cls+'" style="transform: rotate('+rotation+'deg);"></div>') # Prevent blocking of the clock for the refresh duration after widget refresh setTimeout(@refresh) update: (_, domEl) -> # Use the time elapsed (in ms) since 0:00 of the current day time = Date.now() - (new Date()).setHours(0,0,0,0) div = $(domEl) pointers = div.find('.secPtr, .minPtr, .hrPtr') # Set the rotation of the pointers to what they should be at the current time # (without transition, to prevent the pointer from rotating backwards around the beginning of the day) # Disable transition pointers.removeClass('pointer') div.find('.secPtr').css('transform', 'rotate('+(-90+time/60000*360)+'deg)') div.find('.minPtr').css('transform', 'rotate('+(-90+time/3600000*360)+'deg)') div.find('.hrPtr').css('transform', 'rotate('+(-90+time/43200000*360)+'deg)') # Trigger a reflow, flushing the CSS changes (see http://stackoverflow.com/questions/11131875/what-is-the-cleanest-way-to-disable-css-transition-effects-temporarily) div[0].offsetHeight # Enable transition again pointers.addClass('pointer') # Trigger transition to the rotation of the pointers in 10s time += options.intervalLength * 1000 div.find('.secPtr').css('transform', 'rotate('+(-90+time/60000*360)+'deg)') div.find('.minPtr').css('transform', 'rotate('+(-90+time/3600000*360)+'deg)') div.find('.hrPtr').css('transform', 'rotate('+(-90+time/43200000*360)+'deg)') style: """ #{options.pos.x} #{options.pos.y} .clock width: #{options.size * options.scale}px height: #{options.size * options.scale}px border-radius: 50% background-color: rgba(255,255,255,0.8) box-shadow: 0 0 8px rgba(0,0,0,0.1) if #{options.backgroundBlur} -webkit-backdrop-filter: blur(5px) overflow: hidden .pointer transition: transform #{options.intervalLength}s linear .secPtr position: absolute top: #{options.size * options.scale / 2 - options.secPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.secPtr.width / 2 * options.scale}px width: #{options.secPtr.length * options.scale}px height: #{options.secPtr.width * options.scale}px background-color: #{options.secPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.secPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.secPtr.width / 2 * options.scale}px transform-origin: #{options.secPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .minPtr position: absolute top: #{options.size * options.scale / 2 - options.minPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.minPtr.width / 2 * options.scale}px width: #{options.minPtr.length * options.scale}px height: #{options.minPtr.width * options.scale}px background-color: #{options.minPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.minPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.minPtr.width / 2 * options.scale}px transform-origin: #{options.minPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .hrPtr position: absolute top: #{options.size * options.scale / 2 - options.hrPtr.width * options.scale / 2}px left: #{options.size * options.scale / 2 - options.hrPtr.width / 2 * options.scale}px width: #{options.hrPtr.length * options.scale}px height: #{options.hrPtr.width * options.scale}px background-color: #{options.hrPtr.color} border-left: 0px transparent solid border-top-left-radius: #{options.hrPtr.width / 2 * options.scale}px border-bottom-left-radius: #{options.hrPtr.width / 2 * options.scale}px transform-origin: #{options.minPtr.width / 2 * options.scale}px 50% transform: rotate(-90deg) .markers > .major position: absolute top: #{options.size * options.scale / 2 - options.majorMarker.width * options.scale / 2}px left: #{options.size * options.scale / 2 - (-options.size / 2 + options.majorMarker.length + options.markerOffset) * options.scale}px width: #{options.majorMarker.length * options.scale}px height: #{options.majorMarker.width * options.scale}px background-color: rgba(0,0,0,0.3) transform-origin: #{(-options.size / 2 + options.majorMarker.length + options.markerOffset) * options.scale}px 50% .markers > .minor position: absolute top: #{options.size * options.scale / 2 - options.minorMarker.width * options.scale / 2}px left: #{options.size * options.scale / 2 - (-options.size / 2 + options.minorMarker.length + options.markerOffset) * options.scale}px width: #{options.minorMarker.length * options.scale}px height: #{options.minorMarker.width * options.scale}px background-color: rgba(0,0,0,0.1) transform-origin: #{(-options.size / 2 + options.minorMarker.length + options.markerOffset) * options.scale}px 50% """
[ { "context": "###\n\nbump.js\n\nCopyright (c) 2013 Jairo Luiz\nLicensed under the MIT license.\n\n###\n\nArray.proto", "end": 43, "score": 0.9997796416282654, "start": 33, "tag": "NAME", "value": "Jairo Luiz" } ]
src/lib/bump.coffee
tangerinagames/bump.js
1
### bump.js Copyright (c) 2013 Jairo Luiz Licensed under the MIT license. ### Array.prototype.remove = (item) -> from = @indexOf(item) rest = this.slice(from + 1, @length) @length = if from < 0 then @length + from else from @push.apply(@, rest) class HashMap @_currentItemId = 1 constructor: -> @_dict = {} @_keys = {} put: (key, value) -> if (typeof key is "object") key._hashKey ?= "object:#{HashMap._currentItemId++}" @_dict[key._hashKey] = value @_keys[key._hashKey] = key else @_dict[key] = value get: (key) -> if (typeof key is "object") @_dict[key._hashKey] else @_dict[key] remove: (key) -> if (typeof key is "object") delete @_dict[key._hashKey] else delete @_dict[key] values: -> value for _, value of @_dict keys: -> @_keys[key] or key for key, _ of @_dict class Bump @DEFAULT_CELL_SIZE = 128 # Initializes bump with a cell size. constructor: (@_cellSize = Bump.DEFAULT_CELL_SIZE) -> @_cells = [] @_items = new HashMap() @_prevCollisions = new HashMap() # @Overridable # Called when two objects start colliding dx, dy is how much # you have to move item1 so it doesn't collide any more. collision: (item1, item2, dx, dy) -> # @Overridable # Called when two objects stop colliding. endCollision: (item1, item2) -> # @Overridable # Returns true if two objects can collide, false otherwise. # Useful for making categories, and groups of objects that # don't collide between each other. shouldCollide: (item1, item2) -> true # @Overridable # Given an item, return its bounding box (l, t, w, h). getBBox: (item) -> item.getBBox() # Adds an item to bump. add: (item) -> @_items.put(item, @_items.get(item) or {}) _updateItem.call(@, item) # Adds a static item to bump. Static items never change their # bounding box, and never receive collision checks (other items # can collision with them, but they don't collide with others). addStatic: (item) -> @add(item) @_items.get(item).static = true # Removes an item from bump remove: (item) -> _unregisterItem.call(@, item) @_items.remove(item) # Performs collisions and invokes collision() and endCollision() callbacks # If a world region is specified, only the items in that region are updated. # Else all items are updated. collide: (l, t, w, h) -> _each.call(@, _updateItem, l, t, w, h) @_collisions = new HashMap @_tested = new HashMap _each.call(@, _collideItemWithNeighbors, l, t, w, h) _invokeEndCollision.call(@) @_prevCollisions = @_collisions # Applies a function (signature: function(item) end) to all the items that # "touch" the cells specified by a rectangle. If no rectangle is given, # the function is applied to all items _each = (func, l, t, w, h) -> _eachInRegion.call(@, func, _toGridBox.call(@, l, t, w, h)) # @Private # Given a world coordinate, return the coordinates of the cell # that would contain it. _toGrid = (wx, wy) -> [Math.floor(wx / @_cellSize) + 1, Math.floor(wy / @_cellSize) + 1] # @Private # Same as _toGrid, but useful for calculating the right/bottom # borders of a rectangle (so they are still inside the cell when # touching borders). _toGridFromInside = (wx, wy) -> [Math.ceil(wx / @_cellSize), Math.ceil(wy / @_cellSize)] # @Private # Given a box in world coordinates, return a box in grid coordinates # that contains it returns the x,y coordinates of the top-left cell, # the number of cells to the right and the number of cells down. _toGridBox = (l, t, w, h) -> #return null if not (l and t and w and h) [gl, gt] = _toGrid.call(@, l, t) [gr, gb] = _toGridFromInside.call(@, l + w, t + h) [gl, gt, gr - gl, gb - gt] # Updates the information bump has about one zitem # - its boundingbox, and containing region, center. _updateItem = (item) -> info = @_items.get(item) return if not info or info.static # if the new bounding box is different from the stored one [l, t, w, h] = @getBBox(item) if (l isnt info.l) or (t isnt info.t) or (w isnt info.w) or (h isnt info.h) [gl, gt, gw, gh] = _toGridBox.call(@, l, t, w, h) if (gl isnt info.gl) or (gt isnt info.gt) or (gw isnt info.gw) or (gh isnt info.gh) # remove this item from all the cells that used to contain it _unregisterItem.call(@, item) # update the grid info [info.gl, info.gt, info.gw, info.gh] = [gl, gt, gw, gh] # then add it to the new cells _registerItem.call(@, item) [info.l, info.t, info.w, info.h] = [l, t, w, h] [info.cx, info.cy] = [(l + w * 0.5), (t + h * 0.5)] # Parses the cells touching one item, and removes the item from their # list of items. Does not create new cells. _unregisterItem = (item) -> info = @_items.get(item) if info and info.gl info.unregister ?= (cell) -> cell.remove(item) _eachCellInRegion.call(@, info.unregister, info.gl, info.gt, info.gw, info.gh) # Parses all the cells that touch one item, and add the item to their # list of items. Creates cells if they don't exist. _registerItem = (item, gl, gt, gw, gh) -> info = @_items.get(item) info.register ?= (cell) -> cell.push(item) _eachCellInRegion.call(@, info.register, info.gl, info.gt, info.gw, info.gh, true) # Applies a function to all cells in a given region. # The region must be given in the form of gl, gt, gw, gh # (if the region desired is on world coordinates, it must be transformed # in grid coords with _toGridBox). # If the last parameter is true, the function will also create the cells # as it moves. _eachCellInRegion = (func, gl, gt, gw, gh, create) -> for gy in [gt..(gt + gh)] for gx in [gl..(gl + gw)] cell = _getCell.call(@, gx, gy, create) func.call(@, cell, gx, gy) if cell # Returns a cell, given its coordinates (on grid terms) # If create is true, it creates the cells if they don't exist. _getCell = (gx, gy, create) -> return @_cells[gy]?[gx] if not create @_cells[gy] ?= [] @_cells[gy][gx] ?= [] return @_cells[gy][gx] # Applies f to all the items in the specified region # if no region is specified, apply to all items in bump. _eachInRegion = (func, gl, gt, gw, gh) -> func.call(@, item) for item in _collectItemsInRegion.call(@, gl, gt, gw, gh) # Returns the items in a region, as keys in a table # if no region is specified, returns all items in bump. _collectItemsInRegion = (gl, gt, gw, gh) -> return @_items.keys() unless (gl and gt and gw and gh) items = [] collect = (cell) -> (items = items.concat(cell) if cell) _eachCellInRegion.call(@, collect, gl, gt, gw, gh) return items # Given an item, parse all its neighbors, updating the collisions & tested # tables, and invoking the collision callback if there is a collision, the # list of neighbors is recalculated. However, the sameneighbor is not # checked for collisions twice. Static items are ignored. _collideItemWithNeighbors = (item) -> info = @_items.get(item) return if not info or info.static visited = [] finished = false [neighbor, dx, dy] = [null, 0, 0] while @_items.get(item) and not finished [neighbor, dx, dy] = _getNextCollisionForItem.call(@, item, visited) if neighbor visited.push(neighbor) _collideItemWithNeighbor.call(@, item, neighbor, dx, dy) else finished = true # Given an item and the neighbor which is colliding with it the most, # store the result in the collisions and tested tables # invoke the bump collision callback and mark the collision as # "still happening". _collideItemWithNeighbor = (item, neighbor, dx, dy) -> # store the collision @_collisions.put(item, @_collisions.get(item) or []) @_collisions.get(item).push(neighbor) # invoke the collision callback @collision(item, neighbor, dx, dy) # remove the collision from the "previous collisions" list. # The collisions that remain there will trigger the "endCollision" callback @_prevCollisions.get(item).remove(neighbor) if @_prevCollisions.get(item) # recalculate the item & neighbor (in case they have moved) _updateItem.call(@, item) _updateItem.call(@, neighbor) # mark the couple item-neighbor as tested, so the inverse is not calculated @_tested.put(item, @_tested.get(item) or []) @_tested.get(item).push(neighbor) # Given an item and a list of items to ignore (already visited), # find the neighbor (if any) which is colliding with it the most # (the one who occludes more surface) # returns neighbor, dx, dy or nil if no collisions happen. _getNextCollisionForItem = (item, visited) -> neighbors = _getNeighbors.call(@, item, visited) overlaps = _getOverlaps.call(@, item, neighbors) return _getMaximumAreaOverlap.call(@, overlaps) # Obtain the list of neighbors (list of items touching the cells touched by # item) minus the already visited ones. # The neighbors are returned as keys in a table. _getNeighbors = (item, visited) -> info = @_items.get(item) nbors = _collectItemsInRegion.call(@, info.gl, info.gt, info.gw, info.gh) nbors.remove(item) nbors.remove(v) for v in visited return nbors # Given an item and a list of neighbors, # find the overlaps between the item and each neighbor. # The resulting table has this structure: # { {neighbor=n1, area=1, dx=1, dy=1}, {neighbor=n2, ...} } _getOverlaps = (item, neighbors) -> overlaps = [] info = @_items.get(item) [area, dx, dy, ninfo] = [null, 0, 0, null] for neighbor in neighbors continue unless ninfo = @_items.get(neighbor) continue if (@_tested.get(neighbor) and item in @_tested.get(neighbor)) continue unless _boxesIntersect.call(@, info.l, info.t, info.w, info.h, ninfo.l, ninfo.t, ninfo.w, ninfo.h) continue unless @shouldCollide(item, neighbor) [area, dx, dy] = _getOverlapAndDisplacementVector.call(@, info.l, info.t, info.w, info.h, info.cx, info.cy, ninfo.l, ninfo.t, ninfo.w, ninfo.h, ninfo.cx, ninfo.cy) overlaps.push neighbor: neighbor, area: area, dx: dx, dy: dy return overlaps # Given a table of overlaps in the form { {area=1, ...}, {area=2, ...} }, # find the element with the biggest area, and return element.neighbor, # element.dx, element.dy. Returns nil if the table is empty. _getMaximumAreaOverlap = (overlaps) -> return [null, 0, 0] if overlaps.length == 0 maxOverlap = overlaps[0] for overlap in overlaps maxOverlap = overlap if maxOverlap.area < overlap.area return [maxOverlap.neighbor, maxOverlap.dx, maxOverlap.dy] # Fast check that returns true if 2 boxes are intersecting. _boxesIntersect = (l1,t1,w1,h1, l2,t2,w2,h2) -> return l1 < l2+w2 and l1+w1 > l2 and t1 < t2+h2 and t1+h1 > t2 # Returns the area & minimum displacement vector given two intersecting boxes. _getOverlapAndDisplacementVector=(l1,t1,w1,h1,c1x,c1y, l2,t2,w2,h2,c2x,c2y)-> dx = l2 - l1 + (if c1x < c2x then -w1 else w2) dy = t2 - t1 + (if c1y < c2y then -h1 else h2) [ax, ay] = [Math.abs(dx), Math.abs(dy)] area = ax * ay if ax < ay return [area, dx, 0] else return [area, 0, dy] # Fires endCollision with the appropiate parameters. _invokeEndCollision = -> for item in @_prevCollisions.keys() neighbors = @_prevCollisions.get(item) if @_items.get(item) for neighbor in neighbors if @_items.get(neighbor) @endCollision(item, neighbor) (exports ? this).Bump = Bump
26434
### bump.js Copyright (c) 2013 <NAME> Licensed under the MIT license. ### Array.prototype.remove = (item) -> from = @indexOf(item) rest = this.slice(from + 1, @length) @length = if from < 0 then @length + from else from @push.apply(@, rest) class HashMap @_currentItemId = 1 constructor: -> @_dict = {} @_keys = {} put: (key, value) -> if (typeof key is "object") key._hashKey ?= "object:#{HashMap._currentItemId++}" @_dict[key._hashKey] = value @_keys[key._hashKey] = key else @_dict[key] = value get: (key) -> if (typeof key is "object") @_dict[key._hashKey] else @_dict[key] remove: (key) -> if (typeof key is "object") delete @_dict[key._hashKey] else delete @_dict[key] values: -> value for _, value of @_dict keys: -> @_keys[key] or key for key, _ of @_dict class Bump @DEFAULT_CELL_SIZE = 128 # Initializes bump with a cell size. constructor: (@_cellSize = Bump.DEFAULT_CELL_SIZE) -> @_cells = [] @_items = new HashMap() @_prevCollisions = new HashMap() # @Overridable # Called when two objects start colliding dx, dy is how much # you have to move item1 so it doesn't collide any more. collision: (item1, item2, dx, dy) -> # @Overridable # Called when two objects stop colliding. endCollision: (item1, item2) -> # @Overridable # Returns true if two objects can collide, false otherwise. # Useful for making categories, and groups of objects that # don't collide between each other. shouldCollide: (item1, item2) -> true # @Overridable # Given an item, return its bounding box (l, t, w, h). getBBox: (item) -> item.getBBox() # Adds an item to bump. add: (item) -> @_items.put(item, @_items.get(item) or {}) _updateItem.call(@, item) # Adds a static item to bump. Static items never change their # bounding box, and never receive collision checks (other items # can collision with them, but they don't collide with others). addStatic: (item) -> @add(item) @_items.get(item).static = true # Removes an item from bump remove: (item) -> _unregisterItem.call(@, item) @_items.remove(item) # Performs collisions and invokes collision() and endCollision() callbacks # If a world region is specified, only the items in that region are updated. # Else all items are updated. collide: (l, t, w, h) -> _each.call(@, _updateItem, l, t, w, h) @_collisions = new HashMap @_tested = new HashMap _each.call(@, _collideItemWithNeighbors, l, t, w, h) _invokeEndCollision.call(@) @_prevCollisions = @_collisions # Applies a function (signature: function(item) end) to all the items that # "touch" the cells specified by a rectangle. If no rectangle is given, # the function is applied to all items _each = (func, l, t, w, h) -> _eachInRegion.call(@, func, _toGridBox.call(@, l, t, w, h)) # @Private # Given a world coordinate, return the coordinates of the cell # that would contain it. _toGrid = (wx, wy) -> [Math.floor(wx / @_cellSize) + 1, Math.floor(wy / @_cellSize) + 1] # @Private # Same as _toGrid, but useful for calculating the right/bottom # borders of a rectangle (so they are still inside the cell when # touching borders). _toGridFromInside = (wx, wy) -> [Math.ceil(wx / @_cellSize), Math.ceil(wy / @_cellSize)] # @Private # Given a box in world coordinates, return a box in grid coordinates # that contains it returns the x,y coordinates of the top-left cell, # the number of cells to the right and the number of cells down. _toGridBox = (l, t, w, h) -> #return null if not (l and t and w and h) [gl, gt] = _toGrid.call(@, l, t) [gr, gb] = _toGridFromInside.call(@, l + w, t + h) [gl, gt, gr - gl, gb - gt] # Updates the information bump has about one zitem # - its boundingbox, and containing region, center. _updateItem = (item) -> info = @_items.get(item) return if not info or info.static # if the new bounding box is different from the stored one [l, t, w, h] = @getBBox(item) if (l isnt info.l) or (t isnt info.t) or (w isnt info.w) or (h isnt info.h) [gl, gt, gw, gh] = _toGridBox.call(@, l, t, w, h) if (gl isnt info.gl) or (gt isnt info.gt) or (gw isnt info.gw) or (gh isnt info.gh) # remove this item from all the cells that used to contain it _unregisterItem.call(@, item) # update the grid info [info.gl, info.gt, info.gw, info.gh] = [gl, gt, gw, gh] # then add it to the new cells _registerItem.call(@, item) [info.l, info.t, info.w, info.h] = [l, t, w, h] [info.cx, info.cy] = [(l + w * 0.5), (t + h * 0.5)] # Parses the cells touching one item, and removes the item from their # list of items. Does not create new cells. _unregisterItem = (item) -> info = @_items.get(item) if info and info.gl info.unregister ?= (cell) -> cell.remove(item) _eachCellInRegion.call(@, info.unregister, info.gl, info.gt, info.gw, info.gh) # Parses all the cells that touch one item, and add the item to their # list of items. Creates cells if they don't exist. _registerItem = (item, gl, gt, gw, gh) -> info = @_items.get(item) info.register ?= (cell) -> cell.push(item) _eachCellInRegion.call(@, info.register, info.gl, info.gt, info.gw, info.gh, true) # Applies a function to all cells in a given region. # The region must be given in the form of gl, gt, gw, gh # (if the region desired is on world coordinates, it must be transformed # in grid coords with _toGridBox). # If the last parameter is true, the function will also create the cells # as it moves. _eachCellInRegion = (func, gl, gt, gw, gh, create) -> for gy in [gt..(gt + gh)] for gx in [gl..(gl + gw)] cell = _getCell.call(@, gx, gy, create) func.call(@, cell, gx, gy) if cell # Returns a cell, given its coordinates (on grid terms) # If create is true, it creates the cells if they don't exist. _getCell = (gx, gy, create) -> return @_cells[gy]?[gx] if not create @_cells[gy] ?= [] @_cells[gy][gx] ?= [] return @_cells[gy][gx] # Applies f to all the items in the specified region # if no region is specified, apply to all items in bump. _eachInRegion = (func, gl, gt, gw, gh) -> func.call(@, item) for item in _collectItemsInRegion.call(@, gl, gt, gw, gh) # Returns the items in a region, as keys in a table # if no region is specified, returns all items in bump. _collectItemsInRegion = (gl, gt, gw, gh) -> return @_items.keys() unless (gl and gt and gw and gh) items = [] collect = (cell) -> (items = items.concat(cell) if cell) _eachCellInRegion.call(@, collect, gl, gt, gw, gh) return items # Given an item, parse all its neighbors, updating the collisions & tested # tables, and invoking the collision callback if there is a collision, the # list of neighbors is recalculated. However, the sameneighbor is not # checked for collisions twice. Static items are ignored. _collideItemWithNeighbors = (item) -> info = @_items.get(item) return if not info or info.static visited = [] finished = false [neighbor, dx, dy] = [null, 0, 0] while @_items.get(item) and not finished [neighbor, dx, dy] = _getNextCollisionForItem.call(@, item, visited) if neighbor visited.push(neighbor) _collideItemWithNeighbor.call(@, item, neighbor, dx, dy) else finished = true # Given an item and the neighbor which is colliding with it the most, # store the result in the collisions and tested tables # invoke the bump collision callback and mark the collision as # "still happening". _collideItemWithNeighbor = (item, neighbor, dx, dy) -> # store the collision @_collisions.put(item, @_collisions.get(item) or []) @_collisions.get(item).push(neighbor) # invoke the collision callback @collision(item, neighbor, dx, dy) # remove the collision from the "previous collisions" list. # The collisions that remain there will trigger the "endCollision" callback @_prevCollisions.get(item).remove(neighbor) if @_prevCollisions.get(item) # recalculate the item & neighbor (in case they have moved) _updateItem.call(@, item) _updateItem.call(@, neighbor) # mark the couple item-neighbor as tested, so the inverse is not calculated @_tested.put(item, @_tested.get(item) or []) @_tested.get(item).push(neighbor) # Given an item and a list of items to ignore (already visited), # find the neighbor (if any) which is colliding with it the most # (the one who occludes more surface) # returns neighbor, dx, dy or nil if no collisions happen. _getNextCollisionForItem = (item, visited) -> neighbors = _getNeighbors.call(@, item, visited) overlaps = _getOverlaps.call(@, item, neighbors) return _getMaximumAreaOverlap.call(@, overlaps) # Obtain the list of neighbors (list of items touching the cells touched by # item) minus the already visited ones. # The neighbors are returned as keys in a table. _getNeighbors = (item, visited) -> info = @_items.get(item) nbors = _collectItemsInRegion.call(@, info.gl, info.gt, info.gw, info.gh) nbors.remove(item) nbors.remove(v) for v in visited return nbors # Given an item and a list of neighbors, # find the overlaps between the item and each neighbor. # The resulting table has this structure: # { {neighbor=n1, area=1, dx=1, dy=1}, {neighbor=n2, ...} } _getOverlaps = (item, neighbors) -> overlaps = [] info = @_items.get(item) [area, dx, dy, ninfo] = [null, 0, 0, null] for neighbor in neighbors continue unless ninfo = @_items.get(neighbor) continue if (@_tested.get(neighbor) and item in @_tested.get(neighbor)) continue unless _boxesIntersect.call(@, info.l, info.t, info.w, info.h, ninfo.l, ninfo.t, ninfo.w, ninfo.h) continue unless @shouldCollide(item, neighbor) [area, dx, dy] = _getOverlapAndDisplacementVector.call(@, info.l, info.t, info.w, info.h, info.cx, info.cy, ninfo.l, ninfo.t, ninfo.w, ninfo.h, ninfo.cx, ninfo.cy) overlaps.push neighbor: neighbor, area: area, dx: dx, dy: dy return overlaps # Given a table of overlaps in the form { {area=1, ...}, {area=2, ...} }, # find the element with the biggest area, and return element.neighbor, # element.dx, element.dy. Returns nil if the table is empty. _getMaximumAreaOverlap = (overlaps) -> return [null, 0, 0] if overlaps.length == 0 maxOverlap = overlaps[0] for overlap in overlaps maxOverlap = overlap if maxOverlap.area < overlap.area return [maxOverlap.neighbor, maxOverlap.dx, maxOverlap.dy] # Fast check that returns true if 2 boxes are intersecting. _boxesIntersect = (l1,t1,w1,h1, l2,t2,w2,h2) -> return l1 < l2+w2 and l1+w1 > l2 and t1 < t2+h2 and t1+h1 > t2 # Returns the area & minimum displacement vector given two intersecting boxes. _getOverlapAndDisplacementVector=(l1,t1,w1,h1,c1x,c1y, l2,t2,w2,h2,c2x,c2y)-> dx = l2 - l1 + (if c1x < c2x then -w1 else w2) dy = t2 - t1 + (if c1y < c2y then -h1 else h2) [ax, ay] = [Math.abs(dx), Math.abs(dy)] area = ax * ay if ax < ay return [area, dx, 0] else return [area, 0, dy] # Fires endCollision with the appropiate parameters. _invokeEndCollision = -> for item in @_prevCollisions.keys() neighbors = @_prevCollisions.get(item) if @_items.get(item) for neighbor in neighbors if @_items.get(neighbor) @endCollision(item, neighbor) (exports ? this).Bump = Bump
true
### bump.js Copyright (c) 2013 PI:NAME:<NAME>END_PI Licensed under the MIT license. ### Array.prototype.remove = (item) -> from = @indexOf(item) rest = this.slice(from + 1, @length) @length = if from < 0 then @length + from else from @push.apply(@, rest) class HashMap @_currentItemId = 1 constructor: -> @_dict = {} @_keys = {} put: (key, value) -> if (typeof key is "object") key._hashKey ?= "object:#{HashMap._currentItemId++}" @_dict[key._hashKey] = value @_keys[key._hashKey] = key else @_dict[key] = value get: (key) -> if (typeof key is "object") @_dict[key._hashKey] else @_dict[key] remove: (key) -> if (typeof key is "object") delete @_dict[key._hashKey] else delete @_dict[key] values: -> value for _, value of @_dict keys: -> @_keys[key] or key for key, _ of @_dict class Bump @DEFAULT_CELL_SIZE = 128 # Initializes bump with a cell size. constructor: (@_cellSize = Bump.DEFAULT_CELL_SIZE) -> @_cells = [] @_items = new HashMap() @_prevCollisions = new HashMap() # @Overridable # Called when two objects start colliding dx, dy is how much # you have to move item1 so it doesn't collide any more. collision: (item1, item2, dx, dy) -> # @Overridable # Called when two objects stop colliding. endCollision: (item1, item2) -> # @Overridable # Returns true if two objects can collide, false otherwise. # Useful for making categories, and groups of objects that # don't collide between each other. shouldCollide: (item1, item2) -> true # @Overridable # Given an item, return its bounding box (l, t, w, h). getBBox: (item) -> item.getBBox() # Adds an item to bump. add: (item) -> @_items.put(item, @_items.get(item) or {}) _updateItem.call(@, item) # Adds a static item to bump. Static items never change their # bounding box, and never receive collision checks (other items # can collision with them, but they don't collide with others). addStatic: (item) -> @add(item) @_items.get(item).static = true # Removes an item from bump remove: (item) -> _unregisterItem.call(@, item) @_items.remove(item) # Performs collisions and invokes collision() and endCollision() callbacks # If a world region is specified, only the items in that region are updated. # Else all items are updated. collide: (l, t, w, h) -> _each.call(@, _updateItem, l, t, w, h) @_collisions = new HashMap @_tested = new HashMap _each.call(@, _collideItemWithNeighbors, l, t, w, h) _invokeEndCollision.call(@) @_prevCollisions = @_collisions # Applies a function (signature: function(item) end) to all the items that # "touch" the cells specified by a rectangle. If no rectangle is given, # the function is applied to all items _each = (func, l, t, w, h) -> _eachInRegion.call(@, func, _toGridBox.call(@, l, t, w, h)) # @Private # Given a world coordinate, return the coordinates of the cell # that would contain it. _toGrid = (wx, wy) -> [Math.floor(wx / @_cellSize) + 1, Math.floor(wy / @_cellSize) + 1] # @Private # Same as _toGrid, but useful for calculating the right/bottom # borders of a rectangle (so they are still inside the cell when # touching borders). _toGridFromInside = (wx, wy) -> [Math.ceil(wx / @_cellSize), Math.ceil(wy / @_cellSize)] # @Private # Given a box in world coordinates, return a box in grid coordinates # that contains it returns the x,y coordinates of the top-left cell, # the number of cells to the right and the number of cells down. _toGridBox = (l, t, w, h) -> #return null if not (l and t and w and h) [gl, gt] = _toGrid.call(@, l, t) [gr, gb] = _toGridFromInside.call(@, l + w, t + h) [gl, gt, gr - gl, gb - gt] # Updates the information bump has about one zitem # - its boundingbox, and containing region, center. _updateItem = (item) -> info = @_items.get(item) return if not info or info.static # if the new bounding box is different from the stored one [l, t, w, h] = @getBBox(item) if (l isnt info.l) or (t isnt info.t) or (w isnt info.w) or (h isnt info.h) [gl, gt, gw, gh] = _toGridBox.call(@, l, t, w, h) if (gl isnt info.gl) or (gt isnt info.gt) or (gw isnt info.gw) or (gh isnt info.gh) # remove this item from all the cells that used to contain it _unregisterItem.call(@, item) # update the grid info [info.gl, info.gt, info.gw, info.gh] = [gl, gt, gw, gh] # then add it to the new cells _registerItem.call(@, item) [info.l, info.t, info.w, info.h] = [l, t, w, h] [info.cx, info.cy] = [(l + w * 0.5), (t + h * 0.5)] # Parses the cells touching one item, and removes the item from their # list of items. Does not create new cells. _unregisterItem = (item) -> info = @_items.get(item) if info and info.gl info.unregister ?= (cell) -> cell.remove(item) _eachCellInRegion.call(@, info.unregister, info.gl, info.gt, info.gw, info.gh) # Parses all the cells that touch one item, and add the item to their # list of items. Creates cells if they don't exist. _registerItem = (item, gl, gt, gw, gh) -> info = @_items.get(item) info.register ?= (cell) -> cell.push(item) _eachCellInRegion.call(@, info.register, info.gl, info.gt, info.gw, info.gh, true) # Applies a function to all cells in a given region. # The region must be given in the form of gl, gt, gw, gh # (if the region desired is on world coordinates, it must be transformed # in grid coords with _toGridBox). # If the last parameter is true, the function will also create the cells # as it moves. _eachCellInRegion = (func, gl, gt, gw, gh, create) -> for gy in [gt..(gt + gh)] for gx in [gl..(gl + gw)] cell = _getCell.call(@, gx, gy, create) func.call(@, cell, gx, gy) if cell # Returns a cell, given its coordinates (on grid terms) # If create is true, it creates the cells if they don't exist. _getCell = (gx, gy, create) -> return @_cells[gy]?[gx] if not create @_cells[gy] ?= [] @_cells[gy][gx] ?= [] return @_cells[gy][gx] # Applies f to all the items in the specified region # if no region is specified, apply to all items in bump. _eachInRegion = (func, gl, gt, gw, gh) -> func.call(@, item) for item in _collectItemsInRegion.call(@, gl, gt, gw, gh) # Returns the items in a region, as keys in a table # if no region is specified, returns all items in bump. _collectItemsInRegion = (gl, gt, gw, gh) -> return @_items.keys() unless (gl and gt and gw and gh) items = [] collect = (cell) -> (items = items.concat(cell) if cell) _eachCellInRegion.call(@, collect, gl, gt, gw, gh) return items # Given an item, parse all its neighbors, updating the collisions & tested # tables, and invoking the collision callback if there is a collision, the # list of neighbors is recalculated. However, the sameneighbor is not # checked for collisions twice. Static items are ignored. _collideItemWithNeighbors = (item) -> info = @_items.get(item) return if not info or info.static visited = [] finished = false [neighbor, dx, dy] = [null, 0, 0] while @_items.get(item) and not finished [neighbor, dx, dy] = _getNextCollisionForItem.call(@, item, visited) if neighbor visited.push(neighbor) _collideItemWithNeighbor.call(@, item, neighbor, dx, dy) else finished = true # Given an item and the neighbor which is colliding with it the most, # store the result in the collisions and tested tables # invoke the bump collision callback and mark the collision as # "still happening". _collideItemWithNeighbor = (item, neighbor, dx, dy) -> # store the collision @_collisions.put(item, @_collisions.get(item) or []) @_collisions.get(item).push(neighbor) # invoke the collision callback @collision(item, neighbor, dx, dy) # remove the collision from the "previous collisions" list. # The collisions that remain there will trigger the "endCollision" callback @_prevCollisions.get(item).remove(neighbor) if @_prevCollisions.get(item) # recalculate the item & neighbor (in case they have moved) _updateItem.call(@, item) _updateItem.call(@, neighbor) # mark the couple item-neighbor as tested, so the inverse is not calculated @_tested.put(item, @_tested.get(item) or []) @_tested.get(item).push(neighbor) # Given an item and a list of items to ignore (already visited), # find the neighbor (if any) which is colliding with it the most # (the one who occludes more surface) # returns neighbor, dx, dy or nil if no collisions happen. _getNextCollisionForItem = (item, visited) -> neighbors = _getNeighbors.call(@, item, visited) overlaps = _getOverlaps.call(@, item, neighbors) return _getMaximumAreaOverlap.call(@, overlaps) # Obtain the list of neighbors (list of items touching the cells touched by # item) minus the already visited ones. # The neighbors are returned as keys in a table. _getNeighbors = (item, visited) -> info = @_items.get(item) nbors = _collectItemsInRegion.call(@, info.gl, info.gt, info.gw, info.gh) nbors.remove(item) nbors.remove(v) for v in visited return nbors # Given an item and a list of neighbors, # find the overlaps between the item and each neighbor. # The resulting table has this structure: # { {neighbor=n1, area=1, dx=1, dy=1}, {neighbor=n2, ...} } _getOverlaps = (item, neighbors) -> overlaps = [] info = @_items.get(item) [area, dx, dy, ninfo] = [null, 0, 0, null] for neighbor in neighbors continue unless ninfo = @_items.get(neighbor) continue if (@_tested.get(neighbor) and item in @_tested.get(neighbor)) continue unless _boxesIntersect.call(@, info.l, info.t, info.w, info.h, ninfo.l, ninfo.t, ninfo.w, ninfo.h) continue unless @shouldCollide(item, neighbor) [area, dx, dy] = _getOverlapAndDisplacementVector.call(@, info.l, info.t, info.w, info.h, info.cx, info.cy, ninfo.l, ninfo.t, ninfo.w, ninfo.h, ninfo.cx, ninfo.cy) overlaps.push neighbor: neighbor, area: area, dx: dx, dy: dy return overlaps # Given a table of overlaps in the form { {area=1, ...}, {area=2, ...} }, # find the element with the biggest area, and return element.neighbor, # element.dx, element.dy. Returns nil if the table is empty. _getMaximumAreaOverlap = (overlaps) -> return [null, 0, 0] if overlaps.length == 0 maxOverlap = overlaps[0] for overlap in overlaps maxOverlap = overlap if maxOverlap.area < overlap.area return [maxOverlap.neighbor, maxOverlap.dx, maxOverlap.dy] # Fast check that returns true if 2 boxes are intersecting. _boxesIntersect = (l1,t1,w1,h1, l2,t2,w2,h2) -> return l1 < l2+w2 and l1+w1 > l2 and t1 < t2+h2 and t1+h1 > t2 # Returns the area & minimum displacement vector given two intersecting boxes. _getOverlapAndDisplacementVector=(l1,t1,w1,h1,c1x,c1y, l2,t2,w2,h2,c2x,c2y)-> dx = l2 - l1 + (if c1x < c2x then -w1 else w2) dy = t2 - t1 + (if c1y < c2y then -h1 else h2) [ax, ay] = [Math.abs(dx), Math.abs(dy)] area = ax * ay if ax < ay return [area, dx, 0] else return [area, 0, dy] # Fires endCollision with the appropiate parameters. _invokeEndCollision = -> for item in @_prevCollisions.keys() neighbors = @_prevCollisions.get(item) if @_items.get(item) for neighbor in neighbors if @_items.get(neighbor) @endCollision(item, neighbor) (exports ? this).Bump = Bump
[ { "context": ".sync.args[0][2].success fabricate 'artist', id: 'damien-hershey'\n @templateName = renderStub.args[0][0]\n @t", "end": 468, "score": 0.9904417395591736, "start": 454, "tag": "NAME", "value": "damien-hershey" }, { "context": " @templateOptions.artist.get('id').sh...
apps/artist/test/routes.coffee
kanaabe/microgravity
1
{ fabricate } = require 'antigravity' sinon = require 'sinon' Backbone = require 'backbone' rewire = require 'rewire' routes = rewire '../routes' Q = require 'bluebird-q' describe '#index', -> beforeEach -> sinon.stub Backbone, 'sync' routes.index( { params: { id: 'foo' } } { locals: { sd: {}, asset: (->) }, render: renderStub = sinon.stub(), cacheOnCDN: -> } ) Backbone.sync.args[0][2].success fabricate 'artist', id: 'damien-hershey' @templateName = renderStub.args[0][0] @templateOptions = renderStub.args[0][1] afterEach -> Backbone.sync.restore() it 'renders the post page', -> @templateName.should.equal 'page' @templateOptions.artist.get('id').should.equal 'damien-hershey' describe "#biography", -> beforeEach -> artist = fabricate 'artist', id: 'damien-hershey' routes.__set__ 'metaphysics', => Q.resolve { artist: artist } @req = { params: {} } @res = render: sinon.stub(), locals: sd: sinon.stub() it 'renders the biography page', -> routes.biography @req, @res .then => @res.render.args[0][0].should.equal 'biography' @res.render.args[0][1].artist.id.should.equal 'damien-hershey' describe '#auctionResults', -> beforeEach -> sinon.stub Backbone, 'sync' @req = { params: {} } @res = { locals: { sd: {}, asset: (->) }, render: @render = sinon.stub() } afterEach -> Backbone.sync.restore() it 'renders the auction results page', -> routes.auctionResults(@req, @res) Backbone.sync.args[0][2].success fabricate 'artist' Backbone.sync.args[1][2].success [ fabricate 'auction_result' ] @render.args[0][0].should.equal 'auction_results' @render.args[0][1].auctionResults[0].get('estimate_text').should.containEql '120,000'
19873
{ fabricate } = require 'antigravity' sinon = require 'sinon' Backbone = require 'backbone' rewire = require 'rewire' routes = rewire '../routes' Q = require 'bluebird-q' describe '#index', -> beforeEach -> sinon.stub Backbone, 'sync' routes.index( { params: { id: 'foo' } } { locals: { sd: {}, asset: (->) }, render: renderStub = sinon.stub(), cacheOnCDN: -> } ) Backbone.sync.args[0][2].success fabricate 'artist', id: '<NAME>' @templateName = renderStub.args[0][0] @templateOptions = renderStub.args[0][1] afterEach -> Backbone.sync.restore() it 'renders the post page', -> @templateName.should.equal 'page' @templateOptions.artist.get('id').should.equal '<NAME>' describe "#biography", -> beforeEach -> artist = fabricate 'artist', id: '<NAME>' routes.__set__ 'metaphysics', => Q.resolve { artist: artist } @req = { params: {} } @res = render: sinon.stub(), locals: sd: sinon.stub() it 'renders the biography page', -> routes.biography @req, @res .then => @res.render.args[0][0].should.equal 'biography' @res.render.args[0][1].artist.id.should.equal '<NAME>' describe '#auctionResults', -> beforeEach -> sinon.stub Backbone, 'sync' @req = { params: {} } @res = { locals: { sd: {}, asset: (->) }, render: @render = sinon.stub() } afterEach -> Backbone.sync.restore() it 'renders the auction results page', -> routes.auctionResults(@req, @res) Backbone.sync.args[0][2].success fabricate 'artist' Backbone.sync.args[1][2].success [ fabricate 'auction_result' ] @render.args[0][0].should.equal 'auction_results' @render.args[0][1].auctionResults[0].get('estimate_text').should.containEql '120,000'
true
{ fabricate } = require 'antigravity' sinon = require 'sinon' Backbone = require 'backbone' rewire = require 'rewire' routes = rewire '../routes' Q = require 'bluebird-q' describe '#index', -> beforeEach -> sinon.stub Backbone, 'sync' routes.index( { params: { id: 'foo' } } { locals: { sd: {}, asset: (->) }, render: renderStub = sinon.stub(), cacheOnCDN: -> } ) Backbone.sync.args[0][2].success fabricate 'artist', id: 'PI:NAME:<NAME>END_PI' @templateName = renderStub.args[0][0] @templateOptions = renderStub.args[0][1] afterEach -> Backbone.sync.restore() it 'renders the post page', -> @templateName.should.equal 'page' @templateOptions.artist.get('id').should.equal 'PI:NAME:<NAME>END_PI' describe "#biography", -> beforeEach -> artist = fabricate 'artist', id: 'PI:NAME:<NAME>END_PI' routes.__set__ 'metaphysics', => Q.resolve { artist: artist } @req = { params: {} } @res = render: sinon.stub(), locals: sd: sinon.stub() it 'renders the biography page', -> routes.biography @req, @res .then => @res.render.args[0][0].should.equal 'biography' @res.render.args[0][1].artist.id.should.equal 'PI:NAME:<NAME>END_PI' describe '#auctionResults', -> beforeEach -> sinon.stub Backbone, 'sync' @req = { params: {} } @res = { locals: { sd: {}, asset: (->) }, render: @render = sinon.stub() } afterEach -> Backbone.sync.restore() it 'renders the auction results page', -> routes.auctionResults(@req, @res) Backbone.sync.args[0][2].success fabricate 'artist' Backbone.sync.args[1][2].success [ fabricate 'auction_result' ] @render.args[0][0].should.equal 'auction_results' @render.args[0][1].auctionResults[0].get('estimate_text').should.containEql '120,000'
[ { "context": "BEB']\n neuquen:\n name: 'Neuquen'\n kmlURL: 'Neuquen.kml'\n ", "end": 1274, "score": 0.8642660975456238, "start": 1267, "tag": "NAME", "value": "Neuquen" } ]
app/scripts/main.coffee
rafen/sandbox-elections
0
class Elections constructor: -> # Load charts library google.load 'visualization', '1.0', 'packages': ['corechart'] # Load Map google.maps.event.addDomListener window, 'load', @.initialize # static files @.baseURL = 'http://rafen.webfactional.com/elections2015/kml/' initialize: => @.loadMap() @loadStates() @renderStates() @bindEvents() loadMap: -> @.center = new google.maps.LatLng -40.3863590950962, -63.831314974999984 mapOptions = zoom: 4, center: @.center @.map = new google.maps.Map document.getElementById('map'), mapOptions # Responsive map google.maps.event.addDomListener window, "resize", => center = @.map.getCenter() google.maps.event.trigger @.map, "resize" @.map.setCenter center loadStates: -> @.states = buenosAires: name: 'Ciudad Autonoma de Buenos Aires' kmlURL: 'caba.kml' values: [['PRO', 47.3], ['ECO', 22.3], ['FPV', 18.7], ['IZQ', 2.3], ['Otros', 9.4]] colors: ['#FEDB04', '#7CC374', '#1796D7', '#FFAD5C', '#E0EBEB'] neuquen: name: 'Neuquen' kmlURL: 'Neuquen.kml' values: [['MPN', 37.86], ['FPV', 28.87], ['PRO', 19.45], ['Otros', 33.3]] colors: ['#7CC374', '#1796D7', '#FEDB04', '#E0EBEB'] renderStates: -> for state, values of @.states @.renderState state, values renderState: (state, values) -> @.states[state].kml = new google.maps.KmlLayer url: @.baseURL + values.kmlURL + '?' + Math.random() preserveViewport: true @.states[state].kml.setMap @.map bindEvents: -> for state, values of @.states @.bindEvent state, values bindEvent: (state, values) -> google.maps.event.addListener @.states[state].kml, 'click', (event) => @.renderChart @.states[state].values, @.states[state].name, @.states[state].colors event.featureData.infoWindowHtml = $('#chart_div').html() renderChart: (rows, title, colors) => data = new google.visualization.DataTable() data.addColumn 'string', 'Topping' data.addColumn 'number', 'Slices' data.addRows rows # Set chart options options = title: 'Resultados ' + title width: 350, height: 350 colors: colors # Instantiate and draw our chart, passing in some options. chart = new google.visualization.PieChart document.getElementById 'chart_div' chart.draw data, options # Start the page window.elections = new Elections()
31438
class Elections constructor: -> # Load charts library google.load 'visualization', '1.0', 'packages': ['corechart'] # Load Map google.maps.event.addDomListener window, 'load', @.initialize # static files @.baseURL = 'http://rafen.webfactional.com/elections2015/kml/' initialize: => @.loadMap() @loadStates() @renderStates() @bindEvents() loadMap: -> @.center = new google.maps.LatLng -40.3863590950962, -63.831314974999984 mapOptions = zoom: 4, center: @.center @.map = new google.maps.Map document.getElementById('map'), mapOptions # Responsive map google.maps.event.addDomListener window, "resize", => center = @.map.getCenter() google.maps.event.trigger @.map, "resize" @.map.setCenter center loadStates: -> @.states = buenosAires: name: 'Ciudad Autonoma de Buenos Aires' kmlURL: 'caba.kml' values: [['PRO', 47.3], ['ECO', 22.3], ['FPV', 18.7], ['IZQ', 2.3], ['Otros', 9.4]] colors: ['#FEDB04', '#7CC374', '#1796D7', '#FFAD5C', '#E0EBEB'] neuquen: name: '<NAME>' kmlURL: 'Neuquen.kml' values: [['MPN', 37.86], ['FPV', 28.87], ['PRO', 19.45], ['Otros', 33.3]] colors: ['#7CC374', '#1796D7', '#FEDB04', '#E0EBEB'] renderStates: -> for state, values of @.states @.renderState state, values renderState: (state, values) -> @.states[state].kml = new google.maps.KmlLayer url: @.baseURL + values.kmlURL + '?' + Math.random() preserveViewport: true @.states[state].kml.setMap @.map bindEvents: -> for state, values of @.states @.bindEvent state, values bindEvent: (state, values) -> google.maps.event.addListener @.states[state].kml, 'click', (event) => @.renderChart @.states[state].values, @.states[state].name, @.states[state].colors event.featureData.infoWindowHtml = $('#chart_div').html() renderChart: (rows, title, colors) => data = new google.visualization.DataTable() data.addColumn 'string', 'Topping' data.addColumn 'number', 'Slices' data.addRows rows # Set chart options options = title: 'Resultados ' + title width: 350, height: 350 colors: colors # Instantiate and draw our chart, passing in some options. chart = new google.visualization.PieChart document.getElementById 'chart_div' chart.draw data, options # Start the page window.elections = new Elections()
true
class Elections constructor: -> # Load charts library google.load 'visualization', '1.0', 'packages': ['corechart'] # Load Map google.maps.event.addDomListener window, 'load', @.initialize # static files @.baseURL = 'http://rafen.webfactional.com/elections2015/kml/' initialize: => @.loadMap() @loadStates() @renderStates() @bindEvents() loadMap: -> @.center = new google.maps.LatLng -40.3863590950962, -63.831314974999984 mapOptions = zoom: 4, center: @.center @.map = new google.maps.Map document.getElementById('map'), mapOptions # Responsive map google.maps.event.addDomListener window, "resize", => center = @.map.getCenter() google.maps.event.trigger @.map, "resize" @.map.setCenter center loadStates: -> @.states = buenosAires: name: 'Ciudad Autonoma de Buenos Aires' kmlURL: 'caba.kml' values: [['PRO', 47.3], ['ECO', 22.3], ['FPV', 18.7], ['IZQ', 2.3], ['Otros', 9.4]] colors: ['#FEDB04', '#7CC374', '#1796D7', '#FFAD5C', '#E0EBEB'] neuquen: name: 'PI:NAME:<NAME>END_PI' kmlURL: 'Neuquen.kml' values: [['MPN', 37.86], ['FPV', 28.87], ['PRO', 19.45], ['Otros', 33.3]] colors: ['#7CC374', '#1796D7', '#FEDB04', '#E0EBEB'] renderStates: -> for state, values of @.states @.renderState state, values renderState: (state, values) -> @.states[state].kml = new google.maps.KmlLayer url: @.baseURL + values.kmlURL + '?' + Math.random() preserveViewport: true @.states[state].kml.setMap @.map bindEvents: -> for state, values of @.states @.bindEvent state, values bindEvent: (state, values) -> google.maps.event.addListener @.states[state].kml, 'click', (event) => @.renderChart @.states[state].values, @.states[state].name, @.states[state].colors event.featureData.infoWindowHtml = $('#chart_div').html() renderChart: (rows, title, colors) => data = new google.visualization.DataTable() data.addColumn 'string', 'Topping' data.addColumn 'number', 'Slices' data.addRows rows # Set chart options options = title: 'Resultados ' + title width: 350, height: 350 colors: colors # Instantiate and draw our chart, passing in some options. chart = new google.visualization.PieChart document.getElementById 'chart_div' chart.draw data, options # Start the page window.elections = new Elections()
[ { "context": "\n###\nTest CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)\n###\n\nfs = requi", "end": 37, "score": 0.9998374581336975, "start": 26, "tag": "NAME", "value": "David Worms" }, { "context": "\n###\nTest CSV - Copyright David Worms <open@adaltas.com> (BSD Lic...
servers/nodejs/node_modules/restify/node_modules/csv/test/delimiter.coffee
HyperNexus/crashdumper
186
### Test CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed) ### fs = require 'fs' should = require 'should' csv = if process.env.CSV_COV then require '../lib-cov' else require '../src' describe 'delimiter', -> it 'Test empty value', (next) -> csv() .from.string( """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ ) .transform (record, index) -> record.length.should.eql 5 if index is 0 record[1].should.eql '' record[4].should.eql '' else if index is 1 record[0].should.eql '' record[3].should.eql '' record[4].should.eql '' record .on 'end', (count) -> count.should.eql 2 .to.string (result) -> result.should.eql """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ next() it 'Test tabs to comma', (next) -> csv() .from.string( """ 20322051544\t\t8.8017226E7\t45\t \t1974\t8.8392926E7\t\t """, delimiter: '\t' ) .transform (record, index) -> record.length.should.eql 5 if index is 0 record[1].should.eql '' record[4].should.eql '' else if index is 1 record[0].should.eql '' record[3].should.eql '' record[4].should.eql '' record .on 'end', (count) -> count.should.eql 2 .to.string( (result) -> result.should.eql """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ next() , delimiter: ',' )
166830
### Test CSV - Copyright <NAME> <<EMAIL>> (BSD Licensed) ### fs = require 'fs' should = require 'should' csv = if process.env.CSV_COV then require '../lib-cov' else require '../src' describe 'delimiter', -> it 'Test empty value', (next) -> csv() .from.string( """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ ) .transform (record, index) -> record.length.should.eql 5 if index is 0 record[1].should.eql '' record[4].should.eql '' else if index is 1 record[0].should.eql '' record[3].should.eql '' record[4].should.eql '' record .on 'end', (count) -> count.should.eql 2 .to.string (result) -> result.should.eql """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ next() it 'Test tabs to comma', (next) -> csv() .from.string( """ 20322051544\t\t8.8017226E7\t45\t \t1974\t8.8392926E7\t\t """, delimiter: '\t' ) .transform (record, index) -> record.length.should.eql 5 if index is 0 record[1].should.eql '' record[4].should.eql '' else if index is 1 record[0].should.eql '' record[3].should.eql '' record[4].should.eql '' record .on 'end', (count) -> count.should.eql 2 .to.string( (result) -> result.should.eql """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ next() , delimiter: ',' )
true
### Test CSV - Copyright PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (BSD Licensed) ### fs = require 'fs' should = require 'should' csv = if process.env.CSV_COV then require '../lib-cov' else require '../src' describe 'delimiter', -> it 'Test empty value', (next) -> csv() .from.string( """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ ) .transform (record, index) -> record.length.should.eql 5 if index is 0 record[1].should.eql '' record[4].should.eql '' else if index is 1 record[0].should.eql '' record[3].should.eql '' record[4].should.eql '' record .on 'end', (count) -> count.should.eql 2 .to.string (result) -> result.should.eql """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ next() it 'Test tabs to comma', (next) -> csv() .from.string( """ 20322051544\t\t8.8017226E7\t45\t \t1974\t8.8392926E7\t\t """, delimiter: '\t' ) .transform (record, index) -> record.length.should.eql 5 if index is 0 record[1].should.eql '' record[4].should.eql '' else if index is 1 record[0].should.eql '' record[3].should.eql '' record[4].should.eql '' record .on 'end', (count) -> count.should.eql 2 .to.string( (result) -> result.should.eql """ 20322051544,,8.8017226E7,45, ,1974,8.8392926E7,, """ next() , delimiter: ',' )
[ { "context": " scene allow player to defined options\n*\n* @author David Jegat <david.jegat@gmail.com>\n###\nclass OptionsScene ex", "end": 73, "score": 0.9998897314071655, "start": 62, "tag": "NAME", "value": "David Jegat" }, { "context": "layer to defined options\n*\n* @author Davi...
src/Scene/OptionsScene.coffee
Djeg/MicroRacing
1
###* * This scene allow player to defined options * * @author David Jegat <david.jegat@gmail.com> ### class OptionsScene extends BaseScene ###* * Initialize this scene ### init: () -> ###* * Display the scene ### display: () -> @game.context.fillStyle = "rgb(0, 0, 0)" @game.context.fillText "Pending !", @game.element.width/2, 100
70006
###* * This scene allow player to defined options * * @author <NAME> <<EMAIL>> ### class OptionsScene extends BaseScene ###* * Initialize this scene ### init: () -> ###* * Display the scene ### display: () -> @game.context.fillStyle = "rgb(0, 0, 0)" @game.context.fillText "Pending !", @game.element.width/2, 100
true
###* * This scene allow player to defined options * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### class OptionsScene extends BaseScene ###* * Initialize this scene ### init: () -> ###* * Display the scene ### display: () -> @game.context.fillStyle = "rgb(0, 0, 0)" @game.context.fillText "Pending !", @game.element.width/2, 100
[ { "context": "ill we know if the user is logged in.\n\n @author Sebastian Sachtleben\n###\nclass AuthView extends BaseView\n\t\n\tauthTempla", "end": 248, "score": 0.9998924136161804, "start": 228, "tag": "NAME", "value": "Sebastian Sachtleben" } ]
app/assets/javascripts/shared/views/authView.coffee
ssachtleben/herowar
1
BaseView = require 'views/baseView' templates = require 'templates' app = require 'application' db = require 'database' ### The AuthView shows temporarily the auth view untill we know if the user is logged in. @author Sebastian Sachtleben ### class AuthView extends BaseView authTemplate: templates.get 'auth.tmpl' redirectTo: '' initialize: (options) -> @me = db.get 'ui/me' @realTemplate = @template @bindMeEvents() super() bindMeEvents: -> @listenTo @me, 'change:isGuest change:isUser change:isFetched', @render if @me render: -> if @me.get('isFetched') && @me.get('isGuest') app.navigate @redirectTo, true else if @me.get 'isUser' @template = @realTemplate else @template = @authTemplate super() return AuthView
88229
BaseView = require 'views/baseView' templates = require 'templates' app = require 'application' db = require 'database' ### The AuthView shows temporarily the auth view untill we know if the user is logged in. @author <NAME> ### class AuthView extends BaseView authTemplate: templates.get 'auth.tmpl' redirectTo: '' initialize: (options) -> @me = db.get 'ui/me' @realTemplate = @template @bindMeEvents() super() bindMeEvents: -> @listenTo @me, 'change:isGuest change:isUser change:isFetched', @render if @me render: -> if @me.get('isFetched') && @me.get('isGuest') app.navigate @redirectTo, true else if @me.get 'isUser' @template = @realTemplate else @template = @authTemplate super() return AuthView
true
BaseView = require 'views/baseView' templates = require 'templates' app = require 'application' db = require 'database' ### The AuthView shows temporarily the auth view untill we know if the user is logged in. @author PI:NAME:<NAME>END_PI ### class AuthView extends BaseView authTemplate: templates.get 'auth.tmpl' redirectTo: '' initialize: (options) -> @me = db.get 'ui/me' @realTemplate = @template @bindMeEvents() super() bindMeEvents: -> @listenTo @me, 'change:isGuest change:isUser change:isFetched', @render if @me render: -> if @me.get('isFetched') && @me.get('isGuest') app.navigate @redirectTo, true else if @me.get 'isUser' @template = @realTemplate else @template = @authTemplate super() return AuthView
[ { "context": "\nScaffolded with generator-microjs v0.1.2\n\n@author Daniel Lamb <dlamb.open.source@gmail.com>\n###\n\ndescribe 'gras", "end": 118, "score": 0.9998698234558105, "start": 107, "tag": "NAME", "value": "Daniel Lamb" }, { "context": "th generator-microjs v0.1.2\n\n@author ...
test/spec/grasp.spec.coffee
daniellmb/grasp.js
1
### @file ## Responsibilities - unit test grasp.coffee Scaffolded with generator-microjs v0.1.2 @author Daniel Lamb <dlamb.open.source@gmail.com> ### describe 'grasp.coffee', -> beforeEach -> # add spies it 'should have a working test harness', -> # arrange # act # assert expect(true).not.toBe false it 'should exist', -> # arrange # act # assert expect(typeof graspjs).toBe 'function' it 'should return nothing', -> # arrange # act result = graspjs() # assert expect(result).toBeUndefined()
147261
### @file ## Responsibilities - unit test grasp.coffee Scaffolded with generator-microjs v0.1.2 @author <NAME> <<EMAIL>> ### describe 'grasp.coffee', -> beforeEach -> # add spies it 'should have a working test harness', -> # arrange # act # assert expect(true).not.toBe false it 'should exist', -> # arrange # act # assert expect(typeof graspjs).toBe 'function' it 'should return nothing', -> # arrange # act result = graspjs() # assert expect(result).toBeUndefined()
true
### @file ## Responsibilities - unit test grasp.coffee Scaffolded with generator-microjs v0.1.2 @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### describe 'grasp.coffee', -> beforeEach -> # add spies it 'should have a working test harness', -> # arrange # act # assert expect(true).not.toBe false it 'should exist', -> # arrange # act # assert expect(typeof graspjs).toBe 'function' it 'should return nothing', -> # arrange # act result = graspjs() # assert expect(result).toBeUndefined()
[ { "context": "host == 'localhost'\n assert.ok config.user == 'dbmigrate'\n assert.ok config.password == 'dbmigrate'\n ", "end": 247, "score": 0.9859133958816528, "start": 238, "tag": "USERNAME", "value": "dbmigrate" }, { "context": " == 'dbmigrate'\n assert.ok config.passw...
test/config-loader.coffee
holyshared/db-migrate-diff
0
describe 'configLoader', -> it 'returns an instance of applying the long option', -> config = configLoader(__dirname + '/fixtures/migrations.js', 'development') assert.ok config.host == 'localhost' assert.ok config.user == 'dbmigrate' assert.ok config.password == 'dbmigrate' assert.ok config.database == 'dbmigrate'
59997
describe 'configLoader', -> it 'returns an instance of applying the long option', -> config = configLoader(__dirname + '/fixtures/migrations.js', 'development') assert.ok config.host == 'localhost' assert.ok config.user == 'dbmigrate' assert.ok config.password == '<PASSWORD>' assert.ok config.database == 'dbmigrate'
true
describe 'configLoader', -> it 'returns an instance of applying the long option', -> config = configLoader(__dirname + '/fixtures/migrations.js', 'development') assert.ok config.host == 'localhost' assert.ok config.user == 'dbmigrate' assert.ok config.password == 'PI:PASSWORD:<PASSWORD>END_PI' assert.ok config.database == 'dbmigrate'
[ { "context": " addToken: Promise.coroutine ->\n token = uuid.v4()\n [client, done] = yield db.connect()\n ", "end": 682, "score": 0.8078731298446655, "start": 675, "tag": "KEY", "value": "uuid.v4" } ]
storage/lib/access.coffee
foobert/gc
1
uuid = require 'uuid' Promise = require 'bluebird' module.exports = (db) -> init: Promise.coroutine -> return (yield @getToken()) or (yield @addToken()) check: Promise.coroutine (token) -> return false if not token? [client, done] = yield db.connect() try sql = db.select() .from 'tokens' .field 'id' .where 'id = ?', token .toString() result = yield client.queryAsync sql return result.rowCount is 1 catch err return false finally done() addToken: Promise.coroutine -> token = uuid.v4() [client, done] = yield db.connect() try sql = db.insert() .into 'tokens' .set 'id', token .toString() result = yield client.queryAsync sql return token finally done() getToken: Promise.coroutine -> [client, done] = yield db.connect() try sql = db.select() .from 'tokens' .field 'id' .limit 1 .toString() result = yield client.queryAsync sql if result.rowCount is 0 return null else return result.rows[0].id finally done()
19994
uuid = require 'uuid' Promise = require 'bluebird' module.exports = (db) -> init: Promise.coroutine -> return (yield @getToken()) or (yield @addToken()) check: Promise.coroutine (token) -> return false if not token? [client, done] = yield db.connect() try sql = db.select() .from 'tokens' .field 'id' .where 'id = ?', token .toString() result = yield client.queryAsync sql return result.rowCount is 1 catch err return false finally done() addToken: Promise.coroutine -> token = <KEY>() [client, done] = yield db.connect() try sql = db.insert() .into 'tokens' .set 'id', token .toString() result = yield client.queryAsync sql return token finally done() getToken: Promise.coroutine -> [client, done] = yield db.connect() try sql = db.select() .from 'tokens' .field 'id' .limit 1 .toString() result = yield client.queryAsync sql if result.rowCount is 0 return null else return result.rows[0].id finally done()
true
uuid = require 'uuid' Promise = require 'bluebird' module.exports = (db) -> init: Promise.coroutine -> return (yield @getToken()) or (yield @addToken()) check: Promise.coroutine (token) -> return false if not token? [client, done] = yield db.connect() try sql = db.select() .from 'tokens' .field 'id' .where 'id = ?', token .toString() result = yield client.queryAsync sql return result.rowCount is 1 catch err return false finally done() addToken: Promise.coroutine -> token = PI:KEY:<KEY>END_PI() [client, done] = yield db.connect() try sql = db.insert() .into 'tokens' .set 'id', token .toString() result = yield client.queryAsync sql return token finally done() getToken: Promise.coroutine -> [client, done] = yield db.connect() try sql = db.select() .from 'tokens' .field 'id' .limit 1 .toString() result = yield client.queryAsync sql if result.rowCount is 0 return null else return result.rows[0].id finally done()
[ { "context": " 'alice'\n errors:\n password: 'missing'\n reason: 'bad credentials'\n $htt", "end": 1477, "score": 0.9980841875076294, "start": 1470, "tag": "PASSWORD", "value": "missing" }, { "context": "ure and send the xsrf token', ->\n to...
tests/js/session-service-test.coffee
Treora/h
0
assert = chai.assert sinon.assert.expose assert, prefix: null sandbox = sinon.sandbox.create() mockFlash = sandbox.spy() mockDocumentHelpers = {absoluteURI: -> '/session'} describe 'session', -> beforeEach module('h.session') beforeEach module ($provide, sessionProvider) -> $provide.value 'documentHelpers', mockDocumentHelpers $provide.value 'flash', mockFlash sessionProvider.actions = login: url: '/login' method: 'POST' return afterEach -> sandbox.restore() describe 'sessionService', -> $httpBackend = null session = null xsrf = null beforeEach inject (_$httpBackend_, _session_, _xsrf_) -> $httpBackend = _$httpBackend_ session = _session_ xsrf = _xsrf_ describe '#<action>()', -> url = '/login' it 'should send an HTTP POST to the action', -> $httpBackend.expectPOST(url, code: 123).respond({}) result = session.login(code: 123) $httpBackend.flush() it 'should invoke the flash service with any flash messages', -> response = flash: error: 'fail' $httpBackend.expectPOST(url).respond(response) result = session.login({}) $httpBackend.flush() assert.calledWith mockFlash, 'error', 'fail' it 'should assign errors and status reasons to the model', -> response = model: userid: 'alice' errors: password: 'missing' reason: 'bad credentials' $httpBackend.expectPOST(url).respond(response) result = session.login({}) $httpBackend.flush() assert.match result, response.model, 'the model is present' assert.match result.errors, response.errors, 'the errors are present' assert.match result.reason, response.reason, 'the reason is present' it 'should capture and send the xsrf token', -> token = 'deadbeef' headers = 'Accept': 'application/json, text/plain, */*' 'Content-Type': 'application/json;charset=utf-8' 'X-XSRF-TOKEN': token model = {csrf: token} request = $httpBackend.expectPOST(url).respond({model}) result = session.login({}) $httpBackend.flush() assert.equal xsrf.token, token $httpBackend.expectPOST(url, {}, headers).respond({}) session.login({}) $httpBackend.flush()
160625
assert = chai.assert sinon.assert.expose assert, prefix: null sandbox = sinon.sandbox.create() mockFlash = sandbox.spy() mockDocumentHelpers = {absoluteURI: -> '/session'} describe 'session', -> beforeEach module('h.session') beforeEach module ($provide, sessionProvider) -> $provide.value 'documentHelpers', mockDocumentHelpers $provide.value 'flash', mockFlash sessionProvider.actions = login: url: '/login' method: 'POST' return afterEach -> sandbox.restore() describe 'sessionService', -> $httpBackend = null session = null xsrf = null beforeEach inject (_$httpBackend_, _session_, _xsrf_) -> $httpBackend = _$httpBackend_ session = _session_ xsrf = _xsrf_ describe '#<action>()', -> url = '/login' it 'should send an HTTP POST to the action', -> $httpBackend.expectPOST(url, code: 123).respond({}) result = session.login(code: 123) $httpBackend.flush() it 'should invoke the flash service with any flash messages', -> response = flash: error: 'fail' $httpBackend.expectPOST(url).respond(response) result = session.login({}) $httpBackend.flush() assert.calledWith mockFlash, 'error', 'fail' it 'should assign errors and status reasons to the model', -> response = model: userid: 'alice' errors: password: '<PASSWORD>' reason: 'bad credentials' $httpBackend.expectPOST(url).respond(response) result = session.login({}) $httpBackend.flush() assert.match result, response.model, 'the model is present' assert.match result.errors, response.errors, 'the errors are present' assert.match result.reason, response.reason, 'the reason is present' it 'should capture and send the xsrf token', -> token = '<KEY>' headers = 'Accept': 'application/json, text/plain, */*' 'Content-Type': 'application/json;charset=utf-8' 'X-XSRF-TOKEN': token model = {csrf: token} request = $httpBackend.expectPOST(url).respond({model}) result = session.login({}) $httpBackend.flush() assert.equal xsrf.token, token $httpBackend.expectPOST(url, {}, headers).respond({}) session.login({}) $httpBackend.flush()
true
assert = chai.assert sinon.assert.expose assert, prefix: null sandbox = sinon.sandbox.create() mockFlash = sandbox.spy() mockDocumentHelpers = {absoluteURI: -> '/session'} describe 'session', -> beforeEach module('h.session') beforeEach module ($provide, sessionProvider) -> $provide.value 'documentHelpers', mockDocumentHelpers $provide.value 'flash', mockFlash sessionProvider.actions = login: url: '/login' method: 'POST' return afterEach -> sandbox.restore() describe 'sessionService', -> $httpBackend = null session = null xsrf = null beforeEach inject (_$httpBackend_, _session_, _xsrf_) -> $httpBackend = _$httpBackend_ session = _session_ xsrf = _xsrf_ describe '#<action>()', -> url = '/login' it 'should send an HTTP POST to the action', -> $httpBackend.expectPOST(url, code: 123).respond({}) result = session.login(code: 123) $httpBackend.flush() it 'should invoke the flash service with any flash messages', -> response = flash: error: 'fail' $httpBackend.expectPOST(url).respond(response) result = session.login({}) $httpBackend.flush() assert.calledWith mockFlash, 'error', 'fail' it 'should assign errors and status reasons to the model', -> response = model: userid: 'alice' errors: password: 'PI:PASSWORD:<PASSWORD>END_PI' reason: 'bad credentials' $httpBackend.expectPOST(url).respond(response) result = session.login({}) $httpBackend.flush() assert.match result, response.model, 'the model is present' assert.match result.errors, response.errors, 'the errors are present' assert.match result.reason, response.reason, 'the reason is present' it 'should capture and send the xsrf token', -> token = 'PI:KEY:<KEY>END_PI' headers = 'Accept': 'application/json, text/plain, */*' 'Content-Type': 'application/json;charset=utf-8' 'X-XSRF-TOKEN': token model = {csrf: token} request = $httpBackend.expectPOST(url).respond({model}) result = session.login({}) $httpBackend.flush() assert.equal xsrf.token, token $httpBackend.expectPOST(url, {}, headers).respond({}) session.login({}) $httpBackend.flush()
[ { "context": "\n\n requests[0].respond(200, undefined, '[bob, steve, kate]')\n\n\n it 'should check the response if a", "end": 5488, "score": 0.6469221711158752, "start": 5483, "tag": "NAME", "value": "steve" }, { "context": "equests[0].respond(200, undefined, '[bob, steve, k...
src/utils/request/spec.coffee
p-koscielniak/hexagonjs
61
import { request, html, text, json, reshapedRequest } from 'utils/request' import logger from 'utils/logger' describe 'Request API', -> defaultCb = chai.spy() xhr = undefined requests = undefined beforeEach -> xhr = sinon.useFakeXMLHttpRequest() requests = [] xhr.onCreate = (req) -> requests.push(req) XMLHttpRequest.prototype.overrideMimeType = (mimeType) -> this["Content-Type"] = mimeType afterEach -> xhr.restore() describe 'request', -> it 'should use GET by default as the request type when no data is provided', -> request 'test.file', defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should use POST by default as the request type when data is provided', -> request 'test.file', {some: 'data'}, defaultCb requests.length.should.equal(1) requests[0].method.should.equal('POST') requests[0].url.should.equal('test.file') requests[0].requestBody.should.equal(JSON.stringify {some: 'data'}) it 'should correctly set the requestType', -> options = requestType: 'PUT' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('PUT') it 'should correctly set the content type', -> options = contentType: 'some/type' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['Content-Type'].should.equal('some/type;charset=utf-8') it 'should correctly set the response type', -> options = responseType: 'some/type' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].responseType.should.equal('some/type') it 'should allow headers to be explicitly set', -> options = contentType: 'application/json' headers: 'Content-Type': 'something' 'accept': 'everything' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['Content-Type'].should.equal('something;charset=utf-8') requests[0].requestHeaders['accept'].should.equal('everything') it 'should allow custom headers to be set', -> options = headers: custom: 'some custom thing' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['custom'].should.equal('some custom thing') it 'should thrown an error when an incorrect url is passed in', -> origError = console.error console.error = chai.spy() request defaultCb console.error.should.have.been.called.with('Incorrect URL passed into request: ', defaultCb) arr = [] request arr console.error.should.have.been.called.with('Incorrect URL passed into request: ', arr) it 'should pass the correct data to the callback', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.responseText.should.equal('Some text') request 'test.file', cb requests[0].respond(200, undefined, 'Some text') it 'should return the correct source when data is not provided', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.equal('test.file') request 'test.file', cb requests[0].respond(200) it 'should return the correct source when data is provided', -> data = {some: 'data'} cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: data}) request 'test.file', data, cb requests[0].respond(200) it 'should deal with status 304 (cached response)', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.responseText.should.equal('Some text') request 'test.file', cb requests[0].respond(304, undefined, 'Some text') it 'should return an error when an error status is returned', -> cb = (error, result, source, index) -> should.exist(error) should.not.exist(result) error.status.should.equal(404) request 'test.file', cb requests[0].respond(404) it 'should format the response data correctly when one is passed in', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.should.eql({some: 'data'}) opts = formatter: (r) -> JSON.parse r.responseText request 'test.file', cb, opts requests[0].respond(200, undefined, '{"some":"data"}') it 'should return an error when there is an error with the formatter', -> cb = (error, result, source, index) -> should.exist(error.message) should.not.exist(result) source.should.equal('test.file') opts = formatter: (r) -> JSON.parse(r.responseText) request 'test.file', cb, opts requests[0].respond(200, undefined, '[bob, steve, kate]') it 'should check the response if a response type is defined', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) requests[0].responseType.should.equal("arraybuffer") requests[0].response.should.be.instanceOf(ArrayBuffer) opts = responseType: "arraybuffer" request 'test.file', cb, opts requests[0].respond(200, {"Content-Type": "application/octet-stream"}, '01010011 01101111 01101101 01100101 00100000 01110100 01100101 01111000 01110100') describe 'with url as an object', -> it 'should handle sending a request without data', -> url = url: 'test.file' request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a request with data in the arguments', -> url = url: 'test.file' data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending a request with data in the object', -> data = {some: 'data'} url = url: 'test.file' data: data request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should send the object data instead of the provided data', -> data = {some: 'data'} objectData = {some: 'other data'} url = url: 'test.file' data: objectData request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify objectData) it 'should return the correct source in the response', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.equal('test.file') cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: data}) cb3 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: objData}) cb4 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: objData}) data = {some: 'data'} objData = {some: 'other data'} url = url: 'test.file' request url, cb1 requests[0].respond(200) request url, data, cb2 requests[1].respond(200) url.data = objData request url, cb3 requests[2].respond(200) request url, data, cb4 requests[3].respond(200) describe 'with url as an array', -> it 'should handle sending a single request without data', -> url = ['test.file'] request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a single request with data', -> url = ['test.file'] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests without data', -> url = ['test1.file', 'test2.file'] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') it 'should handle sending multiple requests with data', -> url = ['test1.file', 'test2.file'] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests of different types', -> data = {some: 'data'} url = ['test1.file', {url: 'test2.file'}, {url: 'test3.file', data: data}] request url, defaultCb requests.length.should.equal(3) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') should.not.exist(requests[1].requestBody) requests[2].url.should.equal('test3.file') requests[2].method.should.equal('POST') requests[2].requestBody.should.equal(JSON.stringify data) it 'should return the correct source in all the responses', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.equal('test1.file') when 1 then source.should.equal('test2.file') else source.should.eql(['test1.file', 'test2.file']) cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.eql({url: 'test1.file', data: data}) when 1 then source.should.eql({url: 'test2.file', data: data}) else source.should.eql([{url: 'test1.file', data: data}, {url: 'test2.file', data: data}]) url = [ 'test1.file' 'test2.file' ] request url, cb1 requests[0].respond(200) requests[1].respond(200) data = {some: 'data'} request url, data, cb2 requests[2].respond(200) requests[3].respond(200) it 'should call set the index based on the order the urls were called, not the order they return', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) if index isnt -1 responses[index] = true source.should.equal(urls[index]) else source.should.eql(urls) responses = {} urls = [ 'test1.file' 'test2.file' ] request urls, cb requests[1].respond(200) responses[1].should.equal(true) requests[0].respond(200) responses[0].should.equal(true) describe 'of objects', -> it 'should handle sending a single request without data', -> url = [{url: 'test.file'}] request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a single request with data', -> url = [{url: 'test.file'}] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending a single request with data in the object', -> data = {some: 'data'} url = [{url: 'test.file', data: data}] request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests without data', -> url = [{url: 'test1.file'}, {url: 'test2.file'}] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') it 'should handle sending multiple requests with data', -> url = [{url: 'test1.file'}, {url: 'test2.file'}] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests with data in one of the objects', -> data = {some: 'data'} url = [{url: 'test1.file'}, {url: 'test2.file', data: data}] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests with data and data in one of the objects', -> data = {some: 'data'} objectData = {some: 'other data'} url = [{url: 'test1.file'}, {url: 'test2.file', data: objectData}] request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify objectData) it 'should return the correct source in all the responses', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.equal('test1.file') when 1 then source.should.eql({url: 'test2.file', data: objData}) else source.should.eql(['test1.file', {url: 'test2.file', data: objData}]) cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.eql({url: 'test1.file', data: data}) when 1 then source.should.eql({url: 'test2.file', data: objData}) else source.should.eql([{url: 'test1.file', data: data}, {url: 'test2.file', data: objData}]) objData = {some: 'other data'} url = [ { url: 'test1.file' } { url: 'test2.file' data: objData } ] request url, cb1 requests[0].respond(200) requests[1].respond(200) data = {some: 'data'} request url, data, cb2 requests[2].respond(200) requests[3].respond(200) describe 'html', -> it 'should correctly set the mimeType to text/html', -> html 'test.html', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('text/html;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should format and return the correct data', -> test = '<div class="parent"><span class="child">bob</span></div>' cb = (error, result, source, index) -> should.not.exist(error) result.toString().should.equal('[object DocumentFragment]') result.childNodes.length.should.equal(1) result.childNodes[0].className.should.equal('parent') result.childNodes[0].childNodes[0].className.should.equal('child') html 'test.html', cb requests[0].requestHeaders["Content-Type"].should.equal('text/html;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[0].respond(200, undefined, test) it 'should pass the data through', -> data = {some: 'data'} html 'test.html', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) describe 'text', -> it 'should correctly set the mimeType to text/plain', -> text 'test.txt', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('text/plain;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should correctly format and return the correct data', (done) -> cb = (error, result) -> should.not.exist(error) result.should.equal('Test data') done() text 'test.txt', cb requests[0].respond(200, undefined, 'Test data') it 'should pass the data through', -> data = {some: 'data'} text 'test.txt', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) describe 'reshapedRequest', -> describe 'should format and return the correct data', -> it 'for json', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() reshapedRequest 'test.json', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": "application/json"}, '{"some": "data"}') it 'even when there is a charset', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() reshapedRequest 'test.json', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'application/json;charset=UTF-8'}, '{"some": "data"}') it 'for html', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.toString().should.equal('[object DocumentFragment]') result.childNodes.length.should.equal(1) result.childNodes[0].className.should.equal('parent') result.childNodes[0].childNodes[0].className.should.equal('child') done() reshapedRequest 'test.html', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'text/html'}, '<div class="parent"><span class="child">bob</span></div>') it 'should pass the data through', -> data = {some: 'data'} json 'test.json', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) it 'should log a warning when the content type defined is not text, json or plain', (done) -> origConsoleWarning = logger.warn logger.warn = chai.spy() cb = (error, result, source) -> should.not.exist(error) should.exist(result) logger.warn.should.have.been.called.with("Unknown parser for mime type application/octet-stream, carrying on anyway") done() reshapedRequest 'test.bin', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'application/octet-stream'}, '1011010010011101010010') describe 'json', -> it 'should correctly set the mimeType to application/json', -> json 'test.json', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('application/json;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should format and return the correct data', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() json 'test.json', cb requests[0].requestHeaders["Content-Type"].should.equal('application/json;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[0].respond(200, undefined, '{"some": "data"}') it 'should pass the data through', -> data = {some: 'data'} json 'test.json', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle undefined as the response', (done) -> cb = (error, result, source) -> should.not.exist(error) should.not.exist(result) done() json 'test.json', cb requests[0].respond(200, undefined, undefined)
13905
import { request, html, text, json, reshapedRequest } from 'utils/request' import logger from 'utils/logger' describe 'Request API', -> defaultCb = chai.spy() xhr = undefined requests = undefined beforeEach -> xhr = sinon.useFakeXMLHttpRequest() requests = [] xhr.onCreate = (req) -> requests.push(req) XMLHttpRequest.prototype.overrideMimeType = (mimeType) -> this["Content-Type"] = mimeType afterEach -> xhr.restore() describe 'request', -> it 'should use GET by default as the request type when no data is provided', -> request 'test.file', defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should use POST by default as the request type when data is provided', -> request 'test.file', {some: 'data'}, defaultCb requests.length.should.equal(1) requests[0].method.should.equal('POST') requests[0].url.should.equal('test.file') requests[0].requestBody.should.equal(JSON.stringify {some: 'data'}) it 'should correctly set the requestType', -> options = requestType: 'PUT' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('PUT') it 'should correctly set the content type', -> options = contentType: 'some/type' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['Content-Type'].should.equal('some/type;charset=utf-8') it 'should correctly set the response type', -> options = responseType: 'some/type' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].responseType.should.equal('some/type') it 'should allow headers to be explicitly set', -> options = contentType: 'application/json' headers: 'Content-Type': 'something' 'accept': 'everything' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['Content-Type'].should.equal('something;charset=utf-8') requests[0].requestHeaders['accept'].should.equal('everything') it 'should allow custom headers to be set', -> options = headers: custom: 'some custom thing' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['custom'].should.equal('some custom thing') it 'should thrown an error when an incorrect url is passed in', -> origError = console.error console.error = chai.spy() request defaultCb console.error.should.have.been.called.with('Incorrect URL passed into request: ', defaultCb) arr = [] request arr console.error.should.have.been.called.with('Incorrect URL passed into request: ', arr) it 'should pass the correct data to the callback', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.responseText.should.equal('Some text') request 'test.file', cb requests[0].respond(200, undefined, 'Some text') it 'should return the correct source when data is not provided', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.equal('test.file') request 'test.file', cb requests[0].respond(200) it 'should return the correct source when data is provided', -> data = {some: 'data'} cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: data}) request 'test.file', data, cb requests[0].respond(200) it 'should deal with status 304 (cached response)', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.responseText.should.equal('Some text') request 'test.file', cb requests[0].respond(304, undefined, 'Some text') it 'should return an error when an error status is returned', -> cb = (error, result, source, index) -> should.exist(error) should.not.exist(result) error.status.should.equal(404) request 'test.file', cb requests[0].respond(404) it 'should format the response data correctly when one is passed in', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.should.eql({some: 'data'}) opts = formatter: (r) -> JSON.parse r.responseText request 'test.file', cb, opts requests[0].respond(200, undefined, '{"some":"data"}') it 'should return an error when there is an error with the formatter', -> cb = (error, result, source, index) -> should.exist(error.message) should.not.exist(result) source.should.equal('test.file') opts = formatter: (r) -> JSON.parse(r.responseText) request 'test.file', cb, opts requests[0].respond(200, undefined, '[bob, <NAME>, k<NAME>]') it 'should check the response if a response type is defined', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) requests[0].responseType.should.equal("arraybuffer") requests[0].response.should.be.instanceOf(ArrayBuffer) opts = responseType: "arraybuffer" request 'test.file', cb, opts requests[0].respond(200, {"Content-Type": "application/octet-stream"}, '01010011 01101111 01101101 01100101 00100000 01110100 01100101 01111000 01110100') describe 'with url as an object', -> it 'should handle sending a request without data', -> url = url: 'test.file' request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a request with data in the arguments', -> url = url: 'test.file' data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending a request with data in the object', -> data = {some: 'data'} url = url: 'test.file' data: data request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should send the object data instead of the provided data', -> data = {some: 'data'} objectData = {some: 'other data'} url = url: 'test.file' data: objectData request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify objectData) it 'should return the correct source in the response', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.equal('test.file') cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: data}) cb3 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: objData}) cb4 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: objData}) data = {some: 'data'} objData = {some: 'other data'} url = url: 'test.file' request url, cb1 requests[0].respond(200) request url, data, cb2 requests[1].respond(200) url.data = objData request url, cb3 requests[2].respond(200) request url, data, cb4 requests[3].respond(200) describe 'with url as an array', -> it 'should handle sending a single request without data', -> url = ['test.file'] request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a single request with data', -> url = ['test.file'] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests without data', -> url = ['test1.file', 'test2.file'] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') it 'should handle sending multiple requests with data', -> url = ['test1.file', 'test2.file'] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests of different types', -> data = {some: 'data'} url = ['test1.file', {url: 'test2.file'}, {url: 'test3.file', data: data}] request url, defaultCb requests.length.should.equal(3) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') should.not.exist(requests[1].requestBody) requests[2].url.should.equal('test3.file') requests[2].method.should.equal('POST') requests[2].requestBody.should.equal(JSON.stringify data) it 'should return the correct source in all the responses', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.equal('test1.file') when 1 then source.should.equal('test2.file') else source.should.eql(['test1.file', 'test2.file']) cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.eql({url: 'test1.file', data: data}) when 1 then source.should.eql({url: 'test2.file', data: data}) else source.should.eql([{url: 'test1.file', data: data}, {url: 'test2.file', data: data}]) url = [ 'test1.file' 'test2.file' ] request url, cb1 requests[0].respond(200) requests[1].respond(200) data = {some: 'data'} request url, data, cb2 requests[2].respond(200) requests[3].respond(200) it 'should call set the index based on the order the urls were called, not the order they return', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) if index isnt -1 responses[index] = true source.should.equal(urls[index]) else source.should.eql(urls) responses = {} urls = [ 'test1.file' 'test2.file' ] request urls, cb requests[1].respond(200) responses[1].should.equal(true) requests[0].respond(200) responses[0].should.equal(true) describe 'of objects', -> it 'should handle sending a single request without data', -> url = [{url: 'test.file'}] request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a single request with data', -> url = [{url: 'test.file'}] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending a single request with data in the object', -> data = {some: 'data'} url = [{url: 'test.file', data: data}] request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests without data', -> url = [{url: 'test1.file'}, {url: 'test2.file'}] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') it 'should handle sending multiple requests with data', -> url = [{url: 'test1.file'}, {url: 'test2.file'}] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests with data in one of the objects', -> data = {some: 'data'} url = [{url: 'test1.file'}, {url: 'test2.file', data: data}] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests with data and data in one of the objects', -> data = {some: 'data'} objectData = {some: 'other data'} url = [{url: 'test1.file'}, {url: 'test2.file', data: objectData}] request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify objectData) it 'should return the correct source in all the responses', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.equal('test1.file') when 1 then source.should.eql({url: 'test2.file', data: objData}) else source.should.eql(['test1.file', {url: 'test2.file', data: objData}]) cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.eql({url: 'test1.file', data: data}) when 1 then source.should.eql({url: 'test2.file', data: objData}) else source.should.eql([{url: 'test1.file', data: data}, {url: 'test2.file', data: objData}]) objData = {some: 'other data'} url = [ { url: 'test1.file' } { url: 'test2.file' data: objData } ] request url, cb1 requests[0].respond(200) requests[1].respond(200) data = {some: 'data'} request url, data, cb2 requests[2].respond(200) requests[3].respond(200) describe 'html', -> it 'should correctly set the mimeType to text/html', -> html 'test.html', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('text/html;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should format and return the correct data', -> test = '<div class="parent"><span class="child">bob</span></div>' cb = (error, result, source, index) -> should.not.exist(error) result.toString().should.equal('[object DocumentFragment]') result.childNodes.length.should.equal(1) result.childNodes[0].className.should.equal('parent') result.childNodes[0].childNodes[0].className.should.equal('child') html 'test.html', cb requests[0].requestHeaders["Content-Type"].should.equal('text/html;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[0].respond(200, undefined, test) it 'should pass the data through', -> data = {some: 'data'} html 'test.html', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) describe 'text', -> it 'should correctly set the mimeType to text/plain', -> text 'test.txt', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('text/plain;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should correctly format and return the correct data', (done) -> cb = (error, result) -> should.not.exist(error) result.should.equal('Test data') done() text 'test.txt', cb requests[0].respond(200, undefined, 'Test data') it 'should pass the data through', -> data = {some: 'data'} text 'test.txt', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) describe 'reshapedRequest', -> describe 'should format and return the correct data', -> it 'for json', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() reshapedRequest 'test.json', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": "application/json"}, '{"some": "data"}') it 'even when there is a charset', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() reshapedRequest 'test.json', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'application/json;charset=UTF-8'}, '{"some": "data"}') it 'for html', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.toString().should.equal('[object DocumentFragment]') result.childNodes.length.should.equal(1) result.childNodes[0].className.should.equal('parent') result.childNodes[0].childNodes[0].className.should.equal('child') done() reshapedRequest 'test.html', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'text/html'}, '<div class="parent"><span class="child">bob</span></div>') it 'should pass the data through', -> data = {some: 'data'} json 'test.json', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) it 'should log a warning when the content type defined is not text, json or plain', (done) -> origConsoleWarning = logger.warn logger.warn = chai.spy() cb = (error, result, source) -> should.not.exist(error) should.exist(result) logger.warn.should.have.been.called.with("Unknown parser for mime type application/octet-stream, carrying on anyway") done() reshapedRequest 'test.bin', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'application/octet-stream'}, '1011010010011101010010') describe 'json', -> it 'should correctly set the mimeType to application/json', -> json 'test.json', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('application/json;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should format and return the correct data', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() json 'test.json', cb requests[0].requestHeaders["Content-Type"].should.equal('application/json;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[0].respond(200, undefined, '{"some": "data"}') it 'should pass the data through', -> data = {some: 'data'} json 'test.json', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle undefined as the response', (done) -> cb = (error, result, source) -> should.not.exist(error) should.not.exist(result) done() json 'test.json', cb requests[0].respond(200, undefined, undefined)
true
import { request, html, text, json, reshapedRequest } from 'utils/request' import logger from 'utils/logger' describe 'Request API', -> defaultCb = chai.spy() xhr = undefined requests = undefined beforeEach -> xhr = sinon.useFakeXMLHttpRequest() requests = [] xhr.onCreate = (req) -> requests.push(req) XMLHttpRequest.prototype.overrideMimeType = (mimeType) -> this["Content-Type"] = mimeType afterEach -> xhr.restore() describe 'request', -> it 'should use GET by default as the request type when no data is provided', -> request 'test.file', defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should use POST by default as the request type when data is provided', -> request 'test.file', {some: 'data'}, defaultCb requests.length.should.equal(1) requests[0].method.should.equal('POST') requests[0].url.should.equal('test.file') requests[0].requestBody.should.equal(JSON.stringify {some: 'data'}) it 'should correctly set the requestType', -> options = requestType: 'PUT' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('PUT') it 'should correctly set the content type', -> options = contentType: 'some/type' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['Content-Type'].should.equal('some/type;charset=utf-8') it 'should correctly set the response type', -> options = responseType: 'some/type' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].responseType.should.equal('some/type') it 'should allow headers to be explicitly set', -> options = contentType: 'application/json' headers: 'Content-Type': 'something' 'accept': 'everything' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['Content-Type'].should.equal('something;charset=utf-8') requests[0].requestHeaders['accept'].should.equal('everything') it 'should allow custom headers to be set', -> options = headers: custom: 'some custom thing' request 'test.file', defaultCb, options requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].requestHeaders['custom'].should.equal('some custom thing') it 'should thrown an error when an incorrect url is passed in', -> origError = console.error console.error = chai.spy() request defaultCb console.error.should.have.been.called.with('Incorrect URL passed into request: ', defaultCb) arr = [] request arr console.error.should.have.been.called.with('Incorrect URL passed into request: ', arr) it 'should pass the correct data to the callback', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.responseText.should.equal('Some text') request 'test.file', cb requests[0].respond(200, undefined, 'Some text') it 'should return the correct source when data is not provided', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.equal('test.file') request 'test.file', cb requests[0].respond(200) it 'should return the correct source when data is provided', -> data = {some: 'data'} cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: data}) request 'test.file', data, cb requests[0].respond(200) it 'should deal with status 304 (cached response)', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.responseText.should.equal('Some text') request 'test.file', cb requests[0].respond(304, undefined, 'Some text') it 'should return an error when an error status is returned', -> cb = (error, result, source, index) -> should.exist(error) should.not.exist(result) error.status.should.equal(404) request 'test.file', cb requests[0].respond(404) it 'should format the response data correctly when one is passed in', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) result.should.eql({some: 'data'}) opts = formatter: (r) -> JSON.parse r.responseText request 'test.file', cb, opts requests[0].respond(200, undefined, '{"some":"data"}') it 'should return an error when there is an error with the formatter', -> cb = (error, result, source, index) -> should.exist(error.message) should.not.exist(result) source.should.equal('test.file') opts = formatter: (r) -> JSON.parse(r.responseText) request 'test.file', cb, opts requests[0].respond(200, undefined, '[bob, PI:NAME:<NAME>END_PI, kPI:NAME:<NAME>END_PI]') it 'should check the response if a response type is defined', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) requests[0].responseType.should.equal("arraybuffer") requests[0].response.should.be.instanceOf(ArrayBuffer) opts = responseType: "arraybuffer" request 'test.file', cb, opts requests[0].respond(200, {"Content-Type": "application/octet-stream"}, '01010011 01101111 01101101 01100101 00100000 01110100 01100101 01111000 01110100') describe 'with url as an object', -> it 'should handle sending a request without data', -> url = url: 'test.file' request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a request with data in the arguments', -> url = url: 'test.file' data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending a request with data in the object', -> data = {some: 'data'} url = url: 'test.file' data: data request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should send the object data instead of the provided data', -> data = {some: 'data'} objectData = {some: 'other data'} url = url: 'test.file' data: objectData request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify objectData) it 'should return the correct source in the response', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.equal('test.file') cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: data}) cb3 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: objData}) cb4 = (error, result, source, index) -> should.not.exist(error) should.exist(result) source.should.eql({url: 'test.file', data: objData}) data = {some: 'data'} objData = {some: 'other data'} url = url: 'test.file' request url, cb1 requests[0].respond(200) request url, data, cb2 requests[1].respond(200) url.data = objData request url, cb3 requests[2].respond(200) request url, data, cb4 requests[3].respond(200) describe 'with url as an array', -> it 'should handle sending a single request without data', -> url = ['test.file'] request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a single request with data', -> url = ['test.file'] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests without data', -> url = ['test1.file', 'test2.file'] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') it 'should handle sending multiple requests with data', -> url = ['test1.file', 'test2.file'] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests of different types', -> data = {some: 'data'} url = ['test1.file', {url: 'test2.file'}, {url: 'test3.file', data: data}] request url, defaultCb requests.length.should.equal(3) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') should.not.exist(requests[1].requestBody) requests[2].url.should.equal('test3.file') requests[2].method.should.equal('POST') requests[2].requestBody.should.equal(JSON.stringify data) it 'should return the correct source in all the responses', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.equal('test1.file') when 1 then source.should.equal('test2.file') else source.should.eql(['test1.file', 'test2.file']) cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.eql({url: 'test1.file', data: data}) when 1 then source.should.eql({url: 'test2.file', data: data}) else source.should.eql([{url: 'test1.file', data: data}, {url: 'test2.file', data: data}]) url = [ 'test1.file' 'test2.file' ] request url, cb1 requests[0].respond(200) requests[1].respond(200) data = {some: 'data'} request url, data, cb2 requests[2].respond(200) requests[3].respond(200) it 'should call set the index based on the order the urls were called, not the order they return', -> cb = (error, result, source, index) -> should.not.exist(error) should.exist(result) if index isnt -1 responses[index] = true source.should.equal(urls[index]) else source.should.eql(urls) responses = {} urls = [ 'test1.file' 'test2.file' ] request urls, cb requests[1].respond(200) responses[1].should.equal(true) requests[0].respond(200) responses[0].should.equal(true) describe 'of objects', -> it 'should handle sending a single request without data', -> url = [{url: 'test.file'}] request url, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('GET') it 'should handle sending a single request with data', -> url = [{url: 'test.file'}] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending a single request with data in the object', -> data = {some: 'data'} url = [{url: 'test.file', data: data}] request url, data, defaultCb requests.length.should.equal(1) requests[0].url.should.equal('test.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests without data', -> url = [{url: 'test1.file'}, {url: 'test2.file'}] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') requests[1].url.should.equal('test2.file') requests[1].method.should.equal('GET') it 'should handle sending multiple requests with data', -> url = [{url: 'test1.file'}, {url: 'test2.file'}] data = {some: 'data'} request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests with data in one of the objects', -> data = {some: 'data'} url = [{url: 'test1.file'}, {url: 'test2.file', data: data}] request url, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify data) it 'should handle sending multiple requests with data and data in one of the objects', -> data = {some: 'data'} objectData = {some: 'other data'} url = [{url: 'test1.file'}, {url: 'test2.file', data: objectData}] request url, data, defaultCb requests.length.should.equal(2) requests[0].url.should.equal('test1.file') requests[0].method.should.equal('POST') requests[0].requestBody.should.equal(JSON.stringify data) requests[1].url.should.equal('test2.file') requests[1].method.should.equal('POST') requests[1].requestBody.should.equal(JSON.stringify objectData) it 'should return the correct source in all the responses', -> cb1 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.equal('test1.file') when 1 then source.should.eql({url: 'test2.file', data: objData}) else source.should.eql(['test1.file', {url: 'test2.file', data: objData}]) cb2 = (error, result, source, index) -> should.not.exist(error) should.exist(result) switch index when 0 then source.should.eql({url: 'test1.file', data: data}) when 1 then source.should.eql({url: 'test2.file', data: objData}) else source.should.eql([{url: 'test1.file', data: data}, {url: 'test2.file', data: objData}]) objData = {some: 'other data'} url = [ { url: 'test1.file' } { url: 'test2.file' data: objData } ] request url, cb1 requests[0].respond(200) requests[1].respond(200) data = {some: 'data'} request url, data, cb2 requests[2].respond(200) requests[3].respond(200) describe 'html', -> it 'should correctly set the mimeType to text/html', -> html 'test.html', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('text/html;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should format and return the correct data', -> test = '<div class="parent"><span class="child">bob</span></div>' cb = (error, result, source, index) -> should.not.exist(error) result.toString().should.equal('[object DocumentFragment]') result.childNodes.length.should.equal(1) result.childNodes[0].className.should.equal('parent') result.childNodes[0].childNodes[0].className.should.equal('child') html 'test.html', cb requests[0].requestHeaders["Content-Type"].should.equal('text/html;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[0].respond(200, undefined, test) it 'should pass the data through', -> data = {some: 'data'} html 'test.html', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) describe 'text', -> it 'should correctly set the mimeType to text/plain', -> text 'test.txt', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('text/plain;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should correctly format and return the correct data', (done) -> cb = (error, result) -> should.not.exist(error) result.should.equal('Test data') done() text 'test.txt', cb requests[0].respond(200, undefined, 'Test data') it 'should pass the data through', -> data = {some: 'data'} text 'test.txt', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) describe 'reshapedRequest', -> describe 'should format and return the correct data', -> it 'for json', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() reshapedRequest 'test.json', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": "application/json"}, '{"some": "data"}') it 'even when there is a charset', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() reshapedRequest 'test.json', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'application/json;charset=UTF-8'}, '{"some": "data"}') it 'for html', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.toString().should.equal('[object DocumentFragment]') result.childNodes.length.should.equal(1) result.childNodes[0].className.should.equal('parent') result.childNodes[0].childNodes[0].className.should.equal('child') done() reshapedRequest 'test.html', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'text/html'}, '<div class="parent"><span class="child">bob</span></div>') it 'should pass the data through', -> data = {some: 'data'} json 'test.json', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) it 'should log a warning when the content type defined is not text, json or plain', (done) -> origConsoleWarning = logger.warn logger.warn = chai.spy() cb = (error, result, source) -> should.not.exist(error) should.exist(result) logger.warn.should.have.been.called.with("Unknown parser for mime type application/octet-stream, carrying on anyway") done() reshapedRequest 'test.bin', cb requests[0].method.should.equal('GET') requests[0].respond(200, {"Content-Type": 'application/octet-stream'}, '1011010010011101010010') describe 'json', -> it 'should correctly set the mimeType to application/json', -> json 'test.json', defaultCb requests[0].requestHeaders["Content-Type"].should.equal('application/json;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) it 'should format and return the correct data', (done) -> cb = (error, result, source, index) -> should.not.exist(error) result.should.eql({some: "data"}) done() json 'test.json', cb requests[0].requestHeaders["Content-Type"].should.equal('application/json;charset=utf-8') requests[0].method.should.equal('GET') should.not.exist(requests[0].requestBody) requests[0].respond(200, undefined, '{"some": "data"}') it 'should pass the data through', -> data = {some: 'data'} json 'test.json', data, defaultCb requests[0].requestBody.should.equal(JSON.stringify data) it 'should handle undefined as the response', (done) -> cb = (error, result, source) -> should.not.exist(error) should.not.exist(result) done() json 'test.json', cb requests[0].respond(200, undefined, undefined)
[ { "context": "fileoverview Tests for missing-err rule.\n# @author Jamund Ferguson\n###\n\n'use strict'\n\n#-----------------------------", "end": 74, "score": 0.9998528361320496, "start": 59, "tag": "NAME", "value": "Jamund Ferguson" } ]
src/tests/rules/handle-callback-err.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for missing-err rule. # @author Jamund Ferguson ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/handle-callback-err' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedErrorMessage = 'Expected error to be handled.' expectedFunctionExpressionError = message: expectedErrorMessage, type: 'FunctionExpression' ruleTester.run 'handle-callback-err', rule, valid: [ 'test = (error) ->' 'test = (err) -> console.log(err)' "test = (err, data) -> if err then data = 'ERROR'" 'test = (err) -> if err then ### do nothing ###' 'test = (err) -> if !err then doSomethingHere() else ;' 'test = (err, data) -> unless err then good() else bad()' 'try ; catch err ;' ''' getData (err, data) -> if err getMoreDataWith data, (err, moreData) -> if err then ; getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' 'test = (err) -> if ! err then doSomethingHere()' ''' test = (err, data) -> if data doSomething (err) -> console.error err else if err console.log err ''' ''' handler = (err, data) -> if data doSomethingWith data else if err console.log err ''' ''' handler = (err) -> logThisAction (err) -> if err then ; console.log err ''' 'userHandler = (err) -> process.nextTick -> if err then ;' ''' help = -> userHandler = (err) -> tester = -> err process.nextTick -> err ''' ''' help = (done) -> err = new Error 'error' done() ''' 'test = (err) -> err' 'test = (err) => !err' 'test = (err) -> err.message' , code: 'test = (error) -> if error then ### do nothing ###' options: ['error'] , code: 'test = (error) -> if error then ### do nothing ###' options: ['error'] , code: 'test = (error) -> if ! error then doSomethingHere()' options: ['error'] , code: 'test = (err) -> console.log err' options: ['^(err|error)$'] , code: 'test = (error) -> console.log(error)' options: ['^(err|error)$'] , code: 'test = (anyError) -> console.log(anyError)' options: ['^.+Error$'] , code: 'test = (any_error) -> console.log(anyError)' options: ['^.+Error$'] , code: 'test = (any_error) -> console.log(any_error)' options: ['^.+(e|E)rror$'] ] invalid: [ code: 'test = (err) ->', errors: [expectedFunctionExpressionError] , code: 'test = (err, data) ->' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> errorLookingWord()' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> try ; catch err ;' errors: [expectedFunctionExpressionError] , code: 'test = (err, callback) -> foo (err, callback) ->' errors: [expectedFunctionExpressionError, expectedFunctionExpressionError] , code: 'test = (err) ->### if(err){} ###' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> doSomethingHere (err) -> console.log err' errors: [expectedFunctionExpressionError] , code: ''' getData (err, data) -> getMoreDataWith data, (err, moreData) -> if err then ; getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' errors: [expectedFunctionExpressionError] , code: ''' getData (err, data) -> getMoreDataWith data, (err, moreData) -> getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' errors: [expectedFunctionExpressionError, expectedFunctionExpressionError] , code: 'userHandler = (err) -> logThisAction (err) -> if err then console.log err' errors: [expectedFunctionExpressionError] , code: ''' help = -> userHandler = (err) -> tester = (err) -> err process.nextTick -> err ''' errors: [expectedFunctionExpressionError] , code: 'test = (anyError) -> console.log(otherError)' options: ['^.+Error$'] errors: [expectedFunctionExpressionError] , code: 'test = (anyError) ->' options: ['^.+Error$'] errors: [expectedFunctionExpressionError] , code: 'test = (err) ->' options: ['^(err|error)$'] errors: [expectedFunctionExpressionError] ]
213470
###* # @fileoverview Tests for missing-err rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/handle-callback-err' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedErrorMessage = 'Expected error to be handled.' expectedFunctionExpressionError = message: expectedErrorMessage, type: 'FunctionExpression' ruleTester.run 'handle-callback-err', rule, valid: [ 'test = (error) ->' 'test = (err) -> console.log(err)' "test = (err, data) -> if err then data = 'ERROR'" 'test = (err) -> if err then ### do nothing ###' 'test = (err) -> if !err then doSomethingHere() else ;' 'test = (err, data) -> unless err then good() else bad()' 'try ; catch err ;' ''' getData (err, data) -> if err getMoreDataWith data, (err, moreData) -> if err then ; getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' 'test = (err) -> if ! err then doSomethingHere()' ''' test = (err, data) -> if data doSomething (err) -> console.error err else if err console.log err ''' ''' handler = (err, data) -> if data doSomethingWith data else if err console.log err ''' ''' handler = (err) -> logThisAction (err) -> if err then ; console.log err ''' 'userHandler = (err) -> process.nextTick -> if err then ;' ''' help = -> userHandler = (err) -> tester = -> err process.nextTick -> err ''' ''' help = (done) -> err = new Error 'error' done() ''' 'test = (err) -> err' 'test = (err) => !err' 'test = (err) -> err.message' , code: 'test = (error) -> if error then ### do nothing ###' options: ['error'] , code: 'test = (error) -> if error then ### do nothing ###' options: ['error'] , code: 'test = (error) -> if ! error then doSomethingHere()' options: ['error'] , code: 'test = (err) -> console.log err' options: ['^(err|error)$'] , code: 'test = (error) -> console.log(error)' options: ['^(err|error)$'] , code: 'test = (anyError) -> console.log(anyError)' options: ['^.+Error$'] , code: 'test = (any_error) -> console.log(anyError)' options: ['^.+Error$'] , code: 'test = (any_error) -> console.log(any_error)' options: ['^.+(e|E)rror$'] ] invalid: [ code: 'test = (err) ->', errors: [expectedFunctionExpressionError] , code: 'test = (err, data) ->' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> errorLookingWord()' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> try ; catch err ;' errors: [expectedFunctionExpressionError] , code: 'test = (err, callback) -> foo (err, callback) ->' errors: [expectedFunctionExpressionError, expectedFunctionExpressionError] , code: 'test = (err) ->### if(err){} ###' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> doSomethingHere (err) -> console.log err' errors: [expectedFunctionExpressionError] , code: ''' getData (err, data) -> getMoreDataWith data, (err, moreData) -> if err then ; getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' errors: [expectedFunctionExpressionError] , code: ''' getData (err, data) -> getMoreDataWith data, (err, moreData) -> getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' errors: [expectedFunctionExpressionError, expectedFunctionExpressionError] , code: 'userHandler = (err) -> logThisAction (err) -> if err then console.log err' errors: [expectedFunctionExpressionError] , code: ''' help = -> userHandler = (err) -> tester = (err) -> err process.nextTick -> err ''' errors: [expectedFunctionExpressionError] , code: 'test = (anyError) -> console.log(otherError)' options: ['^.+Error$'] errors: [expectedFunctionExpressionError] , code: 'test = (anyError) ->' options: ['^.+Error$'] errors: [expectedFunctionExpressionError] , code: 'test = (err) ->' options: ['^(err|error)$'] errors: [expectedFunctionExpressionError] ]
true
###* # @fileoverview Tests for missing-err rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/handle-callback-err' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' expectedErrorMessage = 'Expected error to be handled.' expectedFunctionExpressionError = message: expectedErrorMessage, type: 'FunctionExpression' ruleTester.run 'handle-callback-err', rule, valid: [ 'test = (error) ->' 'test = (err) -> console.log(err)' "test = (err, data) -> if err then data = 'ERROR'" 'test = (err) -> if err then ### do nothing ###' 'test = (err) -> if !err then doSomethingHere() else ;' 'test = (err, data) -> unless err then good() else bad()' 'try ; catch err ;' ''' getData (err, data) -> if err getMoreDataWith data, (err, moreData) -> if err then ; getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' 'test = (err) -> if ! err then doSomethingHere()' ''' test = (err, data) -> if data doSomething (err) -> console.error err else if err console.log err ''' ''' handler = (err, data) -> if data doSomethingWith data else if err console.log err ''' ''' handler = (err) -> logThisAction (err) -> if err then ; console.log err ''' 'userHandler = (err) -> process.nextTick -> if err then ;' ''' help = -> userHandler = (err) -> tester = -> err process.nextTick -> err ''' ''' help = (done) -> err = new Error 'error' done() ''' 'test = (err) -> err' 'test = (err) => !err' 'test = (err) -> err.message' , code: 'test = (error) -> if error then ### do nothing ###' options: ['error'] , code: 'test = (error) -> if error then ### do nothing ###' options: ['error'] , code: 'test = (error) -> if ! error then doSomethingHere()' options: ['error'] , code: 'test = (err) -> console.log err' options: ['^(err|error)$'] , code: 'test = (error) -> console.log(error)' options: ['^(err|error)$'] , code: 'test = (anyError) -> console.log(anyError)' options: ['^.+Error$'] , code: 'test = (any_error) -> console.log(anyError)' options: ['^.+Error$'] , code: 'test = (any_error) -> console.log(any_error)' options: ['^.+(e|E)rror$'] ] invalid: [ code: 'test = (err) ->', errors: [expectedFunctionExpressionError] , code: 'test = (err, data) ->' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> errorLookingWord()' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> try ; catch err ;' errors: [expectedFunctionExpressionError] , code: 'test = (err, callback) -> foo (err, callback) ->' errors: [expectedFunctionExpressionError, expectedFunctionExpressionError] , code: 'test = (err) ->### if(err){} ###' errors: [expectedFunctionExpressionError] , code: 'test = (err) -> doSomethingHere (err) -> console.log err' errors: [expectedFunctionExpressionError] , code: ''' getData (err, data) -> getMoreDataWith data, (err, moreData) -> if err then ; getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' errors: [expectedFunctionExpressionError] , code: ''' getData (err, data) -> getMoreDataWith data, (err, moreData) -> getEvenMoreDataWith moreData, (err, allOfTheThings) -> if err then ; ''' errors: [expectedFunctionExpressionError, expectedFunctionExpressionError] , code: 'userHandler = (err) -> logThisAction (err) -> if err then console.log err' errors: [expectedFunctionExpressionError] , code: ''' help = -> userHandler = (err) -> tester = (err) -> err process.nextTick -> err ''' errors: [expectedFunctionExpressionError] , code: 'test = (anyError) -> console.log(otherError)' options: ['^.+Error$'] errors: [expectedFunctionExpressionError] , code: 'test = (anyError) ->' options: ['^.+Error$'] errors: [expectedFunctionExpressionError] , code: 'test = (err) ->' options: ['^(err|error)$'] errors: [expectedFunctionExpressionError] ]
[ { "context": "ocol()}://#{uri.host()}#{uri.path()}\"\n auth = \"X-USER-TOKEN=#{uri.query(true)[\"X-USER-TOKEN\"]}\"\n\n # ", "end": 285, "score": 0.6537508964538574, "start": 279, "tag": "KEY", "value": "X-USER" } ]
app/coffee/views/historic-view.coffee
nanobox-io/nanobox-dash-ui-logs
1
# module.exports = class Historic # constructor: (@$node, @options={}, @main) -> # Eventify.extend(@) # parse the uri and build our connection credentials uri = new URI(@options.url); host = "#{uri.protocol()}://#{uri.host()}#{uri.path()}" auth = "X-USER-TOKEN=#{uri.query(true)["X-USER-TOKEN"]}" # perpare connection options @logvacOptions = { host: host, auth: auth, type: @options.type || "app" id: @options.id || "" limit: @options.limit || 50 logging: @options.logging } # connect to logvac @logvac = new Logvac(@logvacOptions) # setup event handlers @_handleDataLoad() @_handleDataError() # load more logs @$node.find('#view-more-logs').click () => @_loadHistoricalData() @on "historic.loading", () => @$node.addClass("loading") @on "historic.loaded", () => @$node.removeClass("loading") # when this view is loaded... load: () -> @main.currentLog = "historicView" @_loadHistoricalData() # when this view is unloaded... unload: () -> delete @lastEntry # handle data _handleDataLoad: () -> @logvac.on "logvac:_xhr.load", (key, data) => # @main.updateStatus "loading-records" # parse log data; if we're unable to parse the log data for some reason # output an error, reset the view and return try @logs = JSON.parse(data) catch console.error "Failed to parse data - #{data}" @_resetView(); return # if there are no logs reset the view and return early if @logs.length == 0 then @_resetView(); return # get the last entry and format it @lastEntry = @logs[0] @lastEntry = @main.format_entry(@lastEntry) # we reverse the array here because the logs or ordered oldest to newest # and we want to build them from the bottom up, newest to oldest for log, i in @logs.reverse() @_addEntry(@main.format_entry(log), (1000/60)*i) # dont allow more logs to load until the current set has finished setTimeout (=> @_resetView() ), (1000/60)*@logs.length # handle error _handleDataError: () -> @logvac.on "logvac:_xhr.error", (key, data) => @_resetView() @main.updateStatus "communication-error" # unless we're already loading log, get the next set of logs (based off the last # entry of the previous set) _loadHistoricalData: () -> unless @loading @loading = true @fire "historic.loading" # @main.updateStatus "retrieving-history-log" # get the next set of logs from the last time of the previous set @logvacOptions.start = (@lastEntry?.utime || 0) @logvac.get(@logvacOptions) # this does the inserting of the HTML _addEntry : (entry, delay) -> # if the log has no length add a space entry.log = "&nbsp;" if (entry.log.length == 0) # if the time of this entry is the same as the last entry then highlight it entry.styles += "background:#1D4856;" if (entry.utime == @lastEntry.utime) # build the entry $entry = $( "<div class=entry style='#{entry.styles}; opacity:0;'> <div class=meta time>#{entry.short_date_time}&nbsp;&nbsp;::&nbsp;&nbsp;</div> <div class=meta id>#{entry.id}&nbsp;&nbsp;::&nbsp;&nbsp;</div> <div class=meta tag>#{entry.tag}</div> </div>" ).delay(delay).animate({opacity:1}, {duration:100}) # $message = $("<span class='message' style='#{entry.styles}; opacity:0;'>#{entry.log}</span>") .data('$entry', $entry) .delay(delay).animate({opacity:1}, {duration:100}) # historic logs prepend entries so it looks like logs are streaming upwards; # we stagger prepending to give it a nice streaming effect setTimeout (=> @main.$entries?.prepend $entry @main.$stream?.prepend $message ), delay # _resetView: () -> @main.updateStatus "" @loading = false @fire "historic.loaded"
84511
# module.exports = class Historic # constructor: (@$node, @options={}, @main) -> # Eventify.extend(@) # parse the uri and build our connection credentials uri = new URI(@options.url); host = "#{uri.protocol()}://#{uri.host()}#{uri.path()}" auth = "<KEY>-TOKEN=#{uri.query(true)["X-USER-TOKEN"]}" # perpare connection options @logvacOptions = { host: host, auth: auth, type: @options.type || "app" id: @options.id || "" limit: @options.limit || 50 logging: @options.logging } # connect to logvac @logvac = new Logvac(@logvacOptions) # setup event handlers @_handleDataLoad() @_handleDataError() # load more logs @$node.find('#view-more-logs').click () => @_loadHistoricalData() @on "historic.loading", () => @$node.addClass("loading") @on "historic.loaded", () => @$node.removeClass("loading") # when this view is loaded... load: () -> @main.currentLog = "historicView" @_loadHistoricalData() # when this view is unloaded... unload: () -> delete @lastEntry # handle data _handleDataLoad: () -> @logvac.on "logvac:_xhr.load", (key, data) => # @main.updateStatus "loading-records" # parse log data; if we're unable to parse the log data for some reason # output an error, reset the view and return try @logs = JSON.parse(data) catch console.error "Failed to parse data - #{data}" @_resetView(); return # if there are no logs reset the view and return early if @logs.length == 0 then @_resetView(); return # get the last entry and format it @lastEntry = @logs[0] @lastEntry = @main.format_entry(@lastEntry) # we reverse the array here because the logs or ordered oldest to newest # and we want to build them from the bottom up, newest to oldest for log, i in @logs.reverse() @_addEntry(@main.format_entry(log), (1000/60)*i) # dont allow more logs to load until the current set has finished setTimeout (=> @_resetView() ), (1000/60)*@logs.length # handle error _handleDataError: () -> @logvac.on "logvac:_xhr.error", (key, data) => @_resetView() @main.updateStatus "communication-error" # unless we're already loading log, get the next set of logs (based off the last # entry of the previous set) _loadHistoricalData: () -> unless @loading @loading = true @fire "historic.loading" # @main.updateStatus "retrieving-history-log" # get the next set of logs from the last time of the previous set @logvacOptions.start = (@lastEntry?.utime || 0) @logvac.get(@logvacOptions) # this does the inserting of the HTML _addEntry : (entry, delay) -> # if the log has no length add a space entry.log = "&nbsp;" if (entry.log.length == 0) # if the time of this entry is the same as the last entry then highlight it entry.styles += "background:#1D4856;" if (entry.utime == @lastEntry.utime) # build the entry $entry = $( "<div class=entry style='#{entry.styles}; opacity:0;'> <div class=meta time>#{entry.short_date_time}&nbsp;&nbsp;::&nbsp;&nbsp;</div> <div class=meta id>#{entry.id}&nbsp;&nbsp;::&nbsp;&nbsp;</div> <div class=meta tag>#{entry.tag}</div> </div>" ).delay(delay).animate({opacity:1}, {duration:100}) # $message = $("<span class='message' style='#{entry.styles}; opacity:0;'>#{entry.log}</span>") .data('$entry', $entry) .delay(delay).animate({opacity:1}, {duration:100}) # historic logs prepend entries so it looks like logs are streaming upwards; # we stagger prepending to give it a nice streaming effect setTimeout (=> @main.$entries?.prepend $entry @main.$stream?.prepend $message ), delay # _resetView: () -> @main.updateStatus "" @loading = false @fire "historic.loaded"
true
# module.exports = class Historic # constructor: (@$node, @options={}, @main) -> # Eventify.extend(@) # parse the uri and build our connection credentials uri = new URI(@options.url); host = "#{uri.protocol()}://#{uri.host()}#{uri.path()}" auth = "PI:KEY:<KEY>END_PI-TOKEN=#{uri.query(true)["X-USER-TOKEN"]}" # perpare connection options @logvacOptions = { host: host, auth: auth, type: @options.type || "app" id: @options.id || "" limit: @options.limit || 50 logging: @options.logging } # connect to logvac @logvac = new Logvac(@logvacOptions) # setup event handlers @_handleDataLoad() @_handleDataError() # load more logs @$node.find('#view-more-logs').click () => @_loadHistoricalData() @on "historic.loading", () => @$node.addClass("loading") @on "historic.loaded", () => @$node.removeClass("loading") # when this view is loaded... load: () -> @main.currentLog = "historicView" @_loadHistoricalData() # when this view is unloaded... unload: () -> delete @lastEntry # handle data _handleDataLoad: () -> @logvac.on "logvac:_xhr.load", (key, data) => # @main.updateStatus "loading-records" # parse log data; if we're unable to parse the log data for some reason # output an error, reset the view and return try @logs = JSON.parse(data) catch console.error "Failed to parse data - #{data}" @_resetView(); return # if there are no logs reset the view and return early if @logs.length == 0 then @_resetView(); return # get the last entry and format it @lastEntry = @logs[0] @lastEntry = @main.format_entry(@lastEntry) # we reverse the array here because the logs or ordered oldest to newest # and we want to build them from the bottom up, newest to oldest for log, i in @logs.reverse() @_addEntry(@main.format_entry(log), (1000/60)*i) # dont allow more logs to load until the current set has finished setTimeout (=> @_resetView() ), (1000/60)*@logs.length # handle error _handleDataError: () -> @logvac.on "logvac:_xhr.error", (key, data) => @_resetView() @main.updateStatus "communication-error" # unless we're already loading log, get the next set of logs (based off the last # entry of the previous set) _loadHistoricalData: () -> unless @loading @loading = true @fire "historic.loading" # @main.updateStatus "retrieving-history-log" # get the next set of logs from the last time of the previous set @logvacOptions.start = (@lastEntry?.utime || 0) @logvac.get(@logvacOptions) # this does the inserting of the HTML _addEntry : (entry, delay) -> # if the log has no length add a space entry.log = "&nbsp;" if (entry.log.length == 0) # if the time of this entry is the same as the last entry then highlight it entry.styles += "background:#1D4856;" if (entry.utime == @lastEntry.utime) # build the entry $entry = $( "<div class=entry style='#{entry.styles}; opacity:0;'> <div class=meta time>#{entry.short_date_time}&nbsp;&nbsp;::&nbsp;&nbsp;</div> <div class=meta id>#{entry.id}&nbsp;&nbsp;::&nbsp;&nbsp;</div> <div class=meta tag>#{entry.tag}</div> </div>" ).delay(delay).animate({opacity:1}, {duration:100}) # $message = $("<span class='message' style='#{entry.styles}; opacity:0;'>#{entry.log}</span>") .data('$entry', $entry) .delay(delay).animate({opacity:1}, {duration:100}) # historic logs prepend entries so it looks like logs are streaming upwards; # we stagger prepending to give it a nice streaming effect setTimeout (=> @main.$entries?.prepend $entry @main.$stream?.prepend $message ), delay # _resetView: () -> @main.updateStatus "" @loading = false @fire "historic.loaded"
[ { "context": "loc = kb.viewModel(kb.locale_manager, {\n\t\tkeys: ['complete_all', 'create_placeholder', 'create_tooltip', 'instruct", "end": 4373, "score": 0.9614107608795166, "start": 4359, "tag": "KEY", "value": "complete_all'," }, { "context": "el(kb.locale_manager, {\n\t\tkeys: [...
app/todos-extended/src/viewmodels/app.coffee
kmalakoff/knockback-todos-app
2
ENTER_KEY = 13 window.AppViewModel = -> ############################# ############################# # CLASSIC APP with some EXTENSION hooks ############################# ############################# ############################# # Shared ############################# # collections @collections = todos: new TodoCollection() @collections.todos.fetch() # shared observables @list_filter_mode = ko.observable('') filter_fn = ko.computed => switch @list_filter_mode() when 'active' then return (model) -> return not model.completed() when 'completed' then return (model) -> return model.completed() else return -> return true @todos = kb.collectionObservable(@collections.todos, {view_model: TodoViewModel, filters: filter_fn, sort_attribute: 'title'}) # EXTENSIONS: Add sorting @todos_changed = kb.triggeredObservable(@collections.todos, 'change add remove') @tasks_exist = ko.computed(=> @todos_changed(); return !!@collections.todos.length) ############################# # Header Section ############################# @title = ko.observable('') @onAddTodo = (view_model, event) => return true if not $.trim(@title()) or (event.keyCode != ENTER_KEY) # Create task and reset UI @collections.todos.create({title: $.trim(@title()), priority: app_settings.default_priority()}) # EXTENDED: Add priority to Todo @title('') ############################# # Todos Section ############################# @remaining_count = ko.computed(=> @todos_changed(); return @collections.todos.remainingCount()) @completed_count = ko.computed(=> @todos_changed(); return @collections.todos.completedCount()) @all_completed = ko.computed( read: => return not @remaining_count() write: (completed) => @collections.todos.completeAll(completed) ) ############################# # Footer Section ############################# @remaining_message = ko.computed(=> return "<strong>#{@remaining_count()}</strong> #{if @remaining_count() == 1 then 'item' else 'items'} left") @onDestroyCompleted = => @collections.todos.destroyCompleted() ############################# # Routing ############################# router = new Backbone.Router router.route('', null, => @list_filter_mode('')) router.route('active', null, => @list_filter_mode('active')) router.route('completed', null, => @list_filter_mode('completed')) Backbone.history.start() ############################# ############################# # Extensions ############################# ############################# ############################# # Header Section ############################# @priority_color = ko.computed(=> return app_settings.default_priority_color()) @tooltip_visible = ko.observable(false) tooltip_visible = @tooltip_visible # closured for onSelectPriority @onSelectPriority = (view_model, event) => event.stopPropagation(); tooltip_visible(false) app_settings.default_priority(ko.utils.unwrapObservable(view_model.priority)) @onToggleTooltip = => @tooltip_visible(!@tooltip_visible()) ############################# # Todos Section ############################# @sort_mode = ko.computed => new_mode = app_settings.selected_list_sorting() switch new_mode when 'label_title' then @todos.sortAttribute('title') when 'label_created' then @todos.comparator( (model_a, model_b) -> return kb.utils.wrappedModel(model_a).get('created_at').valueOf() - kb.utils.wrappedModel(model_b).get('created_at').valueOf() ) when 'label_priority' then @todos.comparator( (model_a, model_b) -> rank_a = _.indexOf(['high', 'medium', 'low'], kb.utils.wrappedModel(model_a).get('priority')) rank_b = _.indexOf(['high', 'medium', 'low'], kb.utils.wrappedModel(model_b).get('priority')) return delta if (delta = (rank_a - rank_b)) isnt 0 return kb.utils.wrappedModel(model_a).get('created_at').valueOf() - kb.utils.wrappedModel(model_b).get('created_at').valueOf() ) ############################# # Localization ############################# @remaining_message_key = ko.computed(=>return if (@remaining_count() == 1) then 'remaining_template_s' else 'remaining_template_pl') @clear_message_key = ko.computed(=>return if ((count = @completed_count()) is 0) then null else (if (count is 1) then 'clear_template_s' else 'clear_template_pl')) @loc = kb.viewModel(kb.locale_manager, { keys: ['complete_all', 'create_placeholder', 'create_tooltip', 'instructions', 'filter_all', 'filter_active', 'filter_completed'] mappings: remaining_message: { key: @remaining_message_key, args: [@remaining_count] } clear_message: { key: @clear_message_key, args: [@completed_count] } }) return
16964
ENTER_KEY = 13 window.AppViewModel = -> ############################# ############################# # CLASSIC APP with some EXTENSION hooks ############################# ############################# ############################# # Shared ############################# # collections @collections = todos: new TodoCollection() @collections.todos.fetch() # shared observables @list_filter_mode = ko.observable('') filter_fn = ko.computed => switch @list_filter_mode() when 'active' then return (model) -> return not model.completed() when 'completed' then return (model) -> return model.completed() else return -> return true @todos = kb.collectionObservable(@collections.todos, {view_model: TodoViewModel, filters: filter_fn, sort_attribute: 'title'}) # EXTENSIONS: Add sorting @todos_changed = kb.triggeredObservable(@collections.todos, 'change add remove') @tasks_exist = ko.computed(=> @todos_changed(); return !!@collections.todos.length) ############################# # Header Section ############################# @title = ko.observable('') @onAddTodo = (view_model, event) => return true if not $.trim(@title()) or (event.keyCode != ENTER_KEY) # Create task and reset UI @collections.todos.create({title: $.trim(@title()), priority: app_settings.default_priority()}) # EXTENDED: Add priority to Todo @title('') ############################# # Todos Section ############################# @remaining_count = ko.computed(=> @todos_changed(); return @collections.todos.remainingCount()) @completed_count = ko.computed(=> @todos_changed(); return @collections.todos.completedCount()) @all_completed = ko.computed( read: => return not @remaining_count() write: (completed) => @collections.todos.completeAll(completed) ) ############################# # Footer Section ############################# @remaining_message = ko.computed(=> return "<strong>#{@remaining_count()}</strong> #{if @remaining_count() == 1 then 'item' else 'items'} left") @onDestroyCompleted = => @collections.todos.destroyCompleted() ############################# # Routing ############################# router = new Backbone.Router router.route('', null, => @list_filter_mode('')) router.route('active', null, => @list_filter_mode('active')) router.route('completed', null, => @list_filter_mode('completed')) Backbone.history.start() ############################# ############################# # Extensions ############################# ############################# ############################# # Header Section ############################# @priority_color = ko.computed(=> return app_settings.default_priority_color()) @tooltip_visible = ko.observable(false) tooltip_visible = @tooltip_visible # closured for onSelectPriority @onSelectPriority = (view_model, event) => event.stopPropagation(); tooltip_visible(false) app_settings.default_priority(ko.utils.unwrapObservable(view_model.priority)) @onToggleTooltip = => @tooltip_visible(!@tooltip_visible()) ############################# # Todos Section ############################# @sort_mode = ko.computed => new_mode = app_settings.selected_list_sorting() switch new_mode when 'label_title' then @todos.sortAttribute('title') when 'label_created' then @todos.comparator( (model_a, model_b) -> return kb.utils.wrappedModel(model_a).get('created_at').valueOf() - kb.utils.wrappedModel(model_b).get('created_at').valueOf() ) when 'label_priority' then @todos.comparator( (model_a, model_b) -> rank_a = _.indexOf(['high', 'medium', 'low'], kb.utils.wrappedModel(model_a).get('priority')) rank_b = _.indexOf(['high', 'medium', 'low'], kb.utils.wrappedModel(model_b).get('priority')) return delta if (delta = (rank_a - rank_b)) isnt 0 return kb.utils.wrappedModel(model_a).get('created_at').valueOf() - kb.utils.wrappedModel(model_b).get('created_at').valueOf() ) ############################# # Localization ############################# @remaining_message_key = ko.computed(=>return if (@remaining_count() == 1) then 'remaining_template_s' else 'remaining_template_pl') @clear_message_key = ko.computed(=>return if ((count = @completed_count()) is 0) then null else (if (count is 1) then 'clear_template_s' else 'clear_template_pl')) @loc = kb.viewModel(kb.locale_manager, { keys: ['<KEY> '<KEY> '<KEY> 'instructions', 'filter_all', 'filter_active', '<KEY>_completed'] mappings: remaining_message: { key: @remaining_message_key, args: [@remaining_count] } clear_message: { key: @clear_message_key, args: [@completed_count] } }) return
true
ENTER_KEY = 13 window.AppViewModel = -> ############################# ############################# # CLASSIC APP with some EXTENSION hooks ############################# ############################# ############################# # Shared ############################# # collections @collections = todos: new TodoCollection() @collections.todos.fetch() # shared observables @list_filter_mode = ko.observable('') filter_fn = ko.computed => switch @list_filter_mode() when 'active' then return (model) -> return not model.completed() when 'completed' then return (model) -> return model.completed() else return -> return true @todos = kb.collectionObservable(@collections.todos, {view_model: TodoViewModel, filters: filter_fn, sort_attribute: 'title'}) # EXTENSIONS: Add sorting @todos_changed = kb.triggeredObservable(@collections.todos, 'change add remove') @tasks_exist = ko.computed(=> @todos_changed(); return !!@collections.todos.length) ############################# # Header Section ############################# @title = ko.observable('') @onAddTodo = (view_model, event) => return true if not $.trim(@title()) or (event.keyCode != ENTER_KEY) # Create task and reset UI @collections.todos.create({title: $.trim(@title()), priority: app_settings.default_priority()}) # EXTENDED: Add priority to Todo @title('') ############################# # Todos Section ############################# @remaining_count = ko.computed(=> @todos_changed(); return @collections.todos.remainingCount()) @completed_count = ko.computed(=> @todos_changed(); return @collections.todos.completedCount()) @all_completed = ko.computed( read: => return not @remaining_count() write: (completed) => @collections.todos.completeAll(completed) ) ############################# # Footer Section ############################# @remaining_message = ko.computed(=> return "<strong>#{@remaining_count()}</strong> #{if @remaining_count() == 1 then 'item' else 'items'} left") @onDestroyCompleted = => @collections.todos.destroyCompleted() ############################# # Routing ############################# router = new Backbone.Router router.route('', null, => @list_filter_mode('')) router.route('active', null, => @list_filter_mode('active')) router.route('completed', null, => @list_filter_mode('completed')) Backbone.history.start() ############################# ############################# # Extensions ############################# ############################# ############################# # Header Section ############################# @priority_color = ko.computed(=> return app_settings.default_priority_color()) @tooltip_visible = ko.observable(false) tooltip_visible = @tooltip_visible # closured for onSelectPriority @onSelectPriority = (view_model, event) => event.stopPropagation(); tooltip_visible(false) app_settings.default_priority(ko.utils.unwrapObservable(view_model.priority)) @onToggleTooltip = => @tooltip_visible(!@tooltip_visible()) ############################# # Todos Section ############################# @sort_mode = ko.computed => new_mode = app_settings.selected_list_sorting() switch new_mode when 'label_title' then @todos.sortAttribute('title') when 'label_created' then @todos.comparator( (model_a, model_b) -> return kb.utils.wrappedModel(model_a).get('created_at').valueOf() - kb.utils.wrappedModel(model_b).get('created_at').valueOf() ) when 'label_priority' then @todos.comparator( (model_a, model_b) -> rank_a = _.indexOf(['high', 'medium', 'low'], kb.utils.wrappedModel(model_a).get('priority')) rank_b = _.indexOf(['high', 'medium', 'low'], kb.utils.wrappedModel(model_b).get('priority')) return delta if (delta = (rank_a - rank_b)) isnt 0 return kb.utils.wrappedModel(model_a).get('created_at').valueOf() - kb.utils.wrappedModel(model_b).get('created_at').valueOf() ) ############################# # Localization ############################# @remaining_message_key = ko.computed(=>return if (@remaining_count() == 1) then 'remaining_template_s' else 'remaining_template_pl') @clear_message_key = ko.computed(=>return if ((count = @completed_count()) is 0) then null else (if (count is 1) then 'clear_template_s' else 'clear_template_pl')) @loc = kb.viewModel(kb.locale_manager, { keys: ['PI:KEY:<KEY>END_PI 'PI:KEY:<KEY>END_PI 'PI:KEY:<KEY>END_PI 'instructions', 'filter_all', 'filter_active', 'PI:KEY:<KEY>END_PI_completed'] mappings: remaining_message: { key: @remaining_message_key, args: [@remaining_count] } clear_message: { key: @clear_message_key, args: [@completed_count] } }) return
[ { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n#", "end": 21, "score": 0.9982496500015259, "start": 14, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n# Last Update ...
node_modules/node-find-folder/gulp/uglify.coffee
long-grass/mikey
0
### # Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'cmprs_js', -> gulp.src cfg.path.root_js_src + '*.js' .pipe $.uglify cfg.cmprs_opts .pipe gulp.dest cfg.path.root_js_src .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'JS Compression' message: cfg.message.cmprs_splited_tasks_js_src
95505
### # Author: iTonyYo <<EMAIL>> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <<EMAIL>> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'cmprs_js', -> gulp.src cfg.path.root_js_src + '*.js' .pipe $.uglify cfg.cmprs_opts .pipe gulp.dest cfg.path.root_js_src .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'JS Compression' message: cfg.message.cmprs_splited_tasks_js_src
true
### # Author: iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'cmprs_js', -> gulp.src cfg.path.root_js_src + '*.js' .pipe $.uglify cfg.cmprs_opts .pipe gulp.dest cfg.path.root_js_src .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'JS Compression' message: cfg.message.cmprs_splited_tasks_js_src
[ { "context": "nly uses arguments\", ->\n person =\n name: \"Jim\"\n nameWithSuffix: (suffix) -> @name + suffix", "end": 3174, "score": 0.9997715353965759, "start": 3171, "tag": "NAME", "value": "Jim" }, { "context": "pect(personNameWithSuffix(person, \"!\")).to.equal(\"J...
test/common/kozu/core_test.coffee
jamesmacaulay/kozu
2
expect = require("chai").expect core = require("../../../../../lib/kozu/core") plus1 = (n) -> n+1 times2 = (n) -> n*2 exclaim = (x) -> "#{x}!" describe "kozu.core.compose(... funcs)", -> it "calls from right to left", -> times2plus1 = core.compose(plus1, times2) expect(times2plus1(3)).to.equal(7) describe "kozu.core.pipe(x, ... funcs)", -> it "calls funcs on x from left to right", -> expect(core.pipe(3, times2, plus1)).to.equal(7) describe "kozu.core.partialRest(func, args...)", -> it "partial application of func with args as the rest of the args after the first", -> mathy = core.partialRest(core.compose, plus1, times2) expect(mathy(exclaim) 3).to.equal("7!") describe "kozu.core.get(obj, key)", -> it "returns obj[key]", -> expect(core.get({foo: 2}, "foo")).to.equal(2) describe "kozu.core.getter(key)", -> it "returns a function which takes an object and returns obj[key]", -> fooGetter = core.getter('foo') expect(fooGetter({foo: 2})).to.equal(2) describe "kozu.core.args", -> it "returns its arguments object", -> expect(Object::toString.call(core.args(1,2,3))).to.equal("[object Arguments]") describe "kozu.core.factory(constructor)", -> it "returns a variadic function which returns a new instance of the constructor with the given arguments", -> class Foo constructor: (@a, @b) -> fooFactory = core.factory(Foo) foo = fooFactory(1,2) expect(foo.a).to.equal(1) expect(foo.b).to.equal(2) expect(foo.constructor).to.equal(Foo) describe "kozu.core.multiGet(obj, keys)", -> it "returns an array of the values in obj at keys", -> expect(core.multiGet({foo: 1, bar: 2, baz: 3}, ['bar', 'foo'])).to.deep.equal([2,1]) describe "kozu.core.castArgumentsAsArray(x)", -> it "returns a new array copy when x is an Arguments object", -> ary = core.castArgumentsAsArray(core.args(1,2,3)) expect(ary).to.deep.equal([1,2,3]) expect(core.isArray(ary)).to.equal(true) it "returns x when x is not an Arguments object", -> ary = [1,2,3] expect(core.castArgumentsAsArray(ary)).to.equal(ary) describe "kozu.core.cons(x, xs)", -> it "returns a new array with x prepended before xs", -> expect(core.cons(1, [2, 3])).to.deep.equal([1,2,3]) describe "kozu.core.partialRest(func, ... args)", -> it "returns a partial application of func, starting from the second argument", -> makeArray = core.variadic(core.identity) somethingTwoThree = core.partialRest(makeArray, 2, 3) expect(somethingTwoThree(1)).to.deep.equal([1,2,3]) describe "kozu.core.merge(... objects)", -> it "returns a new object which merges the given objects, with the keys of later objects overwriting those of previous ones", -> a = {foo: 1, bar: 2} b = {bar: 3, baz: 4} c = {baz: 5, qux: 6} result = core.merge(a, b, c) expect(result).to.deep.equal({foo: 1, bar: 3, baz: 5, qux: 6}) expect(result).to.not.equal(a) expect(result).to.not.equal(b) expect(result).to.not.equal(c) describe "kozu.core.functionalize", -> it "wraps a method-style function (one which uses `this`) such that it only uses arguments", -> person = name: "Jim" nameWithSuffix: (suffix) -> @name + suffix personNameWithSuffix = core.functionalize(person.nameWithSuffix) expect(personNameWithSuffix(person, "!")).to.equal("Jim!") it "is aliased as rotatesThisOutOfArguments", -> expect(core.rotatesThisOutOfArguments).to.equal(core.functionalize) describe "kozu.core.methodize", -> it "wraps a function which does not rely on `this`, turning it into a method-style function such that the original's first argument is supplied as `this` by the caller", -> personNameWithSuffix = (person, suffix) -> person.name + suffix person = name: "Jim" nameWithSuffix: core.methodize(personNameWithSuffix) expect(person.nameWithSuffix("!")).to.equal("Jim!") it "is aliased as rotatesThisIntoArguments", -> expect(core.rotatesThisIntoArguments).to.equal(core.methodize) describe "kozu.core.congealed", -> it "takes a variadic function and returns a unary version which spreads a single array argument to the original", -> arrayToArgs = core.congealed(core.args) expect(arrayToArgs([1,2,3])).to.deep.equal(core.args(1,2,3)) it "is aliased as spreadsArguments", -> expect(core.spreadsArguments).to.equal(core.congealed) describe "kozu.core.variadic", -> it "takes a function which takes a single array argument and returns a variadic version which passes a slice of its arguments as a single argument to the original", -> makeArray = core.variadic(core.identity) expect(makeArray(1,2,3)).to.deep.equal([1,2,3]) it "is aliased as gathersArguments", -> expect(core.gathersArguments).to.equal(core.variadic) describe "kozu.core.flip2", -> it "takes a function of 2 arguments and returns a new version of the function with its arguments flipped", -> divide = (a, b) -> a / b expect(core.flip2(divide)(2, 4)).to.equal(2) describe "kozu.core.mergesReturnValueOntoArgument(func)", -> it "wraps func such that the return value is `merge`d onto the first argument before being returned", -> f = core.mergesReturnValueOntoArgument(-> {ctx: this, args: core.castArgumentsAsArray(arguments), return: "return"}) expect(f.call({a: 1}, {b: 2, foo: "bar"}, {c: 3})).to.deep.equal b: 2 foo: "bar" ctx: {a: 1} args: [{b: 2, foo: "bar"}, {c: 3}] return: "return" describe "kozu.core.gathersThisAndArguments", -> it "wraps a function such that the new version gathers its many inputs into a single array of [this, ... arguments] which is passed to the wrapped function", -> result = core.gathersThisAndArguments(core.identity).call({a: 1}, 1, 2, 3) expect(result).to.deep.equal [{a: 1}, 1, 2, 3] describe "kozu.core.spreadsThisAndArguments", -> it "wraps a function such that the new version spreads its single array argument of [this, ... arguments] into `this` and `arguments` for the wrapped function", -> result = core.spreadsThisAndArguments(-> [this, arguments])([{a: 1}, 1, 2, 3]) expect(result).to.deep.equal([{a: 1}, core.args(1, 2, 3)]) describe "kozu.core.extractsKeys(... keys)", -> it "returns a function wrapper which takes a variadic function and returns a function which takes an object and uses the values at the given keys as the arguments for the original", -> fooPlusBar = core.extractsKeys('foo', 'bar')((foo, bar) -> foo + bar) expect(fooPlusBar({foo: 1, bar: 2, baz: 3})).to.equal(3) describe "kozu.core.transformsArgumentWith(func)", -> it "returns a function wrapper which transforms the wrapped function's argument with func", -> plus1wrapper = core.transformsArgumentWith(plus1) expect(plus1wrapper(times2)(5)).to.equal(12) describe "kozu.core.transformsReturnValueWith(func)", -> it "returns a function wrapper which transforms the wrapped function's return value with func", -> plus1wrapper = core.transformsReturnValueWith(plus1) expect(plus1wrapper(times2)(5)).to.equal(11) describe "kozu.core.mapper(func)", -> it "returns a function which takes an array and maps func onto it", -> mapIncrement = core.mapper(plus1) expect(mapIncrement([1,2,3])).to.deep.equal([2,3,4]) describe "kozu.core.joiner(separator)", -> it "returns a function which joins an array with the given string", -> expect(core.joiner("-")(["foo", "bar"])).to.equal("foo-bar") describe "kozu.core.argumentMapper(func)", -> it "returns a function which maps func onto its arguments", -> expect(core.argumentMapper(plus1)(1,2,3)).to.deep.equal([2,3,4]) describe "kozu.core.argumentJoiner(separator)", -> it "returns a function which joins its arguments with the given string", -> expect(core.argumentJoiner("-")("foo", "bar")).to.equal("foo-bar")
197552
expect = require("chai").expect core = require("../../../../../lib/kozu/core") plus1 = (n) -> n+1 times2 = (n) -> n*2 exclaim = (x) -> "#{x}!" describe "kozu.core.compose(... funcs)", -> it "calls from right to left", -> times2plus1 = core.compose(plus1, times2) expect(times2plus1(3)).to.equal(7) describe "kozu.core.pipe(x, ... funcs)", -> it "calls funcs on x from left to right", -> expect(core.pipe(3, times2, plus1)).to.equal(7) describe "kozu.core.partialRest(func, args...)", -> it "partial application of func with args as the rest of the args after the first", -> mathy = core.partialRest(core.compose, plus1, times2) expect(mathy(exclaim) 3).to.equal("7!") describe "kozu.core.get(obj, key)", -> it "returns obj[key]", -> expect(core.get({foo: 2}, "foo")).to.equal(2) describe "kozu.core.getter(key)", -> it "returns a function which takes an object and returns obj[key]", -> fooGetter = core.getter('foo') expect(fooGetter({foo: 2})).to.equal(2) describe "kozu.core.args", -> it "returns its arguments object", -> expect(Object::toString.call(core.args(1,2,3))).to.equal("[object Arguments]") describe "kozu.core.factory(constructor)", -> it "returns a variadic function which returns a new instance of the constructor with the given arguments", -> class Foo constructor: (@a, @b) -> fooFactory = core.factory(Foo) foo = fooFactory(1,2) expect(foo.a).to.equal(1) expect(foo.b).to.equal(2) expect(foo.constructor).to.equal(Foo) describe "kozu.core.multiGet(obj, keys)", -> it "returns an array of the values in obj at keys", -> expect(core.multiGet({foo: 1, bar: 2, baz: 3}, ['bar', 'foo'])).to.deep.equal([2,1]) describe "kozu.core.castArgumentsAsArray(x)", -> it "returns a new array copy when x is an Arguments object", -> ary = core.castArgumentsAsArray(core.args(1,2,3)) expect(ary).to.deep.equal([1,2,3]) expect(core.isArray(ary)).to.equal(true) it "returns x when x is not an Arguments object", -> ary = [1,2,3] expect(core.castArgumentsAsArray(ary)).to.equal(ary) describe "kozu.core.cons(x, xs)", -> it "returns a new array with x prepended before xs", -> expect(core.cons(1, [2, 3])).to.deep.equal([1,2,3]) describe "kozu.core.partialRest(func, ... args)", -> it "returns a partial application of func, starting from the second argument", -> makeArray = core.variadic(core.identity) somethingTwoThree = core.partialRest(makeArray, 2, 3) expect(somethingTwoThree(1)).to.deep.equal([1,2,3]) describe "kozu.core.merge(... objects)", -> it "returns a new object which merges the given objects, with the keys of later objects overwriting those of previous ones", -> a = {foo: 1, bar: 2} b = {bar: 3, baz: 4} c = {baz: 5, qux: 6} result = core.merge(a, b, c) expect(result).to.deep.equal({foo: 1, bar: 3, baz: 5, qux: 6}) expect(result).to.not.equal(a) expect(result).to.not.equal(b) expect(result).to.not.equal(c) describe "kozu.core.functionalize", -> it "wraps a method-style function (one which uses `this`) such that it only uses arguments", -> person = name: "<NAME>" nameWithSuffix: (suffix) -> @name + suffix personNameWithSuffix = core.functionalize(person.nameWithSuffix) expect(personNameWithSuffix(person, "!")).to.equal("<NAME>!") it "is aliased as rotatesThisOutOfArguments", -> expect(core.rotatesThisOutOfArguments).to.equal(core.functionalize) describe "kozu.core.methodize", -> it "wraps a function which does not rely on `this`, turning it into a method-style function such that the original's first argument is supplied as `this` by the caller", -> personNameWithSuffix = (person, suffix) -> person.name + suffix person = name: "<NAME>" nameWithSuffix: core.methodize(personNameWithSuffix) expect(person.nameWithSuffix("!")).to.equal("<NAME>!") it "is aliased as rotatesThisIntoArguments", -> expect(core.rotatesThisIntoArguments).to.equal(core.methodize) describe "kozu.core.congealed", -> it "takes a variadic function and returns a unary version which spreads a single array argument to the original", -> arrayToArgs = core.congealed(core.args) expect(arrayToArgs([1,2,3])).to.deep.equal(core.args(1,2,3)) it "is aliased as spreadsArguments", -> expect(core.spreadsArguments).to.equal(core.congealed) describe "kozu.core.variadic", -> it "takes a function which takes a single array argument and returns a variadic version which passes a slice of its arguments as a single argument to the original", -> makeArray = core.variadic(core.identity) expect(makeArray(1,2,3)).to.deep.equal([1,2,3]) it "is aliased as gathersArguments", -> expect(core.gathersArguments).to.equal(core.variadic) describe "kozu.core.flip2", -> it "takes a function of 2 arguments and returns a new version of the function with its arguments flipped", -> divide = (a, b) -> a / b expect(core.flip2(divide)(2, 4)).to.equal(2) describe "kozu.core.mergesReturnValueOntoArgument(func)", -> it "wraps func such that the return value is `merge`d onto the first argument before being returned", -> f = core.mergesReturnValueOntoArgument(-> {ctx: this, args: core.castArgumentsAsArray(arguments), return: "return"}) expect(f.call({a: 1}, {b: 2, foo: "bar"}, {c: 3})).to.deep.equal b: 2 foo: "bar" ctx: {a: 1} args: [{b: 2, foo: "bar"}, {c: 3}] return: "return" describe "kozu.core.gathersThisAndArguments", -> it "wraps a function such that the new version gathers its many inputs into a single array of [this, ... arguments] which is passed to the wrapped function", -> result = core.gathersThisAndArguments(core.identity).call({a: 1}, 1, 2, 3) expect(result).to.deep.equal [{a: 1}, 1, 2, 3] describe "kozu.core.spreadsThisAndArguments", -> it "wraps a function such that the new version spreads its single array argument of [this, ... arguments] into `this` and `arguments` for the wrapped function", -> result = core.spreadsThisAndArguments(-> [this, arguments])([{a: 1}, 1, 2, 3]) expect(result).to.deep.equal([{a: 1}, core.args(1, 2, 3)]) describe "kozu.core.extractsKeys(... keys)", -> it "returns a function wrapper which takes a variadic function and returns a function which takes an object and uses the values at the given keys as the arguments for the original", -> fooPlusBar = core.extractsKeys('foo', 'bar')((foo, bar) -> foo + bar) expect(fooPlusBar({foo: 1, bar: 2, baz: 3})).to.equal(3) describe "kozu.core.transformsArgumentWith(func)", -> it "returns a function wrapper which transforms the wrapped function's argument with func", -> plus1wrapper = core.transformsArgumentWith(plus1) expect(plus1wrapper(times2)(5)).to.equal(12) describe "kozu.core.transformsReturnValueWith(func)", -> it "returns a function wrapper which transforms the wrapped function's return value with func", -> plus1wrapper = core.transformsReturnValueWith(plus1) expect(plus1wrapper(times2)(5)).to.equal(11) describe "kozu.core.mapper(func)", -> it "returns a function which takes an array and maps func onto it", -> mapIncrement = core.mapper(plus1) expect(mapIncrement([1,2,3])).to.deep.equal([2,3,4]) describe "kozu.core.joiner(separator)", -> it "returns a function which joins an array with the given string", -> expect(core.joiner("-")(["foo", "bar"])).to.equal("foo-bar") describe "kozu.core.argumentMapper(func)", -> it "returns a function which maps func onto its arguments", -> expect(core.argumentMapper(plus1)(1,2,3)).to.deep.equal([2,3,4]) describe "kozu.core.argumentJoiner(separator)", -> it "returns a function which joins its arguments with the given string", -> expect(core.argumentJoiner("-")("foo", "bar")).to.equal("foo-bar")
true
expect = require("chai").expect core = require("../../../../../lib/kozu/core") plus1 = (n) -> n+1 times2 = (n) -> n*2 exclaim = (x) -> "#{x}!" describe "kozu.core.compose(... funcs)", -> it "calls from right to left", -> times2plus1 = core.compose(plus1, times2) expect(times2plus1(3)).to.equal(7) describe "kozu.core.pipe(x, ... funcs)", -> it "calls funcs on x from left to right", -> expect(core.pipe(3, times2, plus1)).to.equal(7) describe "kozu.core.partialRest(func, args...)", -> it "partial application of func with args as the rest of the args after the first", -> mathy = core.partialRest(core.compose, plus1, times2) expect(mathy(exclaim) 3).to.equal("7!") describe "kozu.core.get(obj, key)", -> it "returns obj[key]", -> expect(core.get({foo: 2}, "foo")).to.equal(2) describe "kozu.core.getter(key)", -> it "returns a function which takes an object and returns obj[key]", -> fooGetter = core.getter('foo') expect(fooGetter({foo: 2})).to.equal(2) describe "kozu.core.args", -> it "returns its arguments object", -> expect(Object::toString.call(core.args(1,2,3))).to.equal("[object Arguments]") describe "kozu.core.factory(constructor)", -> it "returns a variadic function which returns a new instance of the constructor with the given arguments", -> class Foo constructor: (@a, @b) -> fooFactory = core.factory(Foo) foo = fooFactory(1,2) expect(foo.a).to.equal(1) expect(foo.b).to.equal(2) expect(foo.constructor).to.equal(Foo) describe "kozu.core.multiGet(obj, keys)", -> it "returns an array of the values in obj at keys", -> expect(core.multiGet({foo: 1, bar: 2, baz: 3}, ['bar', 'foo'])).to.deep.equal([2,1]) describe "kozu.core.castArgumentsAsArray(x)", -> it "returns a new array copy when x is an Arguments object", -> ary = core.castArgumentsAsArray(core.args(1,2,3)) expect(ary).to.deep.equal([1,2,3]) expect(core.isArray(ary)).to.equal(true) it "returns x when x is not an Arguments object", -> ary = [1,2,3] expect(core.castArgumentsAsArray(ary)).to.equal(ary) describe "kozu.core.cons(x, xs)", -> it "returns a new array with x prepended before xs", -> expect(core.cons(1, [2, 3])).to.deep.equal([1,2,3]) describe "kozu.core.partialRest(func, ... args)", -> it "returns a partial application of func, starting from the second argument", -> makeArray = core.variadic(core.identity) somethingTwoThree = core.partialRest(makeArray, 2, 3) expect(somethingTwoThree(1)).to.deep.equal([1,2,3]) describe "kozu.core.merge(... objects)", -> it "returns a new object which merges the given objects, with the keys of later objects overwriting those of previous ones", -> a = {foo: 1, bar: 2} b = {bar: 3, baz: 4} c = {baz: 5, qux: 6} result = core.merge(a, b, c) expect(result).to.deep.equal({foo: 1, bar: 3, baz: 5, qux: 6}) expect(result).to.not.equal(a) expect(result).to.not.equal(b) expect(result).to.not.equal(c) describe "kozu.core.functionalize", -> it "wraps a method-style function (one which uses `this`) such that it only uses arguments", -> person = name: "PI:NAME:<NAME>END_PI" nameWithSuffix: (suffix) -> @name + suffix personNameWithSuffix = core.functionalize(person.nameWithSuffix) expect(personNameWithSuffix(person, "!")).to.equal("PI:NAME:<NAME>END_PI!") it "is aliased as rotatesThisOutOfArguments", -> expect(core.rotatesThisOutOfArguments).to.equal(core.functionalize) describe "kozu.core.methodize", -> it "wraps a function which does not rely on `this`, turning it into a method-style function such that the original's first argument is supplied as `this` by the caller", -> personNameWithSuffix = (person, suffix) -> person.name + suffix person = name: "PI:NAME:<NAME>END_PI" nameWithSuffix: core.methodize(personNameWithSuffix) expect(person.nameWithSuffix("!")).to.equal("PI:NAME:<NAME>END_PI!") it "is aliased as rotatesThisIntoArguments", -> expect(core.rotatesThisIntoArguments).to.equal(core.methodize) describe "kozu.core.congealed", -> it "takes a variadic function and returns a unary version which spreads a single array argument to the original", -> arrayToArgs = core.congealed(core.args) expect(arrayToArgs([1,2,3])).to.deep.equal(core.args(1,2,3)) it "is aliased as spreadsArguments", -> expect(core.spreadsArguments).to.equal(core.congealed) describe "kozu.core.variadic", -> it "takes a function which takes a single array argument and returns a variadic version which passes a slice of its arguments as a single argument to the original", -> makeArray = core.variadic(core.identity) expect(makeArray(1,2,3)).to.deep.equal([1,2,3]) it "is aliased as gathersArguments", -> expect(core.gathersArguments).to.equal(core.variadic) describe "kozu.core.flip2", -> it "takes a function of 2 arguments and returns a new version of the function with its arguments flipped", -> divide = (a, b) -> a / b expect(core.flip2(divide)(2, 4)).to.equal(2) describe "kozu.core.mergesReturnValueOntoArgument(func)", -> it "wraps func such that the return value is `merge`d onto the first argument before being returned", -> f = core.mergesReturnValueOntoArgument(-> {ctx: this, args: core.castArgumentsAsArray(arguments), return: "return"}) expect(f.call({a: 1}, {b: 2, foo: "bar"}, {c: 3})).to.deep.equal b: 2 foo: "bar" ctx: {a: 1} args: [{b: 2, foo: "bar"}, {c: 3}] return: "return" describe "kozu.core.gathersThisAndArguments", -> it "wraps a function such that the new version gathers its many inputs into a single array of [this, ... arguments] which is passed to the wrapped function", -> result = core.gathersThisAndArguments(core.identity).call({a: 1}, 1, 2, 3) expect(result).to.deep.equal [{a: 1}, 1, 2, 3] describe "kozu.core.spreadsThisAndArguments", -> it "wraps a function such that the new version spreads its single array argument of [this, ... arguments] into `this` and `arguments` for the wrapped function", -> result = core.spreadsThisAndArguments(-> [this, arguments])([{a: 1}, 1, 2, 3]) expect(result).to.deep.equal([{a: 1}, core.args(1, 2, 3)]) describe "kozu.core.extractsKeys(... keys)", -> it "returns a function wrapper which takes a variadic function and returns a function which takes an object and uses the values at the given keys as the arguments for the original", -> fooPlusBar = core.extractsKeys('foo', 'bar')((foo, bar) -> foo + bar) expect(fooPlusBar({foo: 1, bar: 2, baz: 3})).to.equal(3) describe "kozu.core.transformsArgumentWith(func)", -> it "returns a function wrapper which transforms the wrapped function's argument with func", -> plus1wrapper = core.transformsArgumentWith(plus1) expect(plus1wrapper(times2)(5)).to.equal(12) describe "kozu.core.transformsReturnValueWith(func)", -> it "returns a function wrapper which transforms the wrapped function's return value with func", -> plus1wrapper = core.transformsReturnValueWith(plus1) expect(plus1wrapper(times2)(5)).to.equal(11) describe "kozu.core.mapper(func)", -> it "returns a function which takes an array and maps func onto it", -> mapIncrement = core.mapper(plus1) expect(mapIncrement([1,2,3])).to.deep.equal([2,3,4]) describe "kozu.core.joiner(separator)", -> it "returns a function which joins an array with the given string", -> expect(core.joiner("-")(["foo", "bar"])).to.equal("foo-bar") describe "kozu.core.argumentMapper(func)", -> it "returns a function which maps func onto its arguments", -> expect(core.argumentMapper(plus1)(1,2,3)).to.deep.equal([2,3,4]) describe "kozu.core.argumentJoiner(separator)", -> it "returns a function which joins its arguments with the given string", -> expect(core.argumentJoiner("-")("foo", "bar")).to.equal("foo-bar")
[ { "context": "erver = http.createServer(app).listen undefined, '127.0.0.1', ->\n # Obviously, we need to know the port to", "end": 1996, "score": 0.9997673034667969, "start": 1987, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "on, '99'\n assert.deepEqual session....
test/server.coffee
lever/node-browserchannel
108
# # Unit tests for BrowserChannel server # # This contains all the unit tests to make sure the server works like it # should. The tests are written using mocha - you can run them using # % npm test # # For now I'm not going to add in any SSL testing code. I should probably generate # a self-signed key pair, start the server using https and make sure that I can # still use it. # # I'm also missing integration tests. http = require 'http' assert = require 'assert' querystring = require 'querystring' express = require 'express' timer = require 'timerstub' browserChannel = require('..').server browserChannel._setTimerMethods timer # This function provides an easy way for tests to create a new browserchannel server using # connect(). # # I'll create a new server in the setup function of all the tests, but some # tests will need to customise the options, so they can just create another server directly. createServer = (opts, method, callback) -> # Its possible to use the browserChannel middleware without specifying an options # object. This little createServer function will mirror that behaviour. if typeof opts == 'function' [method, callback] = [opts, method] # I want to match up with how its actually going to be used. bc = browserChannel method else bc = browserChannel opts, method # The server is created using connect middleware. I'll simulate other middleware in # the stack by adding a second handler which responds with 200, 'Other middleware' to # any request. app = express() app.use bc app.use (req, res, next) -> # I might not actually need to specify the headers here... (If you don't, nodejs provides # some defaults). res.writeHead 200, 'OK', 'Content-Type': 'text/plain' res.end 'Other middleware' # Calling server.listen() without a port lets the OS pick a port for us. I don't # know why more testing frameworks don't do this by default. server = http.createServer(app).listen undefined, '127.0.0.1', -> # Obviously, we need to know the port to be able to make requests from the server. # The callee could check this itself using the server object, but it'll always need # to know it, so its easier pulling the port out here. port = server.address().port callback server, port, bc # Wait for the function to be called a given number of times, then call the callback. # # This useful little method has been stolen from ShareJS expectCalls = (n, callback) -> return callback() if n == 0 remaining = n -> remaining-- if remaining == 0 callback() else if remaining < 0 throw new Error "expectCalls called more than #{n} times" # This returns a function that calls done() after it has been called n times. Its # useful when you want a bunch of mini tests inside one test case. makePassPart = (test, n) -> expectCalls n, -> done() # Most of these tests will make HTTP requests. A lot of the time, we don't care about the # timing of the response, we just want to know what it was. This method will buffer the # response data from an http response object and when the whole response has been received, # send it on. buffer = (res, callback) -> data = [] res.on 'data', (chunk) -> #console.warn chunk.toString() data.push chunk.toString 'utf8' res.on 'end', -> callback? data.join '' # For some tests we expect certain data, delivered in chunks. Wait until we've # received at least that much data and strcmp. The response will probably be used more, # afterwards, so we'll make sure the listener is removed after we're done. expect = (res, str, callback) -> data = '' res.on 'end', endlistener = -> # This should fail - if the data was as long as str, we would have compared them # already. Its important that we get an error message if the http connection ends # before the string has been received. console.warn 'Connection ended prematurely' assert.strictEqual data, str res.on 'data', listener = (chunk) -> # I'm using string += here because the code is easier that way. data += chunk.toString 'utf8' #console.warn JSON.stringify data #console.warn JSON.stringify str if data.length >= str.length assert.strictEqual data, str res.removeListener 'data', listener res.removeListener 'end', endlistener callback() # A bunch of tests require that we wait for a network connection to get established # before continuing. # # We'll do that using a setTimeout with plenty of time. I hate adding delays, but I # can't see another way to do this. # # This should be plenty of time. I might even be able to reduce this. Note that this # is a real delay, not a stubbed out timer like we give to the server. soon = (f) -> setTimeout f, 10 readLengthPrefixedString = (res, callback) -> data = '' length = null res.on 'data', listener = (chunk) -> data += chunk.toString 'utf8' if length == null # The number of bytes is written in an int on the first line. lines = data.split '\n' # If lines length > 1, then we've read the first newline, which was after the length # field. if lines.length > 1 length = parseInt lines.shift() # Now we'll rewrite the data variable to not include the length. data = lines.join '\n' if data.length == length res.removeListener 'data', listener callback data else if data.length > length console.warn data throw new Error "Read more bytes from stream than expected" # The backchannel is implemented using a bunch of messages which look like this: # # ``` # 36 # [[0,["c","92208FBF76484C10",,8] # ] # ] # ``` # # (At least, thats what they look like using google's server. On mine, they're properly # formatted JSON). # # Each message has a length string (in bytes) followed by a newline and some JSON data. # They can optionally have extra chunks afterwards. # # This format is used for: # # - All XHR backchannel messages # - The response to the initial connect (XHR or HTTP) # - The server acknowledgement to forward channel messages # # This is not used when you're on IE, for normal backchannel requests. On IE, data is sent # through javascript calls from an iframe. readLengthPrefixedJSON = (res, callback) -> readLengthPrefixedString res, (data) -> callback JSON.parse(data) # Copied from google's implementation. The contents of this aren't actually relevant, # but I think its important that its pseudo-random so if the connection is compressed, # it still recieves a bunch of bytes after the first message. ieJunk = "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffe\ e0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c47\ 9050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44\ a9fe92fedacffff48092ee693af\n" suite 'server', -> # #### setup # # Before each test has run, we'll start a new server. The server will only live # for that test and then it'll be torn down again. # # This makes the tests run more slowly, but not slowly enough that I care. setup (callback) -> # This will make sure there's no pesky setTimeouts from previous tests kicking around. # I could instead do a timer.waitAll() in tearDown to let all the timers run & time out # the running sessions. It shouldn't be a big deal. timer.clearAll() # When you instantiate browserchannel, you specify a function which gets called # with each session that connects. I'll proxy that function call to a local function # which tests can override. @onSession = (session) -> # The proxy is inline here. Also, I <3 coffeescript's (@server, @port) -> syntax here. # That will automatically set this.server and this.port to the callback arguments. # # Actually calling the callback starts the test. createServer ((session) => @onSession session), (@server, @port, @bc) => # TODO - This should be exported from lib/server @standardHeaders= 'Content-Type': 'text/plain' 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate' 'Pragma': 'no-cache' 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT' 'X-Content-Type-Options': 'nosniff' # I'll add a couple helper methods for tests to easily message the server. @get = (path, callback) => http.get {host:'localhost', path, @port}, callback @post = (path, data, callback) => req = http.request {method:'POST', host:'localhost', path, @port}, callback req.end data # One of the most common tasks in tests is to create a new session for # some reason. @connect is a little helper method for that. It simply sends the # http POST to create a new session and calls the callback when the session has been # created by the server. # # It also makes @onSession throw an error - very few tests need multiple sessions, # so I special case them when they do. # # Its kind of annoying - for a lot of tests I need to do custom logic in the @post # handler *and* custom logic in @onSession. So, callback can be an object specifying # callbacks for each if you want that. Its a shame though, it makes this function # kinda ugly :/ @connect = (callback) => # This connect helper method is only useful if you don't care about the initial # post response. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0' @onSession = (@session) => @onSession = -> throw new Error 'onSession() called - I didn\'t expect another session to be created' # Keep this bound. I think there's a fancy way to do this in coffeescript, but # I'm not sure what it is. callback.call this # Finally, start the test. callback() teardown (callback) -> # #### tearDown # # This is called after each tests is done. We'll tear down the server we just created. # # The next test is run once the callback is called. I could probably chain the next # test without waiting for close(), but then its possible that an exception thrown # in one test will appear after the next test has started running. Its easier to debug # like this. @server.close callback # The server hosts the client-side javascript at /channel.js. It should have headers set to tell # browsers its javascript. # # Its self contained, with no dependancies on anything. It would be nice to test it as well, # but we'll do that elsewhere. test 'The javascript is hosted at channel/bcsocket.js', (done) -> @get '/channel/bcsocket.js', (response) -> assert.strictEqual response.statusCode, 200 assert.strictEqual response.headers['content-type'], 'application/javascript' assert.ok response.headers['etag'] buffer response, (data) -> # Its about 47k. If the size changes too drastically, I want to know about it. assert.ok data.length > 45000, "Client is unusually small (#{data.length} bytes)" assert.ok data.length < 50000, "Client is bloaty (#{data.length} bytes)" done() # # Testing channel tests # # The first thing a client does when it connects is issue a GET on /test/?mode=INIT. # The server responds with an array of [basePrefix or null,blockedPrefix or null]. Blocked # prefix isn't supported by node-browerchannel and by default no basePrefix is set. So with no # options specified, this GET should return [null,null]. test 'GET /test/?mode=INIT with no baseprefix set returns [null, null]', (done) -> @get '/channel/test?VER=8&MODE=init', (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' done() # If a basePrefix is set in the options, make sure the server returns it. test 'GET /test/?mode=INIT with a basePrefix set returns [basePrefix, null]', (done) -> # You can specify a bunch of host prefixes. If you do, the server will randomly pick between them. # I don't know if thats actually useful behaviour, but *shrug* # I should probably write a test to make sure all host prefixes will be chosen from time to time. createServer hostPrefixes:['chan'], (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '["chan",null]' # I'm being slack here - the server might not close immediately. I could make done() # dependant on it, but I can't be bothered. server.close() done() # Setting a custom url endpoint to bind node-browserchannel to should make it respond at that url endpoint # only. test 'The test channel responds at a bound custom endpoint', (done) -> createServer base:'/foozit', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # Some people will miss out on the leading slash in the URL when they bind browserchannel to a custom # url. That should work too. test 'binding the server to a custom url without a leading slash works', (done) -> createServer base:'foozit', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # Its tempting to think that you need a trailing slash on your URL prefix as well. You don't, but that should # work too. test 'binding the server to a custom url with a trailing slash works', (done) -> # Some day, the copy+paste police are gonna get me. I don't feel *so* bad doing it for tests though, because # it helps readability. createServer base:'foozit/', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # You can control the CORS header ('Access-Control-Allow-Origin') using options.cors. test 'CORS header is not sent if its not set in the options', (done) -> @get '/channel/test?VER=8&MODE=init', (response) -> assert.strictEqual response.headers['access-control-allow-origin'], undefined assert.strictEqual response.headers['access-control-allow-credentials'], undefined response.socket.end() done() test 'CORS headers are sent during the initial phase if set in the options', (done) -> createServer cors:'foo.com', corsAllowCredentials:true, (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual response.headers['access-control-allow-credentials'], 'true' buffer response server.close() done() test 'CORS headers can be set using a function', (done) -> createServer cors: (-> 'something'), (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['access-control-allow-origin'], 'something' buffer response server.close() done() test 'CORS header is set on the backchannel response', (done) -> server = port = null sessionCreated = (session) -> # Make the backchannel flush as soon as its opened session.send "flush" req = http.get {path:"/channel/bind?VER=8&RID=rpc&SID=#{session.id}&AID=0&TYPE=xmlhttp&CI=0", host:'localhost', port:port}, (res) => assert.strictEqual res.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual res.headers['access-control-allow-credentials'], 'true' req.abort() server.close() done() createServer cors:'foo.com', corsAllowCredentials:true, sessionCreated, (_server, _port) -> [server, port] = [_server, _port] req = http.request {method:'POST', path:'/channel/bind?VER=8&RID=1000&t=1', host:'localhost', port:port}, (res) => req.end 'count=0' # This test is just testing one of the error responses for the presence of # the CORS header. It doesn't test all of the ports, and doesn't test IE. # (I'm not actually sure if CORS headers are needed for IE stuff) suite 'CORS header is set in error responses', -> setup (callback) -> createServer cors:'foo.com', corsAllowCredentials:true, (->), (@corsServer, @corsPort) => callback() teardown -> @corsServer.close() testResponse = (done, req, res) -> assert.strictEqual res.statusCode, 400 assert.strictEqual res.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual res.headers['access-control-allow-credentials'], 'true' buffer res, (data) -> assert.ok data.indexOf('Unknown SID') > 0 req.abort() done() test 'backChannel', (done) -> req = http.get {path:'/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=xmlhttp&CI=0', host:'localhost', port:@corsPort}, (res) => testResponse done, req, res test 'forwardChannel', (done) -> req = http.request {method:'POST', path:'/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0', host:'localhost', port:@corsPort}, (res) => testResponse done, req, res req.end 'count=0' #@post "/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0", 'count=0', testResponse(done) test 'Additional headers can be specified in the options', (done) -> createServer headers:{'X-Foo':'bar'}, (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['x-foo'], 'bar' server.close() done() # Interestingly, the CORS header isn't required for old IE (type=html) requests because they're loaded using # iframes anyway. (Though this should really be tested). # node-browserchannel is only responsible for URLs with the specified (or default) prefix. If a request # comes in for a URL outside of that path, it should be passed along to subsequent connect middleware. # # I've set up the createServer() method above to send 'Other middleware' if browserchannel passes # the response on to the next handler. test 'getting a url outside of the bound range gets passed to other middleware', (done) -> @get '/otherapp', (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, 'Other middleware' done() # I decided to make URLs inside the bound range return 404s directly. I can't guarantee that no future # version of node-browserchannel won't add more URLs in the zone, so its important that users don't decide # to start using arbitrary other URLs under channel/. # # That design decision makes it impossible to add a custom 404 page to /channel/FOO, but I don't think thats a # big deal. test 'getting a wacky url inside the bound range returns 404', (done) -> @get '/channel/doesnotexist', (response) -> assert.strictEqual response.statusCode, 404 response.socket.end() done() # For node-browserchannel, we also accept JSON in forward channel POST data. To tell the client that # this is supported, we add an `X-Accept: application/json; application/x-www-form-urlencoded` header # in phase 1 of the test API. test 'The server sends accept:JSON header during test phase 1', (done) -> @get '/channel/test?VER=8&MODE=init', (res) -> assert.strictEqual res.headers['x-accept'], 'application/json; application/x-www-form-urlencoded' res.socket.end() done() # All the standard headers should be sent along with X-Accept test 'The server sends standard headers during test phase 1', (done) -> @get '/channel/test?VER=8&MODE=init', (res) => assert.strictEqual res.headers[k.toLowerCase()].toLowerCase(), v.toLowerCase() for k,v of @standardHeaders res.socket.end() done() # ## Testing phase 2 # # I should really sort the above tests better. # # Testing phase 2 the client GETs /channel/test?VER=8&TYPE= [html / xmlhttp] &zx=558cz3evkwuu&t=1 [&DOMAIN=xxxx] # # The server sends '11111' <2 second break> '2'. If you use html encoding instead, the server sends the client # a webpage which calls: # # document.domain='mail.google.com'; # parent.m('11111'); # parent.m('2'); # parent.d(); suite 'Getting test phase 2 returns 11111 then 2', -> makeTest = (type, message1, message2) -> (done) -> @get "/channel/test?VER=8&TYPE=#{type}", (response) -> assert.strictEqual response.statusCode, 200 expect response, message1, -> # Its important to make sure that message 2 isn't sent too soon (<2 seconds). # We'll advance the server's clock forward by just under 2 seconds and then wait a little bit # for messages from the client. If we get a message during this time, throw an error. response.on 'data', f = -> throw new Error 'should not get more data so early' timer.wait 1999, -> soon -> response.removeListener 'data', f expect response, message2, -> response.once 'end', -> done() timer.wait 1 test 'xmlhttp', makeTest 'xmlhttp', '11111', '2' # I could write this test using JSDom or something like that, and parse out the HTML correctly. # ... but it would be way more complicated (and no more correct) than simply comparing the resulting # strings. test 'html', makeTest('html', # These HTML responses are identical to what I'm getting from google's servers. I think the seemingly # random sequence is just so network framing doesn't try and chunk up the first packet sent to the server # or something like that. """<html><body><script>try {parent.m("11111")} catch(e) {}</script>\n#{ieJunk}""", '''<script>try {parent.m("2")} catch(e) {}</script> <script>try {parent.d(); }catch (e){}</script>\n''') # If a client is connecting with a host prefix, the server sets the iframe's document.domain to match # before sending actual data. 'html with a host prefix': makeTest('html&DOMAIN=foo.bar.com', # I've made a small change from google's implementation here. I'm using double quotes `"` instead of # single quotes `'` because its easier to encode. (I can't just wrap the string in quotes because there # are potential XSS vulnerabilities if I do that). """<html><body><script>try{document.domain="foo.bar.com";}catch(e){}</script> <script>try {parent.m("11111")} catch(e) {}</script>\n#{ieJunk}""", '''<script>try {parent.m("2")} catch(e) {}</script> <script>try {parent.d(); }catch (e){}</script>\n''') # IE doesn't parse the HTML in the response unless the Content-Type is text/html test 'Using type=html sets Content-Type: text/html', (done) -> r = @get "/channel/test?VER=8&TYPE=html", (response) -> assert.strictEqual response.headers['content-type'], 'text/html' r.abort() done() # IE should also get the standard headers test 'Using type=html gets the standard headers', (done) -> r = @get "/channel/test?VER=8&TYPE=html", (response) => for k, v of @standardHeaders when k isnt 'Content-Type' assert.strictEqual response.headers[k.toLowerCase()].toLowerCase(), v.toLowerCase() r.abort() done() # node-browserchannel is only compatible with browserchannel client version 8. I don't know whats changed # since old versions (maybe v6 would be easy to support) but I don't care. If the client specifies # an old version, we'll die with an error. # The alternate phase 2 URL style should have the same behaviour if the version is old or unspecified. # # Google's browserchannel server still works if you miss out on specifying the version - it defaults # to version 1 (which maybe didn't have version numbers in the URLs). I'm kind of impressed that # all that code still works. suite 'Getting /test/* without VER=8 returns an error', -> # All these tests look 95% the same. Instead of writing the same test all those times, I'll use this # little helper method to generate them. check400 = (path) -> (done) -> @get path, (response) -> assert.strictEqual response.statusCode, 400 response.socket.end() done() test 'phase 1, ver 7', check400 '/channel/test?VER=7&MODE=init' test 'phase 1, no version', check400 '/channel/test?MODE=init' test 'phase 2, ver 7, xmlhttp', check400 '/channel/test?VER=7&TYPE=xmlhttp' test 'phase 2, no version, xmlhttp', check400 '/channel/test?TYPE=xmlhttp' # For HTTP connections (IE), the error is sent a different way. Its kinda complicated how the error # is sent back, so for now I'm just going to ignore checking it. test 'phase 2, ver 7, http', check400 '/channel/test?VER=7&TYPE=html' test 'phase 2, no version, http', check400 '/channel/test?TYPE=html' # > At the moment the server expects the client will add a zx=###### query parameter to all requests. # The server isn't strict about this, so I'll ignore it in the tests for now. # # Server connection tests # These tests make server sessions by crafting raw HTTP queries. I'll make another set of # tests later which spam the server with a million fake clients. # # To start with, simply connect to a server using the BIND API. A client sends a server a few parameters: # # - **CVER**: Client application version # - **RID**: Client-side generated random number, which is the initial sequence number for the # client's requests. # - **VER**: Browserchannel protocol version. Must be 8. # - **t**: The connection attempt number. This is currently ignored by the BC server. (I'm not sure # what google's implementation does with this). test 'The server makes a new session if the client POSTs the right connection stuff', (done) -> id = null onSessionCalled = no # When a request comes in, we should get the new session through the server API. # # We need this session in order to find out the session ID, which should match up with part of the # server's response. @onSession = (session) -> assert.ok session assert.strictEqual typeof session.id, 'string' assert.strictEqual session.state, 'init' assert.strictEqual session.appVersion, '99' assert.deepEqual session.address, '127.0.0.1' assert.strictEqual typeof session.headers, 'object' id = session.id session.on 'map', -> throw new Error 'Should not have received data' onSessionCalled = yes # The client starts a BC connection by POSTing to /bind? with no session ID specified. # The client can optionally send data here, but in this case it won't (hence the `count=0`). @post '/channel/bind?VER=8&RID=1000&CVER=99&t=1&junk=asdfasdf', 'count=0', (res) => expected = (JSON.stringify [[0, ['c', id, null, 8]]]) + '\n' buffer res, (data) -> # Even for old IE clients, the server responds in length-prefixed JSON style. assert.strictEqual data, "#{expected.length}\n#{expected}" assert.ok onSessionCalled done() # Once a client's session id is sent, the session moves to the `ok` state. This happens after onSession is # called (so onSession can send messages to the client immediately). # # I'm starting to use the @connect method here, which just POSTs locally to create a session, sets @session and # calls its callback. test 'A session has state=ok after onSession returns', (done) -> @connect -> @session.on 'state changed', (newState, oldState) => assert.strictEqual oldState, 'init' assert.strictEqual newState, 'ok' assert.strictEqual @session.state, 'ok' done() # The CVER= property is optional during client connections. If its left out, session.appVersion is # null. test 'A session connects ok even if it doesnt specify an app version', (done) -> id = null onSessionCalled = no @onSession = (session) -> assert.strictEqual session.appVersion, null id = session.id session.on 'map', -> throw new Error 'Should not have received data' onSessionCalled = yes @post '/channel/bind?VER=8&RID=1000&t=1&junk=asdfasdf', 'count=0', (res) => expected = (JSON.stringify [[0, ['c', id, null, 8]]]) + '\n' buffer res, (data) -> assert.strictEqual data, "#{expected.length}\n#{expected}" assert.ok onSessionCalled done() # Once again, only VER=8 works. suite 'Connecting with a version thats not 8 breaks', -> # This will POST to the requested path and make sure the response sets status 400 check400 = (path) -> (done) -> @post path, 'count=0', (response) -> assert.strictEqual response.statusCode, 400 response.socket.end() done() test 'no version', check400 '/channel/bind?RID=1000&t=1' test 'previous version', check400 '/channel/bind?VER=7&RID=1000&t=1' # This time, we'll send a map to the server during the initial handshake. This should be received # by the server as normal. test 'The client can post messages to the server during initialization', (done) -> @onSession = (session) -> session.on 'map', (data) -> assert.deepEqual data, {k:'v'} done() @post '/channel/bind?VER=8&RID=1000&t=1', 'count=1&ofs=0&req0_k=v', (res) => res.socket.end() # The data received by the server should be properly URL decoded and whatnot. test 'Server messages are properly URL decoded', (done) -> @onSession = (session) -> session.on 'map', (data) -> assert.deepEqual data, {"_int_^&^%#net":'hi"there&&\nsam'} done() @post('/channel/bind?VER=8&RID=1000&t=1', 'count=1&ofs=0&req0__int_%5E%26%5E%25%23net=hi%22there%26%26%0Asam', (res) -> res.socket.end()) # After a client connects, it can POST data to the server using URL-encoded POST data. This data # is sent by POSTing to /bind?SID=.... # # The data looks like this: # # count=5&ofs=1000&req0_KEY1=VAL1&req0_KEY2=VAL2&req1_KEY3=req1_VAL3&... test 'The client can post messages to the server after initialization', (done) -> @connect -> @session.on 'map', (data) -> assert.deepEqual data, {k:'v'} done() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => res.socket.end() # When the server gets a forwardchannel request, it should reply with a little array saying whats # going on. test 'The server acknowledges forward channel messages correctly', (done) -> @connect -> @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => readLengthPrefixedJSON res, (data) => # The server responds with [backchannelMissing ? 0 : 1, lastSentAID, outstandingBytes] assert.deepEqual data, [0, 0, 0] done() # If the server has an active backchannel, it responds to forward channel requests notifying the client # that the backchannel connection is alive and well. test 'The server tells the client if the backchannel is alive', (done) -> @connect -> # This will fire up a backchannel connection to the server. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp", (res) => # The client shouldn't get any data through the backchannel. res.on 'data', -> throw new Error 'Should not get data through backchannel' # Unfortunately, the GET request is sent *after* the POST, so we have to wrap the # post in a timeout to make sure it hits the server after the backchannel connection is # established. soon => @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => readLengthPrefixedJSON res, (data) => # This time, we get a 1 as the first argument because the backchannel connection is # established. assert.deepEqual data, [1, 0, 0] # The backchannel hasn't gotten any data yet. It'll spend 15 seconds or so timing out # if we don't abort it manually. # As of nodejs 0.6, if you abort() a connection, it can emit an error. req.on 'error', -> req.abort() done() # The forward channel response tells the client how many unacknowledged bytes there are, so it can decide # whether or not it thinks the backchannel is dead. test 'The server tells the client how much unacknowledged data there is in the post response', (done) -> @connect -> process.nextTick => # I'm going to send a few messages to the client and acknowledge the first one in a post response. @session.send 'message 1' @session.send 'message 2' @session.send 'message 3' # We'll make a backchannel and get the data req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => # After the data is received, I'll acknowledge the first message using an empty POST @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=1", 'count=0', (res) => readLengthPrefixedJSON res, (data) => # We should get a response saying "The backchannel is connected", "The last message I sent was 3" # "messages 2 and 3 haven't been acknowledged, here's their size" assert.deepEqual data, [1, 3, 25] req.abort() done() # When the user calls send(), data is queued by the server and sent into the next backchannel connection. # # The server will use the initial establishing connection if thats available, or it'll send it the next # time the client opens a backchannel connection. test 'The server returns data on the initial connection when send is called immediately', (done) -> testData = ['hello', 'there', null, 1000, {}, [], [555]] @onSession = (@session) => @session.send testData # I'm not using @connect because we need to know about the response to the first POST. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[0, ['c', @session.id, null, 8]], [1, testData]] done() test 'The server escapes tricky characters before sending JSON over the wire', (done) -> testData = {'a': 'hello\u2028\u2029there\u2028\u2029'} @onSession = (@session) => @session.send testData # I'm not using @connect because we need to know about the response to the first POST. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedString res, (data) => assert.deepEqual data, """[[0,["c","#{@session.id}",null,8]],[1,{"a":"hello\\u2028\\u2029there\\u2028\\u2029"}]]\n""" done() test 'The server buffers data if no backchannel is available', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] # The first response to the server is sent after this method returns, so if we send the data # in process.nextTick, it'll get buffered. process.nextTick => @session.send testData req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] req.abort() done() # This time, we'll fire up the back channel first (and give it time to get established) _then_ # send data through the session. test 'The server returns data through the available backchannel when send is called later', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] # Fire off the backchannel request as soon as the client has connected req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) -> #res.on 'data', (chunk) -> console.warn chunk.toString() readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, testData]] req.abort() done() # Send the data outside of the get block to make sure it makes it through. soon => @session.send testData # The server should call the send callback once the data has been confirmed by the client. # # We'll try sending three messages to the client. The first message will be sent during init and the # third message will not be acknowledged. Only the first two message callbacks should get called. test 'The server calls send callback once data is acknowledged', (done) -> @connect -> lastAck = null @session.send [1], -> assert.strictEqual lastAck, null lastAck = 1 process.nextTick => @session.send [2], -> assert.strictEqual lastAck, 1 # I want to give the test time to die soon -> done() # This callback should actually get called with an error after the client times out. ... but I'm not # giving timeouts a chance to run. @session.send [3], -> throw new Error 'Should not call unacknowledged send callback' req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[2, [2]], [3, [3]]] # Ok, now we'll only acknowledge the second message by sending AID=2 @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=2", 'count=0', (res) => res.socket.end() req.abort() # This tests for a regression - if the stop callback closed the connection, the server was crashing. test 'The send callback can stop the session', (done) -> @connect -> req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => # Acknowledge the stop message @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=2", 'count=0', (res) => res.socket.end() @session.stop => @session.close() soon -> req.abort() done() # If there's a proxy in the way which chunks up responses before sending them on, the client adds a # &CI=1 argument on the backchannel. This causes the server to end the HTTP query after each message # is sent, so the data is sent to the session. test 'The backchannel is closed after each packet if chunking is turned off', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # Instead of the usual CI=0 we're passing CI=1 here. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=1", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] res.on 'end', -> done() # Normally, the server doesn't close the connection after each backchannel message. test 'The backchannel is left open if CI=0', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] # After receiving the data, the client shouldn't close the connection. (At least, not unless # it times out naturally). res.on 'end', -> throw new Error 'connection should have stayed open' soon -> res.removeAllListeners 'end' req.abort() done() # On IE, the data is all loaded using iframes. The backchannel spits out data using inline scripts # in an HTML page. # # I've written this test separately from the tests above, but it would really make more sense # to rerun the same set of tests in both HTML and XHR modes to make sure the behaviour is correct # in both instances. test 'The server gives the client correctly formatted backchannel data if TYPE=html', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # The type is specified as an argument here in the query string. For this test, I'm making # CI=1, because the test is easier to write that way. # # In truth, I don't care about IE support as much as support for modern browsers. This might # be a mistake.. I'm not sure. IE9's XHR support should work just fine for browserchannel, # though google's BC client doesn't use it. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=html&CI=1", (res) => expect res, # Interestingly, google doesn't double-encode the string like this. Instead of turning # quotes `"` into escaped quotes `\"`, it uses unicode encoding to turn them into \42 and # stuff like that. I'm not sure why they do this - it produces the same effect in IE8. # I should test it in IE6 and see if there's any problems. """<html><body><script>try {parent.m(#{JSON.stringify JSON.stringify([[1, testData]]) + '\n'})} catch(e) {}</script> #{ieJunk}<script>try {parent.d(); }catch (e){}</script>\n""", => # Because I'm lazy, I'm going to chain on a test to make sure CI=0 works as well. data2 = {other:'data'} @session.send data2 # I'm setting AID=1 here to indicate that the client has seen array 1. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=html&CI=0", (res) => expect res, """<html><body><script>try {parent.m(#{JSON.stringify JSON.stringify([[2, data2]]) + '\n'})} catch(e) {}</script> #{ieJunk}""", => req.abort() done() # If there's a basePrefix set, the returned HTML sets `document.domain = ` before sending messages. # I'm super lazy, and just copy+pasting from the test above. There's probably a way to factor these tests # nicely, but I'm not in the mood to figure it out at the moment. test 'The server sets the domain if we have a domain set', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # This time we're setting DOMAIN=X, and the response contains a document.domain= block. Woo. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=html&CI=1&DOMAIN=foo.com", (res) => expect res, """<html><body><script>try{document.domain=\"foo.com\";}catch(e){}</script> <script>try {parent.m(#{JSON.stringify JSON.stringify([[1, testData]]) + '\n'})} catch(e) {}</script> #{ieJunk}<script>try {parent.d(); }catch (e){}</script>\n""", => data2 = {other:'data'} @session.send data2 req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=html&CI=0&DOMAIN=foo.com", (res) => expect res, # Its interesting - in the test channel, the ie junk comes right after the document.domain= line, # but in a backchannel like this it comes after. The behaviour here is the same in google's version. # # I'm not sure if its actually significant though. """<html><body><script>try{document.domain=\"foo.com\";}catch(e){}</script> <script>try {parent.m(#{JSON.stringify JSON.stringify([[2, data2]]) + '\n'})} catch(e) {}</script> #{ieJunk}""", => req.abort() done() # If a client thinks their backchannel connection is closed, they might open a second backchannel connection. # In this case, the server should close the old one and resume sending stuff using the new connection. test 'The server closes old backchannel connections', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # As usual, we'll get the sent data through the backchannel connection. The connection is kept open... @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => # ... and the data has been read. Now we'll open another connection and check that the first connection # gets closed. req2 = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res2) => res.on 'end', -> req2.on 'error', -> req2.abort() done() # The client attaches a sequence number (*RID*) to every message, to make sure they don't end up out-of-order at # the server's end. # # We'll purposefully send some messages out of order and make sure they're held and passed through in order. # # Gogo gadget reimplementing TCP. test 'The server orders forwardchannel messages correctly using RIDs', (done) -> @connect -> # @connect sets RID=1000. # We'll send 2 maps, the first one will be {v:1} then {v:0}. They should be swapped around by the server. lastVal = 0 @session.on 'map', (map) -> assert.strictEqual map.v, "#{lastVal++}", 'messages arent reordered in the server' done() if map.v == '2' # First, send `[{v:2}]` @post "/channel/bind?VER=8&RID=1002&SID=#{@session.id}&AID=0", 'count=1&ofs=2&req0_v=2', (res) => res.socket.end() # ... then `[{v:0}, {v:1}]` a few MS later. soon => @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=2&ofs=0&req0_v=0&req1_v=1', (res) => res.socket.end() # Again, think of browserchannel as TCP on top of UDP... test 'Repeated forward channel messages are discarded', (done) -> @connect -> gotMessage = false # The map must only be received once. @session.on 'map', (map) -> if gotMessage == false gotMessage = true else throw new Error 'got map twice' # POST the maps twice. @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() # Wait 50 milliseconds for the map to (maybe!) be received twice, then pass. soon -> assert.strictEqual gotMessage, true done() # The client can retry failed forwardchannel requests with additional maps. We may have gotten the failed # request. An error could have occurred when we reply. test 'Repeat forward channel messages can contain extra maps', (done) -> @connect -> # We should get exactly 2 maps, {v:0} then {v:1} maps = [] @session.on 'map', (map) -> maps.push map @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=2&ofs=0&req0_v=0&req1_v=1', (res) => res.socket.end() soon -> assert.deepEqual maps, [{v:0}, {v:1}] done() # With each request to the server, the client tells the server what array it saw last through the AID= parameter. # # If a client sends a subsequent backchannel request with an old AID= set, that means the client never saw the arrays # the server has previously sent. So, the server should resend them. test 'The server resends lost arrays if the client asks for them', (done) -> @connect -> process.nextTick => @session.send [1,2,3] @session.send [4,5,6] @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, [1,2,3]], [2, [4,5,6]]] # We'll resend that request, pretending that the client never saw the second array sent (`[4,5,6]`) req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[2, [4,5,6]]] # We don't need to abort the first connection because the server should close it. req.abort() done() # If you sleep your laptop or something, by the time you open it again the server could have timed out your session # so your session ID is invalid. This will also happen if the server gets restarted or something like that. # # The server should respond to any query requesting a nonexistant session ID with 400 and put 'Unknown SID' # somewhere in the message. (Actually, the BC client test is `indexOf('Unknown SID') > 0` so there has to be something # before that text in the message or indexOf will return 0. # # The google servers also set Unknown SID as the http status code, which is kinda neat. I can't check for that. suite 'If a client sends an invalid SID in a request, the server responds with 400 Unknown SID', -> testResponse = (done) -> (res) -> assert.strictEqual res.statusCode, 400 buffer res, (data) -> assert.ok data.indexOf('Unknown SID') > 0 done() test 'backChannel', (done) -> @get "/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=xmlhttp&CI=0", testResponse(done) test 'forwardChannel', (done) -> @post "/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0", 'count=0', testResponse(done) # When type=HTML, google's servers still send the same response back to the client. I'm not sure how it detects # the error, but it seems to work. So, I'll copy that behaviour. test 'backChannel with TYPE=html', (done) -> @get "/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=html&CI=0", testResponse(done) # When a client connects, it can optionally specify its old session ID and array ID. This solves the old IRC # ghosting problem - if the old session hasn't timed out on the server yet, you can temporarily be in a state where # multiple connections represent the same user. test 'If a client disconnects then reconnects, specifying OSID= and OAID=, the old session is destroyed', (done) -> @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => res.socket.end() # I want to check the following things: # # - on 'close' is called on the first session # - onSession is called with the second session # - on 'close' is called before the second session is created # # Its kinda gross managing all that state in one function... @onSession = (session1) => # As soon as the client has connected, we'll fire off a new connection claiming the previous session is old. @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{session1.id}&OAID=0", 'count=0', (res) => res.socket.end() c1Closed = false session1.on 'close', -> c1Closed = true # Once the first client has connected, I'm replacing @onSession so the second session's state can be handled # separately. @onSession = (session2) -> assert.ok c1Closed assert.strictEqual session1.state, 'closed' done() # The server might have already timed out an old connection. In this case, the OSID is ignored. test 'The server ignores OSID and OAID if the named session doesnt exist', (done) -> @post "/channel/bind?VER=8&RID=2000&t=1&OSID=doesnotexist&OAID=0", 'count=0', (res) => res.socket.end() # So small & pleasant! @onSession = (session) => assert.ok session done() # OAID is set in the ghosted connection as a final attempt to flush arrays. test 'The server uses OAID to confirm arrays in the old session before closing it', (done) -> @connect -> # We'll follow the same pattern as the first callback test waay above. We'll send three messages, one # in the first callback and two after. We'll pretend that just the first two messages made it through. lastMessage = null # We'll create a new session in a moment when we POST with OSID and OAID. @onSession = -> @session.send 1, (error) -> assert.ifError error assert.strictEqual lastMessage, null lastMessage = 1 # The final message callback should get called after the close event fires @session.on 'close', -> assert.strictEqual lastMessage, 2 process.nextTick => @session.send 2, (error) -> assert.ifError error assert.strictEqual lastMessage, 1 lastMessage = 2 @session.send 3, (error) -> assert.ok error assert.strictEqual lastMessage, 2 lastMessage = 3 assert.strictEqual error.message, 'Reconnected' soon -> req.abort() done() # And now we'll nuke the session and confirm the first two arrays. But first, its important # the client has a backchannel to send data to (confirming arrays before a backchannel is opened # to receive them is undefined and probably does something bad) req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => res.socket.end() @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{@session.id}&OAID=2", 'count=0', (res) => res.socket.end() test 'The session times out after awhile if it doesnt have a backchannel', (done) -> @connect -> start = timer.Date.now() @session.on 'close', (reason) -> assert.strictEqual reason, 'Timed out' # It should take at least 30 seconds. assert.ok timer.Date.now() - start >= 30000 done() timer.waitAll() test 'The session can be disconnected by firing a GET with TYPE=terminate', (done) -> @connect -> # The client doesn't seem to put AID= in here. I'm not sure why - could be a bug in the client. @get "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&TYPE=terminate", (res) -> # The response should be empty. buffer res, (data) -> assert.strictEqual data, '' @session.on 'close', (reason) -> # ... Its a manual disconnect. Is this reason string good enough? assert.strictEqual reason, 'Disconnected' done() test 'If a disconnect message reaches the client before some data, the data is still received', (done) -> @connect -> # The disconnect message is sent first, but its got a higher RID. It shouldn't be handled until # after the data. @get "/channel/bind?VER=8&RID=1003&SID=#{@session.id}&TYPE=terminate", (res) -> res.socket.end() soon => @post "/channel/bind?VER=8&RID=1002&SID=#{@session.id}&AID=0", 'count=1&ofs=1&req0_m=2', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_m=1', (res) => res.socket.end() maps = [] @session.on 'map', (data) -> maps.push data @session.on 'close', (reason) -> assert.strictEqual reason, 'Disconnected' assert.deepEqual maps, [{m:1}, {m:2}] done() # There's a slightly different codepath after a backchannel is opened then closed again. I want to make # sure it still works in this case. # # Its surprising how often this test fails. test 'The session times out if its backchannel is closed', (done) -> @connect -> process.nextTick => req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => res.socket.end() # I'll let the backchannel establish itself for a moment, and then nuke it. soon => req.on 'error', -> req.abort() # It should take about 30 seconds from now to timeout the connection. start = timer.Date.now() @session.on 'close', (reason) -> assert.strictEqual reason, 'Timed out' assert.ok timer.Date.now() - start >= 30000 done() # The timer sessionTimeout won't be queued up until after the abort() message makes it # to the server. I hate all these delays, but its not easy to write this test without them. soon -> timer.waitAll() # The server sends a little heartbeat across the backchannel every 20 seconds if there hasn't been # any chatter anyway. This keeps the machines en route from evicting the backchannel connection. # (noops are ignored by the client.) test 'A heartbeat is sent across the backchannel (by default) every 20 seconds', (done) -> @connect -> start = timer.Date.now() req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (msg) -> # this really just tests that one heartbeat is sent. assert.deepEqual msg, [[1, ['noop']]] assert.ok timer.Date.now() - start >= 20000 req.abort() done() # Once again, we can't call waitAll() until the request has hit the server. soon -> timer.waitAll() # So long as the backchannel stays open, the server should just keep sending heartbeats and # the session doesn't timeout. test 'A server with an active backchannel doesnt timeout', (done) -> @connect -> aid = 1 req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => getNextNoop = -> readLengthPrefixedJSON res, (msg) -> assert.deepEqual msg, [[aid++, ['noop']]] getNextNoop() getNextNoop() # ... give the backchannel time to get established soon -> # wait 500 seconds. In that time, we'll get 25 noops. timer.wait 500 * 1000, -> # and then give the last noop a chance to get sent soon -> assert.strictEqual aid, 26 req.abort() done() #req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => # The send callback should be called _no matter what_. That means if a connection times out, it should # still be called, but we'll pass an error into the callback. suite 'The server calls send callbacks with an error', -> test 'when the session times out', (done) -> @connect -> # It seems like this message shouldn't give an error, but it does because the client never confirms that # its received it. sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Timed out' sendCallbackCalled = yes process.nextTick => @session.send 'Another message', (error) -> assert.ok error assert.strictEqual error.message, 'Timed out' assert.ok sendCallbackCalled done() timer.waitAll() test 'when the session is ghosted', (done) -> @connect -> # As soon as the client has connected, we'll fire off a new connection claiming the previous session is old. @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{@session.id}&OAID=0", 'count=0', (res) => res.socket.end() sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Reconnected' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'Reconnected' assert.ok sendCallbackCalled done() # Ignore the subsequent connection attempt @onSession = -> # The server can also abandon a connection by calling .abort(). Again, this should trigger error callbacks. test 'when the session is closed by the server', (done) -> @connect -> sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'foo' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'foo' assert.ok sendCallbackCalled done() @session.close 'foo' # Finally, the server closes a connection when the client actively closes it (by firing a GET with TYPE=terminate) test 'when the server gets a disconnect request', (done) -> @connect -> sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Disconnected' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'Disconnected' assert.ok sendCallbackCalled done() @get "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&TYPE=terminate", (res) -> res.socket.end() test 'If a session has close() called with no arguments, the send error message says "closed"', (done) -> @connect -> @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'closed' done() @session.close() # stop() sends a message to the client saying basically 'something is wrong, stop trying to # connect'. It triggers a special error in the client, and the client will stop trying to reconnect # at this point. # # The server can still send and receive messages after the stop message has been sent. But the client # probably won't receive them. # # Stop takes a callback which is called when the stop message has been **sent**. (The client never confirms # that it has received the message). suite 'Calling stop() sends the stop command to the client', -> test 'during init', (done) -> @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[0, ['c', @session.id, null, 8]], [1, ['stop']]] done() @onSession = (@session) => @session.stop() test 'after init', (done) -> @connect -> # This test is similar to the test above, but I've put .stop() in a setTimeout. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, ['stop']]] req.abort() done() soon => @session.stop() suite 'A callback passed to stop is called once stop is sent to the client', -> # ... because the stop message will be sent to the client in the initial connection test 'during init', (done) -> @connect -> @session.stop -> done() test 'after init', (done) -> @connect -> process.nextTick => stopCallbackCalled = no req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, ['stop']]] assert stopCallbackCalled req.abort() res.socket.end() done() @session.stop -> # Just a noop test to increase the 'things tested' count stopCallbackCalled = yes # close() aborts the session immediately. After calling close, subsequent requests to the session # should fail with unknown SID errors. suite 'session.close() closes the session', -> test 'during init', (done) -> @connect -> @session.close() @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => assert.strictEqual res.statusCode, 400 res.socket.end() done() test 'after init', (done) -> @connect -> process.nextTick => @session.close() @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => assert.strictEqual res.statusCode, 400 res.socket.end() done() # If you close immediately, the initial POST gets a 403 response (its probably an auth problem?) test 'An immediate session.close() results in the initial connection getting a 403 response', (done) -> @onSession = (@session) => @session.close() @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) -> buffer res, (data) -> assert.strictEqual res.statusCode, 403 res.socket.end() done() # The session runs as a little state machine. It starts in the 'init' state, then moves to # 'ok' when the session is established. When the connection is closed, it moves to 'closed' state # and stays there forever. suite 'The session emits a "state changed" event when you close it', -> test 'immediately', (done) -> @connect -> # Because we're calling close() immediately, the session should never make it to the 'ok' state # before moving to 'closed'. @session.on 'state changed', (nstate, ostate) => assert.strictEqual nstate, 'closed' assert.strictEqual ostate, 'init' assert.strictEqual @session.state, 'closed' done() @session.close() test 'after it has opened', (done) -> @connect -> # This time we'll let the state change to 'ok' before closing the connection. @session.on 'state changed', (nstate, ostate) => if nstate is 'ok' @session.close() else assert.strictEqual nstate, 'closed' assert.strictEqual ostate, 'ok' assert.strictEqual @session.state, 'closed' done() # close() also kills any active backchannel connection. test 'close kills the active backchannel', (done) -> @connect -> @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => res.socket.end() done() # Give it some time for the backchannel to establish itself soon => @session.close() # # node-browserchannel extensions # # browserchannel by default only supports sending string->string maps from the client to server. This # is really awful - I mean, maybe this is useful for some apps, but really you just want to send & receive # JSON. # # To make everything nicer, I have two changes to browserchannel: # # - If a map is `{JSON:"<JSON STRING>"}`, the server will automatically parse the JSON string and # emit 'message', object. In this case, the server *also* emits the data as a map. # - The client can POST the forwardchannel data using a JSON blob. The message looks like this: # # {ofs: 10, data:[null, {...}, 1000.4, 'hi', ....]} # # In this case, the server *does not* emit a map, but merely emits the json object using emit 'message'. # # To advertise this service, during the first test, the server sends X-Accept: application/json; ... test 'The server decodes JSON data in a map if it has a JSON key', (done) -> @connect -> data1 = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] data2 = "hello dear user" qs = querystring.stringify count: 2, ofs: 0, req0_JSON: (JSON.stringify data1), req1_JSON: (JSON.stringify data2) # I can guarantee qs is awful. @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", qs, (res) => res.socket.end() @session.once 'message', (msg) => assert.deepEqual msg, data1 @session.once 'message', (msg) -> assert.deepEqual msg, data2 done() # The server might be JSON decoding the data, but it still needs to emit it as a map. test 'The server emits JSON data in a map, as a map as well', (done) -> @connect -> data1 = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] data2 = "hello dear user" qs = querystring.stringify count: 2, ofs: 0, req0_JSON: (JSON.stringify data1), req1_JSON: (JSON.stringify data2) @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", qs, (res) => res.socket.end() # I would prefer to have more tests mixing maps and JSON data. I'm better off testing that # thoroughly using a randomized tester. @session.once 'map', (map) => assert.deepEqual map, JSON: JSON.stringify data1 @session.once 'map', (map) -> assert.deepEqual map, JSON: JSON.stringify data2 done() # The server also accepts raw JSON. test 'The server accepts JSON data', (done) -> @connect -> # The POST request has to specify Content-Type=application/json so we can't just use # the @post request. (Big tears!) options = method: 'POST' path: "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0" host: 'localhost' port: @port headers: 'Content-Type': 'application/json' # This time I'm going to send the elements of the test object as separate messages. data = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] req = http.request options, (res) -> readLengthPrefixedJSON res, (resData) -> # We won't get this response until all the messages have been processed. assert.deepEqual resData, [0, 0, 0] assert.deepEqual data, [] assert data.length is 0 res.on 'end', -> done() req.end (JSON.stringify {ofs:0, data}) @session.on 'message', (msg) -> assert.deepEqual msg, data.shift() # Hm- this test works, but the client code never recieves the null message. Eh. test 'You can send null', (done) -> @connect -> @session.send null req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, null]] req.abort() res.socket.end() done() test 'Sessions are cancelled when close() is called on the server', (done) -> @connect -> @session.on 'close', done @bc.close() #'print', (done) -> @connect -> console.warn @session; done() # I should also test that you can mix a bunch of JSON requests and map requests, out of order, and the # server sorts it all out.
35309
# # Unit tests for BrowserChannel server # # This contains all the unit tests to make sure the server works like it # should. The tests are written using mocha - you can run them using # % npm test # # For now I'm not going to add in any SSL testing code. I should probably generate # a self-signed key pair, start the server using https and make sure that I can # still use it. # # I'm also missing integration tests. http = require 'http' assert = require 'assert' querystring = require 'querystring' express = require 'express' timer = require 'timerstub' browserChannel = require('..').server browserChannel._setTimerMethods timer # This function provides an easy way for tests to create a new browserchannel server using # connect(). # # I'll create a new server in the setup function of all the tests, but some # tests will need to customise the options, so they can just create another server directly. createServer = (opts, method, callback) -> # Its possible to use the browserChannel middleware without specifying an options # object. This little createServer function will mirror that behaviour. if typeof opts == 'function' [method, callback] = [opts, method] # I want to match up with how its actually going to be used. bc = browserChannel method else bc = browserChannel opts, method # The server is created using connect middleware. I'll simulate other middleware in # the stack by adding a second handler which responds with 200, 'Other middleware' to # any request. app = express() app.use bc app.use (req, res, next) -> # I might not actually need to specify the headers here... (If you don't, nodejs provides # some defaults). res.writeHead 200, 'OK', 'Content-Type': 'text/plain' res.end 'Other middleware' # Calling server.listen() without a port lets the OS pick a port for us. I don't # know why more testing frameworks don't do this by default. server = http.createServer(app).listen undefined, '127.0.0.1', -> # Obviously, we need to know the port to be able to make requests from the server. # The callee could check this itself using the server object, but it'll always need # to know it, so its easier pulling the port out here. port = server.address().port callback server, port, bc # Wait for the function to be called a given number of times, then call the callback. # # This useful little method has been stolen from ShareJS expectCalls = (n, callback) -> return callback() if n == 0 remaining = n -> remaining-- if remaining == 0 callback() else if remaining < 0 throw new Error "expectCalls called more than #{n} times" # This returns a function that calls done() after it has been called n times. Its # useful when you want a bunch of mini tests inside one test case. makePassPart = (test, n) -> expectCalls n, -> done() # Most of these tests will make HTTP requests. A lot of the time, we don't care about the # timing of the response, we just want to know what it was. This method will buffer the # response data from an http response object and when the whole response has been received, # send it on. buffer = (res, callback) -> data = [] res.on 'data', (chunk) -> #console.warn chunk.toString() data.push chunk.toString 'utf8' res.on 'end', -> callback? data.join '' # For some tests we expect certain data, delivered in chunks. Wait until we've # received at least that much data and strcmp. The response will probably be used more, # afterwards, so we'll make sure the listener is removed after we're done. expect = (res, str, callback) -> data = '' res.on 'end', endlistener = -> # This should fail - if the data was as long as str, we would have compared them # already. Its important that we get an error message if the http connection ends # before the string has been received. console.warn 'Connection ended prematurely' assert.strictEqual data, str res.on 'data', listener = (chunk) -> # I'm using string += here because the code is easier that way. data += chunk.toString 'utf8' #console.warn JSON.stringify data #console.warn JSON.stringify str if data.length >= str.length assert.strictEqual data, str res.removeListener 'data', listener res.removeListener 'end', endlistener callback() # A bunch of tests require that we wait for a network connection to get established # before continuing. # # We'll do that using a setTimeout with plenty of time. I hate adding delays, but I # can't see another way to do this. # # This should be plenty of time. I might even be able to reduce this. Note that this # is a real delay, not a stubbed out timer like we give to the server. soon = (f) -> setTimeout f, 10 readLengthPrefixedString = (res, callback) -> data = '' length = null res.on 'data', listener = (chunk) -> data += chunk.toString 'utf8' if length == null # The number of bytes is written in an int on the first line. lines = data.split '\n' # If lines length > 1, then we've read the first newline, which was after the length # field. if lines.length > 1 length = parseInt lines.shift() # Now we'll rewrite the data variable to not include the length. data = lines.join '\n' if data.length == length res.removeListener 'data', listener callback data else if data.length > length console.warn data throw new Error "Read more bytes from stream than expected" # The backchannel is implemented using a bunch of messages which look like this: # # ``` # 36 # [[0,["c","92208FBF76484C10",,8] # ] # ] # ``` # # (At least, thats what they look like using google's server. On mine, they're properly # formatted JSON). # # Each message has a length string (in bytes) followed by a newline and some JSON data. # They can optionally have extra chunks afterwards. # # This format is used for: # # - All XHR backchannel messages # - The response to the initial connect (XHR or HTTP) # - The server acknowledgement to forward channel messages # # This is not used when you're on IE, for normal backchannel requests. On IE, data is sent # through javascript calls from an iframe. readLengthPrefixedJSON = (res, callback) -> readLengthPrefixedString res, (data) -> callback JSON.parse(data) # Copied from google's implementation. The contents of this aren't actually relevant, # but I think its important that its pseudo-random so if the connection is compressed, # it still recieves a bunch of bytes after the first message. ieJunk = "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffe\ e0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c47\ 9050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44\ a9fe92fedacffff48092ee693af\n" suite 'server', -> # #### setup # # Before each test has run, we'll start a new server. The server will only live # for that test and then it'll be torn down again. # # This makes the tests run more slowly, but not slowly enough that I care. setup (callback) -> # This will make sure there's no pesky setTimeouts from previous tests kicking around. # I could instead do a timer.waitAll() in tearDown to let all the timers run & time out # the running sessions. It shouldn't be a big deal. timer.clearAll() # When you instantiate browserchannel, you specify a function which gets called # with each session that connects. I'll proxy that function call to a local function # which tests can override. @onSession = (session) -> # The proxy is inline here. Also, I <3 coffeescript's (@server, @port) -> syntax here. # That will automatically set this.server and this.port to the callback arguments. # # Actually calling the callback starts the test. createServer ((session) => @onSession session), (@server, @port, @bc) => # TODO - This should be exported from lib/server @standardHeaders= 'Content-Type': 'text/plain' 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate' 'Pragma': 'no-cache' 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT' 'X-Content-Type-Options': 'nosniff' # I'll add a couple helper methods for tests to easily message the server. @get = (path, callback) => http.get {host:'localhost', path, @port}, callback @post = (path, data, callback) => req = http.request {method:'POST', host:'localhost', path, @port}, callback req.end data # One of the most common tasks in tests is to create a new session for # some reason. @connect is a little helper method for that. It simply sends the # http POST to create a new session and calls the callback when the session has been # created by the server. # # It also makes @onSession throw an error - very few tests need multiple sessions, # so I special case them when they do. # # Its kind of annoying - for a lot of tests I need to do custom logic in the @post # handler *and* custom logic in @onSession. So, callback can be an object specifying # callbacks for each if you want that. Its a shame though, it makes this function # kinda ugly :/ @connect = (callback) => # This connect helper method is only useful if you don't care about the initial # post response. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0' @onSession = (@session) => @onSession = -> throw new Error 'onSession() called - I didn\'t expect another session to be created' # Keep this bound. I think there's a fancy way to do this in coffeescript, but # I'm not sure what it is. callback.call this # Finally, start the test. callback() teardown (callback) -> # #### tearDown # # This is called after each tests is done. We'll tear down the server we just created. # # The next test is run once the callback is called. I could probably chain the next # test without waiting for close(), but then its possible that an exception thrown # in one test will appear after the next test has started running. Its easier to debug # like this. @server.close callback # The server hosts the client-side javascript at /channel.js. It should have headers set to tell # browsers its javascript. # # Its self contained, with no dependancies on anything. It would be nice to test it as well, # but we'll do that elsewhere. test 'The javascript is hosted at channel/bcsocket.js', (done) -> @get '/channel/bcsocket.js', (response) -> assert.strictEqual response.statusCode, 200 assert.strictEqual response.headers['content-type'], 'application/javascript' assert.ok response.headers['etag'] buffer response, (data) -> # Its about 47k. If the size changes too drastically, I want to know about it. assert.ok data.length > 45000, "Client is unusually small (#{data.length} bytes)" assert.ok data.length < 50000, "Client is bloaty (#{data.length} bytes)" done() # # Testing channel tests # # The first thing a client does when it connects is issue a GET on /test/?mode=INIT. # The server responds with an array of [basePrefix or null,blockedPrefix or null]. Blocked # prefix isn't supported by node-browerchannel and by default no basePrefix is set. So with no # options specified, this GET should return [null,null]. test 'GET /test/?mode=INIT with no baseprefix set returns [null, null]', (done) -> @get '/channel/test?VER=8&MODE=init', (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' done() # If a basePrefix is set in the options, make sure the server returns it. test 'GET /test/?mode=INIT with a basePrefix set returns [basePrefix, null]', (done) -> # You can specify a bunch of host prefixes. If you do, the server will randomly pick between them. # I don't know if thats actually useful behaviour, but *shrug* # I should probably write a test to make sure all host prefixes will be chosen from time to time. createServer hostPrefixes:['chan'], (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '["chan",null]' # I'm being slack here - the server might not close immediately. I could make done() # dependant on it, but I can't be bothered. server.close() done() # Setting a custom url endpoint to bind node-browserchannel to should make it respond at that url endpoint # only. test 'The test channel responds at a bound custom endpoint', (done) -> createServer base:'/foozit', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # Some people will miss out on the leading slash in the URL when they bind browserchannel to a custom # url. That should work too. test 'binding the server to a custom url without a leading slash works', (done) -> createServer base:'foozit', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # Its tempting to think that you need a trailing slash on your URL prefix as well. You don't, but that should # work too. test 'binding the server to a custom url with a trailing slash works', (done) -> # Some day, the copy+paste police are gonna get me. I don't feel *so* bad doing it for tests though, because # it helps readability. createServer base:'foozit/', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # You can control the CORS header ('Access-Control-Allow-Origin') using options.cors. test 'CORS header is not sent if its not set in the options', (done) -> @get '/channel/test?VER=8&MODE=init', (response) -> assert.strictEqual response.headers['access-control-allow-origin'], undefined assert.strictEqual response.headers['access-control-allow-credentials'], undefined response.socket.end() done() test 'CORS headers are sent during the initial phase if set in the options', (done) -> createServer cors:'foo.com', corsAllowCredentials:true, (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual response.headers['access-control-allow-credentials'], 'true' buffer response server.close() done() test 'CORS headers can be set using a function', (done) -> createServer cors: (-> 'something'), (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['access-control-allow-origin'], 'something' buffer response server.close() done() test 'CORS header is set on the backchannel response', (done) -> server = port = null sessionCreated = (session) -> # Make the backchannel flush as soon as its opened session.send "flush" req = http.get {path:"/channel/bind?VER=8&RID=rpc&SID=#{session.id}&AID=0&TYPE=xmlhttp&CI=0", host:'localhost', port:port}, (res) => assert.strictEqual res.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual res.headers['access-control-allow-credentials'], 'true' req.abort() server.close() done() createServer cors:'foo.com', corsAllowCredentials:true, sessionCreated, (_server, _port) -> [server, port] = [_server, _port] req = http.request {method:'POST', path:'/channel/bind?VER=8&RID=1000&t=1', host:'localhost', port:port}, (res) => req.end 'count=0' # This test is just testing one of the error responses for the presence of # the CORS header. It doesn't test all of the ports, and doesn't test IE. # (I'm not actually sure if CORS headers are needed for IE stuff) suite 'CORS header is set in error responses', -> setup (callback) -> createServer cors:'foo.com', corsAllowCredentials:true, (->), (@corsServer, @corsPort) => callback() teardown -> @corsServer.close() testResponse = (done, req, res) -> assert.strictEqual res.statusCode, 400 assert.strictEqual res.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual res.headers['access-control-allow-credentials'], 'true' buffer res, (data) -> assert.ok data.indexOf('Unknown SID') > 0 req.abort() done() test 'backChannel', (done) -> req = http.get {path:'/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=xmlhttp&CI=0', host:'localhost', port:@corsPort}, (res) => testResponse done, req, res test 'forwardChannel', (done) -> req = http.request {method:'POST', path:'/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0', host:'localhost', port:@corsPort}, (res) => testResponse done, req, res req.end 'count=0' #@post "/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0", 'count=0', testResponse(done) test 'Additional headers can be specified in the options', (done) -> createServer headers:{'X-Foo':'bar'}, (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['x-foo'], 'bar' server.close() done() # Interestingly, the CORS header isn't required for old IE (type=html) requests because they're loaded using # iframes anyway. (Though this should really be tested). # node-browserchannel is only responsible for URLs with the specified (or default) prefix. If a request # comes in for a URL outside of that path, it should be passed along to subsequent connect middleware. # # I've set up the createServer() method above to send 'Other middleware' if browserchannel passes # the response on to the next handler. test 'getting a url outside of the bound range gets passed to other middleware', (done) -> @get '/otherapp', (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, 'Other middleware' done() # I decided to make URLs inside the bound range return 404s directly. I can't guarantee that no future # version of node-browserchannel won't add more URLs in the zone, so its important that users don't decide # to start using arbitrary other URLs under channel/. # # That design decision makes it impossible to add a custom 404 page to /channel/FOO, but I don't think thats a # big deal. test 'getting a wacky url inside the bound range returns 404', (done) -> @get '/channel/doesnotexist', (response) -> assert.strictEqual response.statusCode, 404 response.socket.end() done() # For node-browserchannel, we also accept JSON in forward channel POST data. To tell the client that # this is supported, we add an `X-Accept: application/json; application/x-www-form-urlencoded` header # in phase 1 of the test API. test 'The server sends accept:JSON header during test phase 1', (done) -> @get '/channel/test?VER=8&MODE=init', (res) -> assert.strictEqual res.headers['x-accept'], 'application/json; application/x-www-form-urlencoded' res.socket.end() done() # All the standard headers should be sent along with X-Accept test 'The server sends standard headers during test phase 1', (done) -> @get '/channel/test?VER=8&MODE=init', (res) => assert.strictEqual res.headers[k.toLowerCase()].toLowerCase(), v.toLowerCase() for k,v of @standardHeaders res.socket.end() done() # ## Testing phase 2 # # I should really sort the above tests better. # # Testing phase 2 the client GETs /channel/test?VER=8&TYPE= [html / xmlhttp] &zx=558cz3evkwuu&t=1 [&DOMAIN=xxxx] # # The server sends '11111' <2 second break> '2'. If you use html encoding instead, the server sends the client # a webpage which calls: # # document.domain='mail.google.com'; # parent.m('11111'); # parent.m('2'); # parent.d(); suite 'Getting test phase 2 returns 11111 then 2', -> makeTest = (type, message1, message2) -> (done) -> @get "/channel/test?VER=8&TYPE=#{type}", (response) -> assert.strictEqual response.statusCode, 200 expect response, message1, -> # Its important to make sure that message 2 isn't sent too soon (<2 seconds). # We'll advance the server's clock forward by just under 2 seconds and then wait a little bit # for messages from the client. If we get a message during this time, throw an error. response.on 'data', f = -> throw new Error 'should not get more data so early' timer.wait 1999, -> soon -> response.removeListener 'data', f expect response, message2, -> response.once 'end', -> done() timer.wait 1 test 'xmlhttp', makeTest 'xmlhttp', '11111', '2' # I could write this test using JSDom or something like that, and parse out the HTML correctly. # ... but it would be way more complicated (and no more correct) than simply comparing the resulting # strings. test 'html', makeTest('html', # These HTML responses are identical to what I'm getting from google's servers. I think the seemingly # random sequence is just so network framing doesn't try and chunk up the first packet sent to the server # or something like that. """<html><body><script>try {parent.m("11111")} catch(e) {}</script>\n#{ieJunk}""", '''<script>try {parent.m("2")} catch(e) {}</script> <script>try {parent.d(); }catch (e){}</script>\n''') # If a client is connecting with a host prefix, the server sets the iframe's document.domain to match # before sending actual data. 'html with a host prefix': makeTest('html&DOMAIN=foo.bar.com', # I've made a small change from google's implementation here. I'm using double quotes `"` instead of # single quotes `'` because its easier to encode. (I can't just wrap the string in quotes because there # are potential XSS vulnerabilities if I do that). """<html><body><script>try{document.domain="foo.bar.com";}catch(e){}</script> <script>try {parent.m("11111")} catch(e) {}</script>\n#{ieJunk}""", '''<script>try {parent.m("2")} catch(e) {}</script> <script>try {parent.d(); }catch (e){}</script>\n''') # IE doesn't parse the HTML in the response unless the Content-Type is text/html test 'Using type=html sets Content-Type: text/html', (done) -> r = @get "/channel/test?VER=8&TYPE=html", (response) -> assert.strictEqual response.headers['content-type'], 'text/html' r.abort() done() # IE should also get the standard headers test 'Using type=html gets the standard headers', (done) -> r = @get "/channel/test?VER=8&TYPE=html", (response) => for k, v of @standardHeaders when k isnt 'Content-Type' assert.strictEqual response.headers[k.toLowerCase()].toLowerCase(), v.toLowerCase() r.abort() done() # node-browserchannel is only compatible with browserchannel client version 8. I don't know whats changed # since old versions (maybe v6 would be easy to support) but I don't care. If the client specifies # an old version, we'll die with an error. # The alternate phase 2 URL style should have the same behaviour if the version is old or unspecified. # # Google's browserchannel server still works if you miss out on specifying the version - it defaults # to version 1 (which maybe didn't have version numbers in the URLs). I'm kind of impressed that # all that code still works. suite 'Getting /test/* without VER=8 returns an error', -> # All these tests look 95% the same. Instead of writing the same test all those times, I'll use this # little helper method to generate them. check400 = (path) -> (done) -> @get path, (response) -> assert.strictEqual response.statusCode, 400 response.socket.end() done() test 'phase 1, ver 7', check400 '/channel/test?VER=7&MODE=init' test 'phase 1, no version', check400 '/channel/test?MODE=init' test 'phase 2, ver 7, xmlhttp', check400 '/channel/test?VER=7&TYPE=xmlhttp' test 'phase 2, no version, xmlhttp', check400 '/channel/test?TYPE=xmlhttp' # For HTTP connections (IE), the error is sent a different way. Its kinda complicated how the error # is sent back, so for now I'm just going to ignore checking it. test 'phase 2, ver 7, http', check400 '/channel/test?VER=7&TYPE=html' test 'phase 2, no version, http', check400 '/channel/test?TYPE=html' # > At the moment the server expects the client will add a zx=###### query parameter to all requests. # The server isn't strict about this, so I'll ignore it in the tests for now. # # Server connection tests # These tests make server sessions by crafting raw HTTP queries. I'll make another set of # tests later which spam the server with a million fake clients. # # To start with, simply connect to a server using the BIND API. A client sends a server a few parameters: # # - **CVER**: Client application version # - **RID**: Client-side generated random number, which is the initial sequence number for the # client's requests. # - **VER**: Browserchannel protocol version. Must be 8. # - **t**: The connection attempt number. This is currently ignored by the BC server. (I'm not sure # what google's implementation does with this). test 'The server makes a new session if the client POSTs the right connection stuff', (done) -> id = null onSessionCalled = no # When a request comes in, we should get the new session through the server API. # # We need this session in order to find out the session ID, which should match up with part of the # server's response. @onSession = (session) -> assert.ok session assert.strictEqual typeof session.id, 'string' assert.strictEqual session.state, 'init' assert.strictEqual session.appVersion, '99' assert.deepEqual session.address, '127.0.0.1' assert.strictEqual typeof session.headers, 'object' id = session.id session.on 'map', -> throw new Error 'Should not have received data' onSessionCalled = yes # The client starts a BC connection by POSTing to /bind? with no session ID specified. # The client can optionally send data here, but in this case it won't (hence the `count=0`). @post '/channel/bind?VER=8&RID=1000&CVER=99&t=1&junk=asdfasdf', 'count=0', (res) => expected = (JSON.stringify [[0, ['c', id, null, 8]]]) + '\n' buffer res, (data) -> # Even for old IE clients, the server responds in length-prefixed JSON style. assert.strictEqual data, "#{expected.length}\n#{expected}" assert.ok onSessionCalled done() # Once a client's session id is sent, the session moves to the `ok` state. This happens after onSession is # called (so onSession can send messages to the client immediately). # # I'm starting to use the @connect method here, which just POSTs locally to create a session, sets @session and # calls its callback. test 'A session has state=ok after onSession returns', (done) -> @connect -> @session.on 'state changed', (newState, oldState) => assert.strictEqual oldState, 'init' assert.strictEqual newState, 'ok' assert.strictEqual @session.state, 'ok' done() # The CVER= property is optional during client connections. If its left out, session.appVersion is # null. test 'A session connects ok even if it doesnt specify an app version', (done) -> id = null onSessionCalled = no @onSession = (session) -> assert.strictEqual session.appVersion, null id = session.id session.on 'map', -> throw new Error 'Should not have received data' onSessionCalled = yes @post '/channel/bind?VER=8&RID=1000&t=1&junk=asdfasdf', 'count=0', (res) => expected = (JSON.stringify [[0, ['c', id, null, 8]]]) + '\n' buffer res, (data) -> assert.strictEqual data, "#{expected.length}\n#{expected}" assert.ok onSessionCalled done() # Once again, only VER=8 works. suite 'Connecting with a version thats not 8 breaks', -> # This will POST to the requested path and make sure the response sets status 400 check400 = (path) -> (done) -> @post path, 'count=0', (response) -> assert.strictEqual response.statusCode, 400 response.socket.end() done() test 'no version', check400 '/channel/bind?RID=1000&t=1' test 'previous version', check400 '/channel/bind?VER=7&RID=1000&t=1' # This time, we'll send a map to the server during the initial handshake. This should be received # by the server as normal. test 'The client can post messages to the server during initialization', (done) -> @onSession = (session) -> session.on 'map', (data) -> assert.deepEqual data, {k:'v'} done() @post '/channel/bind?VER=8&RID=1000&t=1', 'count=1&ofs=0&req0_k=v', (res) => res.socket.end() # The data received by the server should be properly URL decoded and whatnot. test 'Server messages are properly URL decoded', (done) -> @onSession = (session) -> session.on 'map', (data) -> assert.deepEqual data, {"_int_^&^%#net":'hi"there&&\nsam'} done() @post('/channel/bind?VER=8&RID=1000&t=1', 'count=1&ofs=0&req0__int_%5E%26%5E%25%23net=hi%22there%26%26%0Asam', (res) -> res.socket.end()) # After a client connects, it can POST data to the server using URL-encoded POST data. This data # is sent by POSTing to /bind?SID=.... # # The data looks like this: # # count=5&ofs=1000&req0_KEY1=<KEY>&req0_KEY2=VAL<KEY>&req1_KEY3=req1_VAL<KEY>&... test 'The client can post messages to the server after initialization', (done) -> @connect -> @session.on 'map', (data) -> assert.deepEqual data, {k:'v'} done() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => res.socket.end() # When the server gets a forwardchannel request, it should reply with a little array saying whats # going on. test 'The server acknowledges forward channel messages correctly', (done) -> @connect -> @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => readLengthPrefixedJSON res, (data) => # The server responds with [backchannelMissing ? 0 : 1, lastSentAID, outstandingBytes] assert.deepEqual data, [0, 0, 0] done() # If the server has an active backchannel, it responds to forward channel requests notifying the client # that the backchannel connection is alive and well. test 'The server tells the client if the backchannel is alive', (done) -> @connect -> # This will fire up a backchannel connection to the server. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp", (res) => # The client shouldn't get any data through the backchannel. res.on 'data', -> throw new Error 'Should not get data through backchannel' # Unfortunately, the GET request is sent *after* the POST, so we have to wrap the # post in a timeout to make sure it hits the server after the backchannel connection is # established. soon => @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => readLengthPrefixedJSON res, (data) => # This time, we get a 1 as the first argument because the backchannel connection is # established. assert.deepEqual data, [1, 0, 0] # The backchannel hasn't gotten any data yet. It'll spend 15 seconds or so timing out # if we don't abort it manually. # As of nodejs 0.6, if you abort() a connection, it can emit an error. req.on 'error', -> req.abort() done() # The forward channel response tells the client how many unacknowledged bytes there are, so it can decide # whether or not it thinks the backchannel is dead. test 'The server tells the client how much unacknowledged data there is in the post response', (done) -> @connect -> process.nextTick => # I'm going to send a few messages to the client and acknowledge the first one in a post response. @session.send 'message 1' @session.send 'message 2' @session.send 'message 3' # We'll make a backchannel and get the data req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => # After the data is received, I'll acknowledge the first message using an empty POST @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=1", 'count=0', (res) => readLengthPrefixedJSON res, (data) => # We should get a response saying "The backchannel is connected", "The last message I sent was 3" # "messages 2 and 3 haven't been acknowledged, here's their size" assert.deepEqual data, [1, 3, 25] req.abort() done() # When the user calls send(), data is queued by the server and sent into the next backchannel connection. # # The server will use the initial establishing connection if thats available, or it'll send it the next # time the client opens a backchannel connection. test 'The server returns data on the initial connection when send is called immediately', (done) -> testData = ['hello', 'there', null, 1000, {}, [], [555]] @onSession = (@session) => @session.send testData # I'm not using @connect because we need to know about the response to the first POST. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[0, ['c', @session.id, null, 8]], [1, testData]] done() test 'The server escapes tricky characters before sending JSON over the wire', (done) -> testData = {'a': 'hello\u2028\u2029there\u2028\u2029'} @onSession = (@session) => @session.send testData # I'm not using @connect because we need to know about the response to the first POST. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedString res, (data) => assert.deepEqual data, """[[0,["c","#{@session.id}",null,8]],[1,{"a":"hello\\u2028\\u2029there\\u2028\\u2029"}]]\n""" done() test 'The server buffers data if no backchannel is available', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] # The first response to the server is sent after this method returns, so if we send the data # in process.nextTick, it'll get buffered. process.nextTick => @session.send testData req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] req.abort() done() # This time, we'll fire up the back channel first (and give it time to get established) _then_ # send data through the session. test 'The server returns data through the available backchannel when send is called later', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] # Fire off the backchannel request as soon as the client has connected req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) -> #res.on 'data', (chunk) -> console.warn chunk.toString() readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, testData]] req.abort() done() # Send the data outside of the get block to make sure it makes it through. soon => @session.send testData # The server should call the send callback once the data has been confirmed by the client. # # We'll try sending three messages to the client. The first message will be sent during init and the # third message will not be acknowledged. Only the first two message callbacks should get called. test 'The server calls send callback once data is acknowledged', (done) -> @connect -> lastAck = null @session.send [1], -> assert.strictEqual lastAck, null lastAck = 1 process.nextTick => @session.send [2], -> assert.strictEqual lastAck, 1 # I want to give the test time to die soon -> done() # This callback should actually get called with an error after the client times out. ... but I'm not # giving timeouts a chance to run. @session.send [3], -> throw new Error 'Should not call unacknowledged send callback' req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[2, [2]], [3, [3]]] # Ok, now we'll only acknowledge the second message by sending AID=2 @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=2", 'count=0', (res) => res.socket.end() req.abort() # This tests for a regression - if the stop callback closed the connection, the server was crashing. test 'The send callback can stop the session', (done) -> @connect -> req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => # Acknowledge the stop message @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=2", 'count=0', (res) => res.socket.end() @session.stop => @session.close() soon -> req.abort() done() # If there's a proxy in the way which chunks up responses before sending them on, the client adds a # &CI=1 argument on the backchannel. This causes the server to end the HTTP query after each message # is sent, so the data is sent to the session. test 'The backchannel is closed after each packet if chunking is turned off', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # Instead of the usual CI=0 we're passing CI=1 here. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=1", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] res.on 'end', -> done() # Normally, the server doesn't close the connection after each backchannel message. test 'The backchannel is left open if CI=0', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] # After receiving the data, the client shouldn't close the connection. (At least, not unless # it times out naturally). res.on 'end', -> throw new Error 'connection should have stayed open' soon -> res.removeAllListeners 'end' req.abort() done() # On IE, the data is all loaded using iframes. The backchannel spits out data using inline scripts # in an HTML page. # # I've written this test separately from the tests above, but it would really make more sense # to rerun the same set of tests in both HTML and XHR modes to make sure the behaviour is correct # in both instances. test 'The server gives the client correctly formatted backchannel data if TYPE=html', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # The type is specified as an argument here in the query string. For this test, I'm making # CI=1, because the test is easier to write that way. # # In truth, I don't care about IE support as much as support for modern browsers. This might # be a mistake.. I'm not sure. IE9's XHR support should work just fine for browserchannel, # though google's BC client doesn't use it. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=html&CI=1", (res) => expect res, # Interestingly, google doesn't double-encode the string like this. Instead of turning # quotes `"` into escaped quotes `\"`, it uses unicode encoding to turn them into \42 and # stuff like that. I'm not sure why they do this - it produces the same effect in IE8. # I should test it in IE6 and see if there's any problems. """<html><body><script>try {parent.m(#{JSON.stringify JSON.stringify([[1, testData]]) + '\n'})} catch(e) {}</script> #{ieJunk}<script>try {parent.d(); }catch (e){}</script>\n""", => # Because I'm lazy, I'm going to chain on a test to make sure CI=0 works as well. data2 = {other:'data'} @session.send data2 # I'm setting AID=1 here to indicate that the client has seen array 1. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=html&CI=0", (res) => expect res, """<html><body><script>try {parent.m(#{JSON.stringify JSON.stringify([[2, data2]]) + '\n'})} catch(e) {}</script> #{ieJunk}""", => req.abort() done() # If there's a basePrefix set, the returned HTML sets `document.domain = ` before sending messages. # I'm super lazy, and just copy+pasting from the test above. There's probably a way to factor these tests # nicely, but I'm not in the mood to figure it out at the moment. test 'The server sets the domain if we have a domain set', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # This time we're setting DOMAIN=X, and the response contains a document.domain= block. Woo. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=html&CI=1&DOMAIN=foo.com", (res) => expect res, """<html><body><script>try{document.domain=\"foo.com\";}catch(e){}</script> <script>try {parent.m(#{JSON.stringify JSON.stringify([[1, testData]]) + '\n'})} catch(e) {}</script> #{ieJunk}<script>try {parent.d(); }catch (e){}</script>\n""", => data2 = {other:'data'} @session.send data2 req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=html&CI=0&DOMAIN=foo.com", (res) => expect res, # Its interesting - in the test channel, the ie junk comes right after the document.domain= line, # but in a backchannel like this it comes after. The behaviour here is the same in google's version. # # I'm not sure if its actually significant though. """<html><body><script>try{document.domain=\"foo.com\";}catch(e){}</script> <script>try {parent.m(#{JSON.stringify JSON.stringify([[2, data2]]) + '\n'})} catch(e) {}</script> #{ieJunk}""", => req.abort() done() # If a client thinks their backchannel connection is closed, they might open a second backchannel connection. # In this case, the server should close the old one and resume sending stuff using the new connection. test 'The server closes old backchannel connections', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # As usual, we'll get the sent data through the backchannel connection. The connection is kept open... @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => # ... and the data has been read. Now we'll open another connection and check that the first connection # gets closed. req2 = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res2) => res.on 'end', -> req2.on 'error', -> req2.abort() done() # The client attaches a sequence number (*RID*) to every message, to make sure they don't end up out-of-order at # the server's end. # # We'll purposefully send some messages out of order and make sure they're held and passed through in order. # # Gogo gadget reimplementing TCP. test 'The server orders forwardchannel messages correctly using RIDs', (done) -> @connect -> # @connect sets RID=1000. # We'll send 2 maps, the first one will be {v:1} then {v:0}. They should be swapped around by the server. lastVal = 0 @session.on 'map', (map) -> assert.strictEqual map.v, "#{lastVal++}", 'messages arent reordered in the server' done() if map.v == '2' # First, send `[{v:2}]` @post "/channel/bind?VER=8&RID=1002&SID=#{@session.id}&AID=0", 'count=1&ofs=2&req0_v=2', (res) => res.socket.end() # ... then `[{v:0}, {v:1}]` a few MS later. soon => @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=2&ofs=0&req0_v=0&req1_v=1', (res) => res.socket.end() # Again, think of browserchannel as TCP on top of UDP... test 'Repeated forward channel messages are discarded', (done) -> @connect -> gotMessage = false # The map must only be received once. @session.on 'map', (map) -> if gotMessage == false gotMessage = true else throw new Error 'got map twice' # POST the maps twice. @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() # Wait 50 milliseconds for the map to (maybe!) be received twice, then pass. soon -> assert.strictEqual gotMessage, true done() # The client can retry failed forwardchannel requests with additional maps. We may have gotten the failed # request. An error could have occurred when we reply. test 'Repeat forward channel messages can contain extra maps', (done) -> @connect -> # We should get exactly 2 maps, {v:0} then {v:1} maps = [] @session.on 'map', (map) -> maps.push map @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=2&ofs=0&req0_v=0&req1_v=1', (res) => res.socket.end() soon -> assert.deepEqual maps, [{v:0}, {v:1}] done() # With each request to the server, the client tells the server what array it saw last through the AID= parameter. # # If a client sends a subsequent backchannel request with an old AID= set, that means the client never saw the arrays # the server has previously sent. So, the server should resend them. test 'The server resends lost arrays if the client asks for them', (done) -> @connect -> process.nextTick => @session.send [1,2,3] @session.send [4,5,6] @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, [1,2,3]], [2, [4,5,6]]] # We'll resend that request, pretending that the client never saw the second array sent (`[4,5,6]`) req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[2, [4,5,6]]] # We don't need to abort the first connection because the server should close it. req.abort() done() # If you sleep your laptop or something, by the time you open it again the server could have timed out your session # so your session ID is invalid. This will also happen if the server gets restarted or something like that. # # The server should respond to any query requesting a nonexistant session ID with 400 and put 'Unknown SID' # somewhere in the message. (Actually, the BC client test is `indexOf('Unknown SID') > 0` so there has to be something # before that text in the message or indexOf will return 0. # # The google servers also set Unknown SID as the http status code, which is kinda neat. I can't check for that. suite 'If a client sends an invalid SID in a request, the server responds with 400 Unknown SID', -> testResponse = (done) -> (res) -> assert.strictEqual res.statusCode, 400 buffer res, (data) -> assert.ok data.indexOf('Unknown SID') > 0 done() test 'backChannel', (done) -> @get "/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=xmlhttp&CI=0", testResponse(done) test 'forwardChannel', (done) -> @post "/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0", 'count=0', testResponse(done) # When type=HTML, google's servers still send the same response back to the client. I'm not sure how it detects # the error, but it seems to work. So, I'll copy that behaviour. test 'backChannel with TYPE=html', (done) -> @get "/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=html&CI=0", testResponse(done) # When a client connects, it can optionally specify its old session ID and array ID. This solves the old IRC # ghosting problem - if the old session hasn't timed out on the server yet, you can temporarily be in a state where # multiple connections represent the same user. test 'If a client disconnects then reconnects, specifying OSID= and OAID=, the old session is destroyed', (done) -> @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => res.socket.end() # I want to check the following things: # # - on 'close' is called on the first session # - onSession is called with the second session # - on 'close' is called before the second session is created # # Its kinda gross managing all that state in one function... @onSession = (session1) => # As soon as the client has connected, we'll fire off a new connection claiming the previous session is old. @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{session1.id}&OAID=0", 'count=0', (res) => res.socket.end() c1Closed = false session1.on 'close', -> c1Closed = true # Once the first client has connected, I'm replacing @onSession so the second session's state can be handled # separately. @onSession = (session2) -> assert.ok c1Closed assert.strictEqual session1.state, 'closed' done() # The server might have already timed out an old connection. In this case, the OSID is ignored. test 'The server ignores OSID and OAID if the named session doesnt exist', (done) -> @post "/channel/bind?VER=8&RID=2000&t=1&OSID=doesnotexist&OAID=0", 'count=0', (res) => res.socket.end() # So small & pleasant! @onSession = (session) => assert.ok session done() # OAID is set in the ghosted connection as a final attempt to flush arrays. test 'The server uses OAID to confirm arrays in the old session before closing it', (done) -> @connect -> # We'll follow the same pattern as the first callback test waay above. We'll send three messages, one # in the first callback and two after. We'll pretend that just the first two messages made it through. lastMessage = null # We'll create a new session in a moment when we POST with OSID and OAID. @onSession = -> @session.send 1, (error) -> assert.ifError error assert.strictEqual lastMessage, null lastMessage = 1 # The final message callback should get called after the close event fires @session.on 'close', -> assert.strictEqual lastMessage, 2 process.nextTick => @session.send 2, (error) -> assert.ifError error assert.strictEqual lastMessage, 1 lastMessage = 2 @session.send 3, (error) -> assert.ok error assert.strictEqual lastMessage, 2 lastMessage = 3 assert.strictEqual error.message, 'Reconnected' soon -> req.abort() done() # And now we'll nuke the session and confirm the first two arrays. But first, its important # the client has a backchannel to send data to (confirming arrays before a backchannel is opened # to receive them is undefined and probably does something bad) req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => res.socket.end() @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{@session.id}&OAID=2", 'count=0', (res) => res.socket.end() test 'The session times out after awhile if it doesnt have a backchannel', (done) -> @connect -> start = timer.Date.now() @session.on 'close', (reason) -> assert.strictEqual reason, 'Timed out' # It should take at least 30 seconds. assert.ok timer.Date.now() - start >= 30000 done() timer.waitAll() test 'The session can be disconnected by firing a GET with TYPE=terminate', (done) -> @connect -> # The client doesn't seem to put AID= in here. I'm not sure why - could be a bug in the client. @get "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&TYPE=terminate", (res) -> # The response should be empty. buffer res, (data) -> assert.strictEqual data, '' @session.on 'close', (reason) -> # ... Its a manual disconnect. Is this reason string good enough? assert.strictEqual reason, 'Disconnected' done() test 'If a disconnect message reaches the client before some data, the data is still received', (done) -> @connect -> # The disconnect message is sent first, but its got a higher RID. It shouldn't be handled until # after the data. @get "/channel/bind?VER=8&RID=1003&SID=#{@session.id}&TYPE=terminate", (res) -> res.socket.end() soon => @post "/channel/bind?VER=8&RID=1002&SID=#{@session.id}&AID=0", 'count=1&ofs=1&req0_m=2', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_m=1', (res) => res.socket.end() maps = [] @session.on 'map', (data) -> maps.push data @session.on 'close', (reason) -> assert.strictEqual reason, 'Disconnected' assert.deepEqual maps, [{m:1}, {m:2}] done() # There's a slightly different codepath after a backchannel is opened then closed again. I want to make # sure it still works in this case. # # Its surprising how often this test fails. test 'The session times out if its backchannel is closed', (done) -> @connect -> process.nextTick => req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => res.socket.end() # I'll let the backchannel establish itself for a moment, and then nuke it. soon => req.on 'error', -> req.abort() # It should take about 30 seconds from now to timeout the connection. start = timer.Date.now() @session.on 'close', (reason) -> assert.strictEqual reason, 'Timed out' assert.ok timer.Date.now() - start >= 30000 done() # The timer sessionTimeout won't be queued up until after the abort() message makes it # to the server. I hate all these delays, but its not easy to write this test without them. soon -> timer.waitAll() # The server sends a little heartbeat across the backchannel every 20 seconds if there hasn't been # any chatter anyway. This keeps the machines en route from evicting the backchannel connection. # (noops are ignored by the client.) test 'A heartbeat is sent across the backchannel (by default) every 20 seconds', (done) -> @connect -> start = timer.Date.now() req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (msg) -> # this really just tests that one heartbeat is sent. assert.deepEqual msg, [[1, ['noop']]] assert.ok timer.Date.now() - start >= 20000 req.abort() done() # Once again, we can't call waitAll() until the request has hit the server. soon -> timer.waitAll() # So long as the backchannel stays open, the server should just keep sending heartbeats and # the session doesn't timeout. test 'A server with an active backchannel doesnt timeout', (done) -> @connect -> aid = 1 req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => getNextNoop = -> readLengthPrefixedJSON res, (msg) -> assert.deepEqual msg, [[aid++, ['noop']]] getNextNoop() getNextNoop() # ... give the backchannel time to get established soon -> # wait 500 seconds. In that time, we'll get 25 noops. timer.wait 500 * 1000, -> # and then give the last noop a chance to get sent soon -> assert.strictEqual aid, 26 req.abort() done() #req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => # The send callback should be called _no matter what_. That means if a connection times out, it should # still be called, but we'll pass an error into the callback. suite 'The server calls send callbacks with an error', -> test 'when the session times out', (done) -> @connect -> # It seems like this message shouldn't give an error, but it does because the client never confirms that # its received it. sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Timed out' sendCallbackCalled = yes process.nextTick => @session.send 'Another message', (error) -> assert.ok error assert.strictEqual error.message, 'Timed out' assert.ok sendCallbackCalled done() timer.waitAll() test 'when the session is ghosted', (done) -> @connect -> # As soon as the client has connected, we'll fire off a new connection claiming the previous session is old. @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{@session.id}&OAID=0", 'count=0', (res) => res.socket.end() sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Reconnected' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'Reconnected' assert.ok sendCallbackCalled done() # Ignore the subsequent connection attempt @onSession = -> # The server can also abandon a connection by calling .abort(). Again, this should trigger error callbacks. test 'when the session is closed by the server', (done) -> @connect -> sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'foo' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'foo' assert.ok sendCallbackCalled done() @session.close 'foo' # Finally, the server closes a connection when the client actively closes it (by firing a GET with TYPE=terminate) test 'when the server gets a disconnect request', (done) -> @connect -> sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Disconnected' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'Disconnected' assert.ok sendCallbackCalled done() @get "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&TYPE=terminate", (res) -> res.socket.end() test 'If a session has close() called with no arguments, the send error message says "closed"', (done) -> @connect -> @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'closed' done() @session.close() # stop() sends a message to the client saying basically 'something is wrong, stop trying to # connect'. It triggers a special error in the client, and the client will stop trying to reconnect # at this point. # # The server can still send and receive messages after the stop message has been sent. But the client # probably won't receive them. # # Stop takes a callback which is called when the stop message has been **sent**. (The client never confirms # that it has received the message). suite 'Calling stop() sends the stop command to the client', -> test 'during init', (done) -> @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[0, ['c', @session.id, null, 8]], [1, ['stop']]] done() @onSession = (@session) => @session.stop() test 'after init', (done) -> @connect -> # This test is similar to the test above, but I've put .stop() in a setTimeout. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, ['stop']]] req.abort() done() soon => @session.stop() suite 'A callback passed to stop is called once stop is sent to the client', -> # ... because the stop message will be sent to the client in the initial connection test 'during init', (done) -> @connect -> @session.stop -> done() test 'after init', (done) -> @connect -> process.nextTick => stopCallbackCalled = no req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, ['stop']]] assert stopCallbackCalled req.abort() res.socket.end() done() @session.stop -> # Just a noop test to increase the 'things tested' count stopCallbackCalled = yes # close() aborts the session immediately. After calling close, subsequent requests to the session # should fail with unknown SID errors. suite 'session.close() closes the session', -> test 'during init', (done) -> @connect -> @session.close() @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => assert.strictEqual res.statusCode, 400 res.socket.end() done() test 'after init', (done) -> @connect -> process.nextTick => @session.close() @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => assert.strictEqual res.statusCode, 400 res.socket.end() done() # If you close immediately, the initial POST gets a 403 response (its probably an auth problem?) test 'An immediate session.close() results in the initial connection getting a 403 response', (done) -> @onSession = (@session) => @session.close() @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) -> buffer res, (data) -> assert.strictEqual res.statusCode, 403 res.socket.end() done() # The session runs as a little state machine. It starts in the 'init' state, then moves to # 'ok' when the session is established. When the connection is closed, it moves to 'closed' state # and stays there forever. suite 'The session emits a "state changed" event when you close it', -> test 'immediately', (done) -> @connect -> # Because we're calling close() immediately, the session should never make it to the 'ok' state # before moving to 'closed'. @session.on 'state changed', (nstate, ostate) => assert.strictEqual nstate, 'closed' assert.strictEqual ostate, 'init' assert.strictEqual @session.state, 'closed' done() @session.close() test 'after it has opened', (done) -> @connect -> # This time we'll let the state change to 'ok' before closing the connection. @session.on 'state changed', (nstate, ostate) => if nstate is 'ok' @session.close() else assert.strictEqual nstate, 'closed' assert.strictEqual ostate, 'ok' assert.strictEqual @session.state, 'closed' done() # close() also kills any active backchannel connection. test 'close kills the active backchannel', (done) -> @connect -> @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => res.socket.end() done() # Give it some time for the backchannel to establish itself soon => @session.close() # # node-browserchannel extensions # # browserchannel by default only supports sending string->string maps from the client to server. This # is really awful - I mean, maybe this is useful for some apps, but really you just want to send & receive # JSON. # # To make everything nicer, I have two changes to browserchannel: # # - If a map is `{JSON:"<JSON STRING>"}`, the server will automatically parse the JSON string and # emit 'message', object. In this case, the server *also* emits the data as a map. # - The client can POST the forwardchannel data using a JSON blob. The message looks like this: # # {ofs: 10, data:[null, {...}, 1000.4, 'hi', ....]} # # In this case, the server *does not* emit a map, but merely emits the json object using emit 'message'. # # To advertise this service, during the first test, the server sends X-Accept: application/json; ... test 'The server decodes JSON data in a map if it has a JSON key', (done) -> @connect -> data1 = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] data2 = "hello de<NAME> user" qs = querystring.stringify count: 2, ofs: 0, req0_JSON: (JSON.stringify data1), req1_JSON: (JSON.stringify data2) # I can guarantee qs is awful. @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", qs, (res) => res.socket.end() @session.once 'message', (msg) => assert.deepEqual msg, data1 @session.once 'message', (msg) -> assert.deepEqual msg, data2 done() # The server might be JSON decoding the data, but it still needs to emit it as a map. test 'The server emits JSON data in a map, as a map as well', (done) -> @connect -> data1 = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] data2 = "hello de<NAME> user" qs = querystring.stringify count: 2, ofs: 0, req0_JSON: (JSON.stringify data1), req1_JSON: (JSON.stringify data2) @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", qs, (res) => res.socket.end() # I would prefer to have more tests mixing maps and JSON data. I'm better off testing that # thoroughly using a randomized tester. @session.once 'map', (map) => assert.deepEqual map, JSON: JSON.stringify data1 @session.once 'map', (map) -> assert.deepEqual map, JSON: JSON.stringify data2 done() # The server also accepts raw JSON. test 'The server accepts JSON data', (done) -> @connect -> # The POST request has to specify Content-Type=application/json so we can't just use # the @post request. (Big tears!) options = method: 'POST' path: "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0" host: 'localhost' port: @port headers: 'Content-Type': 'application/json' # This time I'm going to send the elements of the test object as separate messages. data = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] req = http.request options, (res) -> readLengthPrefixedJSON res, (resData) -> # We won't get this response until all the messages have been processed. assert.deepEqual resData, [0, 0, 0] assert.deepEqual data, [] assert data.length is 0 res.on 'end', -> done() req.end (JSON.stringify {ofs:0, data}) @session.on 'message', (msg) -> assert.deepEqual msg, data.shift() # Hm- this test works, but the client code never recieves the null message. Eh. test 'You can send null', (done) -> @connect -> @session.send null req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, null]] req.abort() res.socket.end() done() test 'Sessions are cancelled when close() is called on the server', (done) -> @connect -> @session.on 'close', done @bc.close() #'print', (done) -> @connect -> console.warn @session; done() # I should also test that you can mix a bunch of JSON requests and map requests, out of order, and the # server sorts it all out.
true
# # Unit tests for BrowserChannel server # # This contains all the unit tests to make sure the server works like it # should. The tests are written using mocha - you can run them using # % npm test # # For now I'm not going to add in any SSL testing code. I should probably generate # a self-signed key pair, start the server using https and make sure that I can # still use it. # # I'm also missing integration tests. http = require 'http' assert = require 'assert' querystring = require 'querystring' express = require 'express' timer = require 'timerstub' browserChannel = require('..').server browserChannel._setTimerMethods timer # This function provides an easy way for tests to create a new browserchannel server using # connect(). # # I'll create a new server in the setup function of all the tests, but some # tests will need to customise the options, so they can just create another server directly. createServer = (opts, method, callback) -> # Its possible to use the browserChannel middleware without specifying an options # object. This little createServer function will mirror that behaviour. if typeof opts == 'function' [method, callback] = [opts, method] # I want to match up with how its actually going to be used. bc = browserChannel method else bc = browserChannel opts, method # The server is created using connect middleware. I'll simulate other middleware in # the stack by adding a second handler which responds with 200, 'Other middleware' to # any request. app = express() app.use bc app.use (req, res, next) -> # I might not actually need to specify the headers here... (If you don't, nodejs provides # some defaults). res.writeHead 200, 'OK', 'Content-Type': 'text/plain' res.end 'Other middleware' # Calling server.listen() without a port lets the OS pick a port for us. I don't # know why more testing frameworks don't do this by default. server = http.createServer(app).listen undefined, '127.0.0.1', -> # Obviously, we need to know the port to be able to make requests from the server. # The callee could check this itself using the server object, but it'll always need # to know it, so its easier pulling the port out here. port = server.address().port callback server, port, bc # Wait for the function to be called a given number of times, then call the callback. # # This useful little method has been stolen from ShareJS expectCalls = (n, callback) -> return callback() if n == 0 remaining = n -> remaining-- if remaining == 0 callback() else if remaining < 0 throw new Error "expectCalls called more than #{n} times" # This returns a function that calls done() after it has been called n times. Its # useful when you want a bunch of mini tests inside one test case. makePassPart = (test, n) -> expectCalls n, -> done() # Most of these tests will make HTTP requests. A lot of the time, we don't care about the # timing of the response, we just want to know what it was. This method will buffer the # response data from an http response object and when the whole response has been received, # send it on. buffer = (res, callback) -> data = [] res.on 'data', (chunk) -> #console.warn chunk.toString() data.push chunk.toString 'utf8' res.on 'end', -> callback? data.join '' # For some tests we expect certain data, delivered in chunks. Wait until we've # received at least that much data and strcmp. The response will probably be used more, # afterwards, so we'll make sure the listener is removed after we're done. expect = (res, str, callback) -> data = '' res.on 'end', endlistener = -> # This should fail - if the data was as long as str, we would have compared them # already. Its important that we get an error message if the http connection ends # before the string has been received. console.warn 'Connection ended prematurely' assert.strictEqual data, str res.on 'data', listener = (chunk) -> # I'm using string += here because the code is easier that way. data += chunk.toString 'utf8' #console.warn JSON.stringify data #console.warn JSON.stringify str if data.length >= str.length assert.strictEqual data, str res.removeListener 'data', listener res.removeListener 'end', endlistener callback() # A bunch of tests require that we wait for a network connection to get established # before continuing. # # We'll do that using a setTimeout with plenty of time. I hate adding delays, but I # can't see another way to do this. # # This should be plenty of time. I might even be able to reduce this. Note that this # is a real delay, not a stubbed out timer like we give to the server. soon = (f) -> setTimeout f, 10 readLengthPrefixedString = (res, callback) -> data = '' length = null res.on 'data', listener = (chunk) -> data += chunk.toString 'utf8' if length == null # The number of bytes is written in an int on the first line. lines = data.split '\n' # If lines length > 1, then we've read the first newline, which was after the length # field. if lines.length > 1 length = parseInt lines.shift() # Now we'll rewrite the data variable to not include the length. data = lines.join '\n' if data.length == length res.removeListener 'data', listener callback data else if data.length > length console.warn data throw new Error "Read more bytes from stream than expected" # The backchannel is implemented using a bunch of messages which look like this: # # ``` # 36 # [[0,["c","92208FBF76484C10",,8] # ] # ] # ``` # # (At least, thats what they look like using google's server. On mine, they're properly # formatted JSON). # # Each message has a length string (in bytes) followed by a newline and some JSON data. # They can optionally have extra chunks afterwards. # # This format is used for: # # - All XHR backchannel messages # - The response to the initial connect (XHR or HTTP) # - The server acknowledgement to forward channel messages # # This is not used when you're on IE, for normal backchannel requests. On IE, data is sent # through javascript calls from an iframe. readLengthPrefixedJSON = (res, callback) -> readLengthPrefixedString res, (data) -> callback JSON.parse(data) # Copied from google's implementation. The contents of this aren't actually relevant, # but I think its important that its pseudo-random so if the connection is compressed, # it still recieves a bunch of bytes after the first message. ieJunk = "7cca69475363026330a0d99468e88d23ce95e222591126443015f5f462d9a177186c8701fb45a6ffe\ e0daf1a178fc0f58cd309308fba7e6f011ac38c9cdd4580760f1d4560a84d5ca0355ecbbed2ab715a3350fe0c47\ 9050640bd0e77acec90c58c4d3dd0f5cf8d4510e68c8b12e087bd88cad349aafd2ab16b07b0b1b8276091217a44\ a9fe92fedacffff48092ee693af\n" suite 'server', -> # #### setup # # Before each test has run, we'll start a new server. The server will only live # for that test and then it'll be torn down again. # # This makes the tests run more slowly, but not slowly enough that I care. setup (callback) -> # This will make sure there's no pesky setTimeouts from previous tests kicking around. # I could instead do a timer.waitAll() in tearDown to let all the timers run & time out # the running sessions. It shouldn't be a big deal. timer.clearAll() # When you instantiate browserchannel, you specify a function which gets called # with each session that connects. I'll proxy that function call to a local function # which tests can override. @onSession = (session) -> # The proxy is inline here. Also, I <3 coffeescript's (@server, @port) -> syntax here. # That will automatically set this.server and this.port to the callback arguments. # # Actually calling the callback starts the test. createServer ((session) => @onSession session), (@server, @port, @bc) => # TODO - This should be exported from lib/server @standardHeaders= 'Content-Type': 'text/plain' 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate' 'Pragma': 'no-cache' 'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT' 'X-Content-Type-Options': 'nosniff' # I'll add a couple helper methods for tests to easily message the server. @get = (path, callback) => http.get {host:'localhost', path, @port}, callback @post = (path, data, callback) => req = http.request {method:'POST', host:'localhost', path, @port}, callback req.end data # One of the most common tasks in tests is to create a new session for # some reason. @connect is a little helper method for that. It simply sends the # http POST to create a new session and calls the callback when the session has been # created by the server. # # It also makes @onSession throw an error - very few tests need multiple sessions, # so I special case them when they do. # # Its kind of annoying - for a lot of tests I need to do custom logic in the @post # handler *and* custom logic in @onSession. So, callback can be an object specifying # callbacks for each if you want that. Its a shame though, it makes this function # kinda ugly :/ @connect = (callback) => # This connect helper method is only useful if you don't care about the initial # post response. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0' @onSession = (@session) => @onSession = -> throw new Error 'onSession() called - I didn\'t expect another session to be created' # Keep this bound. I think there's a fancy way to do this in coffeescript, but # I'm not sure what it is. callback.call this # Finally, start the test. callback() teardown (callback) -> # #### tearDown # # This is called after each tests is done. We'll tear down the server we just created. # # The next test is run once the callback is called. I could probably chain the next # test without waiting for close(), but then its possible that an exception thrown # in one test will appear after the next test has started running. Its easier to debug # like this. @server.close callback # The server hosts the client-side javascript at /channel.js. It should have headers set to tell # browsers its javascript. # # Its self contained, with no dependancies on anything. It would be nice to test it as well, # but we'll do that elsewhere. test 'The javascript is hosted at channel/bcsocket.js', (done) -> @get '/channel/bcsocket.js', (response) -> assert.strictEqual response.statusCode, 200 assert.strictEqual response.headers['content-type'], 'application/javascript' assert.ok response.headers['etag'] buffer response, (data) -> # Its about 47k. If the size changes too drastically, I want to know about it. assert.ok data.length > 45000, "Client is unusually small (#{data.length} bytes)" assert.ok data.length < 50000, "Client is bloaty (#{data.length} bytes)" done() # # Testing channel tests # # The first thing a client does when it connects is issue a GET on /test/?mode=INIT. # The server responds with an array of [basePrefix or null,blockedPrefix or null]. Blocked # prefix isn't supported by node-browerchannel and by default no basePrefix is set. So with no # options specified, this GET should return [null,null]. test 'GET /test/?mode=INIT with no baseprefix set returns [null, null]', (done) -> @get '/channel/test?VER=8&MODE=init', (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' done() # If a basePrefix is set in the options, make sure the server returns it. test 'GET /test/?mode=INIT with a basePrefix set returns [basePrefix, null]', (done) -> # You can specify a bunch of host prefixes. If you do, the server will randomly pick between them. # I don't know if thats actually useful behaviour, but *shrug* # I should probably write a test to make sure all host prefixes will be chosen from time to time. createServer hostPrefixes:['chan'], (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '["chan",null]' # I'm being slack here - the server might not close immediately. I could make done() # dependant on it, but I can't be bothered. server.close() done() # Setting a custom url endpoint to bind node-browserchannel to should make it respond at that url endpoint # only. test 'The test channel responds at a bound custom endpoint', (done) -> createServer base:'/foozit', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # Some people will miss out on the leading slash in the URL when they bind browserchannel to a custom # url. That should work too. test 'binding the server to a custom url without a leading slash works', (done) -> createServer base:'foozit', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # Its tempting to think that you need a trailing slash on your URL prefix as well. You don't, but that should # work too. test 'binding the server to a custom url with a trailing slash works', (done) -> # Some day, the copy+paste police are gonna get me. I don't feel *so* bad doing it for tests though, because # it helps readability. createServer base:'foozit/', (->), (server, port) -> http.get {path:'/foozit/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, '[null,null]' server.close() done() # You can control the CORS header ('Access-Control-Allow-Origin') using options.cors. test 'CORS header is not sent if its not set in the options', (done) -> @get '/channel/test?VER=8&MODE=init', (response) -> assert.strictEqual response.headers['access-control-allow-origin'], undefined assert.strictEqual response.headers['access-control-allow-credentials'], undefined response.socket.end() done() test 'CORS headers are sent during the initial phase if set in the options', (done) -> createServer cors:'foo.com', corsAllowCredentials:true, (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual response.headers['access-control-allow-credentials'], 'true' buffer response server.close() done() test 'CORS headers can be set using a function', (done) -> createServer cors: (-> 'something'), (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['access-control-allow-origin'], 'something' buffer response server.close() done() test 'CORS header is set on the backchannel response', (done) -> server = port = null sessionCreated = (session) -> # Make the backchannel flush as soon as its opened session.send "flush" req = http.get {path:"/channel/bind?VER=8&RID=rpc&SID=#{session.id}&AID=0&TYPE=xmlhttp&CI=0", host:'localhost', port:port}, (res) => assert.strictEqual res.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual res.headers['access-control-allow-credentials'], 'true' req.abort() server.close() done() createServer cors:'foo.com', corsAllowCredentials:true, sessionCreated, (_server, _port) -> [server, port] = [_server, _port] req = http.request {method:'POST', path:'/channel/bind?VER=8&RID=1000&t=1', host:'localhost', port:port}, (res) => req.end 'count=0' # This test is just testing one of the error responses for the presence of # the CORS header. It doesn't test all of the ports, and doesn't test IE. # (I'm not actually sure if CORS headers are needed for IE stuff) suite 'CORS header is set in error responses', -> setup (callback) -> createServer cors:'foo.com', corsAllowCredentials:true, (->), (@corsServer, @corsPort) => callback() teardown -> @corsServer.close() testResponse = (done, req, res) -> assert.strictEqual res.statusCode, 400 assert.strictEqual res.headers['access-control-allow-origin'], 'foo.com' assert.strictEqual res.headers['access-control-allow-credentials'], 'true' buffer res, (data) -> assert.ok data.indexOf('Unknown SID') > 0 req.abort() done() test 'backChannel', (done) -> req = http.get {path:'/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=xmlhttp&CI=0', host:'localhost', port:@corsPort}, (res) => testResponse done, req, res test 'forwardChannel', (done) -> req = http.request {method:'POST', path:'/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0', host:'localhost', port:@corsPort}, (res) => testResponse done, req, res req.end 'count=0' #@post "/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0", 'count=0', testResponse(done) test 'Additional headers can be specified in the options', (done) -> createServer headers:{'X-Foo':'bar'}, (->), (server, port) -> http.get {path:'/channel/test?VER=8&MODE=init', host: 'localhost', port: port}, (response) -> assert.strictEqual response.headers['x-foo'], 'bar' server.close() done() # Interestingly, the CORS header isn't required for old IE (type=html) requests because they're loaded using # iframes anyway. (Though this should really be tested). # node-browserchannel is only responsible for URLs with the specified (or default) prefix. If a request # comes in for a URL outside of that path, it should be passed along to subsequent connect middleware. # # I've set up the createServer() method above to send 'Other middleware' if browserchannel passes # the response on to the next handler. test 'getting a url outside of the bound range gets passed to other middleware', (done) -> @get '/otherapp', (response) -> assert.strictEqual response.statusCode, 200 buffer response, (data) -> assert.strictEqual data, 'Other middleware' done() # I decided to make URLs inside the bound range return 404s directly. I can't guarantee that no future # version of node-browserchannel won't add more URLs in the zone, so its important that users don't decide # to start using arbitrary other URLs under channel/. # # That design decision makes it impossible to add a custom 404 page to /channel/FOO, but I don't think thats a # big deal. test 'getting a wacky url inside the bound range returns 404', (done) -> @get '/channel/doesnotexist', (response) -> assert.strictEqual response.statusCode, 404 response.socket.end() done() # For node-browserchannel, we also accept JSON in forward channel POST data. To tell the client that # this is supported, we add an `X-Accept: application/json; application/x-www-form-urlencoded` header # in phase 1 of the test API. test 'The server sends accept:JSON header during test phase 1', (done) -> @get '/channel/test?VER=8&MODE=init', (res) -> assert.strictEqual res.headers['x-accept'], 'application/json; application/x-www-form-urlencoded' res.socket.end() done() # All the standard headers should be sent along with X-Accept test 'The server sends standard headers during test phase 1', (done) -> @get '/channel/test?VER=8&MODE=init', (res) => assert.strictEqual res.headers[k.toLowerCase()].toLowerCase(), v.toLowerCase() for k,v of @standardHeaders res.socket.end() done() # ## Testing phase 2 # # I should really sort the above tests better. # # Testing phase 2 the client GETs /channel/test?VER=8&TYPE= [html / xmlhttp] &zx=558cz3evkwuu&t=1 [&DOMAIN=xxxx] # # The server sends '11111' <2 second break> '2'. If you use html encoding instead, the server sends the client # a webpage which calls: # # document.domain='mail.google.com'; # parent.m('11111'); # parent.m('2'); # parent.d(); suite 'Getting test phase 2 returns 11111 then 2', -> makeTest = (type, message1, message2) -> (done) -> @get "/channel/test?VER=8&TYPE=#{type}", (response) -> assert.strictEqual response.statusCode, 200 expect response, message1, -> # Its important to make sure that message 2 isn't sent too soon (<2 seconds). # We'll advance the server's clock forward by just under 2 seconds and then wait a little bit # for messages from the client. If we get a message during this time, throw an error. response.on 'data', f = -> throw new Error 'should not get more data so early' timer.wait 1999, -> soon -> response.removeListener 'data', f expect response, message2, -> response.once 'end', -> done() timer.wait 1 test 'xmlhttp', makeTest 'xmlhttp', '11111', '2' # I could write this test using JSDom or something like that, and parse out the HTML correctly. # ... but it would be way more complicated (and no more correct) than simply comparing the resulting # strings. test 'html', makeTest('html', # These HTML responses are identical to what I'm getting from google's servers. I think the seemingly # random sequence is just so network framing doesn't try and chunk up the first packet sent to the server # or something like that. """<html><body><script>try {parent.m("11111")} catch(e) {}</script>\n#{ieJunk}""", '''<script>try {parent.m("2")} catch(e) {}</script> <script>try {parent.d(); }catch (e){}</script>\n''') # If a client is connecting with a host prefix, the server sets the iframe's document.domain to match # before sending actual data. 'html with a host prefix': makeTest('html&DOMAIN=foo.bar.com', # I've made a small change from google's implementation here. I'm using double quotes `"` instead of # single quotes `'` because its easier to encode. (I can't just wrap the string in quotes because there # are potential XSS vulnerabilities if I do that). """<html><body><script>try{document.domain="foo.bar.com";}catch(e){}</script> <script>try {parent.m("11111")} catch(e) {}</script>\n#{ieJunk}""", '''<script>try {parent.m("2")} catch(e) {}</script> <script>try {parent.d(); }catch (e){}</script>\n''') # IE doesn't parse the HTML in the response unless the Content-Type is text/html test 'Using type=html sets Content-Type: text/html', (done) -> r = @get "/channel/test?VER=8&TYPE=html", (response) -> assert.strictEqual response.headers['content-type'], 'text/html' r.abort() done() # IE should also get the standard headers test 'Using type=html gets the standard headers', (done) -> r = @get "/channel/test?VER=8&TYPE=html", (response) => for k, v of @standardHeaders when k isnt 'Content-Type' assert.strictEqual response.headers[k.toLowerCase()].toLowerCase(), v.toLowerCase() r.abort() done() # node-browserchannel is only compatible with browserchannel client version 8. I don't know whats changed # since old versions (maybe v6 would be easy to support) but I don't care. If the client specifies # an old version, we'll die with an error. # The alternate phase 2 URL style should have the same behaviour if the version is old or unspecified. # # Google's browserchannel server still works if you miss out on specifying the version - it defaults # to version 1 (which maybe didn't have version numbers in the URLs). I'm kind of impressed that # all that code still works. suite 'Getting /test/* without VER=8 returns an error', -> # All these tests look 95% the same. Instead of writing the same test all those times, I'll use this # little helper method to generate them. check400 = (path) -> (done) -> @get path, (response) -> assert.strictEqual response.statusCode, 400 response.socket.end() done() test 'phase 1, ver 7', check400 '/channel/test?VER=7&MODE=init' test 'phase 1, no version', check400 '/channel/test?MODE=init' test 'phase 2, ver 7, xmlhttp', check400 '/channel/test?VER=7&TYPE=xmlhttp' test 'phase 2, no version, xmlhttp', check400 '/channel/test?TYPE=xmlhttp' # For HTTP connections (IE), the error is sent a different way. Its kinda complicated how the error # is sent back, so for now I'm just going to ignore checking it. test 'phase 2, ver 7, http', check400 '/channel/test?VER=7&TYPE=html' test 'phase 2, no version, http', check400 '/channel/test?TYPE=html' # > At the moment the server expects the client will add a zx=###### query parameter to all requests. # The server isn't strict about this, so I'll ignore it in the tests for now. # # Server connection tests # These tests make server sessions by crafting raw HTTP queries. I'll make another set of # tests later which spam the server with a million fake clients. # # To start with, simply connect to a server using the BIND API. A client sends a server a few parameters: # # - **CVER**: Client application version # - **RID**: Client-side generated random number, which is the initial sequence number for the # client's requests. # - **VER**: Browserchannel protocol version. Must be 8. # - **t**: The connection attempt number. This is currently ignored by the BC server. (I'm not sure # what google's implementation does with this). test 'The server makes a new session if the client POSTs the right connection stuff', (done) -> id = null onSessionCalled = no # When a request comes in, we should get the new session through the server API. # # We need this session in order to find out the session ID, which should match up with part of the # server's response. @onSession = (session) -> assert.ok session assert.strictEqual typeof session.id, 'string' assert.strictEqual session.state, 'init' assert.strictEqual session.appVersion, '99' assert.deepEqual session.address, '127.0.0.1' assert.strictEqual typeof session.headers, 'object' id = session.id session.on 'map', -> throw new Error 'Should not have received data' onSessionCalled = yes # The client starts a BC connection by POSTing to /bind? with no session ID specified. # The client can optionally send data here, but in this case it won't (hence the `count=0`). @post '/channel/bind?VER=8&RID=1000&CVER=99&t=1&junk=asdfasdf', 'count=0', (res) => expected = (JSON.stringify [[0, ['c', id, null, 8]]]) + '\n' buffer res, (data) -> # Even for old IE clients, the server responds in length-prefixed JSON style. assert.strictEqual data, "#{expected.length}\n#{expected}" assert.ok onSessionCalled done() # Once a client's session id is sent, the session moves to the `ok` state. This happens after onSession is # called (so onSession can send messages to the client immediately). # # I'm starting to use the @connect method here, which just POSTs locally to create a session, sets @session and # calls its callback. test 'A session has state=ok after onSession returns', (done) -> @connect -> @session.on 'state changed', (newState, oldState) => assert.strictEqual oldState, 'init' assert.strictEqual newState, 'ok' assert.strictEqual @session.state, 'ok' done() # The CVER= property is optional during client connections. If its left out, session.appVersion is # null. test 'A session connects ok even if it doesnt specify an app version', (done) -> id = null onSessionCalled = no @onSession = (session) -> assert.strictEqual session.appVersion, null id = session.id session.on 'map', -> throw new Error 'Should not have received data' onSessionCalled = yes @post '/channel/bind?VER=8&RID=1000&t=1&junk=asdfasdf', 'count=0', (res) => expected = (JSON.stringify [[0, ['c', id, null, 8]]]) + '\n' buffer res, (data) -> assert.strictEqual data, "#{expected.length}\n#{expected}" assert.ok onSessionCalled done() # Once again, only VER=8 works. suite 'Connecting with a version thats not 8 breaks', -> # This will POST to the requested path and make sure the response sets status 400 check400 = (path) -> (done) -> @post path, 'count=0', (response) -> assert.strictEqual response.statusCode, 400 response.socket.end() done() test 'no version', check400 '/channel/bind?RID=1000&t=1' test 'previous version', check400 '/channel/bind?VER=7&RID=1000&t=1' # This time, we'll send a map to the server during the initial handshake. This should be received # by the server as normal. test 'The client can post messages to the server during initialization', (done) -> @onSession = (session) -> session.on 'map', (data) -> assert.deepEqual data, {k:'v'} done() @post '/channel/bind?VER=8&RID=1000&t=1', 'count=1&ofs=0&req0_k=v', (res) => res.socket.end() # The data received by the server should be properly URL decoded and whatnot. test 'Server messages are properly URL decoded', (done) -> @onSession = (session) -> session.on 'map', (data) -> assert.deepEqual data, {"_int_^&^%#net":'hi"there&&\nsam'} done() @post('/channel/bind?VER=8&RID=1000&t=1', 'count=1&ofs=0&req0__int_%5E%26%5E%25%23net=hi%22there%26%26%0Asam', (res) -> res.socket.end()) # After a client connects, it can POST data to the server using URL-encoded POST data. This data # is sent by POSTing to /bind?SID=.... # # The data looks like this: # # count=5&ofs=1000&req0_KEY1=PI:KEY:<KEY>END_PI&req0_KEY2=VALPI:KEY:<KEY>END_PI&req1_KEY3=req1_VALPI:KEY:<KEY>END_PI&... test 'The client can post messages to the server after initialization', (done) -> @connect -> @session.on 'map', (data) -> assert.deepEqual data, {k:'v'} done() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => res.socket.end() # When the server gets a forwardchannel request, it should reply with a little array saying whats # going on. test 'The server acknowledges forward channel messages correctly', (done) -> @connect -> @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => readLengthPrefixedJSON res, (data) => # The server responds with [backchannelMissing ? 0 : 1, lastSentAID, outstandingBytes] assert.deepEqual data, [0, 0, 0] done() # If the server has an active backchannel, it responds to forward channel requests notifying the client # that the backchannel connection is alive and well. test 'The server tells the client if the backchannel is alive', (done) -> @connect -> # This will fire up a backchannel connection to the server. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp", (res) => # The client shouldn't get any data through the backchannel. res.on 'data', -> throw new Error 'Should not get data through backchannel' # Unfortunately, the GET request is sent *after* the POST, so we have to wrap the # post in a timeout to make sure it hits the server after the backchannel connection is # established. soon => @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_k=v', (res) => readLengthPrefixedJSON res, (data) => # This time, we get a 1 as the first argument because the backchannel connection is # established. assert.deepEqual data, [1, 0, 0] # The backchannel hasn't gotten any data yet. It'll spend 15 seconds or so timing out # if we don't abort it manually. # As of nodejs 0.6, if you abort() a connection, it can emit an error. req.on 'error', -> req.abort() done() # The forward channel response tells the client how many unacknowledged bytes there are, so it can decide # whether or not it thinks the backchannel is dead. test 'The server tells the client how much unacknowledged data there is in the post response', (done) -> @connect -> process.nextTick => # I'm going to send a few messages to the client and acknowledge the first one in a post response. @session.send 'message 1' @session.send 'message 2' @session.send 'message 3' # We'll make a backchannel and get the data req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => # After the data is received, I'll acknowledge the first message using an empty POST @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=1", 'count=0', (res) => readLengthPrefixedJSON res, (data) => # We should get a response saying "The backchannel is connected", "The last message I sent was 3" # "messages 2 and 3 haven't been acknowledged, here's their size" assert.deepEqual data, [1, 3, 25] req.abort() done() # When the user calls send(), data is queued by the server and sent into the next backchannel connection. # # The server will use the initial establishing connection if thats available, or it'll send it the next # time the client opens a backchannel connection. test 'The server returns data on the initial connection when send is called immediately', (done) -> testData = ['hello', 'there', null, 1000, {}, [], [555]] @onSession = (@session) => @session.send testData # I'm not using @connect because we need to know about the response to the first POST. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[0, ['c', @session.id, null, 8]], [1, testData]] done() test 'The server escapes tricky characters before sending JSON over the wire', (done) -> testData = {'a': 'hello\u2028\u2029there\u2028\u2029'} @onSession = (@session) => @session.send testData # I'm not using @connect because we need to know about the response to the first POST. @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedString res, (data) => assert.deepEqual data, """[[0,["c","#{@session.id}",null,8]],[1,{"a":"hello\\u2028\\u2029there\\u2028\\u2029"}]]\n""" done() test 'The server buffers data if no backchannel is available', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] # The first response to the server is sent after this method returns, so if we send the data # in process.nextTick, it'll get buffered. process.nextTick => @session.send testData req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] req.abort() done() # This time, we'll fire up the back channel first (and give it time to get established) _then_ # send data through the session. test 'The server returns data through the available backchannel when send is called later', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] # Fire off the backchannel request as soon as the client has connected req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) -> #res.on 'data', (chunk) -> console.warn chunk.toString() readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, testData]] req.abort() done() # Send the data outside of the get block to make sure it makes it through. soon => @session.send testData # The server should call the send callback once the data has been confirmed by the client. # # We'll try sending three messages to the client. The first message will be sent during init and the # third message will not be acknowledged. Only the first two message callbacks should get called. test 'The server calls send callback once data is acknowledged', (done) -> @connect -> lastAck = null @session.send [1], -> assert.strictEqual lastAck, null lastAck = 1 process.nextTick => @session.send [2], -> assert.strictEqual lastAck, 1 # I want to give the test time to die soon -> done() # This callback should actually get called with an error after the client times out. ... but I'm not # giving timeouts a chance to run. @session.send [3], -> throw new Error 'Should not call unacknowledged send callback' req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[2, [2]], [3, [3]]] # Ok, now we'll only acknowledge the second message by sending AID=2 @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=2", 'count=0', (res) => res.socket.end() req.abort() # This tests for a regression - if the stop callback closed the connection, the server was crashing. test 'The send callback can stop the session', (done) -> @connect -> req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => # Acknowledge the stop message @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=2", 'count=0', (res) => res.socket.end() @session.stop => @session.close() soon -> req.abort() done() # If there's a proxy in the way which chunks up responses before sending them on, the client adds a # &CI=1 argument on the backchannel. This causes the server to end the HTTP query after each message # is sent, so the data is sent to the session. test 'The backchannel is closed after each packet if chunking is turned off', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # Instead of the usual CI=0 we're passing CI=1 here. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=1", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] res.on 'end', -> done() # Normally, the server doesn't close the connection after each backchannel message. test 'The backchannel is left open if CI=0', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, testData]] # After receiving the data, the client shouldn't close the connection. (At least, not unless # it times out naturally). res.on 'end', -> throw new Error 'connection should have stayed open' soon -> res.removeAllListeners 'end' req.abort() done() # On IE, the data is all loaded using iframes. The backchannel spits out data using inline scripts # in an HTML page. # # I've written this test separately from the tests above, but it would really make more sense # to rerun the same set of tests in both HTML and XHR modes to make sure the behaviour is correct # in both instances. test 'The server gives the client correctly formatted backchannel data if TYPE=html', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # The type is specified as an argument here in the query string. For this test, I'm making # CI=1, because the test is easier to write that way. # # In truth, I don't care about IE support as much as support for modern browsers. This might # be a mistake.. I'm not sure. IE9's XHR support should work just fine for browserchannel, # though google's BC client doesn't use it. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=html&CI=1", (res) => expect res, # Interestingly, google doesn't double-encode the string like this. Instead of turning # quotes `"` into escaped quotes `\"`, it uses unicode encoding to turn them into \42 and # stuff like that. I'm not sure why they do this - it produces the same effect in IE8. # I should test it in IE6 and see if there's any problems. """<html><body><script>try {parent.m(#{JSON.stringify JSON.stringify([[1, testData]]) + '\n'})} catch(e) {}</script> #{ieJunk}<script>try {parent.d(); }catch (e){}</script>\n""", => # Because I'm lazy, I'm going to chain on a test to make sure CI=0 works as well. data2 = {other:'data'} @session.send data2 # I'm setting AID=1 here to indicate that the client has seen array 1. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=html&CI=0", (res) => expect res, """<html><body><script>try {parent.m(#{JSON.stringify JSON.stringify([[2, data2]]) + '\n'})} catch(e) {}</script> #{ieJunk}""", => req.abort() done() # If there's a basePrefix set, the returned HTML sets `document.domain = ` before sending messages. # I'm super lazy, and just copy+pasting from the test above. There's probably a way to factor these tests # nicely, but I'm not in the mood to figure it out at the moment. test 'The server sets the domain if we have a domain set', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # This time we're setting DOMAIN=X, and the response contains a document.domain= block. Woo. @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=html&CI=1&DOMAIN=foo.com", (res) => expect res, """<html><body><script>try{document.domain=\"foo.com\";}catch(e){}</script> <script>try {parent.m(#{JSON.stringify JSON.stringify([[1, testData]]) + '\n'})} catch(e) {}</script> #{ieJunk}<script>try {parent.d(); }catch (e){}</script>\n""", => data2 = {other:'data'} @session.send data2 req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=html&CI=0&DOMAIN=foo.com", (res) => expect res, # Its interesting - in the test channel, the ie junk comes right after the document.domain= line, # but in a backchannel like this it comes after. The behaviour here is the same in google's version. # # I'm not sure if its actually significant though. """<html><body><script>try{document.domain=\"foo.com\";}catch(e){}</script> <script>try {parent.m(#{JSON.stringify JSON.stringify([[2, data2]]) + '\n'})} catch(e) {}</script> #{ieJunk}""", => req.abort() done() # If a client thinks their backchannel connection is closed, they might open a second backchannel connection. # In this case, the server should close the old one and resume sending stuff using the new connection. test 'The server closes old backchannel connections', (done) -> @connect -> testData = ['hello', 'there', null, 1000, {}, [], [555]] process.nextTick => @session.send testData # As usual, we'll get the sent data through the backchannel connection. The connection is kept open... @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => # ... and the data has been read. Now we'll open another connection and check that the first connection # gets closed. req2 = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res2) => res.on 'end', -> req2.on 'error', -> req2.abort() done() # The client attaches a sequence number (*RID*) to every message, to make sure they don't end up out-of-order at # the server's end. # # We'll purposefully send some messages out of order and make sure they're held and passed through in order. # # Gogo gadget reimplementing TCP. test 'The server orders forwardchannel messages correctly using RIDs', (done) -> @connect -> # @connect sets RID=1000. # We'll send 2 maps, the first one will be {v:1} then {v:0}. They should be swapped around by the server. lastVal = 0 @session.on 'map', (map) -> assert.strictEqual map.v, "#{lastVal++}", 'messages arent reordered in the server' done() if map.v == '2' # First, send `[{v:2}]` @post "/channel/bind?VER=8&RID=1002&SID=#{@session.id}&AID=0", 'count=1&ofs=2&req0_v=2', (res) => res.socket.end() # ... then `[{v:0}, {v:1}]` a few MS later. soon => @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=2&ofs=0&req0_v=0&req1_v=1', (res) => res.socket.end() # Again, think of browserchannel as TCP on top of UDP... test 'Repeated forward channel messages are discarded', (done) -> @connect -> gotMessage = false # The map must only be received once. @session.on 'map', (map) -> if gotMessage == false gotMessage = true else throw new Error 'got map twice' # POST the maps twice. @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() # Wait 50 milliseconds for the map to (maybe!) be received twice, then pass. soon -> assert.strictEqual gotMessage, true done() # The client can retry failed forwardchannel requests with additional maps. We may have gotten the failed # request. An error could have occurred when we reply. test 'Repeat forward channel messages can contain extra maps', (done) -> @connect -> # We should get exactly 2 maps, {v:0} then {v:1} maps = [] @session.on 'map', (map) -> maps.push map @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_v=0', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=2&ofs=0&req0_v=0&req1_v=1', (res) => res.socket.end() soon -> assert.deepEqual maps, [{v:0}, {v:1}] done() # With each request to the server, the client tells the server what array it saw last through the AID= parameter. # # If a client sends a subsequent backchannel request with an old AID= set, that means the client never saw the arrays # the server has previously sent. So, the server should resend them. test 'The server resends lost arrays if the client asks for them', (done) -> @connect -> process.nextTick => @session.send [1,2,3] @session.send [4,5,6] @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[1, [1,2,3]], [2, [4,5,6]]] # We'll resend that request, pretending that the client never saw the second array sent (`[4,5,6]`) req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[2, [4,5,6]]] # We don't need to abort the first connection because the server should close it. req.abort() done() # If you sleep your laptop or something, by the time you open it again the server could have timed out your session # so your session ID is invalid. This will also happen if the server gets restarted or something like that. # # The server should respond to any query requesting a nonexistant session ID with 400 and put 'Unknown SID' # somewhere in the message. (Actually, the BC client test is `indexOf('Unknown SID') > 0` so there has to be something # before that text in the message or indexOf will return 0. # # The google servers also set Unknown SID as the http status code, which is kinda neat. I can't check for that. suite 'If a client sends an invalid SID in a request, the server responds with 400 Unknown SID', -> testResponse = (done) -> (res) -> assert.strictEqual res.statusCode, 400 buffer res, (data) -> assert.ok data.indexOf('Unknown SID') > 0 done() test 'backChannel', (done) -> @get "/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=xmlhttp&CI=0", testResponse(done) test 'forwardChannel', (done) -> @post "/channel/bind?VER=8&RID=1001&SID=junkyjunk&AID=0", 'count=0', testResponse(done) # When type=HTML, google's servers still send the same response back to the client. I'm not sure how it detects # the error, but it seems to work. So, I'll copy that behaviour. test 'backChannel with TYPE=html', (done) -> @get "/channel/bind?VER=8&RID=rpc&SID=madeup&AID=0&TYPE=html&CI=0", testResponse(done) # When a client connects, it can optionally specify its old session ID and array ID. This solves the old IRC # ghosting problem - if the old session hasn't timed out on the server yet, you can temporarily be in a state where # multiple connections represent the same user. test 'If a client disconnects then reconnects, specifying OSID= and OAID=, the old session is destroyed', (done) -> @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => res.socket.end() # I want to check the following things: # # - on 'close' is called on the first session # - onSession is called with the second session # - on 'close' is called before the second session is created # # Its kinda gross managing all that state in one function... @onSession = (session1) => # As soon as the client has connected, we'll fire off a new connection claiming the previous session is old. @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{session1.id}&OAID=0", 'count=0', (res) => res.socket.end() c1Closed = false session1.on 'close', -> c1Closed = true # Once the first client has connected, I'm replacing @onSession so the second session's state can be handled # separately. @onSession = (session2) -> assert.ok c1Closed assert.strictEqual session1.state, 'closed' done() # The server might have already timed out an old connection. In this case, the OSID is ignored. test 'The server ignores OSID and OAID if the named session doesnt exist', (done) -> @post "/channel/bind?VER=8&RID=2000&t=1&OSID=doesnotexist&OAID=0", 'count=0', (res) => res.socket.end() # So small & pleasant! @onSession = (session) => assert.ok session done() # OAID is set in the ghosted connection as a final attempt to flush arrays. test 'The server uses OAID to confirm arrays in the old session before closing it', (done) -> @connect -> # We'll follow the same pattern as the first callback test waay above. We'll send three messages, one # in the first callback and two after. We'll pretend that just the first two messages made it through. lastMessage = null # We'll create a new session in a moment when we POST with OSID and OAID. @onSession = -> @session.send 1, (error) -> assert.ifError error assert.strictEqual lastMessage, null lastMessage = 1 # The final message callback should get called after the close event fires @session.on 'close', -> assert.strictEqual lastMessage, 2 process.nextTick => @session.send 2, (error) -> assert.ifError error assert.strictEqual lastMessage, 1 lastMessage = 2 @session.send 3, (error) -> assert.ok error assert.strictEqual lastMessage, 2 lastMessage = 3 assert.strictEqual error.message, 'Reconnected' soon -> req.abort() done() # And now we'll nuke the session and confirm the first two arrays. But first, its important # the client has a backchannel to send data to (confirming arrays before a backchannel is opened # to receive them is undefined and probably does something bad) req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=1&TYPE=xmlhttp&CI=0", (res) => res.socket.end() @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{@session.id}&OAID=2", 'count=0', (res) => res.socket.end() test 'The session times out after awhile if it doesnt have a backchannel', (done) -> @connect -> start = timer.Date.now() @session.on 'close', (reason) -> assert.strictEqual reason, 'Timed out' # It should take at least 30 seconds. assert.ok timer.Date.now() - start >= 30000 done() timer.waitAll() test 'The session can be disconnected by firing a GET with TYPE=terminate', (done) -> @connect -> # The client doesn't seem to put AID= in here. I'm not sure why - could be a bug in the client. @get "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&TYPE=terminate", (res) -> # The response should be empty. buffer res, (data) -> assert.strictEqual data, '' @session.on 'close', (reason) -> # ... Its a manual disconnect. Is this reason string good enough? assert.strictEqual reason, 'Disconnected' done() test 'If a disconnect message reaches the client before some data, the data is still received', (done) -> @connect -> # The disconnect message is sent first, but its got a higher RID. It shouldn't be handled until # after the data. @get "/channel/bind?VER=8&RID=1003&SID=#{@session.id}&TYPE=terminate", (res) -> res.socket.end() soon => @post "/channel/bind?VER=8&RID=1002&SID=#{@session.id}&AID=0", 'count=1&ofs=1&req0_m=2', (res) => res.socket.end() @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", 'count=1&ofs=0&req0_m=1', (res) => res.socket.end() maps = [] @session.on 'map', (data) -> maps.push data @session.on 'close', (reason) -> assert.strictEqual reason, 'Disconnected' assert.deepEqual maps, [{m:1}, {m:2}] done() # There's a slightly different codepath after a backchannel is opened then closed again. I want to make # sure it still works in this case. # # Its surprising how often this test fails. test 'The session times out if its backchannel is closed', (done) -> @connect -> process.nextTick => req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => res.socket.end() # I'll let the backchannel establish itself for a moment, and then nuke it. soon => req.on 'error', -> req.abort() # It should take about 30 seconds from now to timeout the connection. start = timer.Date.now() @session.on 'close', (reason) -> assert.strictEqual reason, 'Timed out' assert.ok timer.Date.now() - start >= 30000 done() # The timer sessionTimeout won't be queued up until after the abort() message makes it # to the server. I hate all these delays, but its not easy to write this test without them. soon -> timer.waitAll() # The server sends a little heartbeat across the backchannel every 20 seconds if there hasn't been # any chatter anyway. This keeps the machines en route from evicting the backchannel connection. # (noops are ignored by the client.) test 'A heartbeat is sent across the backchannel (by default) every 20 seconds', (done) -> @connect -> start = timer.Date.now() req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (msg) -> # this really just tests that one heartbeat is sent. assert.deepEqual msg, [[1, ['noop']]] assert.ok timer.Date.now() - start >= 20000 req.abort() done() # Once again, we can't call waitAll() until the request has hit the server. soon -> timer.waitAll() # So long as the backchannel stays open, the server should just keep sending heartbeats and # the session doesn't timeout. test 'A server with an active backchannel doesnt timeout', (done) -> @connect -> aid = 1 req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => getNextNoop = -> readLengthPrefixedJSON res, (msg) -> assert.deepEqual msg, [[aid++, ['noop']]] getNextNoop() getNextNoop() # ... give the backchannel time to get established soon -> # wait 500 seconds. In that time, we'll get 25 noops. timer.wait 500 * 1000, -> # and then give the last noop a chance to get sent soon -> assert.strictEqual aid, 26 req.abort() done() #req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => # The send callback should be called _no matter what_. That means if a connection times out, it should # still be called, but we'll pass an error into the callback. suite 'The server calls send callbacks with an error', -> test 'when the session times out', (done) -> @connect -> # It seems like this message shouldn't give an error, but it does because the client never confirms that # its received it. sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Timed out' sendCallbackCalled = yes process.nextTick => @session.send 'Another message', (error) -> assert.ok error assert.strictEqual error.message, 'Timed out' assert.ok sendCallbackCalled done() timer.waitAll() test 'when the session is ghosted', (done) -> @connect -> # As soon as the client has connected, we'll fire off a new connection claiming the previous session is old. @post "/channel/bind?VER=8&RID=2000&t=1&OSID=#{@session.id}&OAID=0", 'count=0', (res) => res.socket.end() sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Reconnected' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'Reconnected' assert.ok sendCallbackCalled done() # Ignore the subsequent connection attempt @onSession = -> # The server can also abandon a connection by calling .abort(). Again, this should trigger error callbacks. test 'when the session is closed by the server', (done) -> @connect -> sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'foo' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'foo' assert.ok sendCallbackCalled done() @session.close 'foo' # Finally, the server closes a connection when the client actively closes it (by firing a GET with TYPE=terminate) test 'when the server gets a disconnect request', (done) -> @connect -> sendCallbackCalled = no @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'Disconnected' sendCallbackCalled = yes process.nextTick => @session.send 'hi', (error) -> assert.ok error assert.strictEqual error.message, 'Disconnected' assert.ok sendCallbackCalled done() @get "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&TYPE=terminate", (res) -> res.socket.end() test 'If a session has close() called with no arguments, the send error message says "closed"', (done) -> @connect -> @session.send 'hello there', (error) -> assert.ok error assert.strictEqual error.message, 'closed' done() @session.close() # stop() sends a message to the client saying basically 'something is wrong, stop trying to # connect'. It triggers a special error in the client, and the client will stop trying to reconnect # at this point. # # The server can still send and receive messages after the stop message has been sent. But the client # probably won't receive them. # # Stop takes a callback which is called when the stop message has been **sent**. (The client never confirms # that it has received the message). suite 'Calling stop() sends the stop command to the client', -> test 'during init', (done) -> @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) => readLengthPrefixedJSON res, (data) => assert.deepEqual data, [[0, ['c', @session.id, null, 8]], [1, ['stop']]] done() @onSession = (@session) => @session.stop() test 'after init', (done) -> @connect -> # This test is similar to the test above, but I've put .stop() in a setTimeout. req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, ['stop']]] req.abort() done() soon => @session.stop() suite 'A callback passed to stop is called once stop is sent to the client', -> # ... because the stop message will be sent to the client in the initial connection test 'during init', (done) -> @connect -> @session.stop -> done() test 'after init', (done) -> @connect -> process.nextTick => stopCallbackCalled = no req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, ['stop']]] assert stopCallbackCalled req.abort() res.socket.end() done() @session.stop -> # Just a noop test to increase the 'things tested' count stopCallbackCalled = yes # close() aborts the session immediately. After calling close, subsequent requests to the session # should fail with unknown SID errors. suite 'session.close() closes the session', -> test 'during init', (done) -> @connect -> @session.close() @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => assert.strictEqual res.statusCode, 400 res.socket.end() done() test 'after init', (done) -> @connect -> process.nextTick => @session.close() @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => assert.strictEqual res.statusCode, 400 res.socket.end() done() # If you close immediately, the initial POST gets a 403 response (its probably an auth problem?) test 'An immediate session.close() results in the initial connection getting a 403 response', (done) -> @onSession = (@session) => @session.close() @post '/channel/bind?VER=8&RID=1000&t=1', 'count=0', (res) -> buffer res, (data) -> assert.strictEqual res.statusCode, 403 res.socket.end() done() # The session runs as a little state machine. It starts in the 'init' state, then moves to # 'ok' when the session is established. When the connection is closed, it moves to 'closed' state # and stays there forever. suite 'The session emits a "state changed" event when you close it', -> test 'immediately', (done) -> @connect -> # Because we're calling close() immediately, the session should never make it to the 'ok' state # before moving to 'closed'. @session.on 'state changed', (nstate, ostate) => assert.strictEqual nstate, 'closed' assert.strictEqual ostate, 'init' assert.strictEqual @session.state, 'closed' done() @session.close() test 'after it has opened', (done) -> @connect -> # This time we'll let the state change to 'ok' before closing the connection. @session.on 'state changed', (nstate, ostate) => if nstate is 'ok' @session.close() else assert.strictEqual nstate, 'closed' assert.strictEqual ostate, 'ok' assert.strictEqual @session.state, 'closed' done() # close() also kills any active backchannel connection. test 'close kills the active backchannel', (done) -> @connect -> @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => res.socket.end() done() # Give it some time for the backchannel to establish itself soon => @session.close() # # node-browserchannel extensions # # browserchannel by default only supports sending string->string maps from the client to server. This # is really awful - I mean, maybe this is useful for some apps, but really you just want to send & receive # JSON. # # To make everything nicer, I have two changes to browserchannel: # # - If a map is `{JSON:"<JSON STRING>"}`, the server will automatically parse the JSON string and # emit 'message', object. In this case, the server *also* emits the data as a map. # - The client can POST the forwardchannel data using a JSON blob. The message looks like this: # # {ofs: 10, data:[null, {...}, 1000.4, 'hi', ....]} # # In this case, the server *does not* emit a map, but merely emits the json object using emit 'message'. # # To advertise this service, during the first test, the server sends X-Accept: application/json; ... test 'The server decodes JSON data in a map if it has a JSON key', (done) -> @connect -> data1 = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] data2 = "hello dePI:NAME:<NAME>END_PI user" qs = querystring.stringify count: 2, ofs: 0, req0_JSON: (JSON.stringify data1), req1_JSON: (JSON.stringify data2) # I can guarantee qs is awful. @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", qs, (res) => res.socket.end() @session.once 'message', (msg) => assert.deepEqual msg, data1 @session.once 'message', (msg) -> assert.deepEqual msg, data2 done() # The server might be JSON decoding the data, but it still needs to emit it as a map. test 'The server emits JSON data in a map, as a map as well', (done) -> @connect -> data1 = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] data2 = "hello dePI:NAME:<NAME>END_PI user" qs = querystring.stringify count: 2, ofs: 0, req0_JSON: (JSON.stringify data1), req1_JSON: (JSON.stringify data2) @post "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0", qs, (res) => res.socket.end() # I would prefer to have more tests mixing maps and JSON data. I'm better off testing that # thoroughly using a randomized tester. @session.once 'map', (map) => assert.deepEqual map, JSON: JSON.stringify data1 @session.once 'map', (map) -> assert.deepEqual map, JSON: JSON.stringify data2 done() # The server also accepts raw JSON. test 'The server accepts JSON data', (done) -> @connect -> # The POST request has to specify Content-Type=application/json so we can't just use # the @post request. (Big tears!) options = method: 'POST' path: "/channel/bind?VER=8&RID=1001&SID=#{@session.id}&AID=0" host: 'localhost' port: @port headers: 'Content-Type': 'application/json' # This time I'm going to send the elements of the test object as separate messages. data = [{}, {'x':null}, 'hi', '!@#$%^&*()-=', '\'"'] req = http.request options, (res) -> readLengthPrefixedJSON res, (resData) -> # We won't get this response until all the messages have been processed. assert.deepEqual resData, [0, 0, 0] assert.deepEqual data, [] assert data.length is 0 res.on 'end', -> done() req.end (JSON.stringify {ofs:0, data}) @session.on 'message', (msg) -> assert.deepEqual msg, data.shift() # Hm- this test works, but the client code never recieves the null message. Eh. test 'You can send null', (done) -> @connect -> @session.send null req = @get "/channel/bind?VER=8&RID=rpc&SID=#{@session.id}&AID=0&TYPE=xmlhttp&CI=0", (res) => readLengthPrefixedJSON res, (data) -> assert.deepEqual data, [[1, null]] req.abort() res.socket.end() done() test 'Sessions are cancelled when close() is called on the server', (done) -> @connect -> @session.on 'close', done @bc.close() #'print', (done) -> @connect -> console.warn @session; done() # I should also test that you can mix a bunch of JSON requests and map requests, out of order, and the # server sorts it all out.
[ { "context": "# regex by Diego Perini \n# https://gist.github.com/dperini/729294\n# modif", "end": 23, "score": 0.9998882412910461, "start": 11, "tag": "NAME", "value": "Diego Perini" }, { "context": " regex by Diego Perini \n# https://gist.github.com/dperini/729294\n# modified to be...
_src/lib/utils.coffee
smrchy/task-queue-worker
11
# regex by Diego Perini # https://gist.github.com/dperini/729294 # modified to be able to use 127.x.x.x and 192.x.x.x regExUrl = new RegExp( "^" + # protocol identifier "(?:(?:https?|ftp)://)" + # user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + # IP address exclusion # private & local networks "(?!10(?:\\.\\d{1,3}){3})" + #"(?!127(?:\\.\\d{1,3}){3})" + "(?!169\\.254(?:\\.\\d{1,3}){2})" + #"(?!192\\.168(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + # IP address dotted notation octets # excludes loopback network 0.0.0.0 # excludes reserved space >= 224.0.0.0 # excludes network & broacast addresses # (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + # host name "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" + # domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" + # TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + ")" + "(?::\\d{2,5})?" + # resource path "(?:/[^\\s]*)?" + "$", "i" ) utils = randRange: ( lowVal, highVal )-> return Math.floor( Math.random()*(highVal-lowVal+1 ))+lowVal arrayRandom: ( array )-> idx = utils.randRange( 0, array.length-1 ) return array[ idx ] isUrl: (url)-> return regExUrl.test( url ) now: -> return Math.round( Date.now() / 1000 ) probability: ( val = 50 )-> return utils.randRange( 0,100 ) > val module.exports = utils
9439
# regex by <NAME> # https://gist.github.com/dperini/729294 # modified to be able to use 127.x.x.x and 192.x.x.x regExUrl = new RegExp( "^" + # protocol identifier "(?:(?:https?|ftp)://)" + # user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + # IP address exclusion # private & local networks "(?!10(?:\\.\\d{1,3}){3})" + #"(?!127(?:\\.\\d{1,3}){3})" + "(?!169\\.254(?:\\.\\d{1,3}){2})" + #"(?!192\\.168(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + # IP address dotted notation octets # excludes loopback network 0.0.0.0 # excludes reserved space >= 172.16.31.10 # excludes network & broacast addresses # (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + # host name "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" + # domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" + # TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + ")" + "(?::\\d{2,5})?" + # resource path "(?:/[^\\s]*)?" + "$", "i" ) utils = randRange: ( lowVal, highVal )-> return Math.floor( Math.random()*(highVal-lowVal+1 ))+lowVal arrayRandom: ( array )-> idx = utils.randRange( 0, array.length-1 ) return array[ idx ] isUrl: (url)-> return regExUrl.test( url ) now: -> return Math.round( Date.now() / 1000 ) probability: ( val = 50 )-> return utils.randRange( 0,100 ) > val module.exports = utils
true
# regex by PI:NAME:<NAME>END_PI # https://gist.github.com/dperini/729294 # modified to be able to use 127.x.x.x and 192.x.x.x regExUrl = new RegExp( "^" + # protocol identifier "(?:(?:https?|ftp)://)" + # user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + # IP address exclusion # private & local networks "(?!10(?:\\.\\d{1,3}){3})" + #"(?!127(?:\\.\\d{1,3}){3})" + "(?!169\\.254(?:\\.\\d{1,3}){2})" + #"(?!192\\.168(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + # IP address dotted notation octets # excludes loopback network 0.0.0.0 # excludes reserved space >= PI:IP_ADDRESS:172.16.31.10END_PI # excludes network & broacast addresses # (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + # host name "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" + # domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" + # TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + ")" + "(?::\\d{2,5})?" + # resource path "(?:/[^\\s]*)?" + "$", "i" ) utils = randRange: ( lowVal, highVal )-> return Math.floor( Math.random()*(highVal-lowVal+1 ))+lowVal arrayRandom: ( array )-> idx = utils.randRange( 0, array.length-1 ) return array[ idx ] isUrl: (url)-> return regExUrl.test( url ) now: -> return Math.round( Date.now() / 1000 ) probability: ( val = 50 )-> return utils.randRange( 0,100 ) > val module.exports = utils
[ { "context": "ca 2\"]\n port: 1000 #port number\n user: \"dbUser\"\n pass: \"dbPass\"\n options:\n mong", "end": 471, "score": 0.9128919839859009, "start": 465, "tag": "USERNAME", "value": "dbUser" }, { "context": "00 #port number\n user: \"dbUser\"\n ...
src/core/initializers.database/index.coffee
classdojo/mongoose-builder
0
exports.plugin = () -> ### This is class abstracts away mongoose connections ### mongoose = require("mongoose") _ = require("underscore") class Connections ### databaseSettings: {Object} -> This should be a hash with the following structure: databaseTag1: name: "name of the database in the mongo cluster" host: ["primary host", "optional replica 1", "optional replica 2"] port: 1000 #port number user: "dbUser" pass: "dbPass" options: mongoNativeOption1: Value1 moreDocumentation: http://docs.mongodb.org/manual/reference/connection-string/ databaseTag2: ...... ### constructor: (databaseSettings) -> @_settings = databaseSettings @_connections = null @initialized = false ### Method: connect ### connect: (callback) => @_connections = {} for database, setting of @_settings.databases connString = @_constructConnectionString database, setting @_connections[database] = mongoose.createConnection connString @initialized = true callback null get: () => return @_connections _constructConnectionString: (database, settings) => connStrings = [] if settings.user? and settings.pass? authString = "#{settings.user}:#{settings.pass}@" else authString = "" if not _.isArray(settings.host) throw new Error("Host must be an array of strings") #construct options string optionsStr = "" if settings.options? for opt, val of settings.options optionsStr += "#{opt}=#{val}&" optionsStr = optionsStr.replace(/&$/, "") for host in settings.host s = "#{authString}#{host}:#{settings.port}/#{settings.name}" if optionsStr.length > 0 s += "?#{optionsStr}" #add connection options here! connStrings.push(s) return connStrings.join(",") Connections
126946
exports.plugin = () -> ### This is class abstracts away mongoose connections ### mongoose = require("mongoose") _ = require("underscore") class Connections ### databaseSettings: {Object} -> This should be a hash with the following structure: databaseTag1: name: "name of the database in the mongo cluster" host: ["primary host", "optional replica 1", "optional replica 2"] port: 1000 #port number user: "dbUser" pass: "<PASSWORD>" options: mongoNativeOption1: Value1 moreDocumentation: http://docs.mongodb.org/manual/reference/connection-string/ databaseTag2: ...... ### constructor: (databaseSettings) -> @_settings = databaseSettings @_connections = null @initialized = false ### Method: connect ### connect: (callback) => @_connections = {} for database, setting of @_settings.databases connString = @_constructConnectionString database, setting @_connections[database] = mongoose.createConnection connString @initialized = true callback null get: () => return @_connections _constructConnectionString: (database, settings) => connStrings = [] if settings.user? and settings.pass? authString = "#{settings.user}:#{settings.pass}@" else authString = "" if not _.isArray(settings.host) throw new Error("Host must be an array of strings") #construct options string optionsStr = "" if settings.options? for opt, val of settings.options optionsStr += "#{opt}=#{val}&" optionsStr = optionsStr.replace(/&$/, "") for host in settings.host s = "#{authString}#{host}:#{settings.port}/#{settings.name}" if optionsStr.length > 0 s += "?#{optionsStr}" #add connection options here! connStrings.push(s) return connStrings.join(",") Connections
true
exports.plugin = () -> ### This is class abstracts away mongoose connections ### mongoose = require("mongoose") _ = require("underscore") class Connections ### databaseSettings: {Object} -> This should be a hash with the following structure: databaseTag1: name: "name of the database in the mongo cluster" host: ["primary host", "optional replica 1", "optional replica 2"] port: 1000 #port number user: "dbUser" pass: "PI:PASSWORD:<PASSWORD>END_PI" options: mongoNativeOption1: Value1 moreDocumentation: http://docs.mongodb.org/manual/reference/connection-string/ databaseTag2: ...... ### constructor: (databaseSettings) -> @_settings = databaseSettings @_connections = null @initialized = false ### Method: connect ### connect: (callback) => @_connections = {} for database, setting of @_settings.databases connString = @_constructConnectionString database, setting @_connections[database] = mongoose.createConnection connString @initialized = true callback null get: () => return @_connections _constructConnectionString: (database, settings) => connStrings = [] if settings.user? and settings.pass? authString = "#{settings.user}:#{settings.pass}@" else authString = "" if not _.isArray(settings.host) throw new Error("Host must be an array of strings") #construct options string optionsStr = "" if settings.options? for opt, val of settings.options optionsStr += "#{opt}=#{val}&" optionsStr = optionsStr.replace(/&$/, "") for host in settings.host s = "#{authString}#{host}:#{settings.port}/#{settings.name}" if optionsStr.length > 0 s += "?#{optionsStr}" #add connection options here! connStrings.push(s) return connStrings.join(",") Connections
[ { "context": "0, 0, 1\n 1, 1, 0\n]\n\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: ", "end": 159, "score": 0.9998762607574463, "start": 156, "tag": "NAME", "value": "Max" }, { "context": " name: \"Max\"\n age: 11\n sister:\n ...
public/node_modules/coffee-register/benchmarks/samples/medium2.coffee
nandartika/bibe
1
song = ["do", "re", "mi", "fa", "so"] singers = {Jagger: "Rock", Elvis: "Roll"} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ] kids = brother: name: "Max" age: 11 sister: name: "Ida" age: 9 gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" "Roman Sebrle" "Guo Jingjing" "Tyson Gay" "Asafa Powell" "Usain Bolt" ] awardMedals contenders... a = "Gold: " + gold b = "Silver: " + silver c = "The Field: " + rest eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) module.exports = EventfulPromise eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) module.exports = EventfulPromise
11609
song = ["do", "re", "mi", "fa", "so"] singers = {Jagger: "Rock", Elvis: "Roll"} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ] kids = brother: name: "<NAME>" age: 11 sister: name: "<NAME>" age: 9 gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" ] awardMedals contenders... a = "Gold: " + gold b = "Silver: " + silver c = "The Field: " + rest eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) module.exports = EventfulPromise eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) module.exports = EventfulPromise
true
song = ["do", "re", "mi", "fa", "so"] singers = {Jagger: "Rock", Elvis: "Roll"} bitlist = [ 1, 0, 1 0, 0, 1 1, 1, 0 ] kids = brother: name: "PI:NAME:<NAME>END_PI" age: 11 sister: name: "PI:NAME:<NAME>END_PI" age: 9 gold = silver = rest = "unknown" awardMedals = (first, second, others...) -> gold = first silver = second rest = others contenders = [ "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ] awardMedals contenders... a = "Gold: " + gold b = "Silver: " + silver c = "The Field: " + rest eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) module.exports = EventfulPromise eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) eat = (args...)-> return args menu = (args...)-> return args # Eat lunch. eat food for food in ['toast', 'cheese', 'wine'] # Fine five course dining. courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'] menu i + 1, dish for dish, i in courses # Health conscious meal. foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' class EventfulPromise extends require('events') constructor: (task)-> super @init(task) init: (@task)-> @taskPromise = Promise.resolve(if typeof @task is 'function' then @task.call(@) else @task) return @ then: ()-> @taskPromise.then(arguments...) catch: ()-> @taskPromise.catch(arguments...) module.exports = EventfulPromise
[ { "context": "ards_data[0].user = new ObjectId(results[1]._id) #test@test.com' operator\n dashboards_data[1].user = n", "end": 2118, "score": 0.9988983273506165, "start": 2105, "tag": "EMAIL", "value": "test@test.com" }, { "context": "ards_data[1].user = new ObjectId(resul...
test/hooks.coffee
J-JRC/ureport-standalone
0
process.env.NODE_ENV = 'test' mongoose = require('mongoose') config = require('config') process.env.PORT = config.PORT Promise = require("bluebird") async = require("async") ObjectId = mongoose.Types.ObjectId; Setting = require('../src/models/setting') settings_data = require('./seed/settings') Assignment = require('../src/models/assignment') assignments_data = require('./seed/assignments') Build = require('../src/models/build') builds_data = require('./seed/builds') Dashboard = require('../src/models/dashboard') dashboards_data = require('./seed/dashboards') Test = require('../src/models/test') tests_data = require('./seed/tests') InvestigatedTest = require('../src/models/investigated_test') investigated_tests_data = require('./seed/investigated_tests') TestRelation = require('../src/models/test_relation') test_relation_data = require('./seed/test_relations') User = require('../src/models/user') user_data = require('./seed/users') Audit = require('../src/models/audit') #load models before (done) -> this.timeout(30000); console.log "Perform DB setup" if config != undefined mongoose = require('mongoose') mongoose.connect(config.DBHost, { useNewUrlParser: true }); mongoose.set('useFindAndModify', false); mongoose.set('useCreateIndex', true); Promise.all([ Build.create(builds_data), User.create(user_data), InvestigatedTest.create(investigated_tests_data), TestRelation.create(test_relation_data), Setting.create(settings_data), Assignment.create(assignments_data), ]).then( (values) -> async.filter(values[0].concat(values[1]), (item, callback) -> callback(null, (item.product && item.product == 'UpdateProduct' || item.username!=undefined)) (err,results) -> if(results) # set build id to test i = 0 while i < tests_data.length tests_data[i].build = new ObjectId(results[0]._id) i++ # set user to dashboard dashboards_data[0].user = new ObjectId(results[1]._id) #test@test.com' operator dashboards_data[1].user = new ObjectId(results[3]._id) #admin@test.com admin Promise.all([ Test.create(tests_data), Dashboard.create(dashboards_data) ]).then( -> console.log "===== Finish DB setup =====" done() ) ) ).catch((err) -> console.log(err.message); ); return after (done) -> console.log "Perform global DB clean up" Promise.all([ Setting.deleteMany({}).exec(), Setting.collection.dropIndexes(), User.deleteMany({}).exec(), User.collection.dropIndexes(), Build.deleteMany({}).exec(), Test.deleteMany({}).exec(), InvestigatedTest.deleteMany({}).exec() TestRelation.deleteMany().exec(), Assignment.deleteMany().exec(), Dashboard.deleteMany().exec(), Audit.deleteMany().exec() ]).then -> console.log "Finish DB cleanup" done() return
179247
process.env.NODE_ENV = 'test' mongoose = require('mongoose') config = require('config') process.env.PORT = config.PORT Promise = require("bluebird") async = require("async") ObjectId = mongoose.Types.ObjectId; Setting = require('../src/models/setting') settings_data = require('./seed/settings') Assignment = require('../src/models/assignment') assignments_data = require('./seed/assignments') Build = require('../src/models/build') builds_data = require('./seed/builds') Dashboard = require('../src/models/dashboard') dashboards_data = require('./seed/dashboards') Test = require('../src/models/test') tests_data = require('./seed/tests') InvestigatedTest = require('../src/models/investigated_test') investigated_tests_data = require('./seed/investigated_tests') TestRelation = require('../src/models/test_relation') test_relation_data = require('./seed/test_relations') User = require('../src/models/user') user_data = require('./seed/users') Audit = require('../src/models/audit') #load models before (done) -> this.timeout(30000); console.log "Perform DB setup" if config != undefined mongoose = require('mongoose') mongoose.connect(config.DBHost, { useNewUrlParser: true }); mongoose.set('useFindAndModify', false); mongoose.set('useCreateIndex', true); Promise.all([ Build.create(builds_data), User.create(user_data), InvestigatedTest.create(investigated_tests_data), TestRelation.create(test_relation_data), Setting.create(settings_data), Assignment.create(assignments_data), ]).then( (values) -> async.filter(values[0].concat(values[1]), (item, callback) -> callback(null, (item.product && item.product == 'UpdateProduct' || item.username!=undefined)) (err,results) -> if(results) # set build id to test i = 0 while i < tests_data.length tests_data[i].build = new ObjectId(results[0]._id) i++ # set user to dashboard dashboards_data[0].user = new ObjectId(results[1]._id) #<EMAIL>' operator dashboards_data[1].user = new ObjectId(results[3]._id) #<EMAIL> admin Promise.all([ Test.create(tests_data), Dashboard.create(dashboards_data) ]).then( -> console.log "===== Finish DB setup =====" done() ) ) ).catch((err) -> console.log(err.message); ); return after (done) -> console.log "Perform global DB clean up" Promise.all([ Setting.deleteMany({}).exec(), Setting.collection.dropIndexes(), User.deleteMany({}).exec(), User.collection.dropIndexes(), Build.deleteMany({}).exec(), Test.deleteMany({}).exec(), InvestigatedTest.deleteMany({}).exec() TestRelation.deleteMany().exec(), Assignment.deleteMany().exec(), Dashboard.deleteMany().exec(), Audit.deleteMany().exec() ]).then -> console.log "Finish DB cleanup" done() return
true
process.env.NODE_ENV = 'test' mongoose = require('mongoose') config = require('config') process.env.PORT = config.PORT Promise = require("bluebird") async = require("async") ObjectId = mongoose.Types.ObjectId; Setting = require('../src/models/setting') settings_data = require('./seed/settings') Assignment = require('../src/models/assignment') assignments_data = require('./seed/assignments') Build = require('../src/models/build') builds_data = require('./seed/builds') Dashboard = require('../src/models/dashboard') dashboards_data = require('./seed/dashboards') Test = require('../src/models/test') tests_data = require('./seed/tests') InvestigatedTest = require('../src/models/investigated_test') investigated_tests_data = require('./seed/investigated_tests') TestRelation = require('../src/models/test_relation') test_relation_data = require('./seed/test_relations') User = require('../src/models/user') user_data = require('./seed/users') Audit = require('../src/models/audit') #load models before (done) -> this.timeout(30000); console.log "Perform DB setup" if config != undefined mongoose = require('mongoose') mongoose.connect(config.DBHost, { useNewUrlParser: true }); mongoose.set('useFindAndModify', false); mongoose.set('useCreateIndex', true); Promise.all([ Build.create(builds_data), User.create(user_data), InvestigatedTest.create(investigated_tests_data), TestRelation.create(test_relation_data), Setting.create(settings_data), Assignment.create(assignments_data), ]).then( (values) -> async.filter(values[0].concat(values[1]), (item, callback) -> callback(null, (item.product && item.product == 'UpdateProduct' || item.username!=undefined)) (err,results) -> if(results) # set build id to test i = 0 while i < tests_data.length tests_data[i].build = new ObjectId(results[0]._id) i++ # set user to dashboard dashboards_data[0].user = new ObjectId(results[1]._id) #PI:EMAIL:<EMAIL>END_PI' operator dashboards_data[1].user = new ObjectId(results[3]._id) #PI:EMAIL:<EMAIL>END_PI admin Promise.all([ Test.create(tests_data), Dashboard.create(dashboards_data) ]).then( -> console.log "===== Finish DB setup =====" done() ) ) ).catch((err) -> console.log(err.message); ); return after (done) -> console.log "Perform global DB clean up" Promise.all([ Setting.deleteMany({}).exec(), Setting.collection.dropIndexes(), User.deleteMany({}).exec(), User.collection.dropIndexes(), Build.deleteMany({}).exec(), Test.deleteMany({}).exec(), InvestigatedTest.deleteMany({}).exec() TestRelation.deleteMany().exec(), Assignment.deleteMany().exec(), Dashboard.deleteMany().exec(), Audit.deleteMany().exec() ]).then -> console.log "Finish DB cleanup" done() return
[ { "context": "urn the name of the style', () ->\n name = 'Test'\n style = new ContentTools.Style(name, 'te", "end": 1994, "score": 0.9711862802505493, "start": 1990, "tag": "NAME", "value": "Test" } ]
src/spec/styles.coffee
robinlluu2002/ContentTools
0
# StylePalette describe 'ContentTools.StylePalette.add()', () -> it 'should return a `ContentTools.Style` instance', () -> style = new ContentTools.Style('test', 'test', ['test']) ContentTools.StylePalette.add(style) expect(ContentTools.StylePalette.styles('test')).toEqual [style] describe 'ContentTools.StylePalette.styles()', () -> it 'should return a list of `ContentTools.Style` instances by tag name', () -> # Add a set of styles for by different tags test1 = new ContentTools.Style('Test 1', 'test-1', ['p']) test2 = new ContentTools.Style('Test 2', 'test-2', ['h1', 'p']) test3 = new ContentTools.Style('Test 3', 'test-3', ['h1', 'h2']) ContentTools.StylePalette.add(test1) ContentTools.StylePalette.add(test2) ContentTools.StylePalette.add(test3) expect(ContentTools.StylePalette.styles('p')).toEqual [test1, test2] expect(ContentTools.StylePalette.styles('h1')).toEqual [test2, test3] expect(ContentTools.StylePalette.styles('h2')).toEqual [test3] # Styles describe 'ContentTools.Style()', () -> it 'should create `ContentTools.Style` instance', () -> style = new ContentTools.Style('Test', 'test', ['p']) expect(style instanceof ContentTools.Style).toBe true describe 'ContentTools.Style.applicableTo()', () -> it 'should return a list of tag names the style is applicable to', () -> tagNames = ['p', 'img', 'table'] style = new ContentTools.Style('Test', 'test', tagNames) expect(style.applicableTo()).toBe tagNames describe 'ContentTools.Style.cssClass()', () -> it 'should return the CSS class name for the style', () -> cssClassName = 'test' style = new ContentTools.Style('Test', cssClassName, 'p') expect(style.cssClass()).toBe cssClassName describe 'ContentTools.Style.name()', () -> it 'should return the name of the style', () -> name = 'Test' style = new ContentTools.Style(name, 'test', 'p') expect(style.name()).toBe name
57863
# StylePalette describe 'ContentTools.StylePalette.add()', () -> it 'should return a `ContentTools.Style` instance', () -> style = new ContentTools.Style('test', 'test', ['test']) ContentTools.StylePalette.add(style) expect(ContentTools.StylePalette.styles('test')).toEqual [style] describe 'ContentTools.StylePalette.styles()', () -> it 'should return a list of `ContentTools.Style` instances by tag name', () -> # Add a set of styles for by different tags test1 = new ContentTools.Style('Test 1', 'test-1', ['p']) test2 = new ContentTools.Style('Test 2', 'test-2', ['h1', 'p']) test3 = new ContentTools.Style('Test 3', 'test-3', ['h1', 'h2']) ContentTools.StylePalette.add(test1) ContentTools.StylePalette.add(test2) ContentTools.StylePalette.add(test3) expect(ContentTools.StylePalette.styles('p')).toEqual [test1, test2] expect(ContentTools.StylePalette.styles('h1')).toEqual [test2, test3] expect(ContentTools.StylePalette.styles('h2')).toEqual [test3] # Styles describe 'ContentTools.Style()', () -> it 'should create `ContentTools.Style` instance', () -> style = new ContentTools.Style('Test', 'test', ['p']) expect(style instanceof ContentTools.Style).toBe true describe 'ContentTools.Style.applicableTo()', () -> it 'should return a list of tag names the style is applicable to', () -> tagNames = ['p', 'img', 'table'] style = new ContentTools.Style('Test', 'test', tagNames) expect(style.applicableTo()).toBe tagNames describe 'ContentTools.Style.cssClass()', () -> it 'should return the CSS class name for the style', () -> cssClassName = 'test' style = new ContentTools.Style('Test', cssClassName, 'p') expect(style.cssClass()).toBe cssClassName describe 'ContentTools.Style.name()', () -> it 'should return the name of the style', () -> name = '<NAME>' style = new ContentTools.Style(name, 'test', 'p') expect(style.name()).toBe name
true
# StylePalette describe 'ContentTools.StylePalette.add()', () -> it 'should return a `ContentTools.Style` instance', () -> style = new ContentTools.Style('test', 'test', ['test']) ContentTools.StylePalette.add(style) expect(ContentTools.StylePalette.styles('test')).toEqual [style] describe 'ContentTools.StylePalette.styles()', () -> it 'should return a list of `ContentTools.Style` instances by tag name', () -> # Add a set of styles for by different tags test1 = new ContentTools.Style('Test 1', 'test-1', ['p']) test2 = new ContentTools.Style('Test 2', 'test-2', ['h1', 'p']) test3 = new ContentTools.Style('Test 3', 'test-3', ['h1', 'h2']) ContentTools.StylePalette.add(test1) ContentTools.StylePalette.add(test2) ContentTools.StylePalette.add(test3) expect(ContentTools.StylePalette.styles('p')).toEqual [test1, test2] expect(ContentTools.StylePalette.styles('h1')).toEqual [test2, test3] expect(ContentTools.StylePalette.styles('h2')).toEqual [test3] # Styles describe 'ContentTools.Style()', () -> it 'should create `ContentTools.Style` instance', () -> style = new ContentTools.Style('Test', 'test', ['p']) expect(style instanceof ContentTools.Style).toBe true describe 'ContentTools.Style.applicableTo()', () -> it 'should return a list of tag names the style is applicable to', () -> tagNames = ['p', 'img', 'table'] style = new ContentTools.Style('Test', 'test', tagNames) expect(style.applicableTo()).toBe tagNames describe 'ContentTools.Style.cssClass()', () -> it 'should return the CSS class name for the style', () -> cssClassName = 'test' style = new ContentTools.Style('Test', cssClassName, 'p') expect(style.cssClass()).toBe cssClassName describe 'ContentTools.Style.name()', () -> it 'should return the name of the style', () -> name = 'PI:NAME:<NAME>END_PI' style = new ContentTools.Style(name, 'test', 'p') expect(style.name()).toBe name