code
stringlengths 2
1.05M
|
|---|
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: { sourceType: 'module', ecmaVersion: 8 },
env: { browser: true, es6: true, },
extends: 'eslint:recommended',
plugins: [ 'html' ],
rules: {
yoda: 0,
curly: 0,
indent: [ "error", 2 ],
quotes: [ "error", "single" ],
semi: [ "error", "never" ],
'linebreak-style': [ "error", "unix" ],
'comma-dangle': 0,
'no-console': 2,
'space-before-function-paren': 0,
'no-multiple-empty-lines': 0,
'no-multi-spaces': 0,
'key-spacing': 0,
'operator-linebreak': 0,
'array-bracket-even-spacing': 0,
'brace-style': 0,
'arrow-parens': 0,
'generator-star-spacing': 0,
'no-ebugger': process.env.NODE_ENV === 'production' ? 2 : 0,
}
}
// TODO still doesn't work for .html files...
|
import mod211 from './mod211';
var value=mod211+1;
export default value;
|
SystemJS.config({
paths: {
"@ignavia/draph/": "src/"
},
devConfig: {
"map": {
"babel-plugin-transform-export-extensions": "npm:babel-plugin-transform-export-extensions@6.8.0",
"babel-preset-stage-0": "npm:babel-preset-stage-0@6.5.0",
"babel-regenerator-runtime": "npm:babel-regenerator-runtime@6.5.0",
"plugin-babel": "npm:systemjs-plugin-babel@0.0.8",
"systemjs-hot-reloader": "github:capaj/systemjs-hot-reloader@0.5.9"
},
"packages": {
"npm:babel-preset-stage-0@6.5.0": {
"map": {
"babel-plugin-transform-do-expressions": "npm:babel-plugin-transform-do-expressions@6.8.0",
"babel-plugin-transform-function-bind": "npm:babel-plugin-transform-function-bind@6.8.0",
"babel-preset-stage-1": "npm:babel-preset-stage-1@6.5.0"
}
},
"npm:babel-preset-stage-1@6.5.0": {
"map": {
"babel-plugin-transform-class-constructor-call": "npm:babel-plugin-transform-class-constructor-call@6.8.0",
"babel-plugin-transform-class-properties": "npm:babel-plugin-transform-class-properties@6.10.2",
"babel-plugin-transform-decorators": "npm:babel-plugin-transform-decorators@6.8.0",
"babel-plugin-transform-export-extensions": "npm:babel-plugin-transform-export-extensions@6.8.0",
"babel-preset-stage-2": "npm:babel-preset-stage-2@6.11.0"
}
},
"npm:chalk@1.1.3": {
"map": {
"ansi-styles": "npm:ansi-styles@2.2.1",
"escape-string-regexp": "npm:escape-string-regexp@1.0.5",
"has-ansi": "npm:has-ansi@2.0.0",
"strip-ansi": "npm:strip-ansi@3.0.1",
"supports-color": "npm:supports-color@2.0.0"
}
},
"npm:debug@2.2.0": {
"map": {
"ms": "npm:ms@0.7.1"
}
},
"npm:has-ansi@2.0.0": {
"map": {
"ansi-regex": "npm:ansi-regex@2.0.0"
}
},
"npm:invariant@2.2.1": {
"map": {
"loose-envify": "npm:loose-envify@1.2.0"
}
},
"npm:strip-ansi@3.0.1": {
"map": {
"ansi-regex": "npm:ansi-regex@2.0.0"
}
},
"npm:babel-plugin-transform-export-extensions@6.8.0": {
"map": {
"babel-plugin-syntax-export-extensions": "npm:babel-plugin-syntax-export-extensions@6.8.0",
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-syntax-export-extensions@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-transform-function-bind@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-plugin-syntax-function-bind": "npm:babel-plugin-syntax-function-bind@6.8.0"
}
},
"npm:babel-plugin-transform-do-expressions@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-plugin-syntax-do-expressions": "npm:babel-plugin-syntax-do-expressions@6.8.0"
}
},
"npm:babel-runtime@6.9.2": {
"map": {
"core-js": "npm:core-js@2.4.0",
"regenerator-runtime": "npm:regenerator-runtime@0.9.5"
}
},
"npm:babel-plugin-syntax-function-bind@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-transform-decorators@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1",
"babel-helper-define-map": "npm:babel-helper-define-map@6.9.0",
"babel-plugin-syntax-decorators": "npm:babel-plugin-syntax-decorators@6.8.0",
"babel-template": "npm:babel-template@6.9.0",
"babel-helper-explode-class": "npm:babel-helper-explode-class@6.8.0"
}
},
"npm:babel-plugin-transform-class-constructor-call@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-template": "npm:babel-template@6.9.0",
"babel-plugin-syntax-class-constructor-call": "npm:babel-plugin-syntax-class-constructor-call@6.8.0"
}
},
"npm:babel-plugin-syntax-do-expressions@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-syntax-class-properties@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-syntax-decorators@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-template@6.9.0": {
"map": {
"babel-types": "npm:babel-types@6.11.1",
"babel-runtime": "npm:babel-runtime@6.9.2",
"lodash": "npm:lodash@4.14.1",
"babel-traverse": "npm:babel-traverse@6.10.4",
"babylon": "npm:babylon@6.8.2"
}
},
"npm:babel-helper-explode-class@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1",
"babel-traverse": "npm:babel-traverse@6.10.4",
"babel-helper-bindify-decorators": "npm:babel-helper-bindify-decorators@6.8.0"
}
},
"npm:babel-plugin-syntax-class-constructor-call@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-helper-define-map@6.9.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"lodash": "npm:lodash@4.14.1",
"babel-types": "npm:babel-types@6.11.1",
"babel-helper-function-name": "npm:babel-helper-function-name@6.8.0"
}
},
"npm:babel-plugin-transform-object-rest-spread@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-plugin-syntax-object-rest-spread": "npm:babel-plugin-syntax-object-rest-spread@6.8.0"
}
},
"npm:babel-plugin-syntax-trailing-function-commas@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-syntax-object-rest-spread@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-helper-function-name@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1",
"babel-traverse": "npm:babel-traverse@6.10.4",
"babel-template": "npm:babel-template@6.9.0",
"babel-helper-get-function-arity": "npm:babel-helper-get-function-arity@6.8.0"
}
},
"npm:babel-plugin-transform-exponentiation-operator@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-plugin-syntax-exponentiation-operator": "npm:babel-plugin-syntax-exponentiation-operator@6.8.0",
"babel-helper-builder-binary-assignment-operator-visitor": "npm:babel-helper-builder-binary-assignment-operator-visitor@6.8.0"
}
},
"npm:babel-plugin-transform-async-to-generator@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-helper-remap-async-to-generator": "npm:babel-helper-remap-async-to-generator@6.11.2",
"babel-plugin-syntax-async-functions": "npm:babel-plugin-syntax-async-functions@6.8.0"
}
},
"npm:babel-helper-bindify-decorators@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-traverse": "npm:babel-traverse@6.10.4",
"babel-types": "npm:babel-types@6.11.1"
}
},
"npm:babel-messages@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-plugin-syntax-exponentiation-operator@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-helper-get-function-arity@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1"
}
},
"npm:babel-helper-builder-binary-assignment-operator-visitor@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1",
"babel-helper-explode-assignable-expression": "npm:babel-helper-explode-assignable-expression@6.8.0"
}
},
"npm:babel-plugin-syntax-async-functions@6.8.0": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-helper-explode-assignable-expression@6.8.0": {
"map": {
"babel-traverse": "npm:babel-traverse@6.10.4",
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1"
}
},
"npm:loose-envify@1.2.0": {
"map": {
"js-tokens": "npm:js-tokens@1.0.3"
}
},
"github:capaj/systemjs-hot-reloader@0.5.9": {
"map": {
"debug": "npm:debug@2.2.0",
"weakee": "npm:weakee@1.0.0",
"socket.io-client": "github:socketio/socket.io-client@1.4.8"
}
},
"npm:babel-plugin-transform-class-properties@6.10.2": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-plugin-syntax-class-properties": "npm:babel-plugin-syntax-class-properties@6.8.0"
}
},
"npm:babel-preset-stage-2@6.11.0": {
"map": {
"babel-plugin-transform-object-rest-spread": "npm:babel-plugin-transform-object-rest-spread@6.8.0",
"babel-preset-stage-3": "npm:babel-preset-stage-3@6.11.0"
}
},
"npm:babel-preset-stage-3@6.11.0": {
"map": {
"babel-plugin-transform-async-to-generator": "npm:babel-plugin-transform-async-to-generator@6.8.0",
"babel-plugin-syntax-trailing-function-commas": "npm:babel-plugin-syntax-trailing-function-commas@6.8.0",
"babel-plugin-transform-exponentiation-operator": "npm:babel-plugin-transform-exponentiation-operator@6.8.0"
}
},
"npm:babel-types@6.11.1": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2",
"lodash": "npm:lodash@4.14.1",
"babel-traverse": "npm:babel-traverse@6.10.4",
"to-fast-properties": "npm:to-fast-properties@1.0.2",
"esutils": "npm:esutils@2.0.2"
}
},
"npm:babel-traverse@6.10.4": {
"map": {
"lodash": "npm:lodash@4.14.1",
"babylon": "npm:babylon@6.8.2",
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1",
"babel-messages": "npm:babel-messages@6.8.0",
"debug": "npm:debug@2.2.0",
"globals": "npm:globals@8.18.0",
"invariant": "npm:invariant@2.2.1",
"babel-code-frame": "npm:babel-code-frame@6.11.0"
}
},
"npm:babylon@6.8.2": {
"map": {
"babel-runtime": "npm:babel-runtime@6.9.2"
}
},
"npm:babel-code-frame@6.11.0": {
"map": {
"esutils": "npm:esutils@2.0.2",
"babel-runtime": "npm:babel-runtime@6.9.2",
"js-tokens": "npm:js-tokens@2.0.0",
"chalk": "npm:chalk@1.1.3"
}
},
"npm:babel-helper-remap-async-to-generator@6.11.2": {
"map": {
"babel-template": "npm:babel-template@6.9.0",
"babel-traverse": "npm:babel-traverse@6.10.4",
"babel-helper-function-name": "npm:babel-helper-function-name@6.8.0",
"babel-runtime": "npm:babel-runtime@6.9.2",
"babel-types": "npm:babel-types@6.11.1"
}
}
}
},
transpiler: "plugin-babel",
trace: true,
packages: {
"@ignavia/draph": {
"main": "draph.js",
"format": "esm",
"defaultExtension": "js",
"meta": {
"*.js": {
"loader": "plugin-babel",
"babelOptions": {
"plugins": [
"babel-plugin-transform-export-extensions"
],
"presets": [
"babel-preset-stage-0"
]
}
}
}
}
}
});
SystemJS.config({
packageConfigPaths: [
"npm:@*/*.json",
"npm:*.json",
"github:*/*.json"
],
map: {
"constants": "github:jspm/nodelibs-constants@0.2.0-alpha",
"crypto": "github:jspm/nodelibs-crypto@0.2.0-alpha",
"lodash": "npm:lodash@4.14.1",
"@ignavia/util": "npm:@ignavia/util@2.0.0",
"@ignavia/earl": "npm:@ignavia/earl@1.5.0",
"@ignavia/ella": "npm:@ignavia/ella@2.0.0",
"assert": "github:jspm/nodelibs-assert@0.2.0-alpha",
"buffer": "github:jspm/nodelibs-buffer@0.2.0-alpha",
"child_process": "github:jspm/nodelibs-child_process@0.2.0-alpha",
"core-js": "npm:core-js@1.2.6",
"events": "github:jspm/nodelibs-events@0.2.0-alpha",
"fs": "github:jspm/nodelibs-fs@0.2.0-alpha",
"jquery": "npm:jquery@3.0.0",
"jquery-mousewheel": "npm:jquery-mousewheel@3.1.13",
"module": "github:jspm/nodelibs-module@0.2.0-alpha",
"net": "github:jspm/nodelibs-net@0.2.0-alpha",
"os": "github:jspm/nodelibs-os@0.2.0-alpha",
"path": "github:jspm/nodelibs-path@0.2.0-alpha",
"pixi.js": "npm:pixi.js@3.0.11",
"process": "github:jspm/nodelibs-process@0.2.0-alpha",
"punycode": "github:jspm/nodelibs-punycode@0.2.0-alpha",
"querystring": "github:jspm/nodelibs-querystring@0.2.0-alpha",
"source-map": "npm:source-map@0.1.43",
"stream": "github:jspm/nodelibs-stream@0.2.0-alpha",
"string_decoder": "github:jspm/nodelibs-string_decoder@0.2.0-alpha",
"tls": "github:jspm/nodelibs-tls@0.2.0-alpha",
"tty": "github:jspm/nodelibs-tty@0.2.0-alpha",
"url": "github:jspm/nodelibs-url@0.2.0-alpha",
"util": "github:jspm/nodelibs-util@0.2.0-alpha",
"vm": "github:jspm/nodelibs-vm@0.2.0-alpha",
"zlib": "github:jspm/nodelibs-zlib@0.2.0-alpha"
},
packages: {
"github:jspm/nodelibs-buffer@0.2.0-alpha": {
"map": {
"buffer-browserify": "npm:buffer@4.9.1"
}
},
"github:jspm/nodelibs-os@0.2.0-alpha": {
"map": {
"os-browserify": "npm:os-browserify@0.2.1"
}
},
"github:jspm/nodelibs-stream@0.2.0-alpha": {
"map": {
"stream-browserify": "npm:stream-browserify@2.0.1"
}
},
"github:jspm/nodelibs-url@0.2.0-alpha": {
"map": {
"url-browserify": "npm:url@0.11.0"
}
},
"npm:brfs@1.4.3": {
"map": {
"quote-stream": "npm:quote-stream@1.0.2",
"resolve": "npm:resolve@1.1.7",
"static-module": "npm:static-module@1.3.1",
"through2": "npm:through2@2.0.1"
}
},
"npm:browserify-versionify@1.0.6": {
"map": {
"find-root": "npm:find-root@0.1.2",
"through2": "npm:through2@0.6.3"
}
},
"npm:concat-stream@1.4.10": {
"map": {
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.14",
"typedarray": "npm:typedarray@0.0.6"
}
},
"npm:duplexer2@0.0.2": {
"map": {
"readable-stream": "npm:readable-stream@1.1.14"
}
},
"npm:escodegen@0.0.28": {
"map": {
"esprima": "npm:esprima@1.0.4",
"estraverse": "npm:estraverse@1.3.2"
}
},
"npm:escodegen@1.3.3": {
"map": {
"esprima": "npm:esprima@1.1.1",
"estraverse": "npm:estraverse@1.5.1",
"esutils": "npm:esutils@1.0.0"
}
},
"npm:falafel@1.2.0": {
"map": {
"acorn": "npm:acorn@1.2.2",
"foreach": "npm:foreach@2.0.5",
"isarray": "npm:isarray@0.0.1",
"object-keys": "npm:object-keys@1.0.11"
}
},
"npm:has@1.0.1": {
"map": {
"function-bind": "npm:function-bind@1.1.0"
}
},
"npm:pixi.js@3.0.11": {
"map": {
"async": "npm:async@1.5.2",
"brfs": "npm:brfs@1.4.3",
"browserify-versionify": "npm:browserify-versionify@1.0.6",
"earcut": "npm:earcut@2.1.1",
"eventemitter3": "npm:eventemitter3@1.2.0",
"object-assign": "npm:object-assign@4.1.0",
"resource-loader": "npm:resource-loader@1.7.0"
}
},
"npm:quote-stream@0.0.0": {
"map": {
"minimist": "npm:minimist@0.0.8",
"through2": "npm:through2@0.4.2"
}
},
"npm:quote-stream@1.0.2": {
"map": {
"buffer-equal": "npm:buffer-equal@0.0.1",
"minimist": "npm:minimist@1.2.0",
"through2": "npm:through2@2.0.1"
}
},
"npm:readable-stream@1.0.34": {
"map": {
"core-util-is": "npm:core-util-is@1.0.2",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
}
},
"npm:readable-stream@1.1.14": {
"map": {
"core-util-is": "npm:core-util-is@1.0.2",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
}
},
"npm:readable-stream@2.0.6": {
"map": {
"core-util-is": "npm:core-util-is@1.0.2",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@1.0.0",
"process-nextick-args": "npm:process-nextick-args@1.0.7",
"string_decoder": "npm:string_decoder@0.10.31",
"util-deprecate": "npm:util-deprecate@1.0.2"
}
},
"npm:source-map@0.1.43": {
"map": {
"amdefine": "npm:amdefine@1.0.0"
}
},
"npm:static-eval@0.2.4": {
"map": {
"escodegen": "npm:escodegen@0.0.28"
}
},
"npm:static-module@1.3.1": {
"map": {
"concat-stream": "npm:concat-stream@1.4.10",
"duplexer2": "npm:duplexer2@0.0.2",
"escodegen": "npm:escodegen@1.3.3",
"falafel": "npm:falafel@1.2.0",
"has": "npm:has@1.0.1",
"object-inspect": "npm:object-inspect@0.4.0",
"quote-stream": "npm:quote-stream@0.0.0",
"readable-stream": "npm:readable-stream@1.0.34",
"shallow-copy": "npm:shallow-copy@0.0.1",
"static-eval": "npm:static-eval@0.2.4",
"through2": "npm:through2@0.4.2"
}
},
"npm:stream-browserify@1.0.0": {
"map": {
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.14"
}
},
"npm:stream-browserify@2.0.1": {
"map": {
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@2.1.5"
}
},
"npm:through2@0.4.2": {
"map": {
"readable-stream": "npm:readable-stream@1.0.34",
"xtend": "npm:xtend@2.1.2"
}
},
"npm:through2@0.6.3": {
"map": {
"readable-stream": "npm:readable-stream@1.0.34",
"xtend": "npm:xtend@4.0.1"
}
},
"npm:through2@2.0.1": {
"map": {
"readable-stream": "npm:readable-stream@2.0.6",
"xtend": "npm:xtend@4.0.1"
}
},
"npm:url@0.11.0": {
"map": {
"punycode": "npm:punycode@1.3.2",
"querystring": "npm:querystring@0.2.0"
}
},
"npm:xtend@2.1.2": {
"map": {
"object-keys": "npm:object-keys@0.4.0"
}
},
"npm:readable-stream@2.1.4": {
"map": {
"inherits": "npm:inherits@2.0.1",
"process-nextick-args": "npm:process-nextick-args@1.0.7",
"util-deprecate": "npm:util-deprecate@1.0.2",
"core-util-is": "npm:core-util-is@1.0.2",
"isarray": "npm:isarray@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31",
"buffer-shims": "npm:buffer-shims@1.0.0"
}
},
"github:jspm/nodelibs-zlib@0.2.0-alpha": {
"map": {
"zlib-browserify": "npm:browserify-zlib@0.1.4"
}
},
"npm:browserify-zlib@0.1.4": {
"map": {
"readable-stream": "npm:readable-stream@2.1.4",
"pako": "npm:pako@0.2.9"
}
},
"github:jspm/nodelibs-crypto@0.2.0-alpha": {
"map": {
"crypto-browserify": "npm:crypto-browserify@3.11.0"
}
},
"npm:crypto-browserify@3.11.0": {
"map": {
"inherits": "npm:inherits@2.0.1",
"browserify-sign": "npm:browserify-sign@4.0.0",
"browserify-cipher": "npm:browserify-cipher@1.0.0",
"create-hash": "npm:create-hash@1.1.2",
"diffie-hellman": "npm:diffie-hellman@5.0.2",
"pbkdf2": "npm:pbkdf2@3.0.4",
"create-hmac": "npm:create-hmac@1.1.4",
"public-encrypt": "npm:public-encrypt@4.0.0",
"create-ecdh": "npm:create-ecdh@4.0.0",
"randombytes": "npm:randombytes@2.0.3"
}
},
"npm:browserify-sign@4.0.0": {
"map": {
"inherits": "npm:inherits@2.0.1",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"browserify-rsa": "npm:browserify-rsa@4.0.1",
"bn.js": "npm:bn.js@4.11.6",
"parse-asn1": "npm:parse-asn1@5.0.0",
"elliptic": "npm:elliptic@6.3.1"
}
},
"npm:create-hash@1.1.2": {
"map": {
"inherits": "npm:inherits@2.0.1",
"sha.js": "npm:sha.js@2.4.5",
"cipher-base": "npm:cipher-base@1.0.2",
"ripemd160": "npm:ripemd160@1.0.1"
}
},
"npm:pbkdf2@3.0.4": {
"map": {
"create-hmac": "npm:create-hmac@1.1.4"
}
},
"npm:create-hmac@1.1.4": {
"map": {
"inherits": "npm:inherits@2.0.1",
"create-hash": "npm:create-hash@1.1.2"
}
},
"npm:public-encrypt@4.0.0": {
"map": {
"create-hash": "npm:create-hash@1.1.2",
"browserify-rsa": "npm:browserify-rsa@4.0.1",
"bn.js": "npm:bn.js@4.11.6",
"parse-asn1": "npm:parse-asn1@5.0.0",
"randombytes": "npm:randombytes@2.0.3"
}
},
"npm:diffie-hellman@5.0.2": {
"map": {
"bn.js": "npm:bn.js@4.11.6",
"miller-rabin": "npm:miller-rabin@4.0.0",
"randombytes": "npm:randombytes@2.0.3"
}
},
"npm:browserify-cipher@1.0.0": {
"map": {
"browserify-des": "npm:browserify-des@1.0.0",
"browserify-aes": "npm:browserify-aes@1.0.6",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0"
}
},
"npm:browserify-rsa@4.0.1": {
"map": {
"bn.js": "npm:bn.js@4.11.6",
"randombytes": "npm:randombytes@2.0.3"
}
},
"npm:parse-asn1@5.0.0": {
"map": {
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"browserify-aes": "npm:browserify-aes@1.0.6",
"create-hash": "npm:create-hash@1.1.2",
"pbkdf2": "npm:pbkdf2@3.0.4",
"asn1.js": "npm:asn1.js@4.8.0"
}
},
"npm:browserify-des@1.0.0": {
"map": {
"inherits": "npm:inherits@2.0.1",
"cipher-base": "npm:cipher-base@1.0.2",
"des.js": "npm:des.js@1.0.0"
}
},
"npm:browserify-aes@1.0.6": {
"map": {
"inherits": "npm:inherits@2.0.1",
"cipher-base": "npm:cipher-base@1.0.2",
"create-hash": "npm:create-hash@1.1.2",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"buffer-xor": "npm:buffer-xor@1.0.3"
}
},
"npm:cipher-base@1.0.2": {
"map": {
"inherits": "npm:inherits@2.0.1"
}
},
"npm:sha.js@2.4.5": {
"map": {
"inherits": "npm:inherits@2.0.1"
}
},
"npm:miller-rabin@4.0.0": {
"map": {
"bn.js": "npm:bn.js@4.11.6",
"brorand": "npm:brorand@1.0.5"
}
},
"npm:evp_bytestokey@1.0.0": {
"map": {
"create-hash": "npm:create-hash@1.1.2"
}
},
"npm:create-ecdh@4.0.0": {
"map": {
"bn.js": "npm:bn.js@4.11.6",
"elliptic": "npm:elliptic@6.3.1"
}
},
"npm:des.js@1.0.0": {
"map": {
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
}
},
"npm:hash.js@1.0.3": {
"map": {
"inherits": "npm:inherits@2.0.1"
}
},
"github:jspm/nodelibs-string_decoder@0.2.0-alpha": {
"map": {
"string_decoder-browserify": "npm:string_decoder@0.10.31"
}
},
"npm:elliptic@6.3.1": {
"map": {
"inherits": "npm:inherits@2.0.1",
"bn.js": "npm:bn.js@4.11.6",
"brorand": "npm:brorand@1.0.5",
"hash.js": "npm:hash.js@1.0.3"
}
},
"npm:@ignavia/util@2.0.0": {
"map": {
"lodash": "npm:lodash@4.14.1"
}
},
"npm:@ignavia/earl@1.5.0": {
"map": {
"@ignavia/util": "npm:@ignavia/util@2.0.0",
"lodash": "npm:lodash@4.14.1",
"@ignavia/ella": "npm:@ignavia/ella@1.2.0"
}
},
"npm:resource-loader@1.7.0": {
"map": {
"async": "npm:async@2.0.1",
"eventemitter3": "npm:eventemitter3@1.2.0"
}
},
"npm:async@2.0.1": {
"map": {
"lodash": "npm:lodash@4.14.1"
}
},
"github:jspm/nodelibs-punycode@0.2.0-alpha": {
"map": {
"punycode-browserify": "npm:punycode@1.4.1"
}
},
"npm:asn1.js@4.8.0": {
"map": {
"bn.js": "npm:bn.js@4.11.6",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
}
},
"npm:buffer@4.9.1": {
"map": {
"base64-js": "npm:base64-js@1.1.2",
"isarray": "npm:isarray@1.0.0",
"ieee754": "npm:ieee754@1.1.6"
}
},
"npm:readable-stream@2.1.5": {
"map": {
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31",
"buffer-shims": "npm:buffer-shims@1.0.0",
"util-deprecate": "npm:util-deprecate@1.0.2",
"core-util-is": "npm:core-util-is@1.0.2",
"process-nextick-args": "npm:process-nextick-args@1.0.7"
}
}
}
});
|
'use strict'
let cli = require('heroku-cli-util')
let co = require('co')
function styledDrain (id, name, drain) {
let output = `${id} (${name})`
if (drain.extended) output = output + ` drain_id=${drain.extended.drain_id}`
cli.log(output)
}
function * run (context, heroku) {
const {partition} = require('lodash')
let path = `/apps/${context.app}/log-drains`
if (context.flags.extended) path = path + '?extended=true'
let drains = yield heroku.request({path})
if (context.flags.json) {
cli.styledJSON(drains)
} else {
drains = partition(drains, 'addon')
if (drains[1].length > 0) {
cli.styledHeader('Drains')
drains[1].forEach((drain) => {
styledDrain(drain.url, cli.color.green(drain.token), drain)
})
}
if (drains[0].length > 0) {
let addons = yield drains[0].map((d) => heroku.get(`/apps/${context.app}/addons/${d.addon.name}`))
cli.styledHeader('Add-on Drains')
addons.forEach((addon, i) => {
styledDrain(cli.color.yellow(addon.plan.name), cli.color.green(addon.name), drains[0][i])
})
}
}
}
module.exports = {
topic: 'drains',
description: 'display the log drains of an app',
needsApp: true,
needsAuth: true,
flags: [
{name: 'json', description: 'output in json format'},
{name: 'extended', char: 'x', hidden: true}
],
run: cli.command(co.wrap(run))
}
|
var mod = require('./index');
mod({
foo: 'other'
});
|
function(head, req) {
var ddoc = this,
path = require("vendor/couchapp/lib/path").init(req);
send('{"dateTimeFormat": "iso8601", "events": [');
var sep = "";
while(row = getRow()) {
var doc = row.doc;
var coordinates = null;
if (doc.Latitude && doc.Longitude) {
coordinates = [parseFloat(doc.Longitude), parseFloat(doc.Latitude)];
var date_parts = doc.Date.split(" ");
var summary = '';
if (doc.Summary && doc.Summary.length <= 350) {
summary = doc.Summary;
} else {
summary = (doc.Summary.replace(/<(.|\n)*?>/g, '').substring(0,350) + '...');
}
var event = {
start: date_parts[0] + "T" + date_parts[1],
title: doc.Type,
description: summary,
link: path.show("report", doc._id),
coordinates: coordinates,
id: doc._id,
long_title: doc.Title,
affiliation: doc.Affiliation,
category: doc.Category
}
send(sep + toJSON(event));
sep = ",";
}
}
return(']}');
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:7b178c98098ef61e6ebfdc8b32169fd3dbcd6e75bf391a88fffde51be43dec8a
size 129934
|
$(function() {
var canvas = $("#canvas0").get(0);
if (!canvas || !canvas.getContext || !canvas.getContext("2d"))
alert("You must use a browser that supports HTML5 Canvas to run this demo.");
function start() {
var marioRef = new Firebase("https://drvirus.firebaseio.com/mario");
var marioController = new Mario.Controller(marioRef);
}
var Mario = { };
/**
* Various constants related to board size / drawing.
*/
Mario.BOARD_WIDTH = 8; // (in "blocks", not pixels)
Mario.BOARD_HEIGHT = 16;
Mario.BLOCK_SIZE_PIXELS = 25;
Mario.BOARD_HEIGHT_PIXELS = Mario.BOARD_HEIGHT * Mario.BLOCK_SIZE_PIXELS;
Mario.BOARD_WIDTH_PIXELS = Mario.BOARD_WIDTH * Mario.BLOCK_SIZE_PIXELS;
Mario.BLOCK_RADIUS_PIXELS = 5;
Mario.BLOCK_BORDER_COLOR = "#484848";
Mario.BLOCK_COLORS = { "r": "#f44336", "y": "#ffeb3b", "b": "#2196f3",
"R": "#d50000", "Y": "#ffd600", "B": "#2962ff" };
Mario.EMPTY_COL = Array(Mario.BOARD_HEIGHT + 1).join(" "); //" ";
Mario.EMPTY_LINE = Array(Mario.BOARD_WIDTH + 1).join(" "); //" ";
Mario.FILLED_LINE = Array(Mario.BOARD_WIDTH + 1).join("X"); //"XXXXXXXX";
Mario.COMPLETE_SET_PATTERN = /[yY]{4,}|[rR]{4,}|[bB]{4,}/; // Match 4 or more blocks
// Pills. (Indexed by piece rotation (0-3), row (0-1), piece number (0-5))
Mario.PILLS = [];
for (var i = 0; i < 4; i++) { Mario.PILLS[i] = []; }
Mario.PILLS[0][0] = [ " ", " ", " ", " ", " ", " " ];
Mario.PILLS[0][1] = [ "bb", "br", "rr", "yr", "yy", "yb" ];
Mario.PILLS[1][0] = [ "b ", "r ", "r ", "r ", "y ", "b " ];
Mario.PILLS[1][1] = [ "b ", "b ", "r ", "y ", "y ", "y " ];
Mario.PILLS[2][0] = [ "bb", " ", " ", " ", " ", " " ];
Mario.PILLS[2][1] = [ " ", "rb", "rr", "ry", "yy", "by" ];
Mario.PILLS[3][0] = [ " b", " b", " r", " y", " y", " y" ];
Mario.PILLS[3][1] = [ " b", " r", " r", " r", " y", " b" ];
// Virus. Stores designation for colored virus' to place on board.
Mario.VIRUS = ["R", "Y", "B"];
Mario.DEFAULT_DIFFICULTY = 1; // 4 Viruses
Mario.GRAVITY_DELAY = 900; // 300ms TODO Link difficulty to speed (ln 641)
/**
* Stores the state of a mario board and handles drawing it.
*/
Mario.Board = function (canvas, playerRef) {
this.context = canvas.getContext("2d");
this.playerRef = playerRef;
this.snapshot = null;
this.isMyBoard = false;
this.virus = null;
// Listen for changes to our board.
var self = this;
playerRef.on("value", function(snapshot) {
self.snapshot = snapshot;
self.draw();
});
};
/**
* Draws the contents of the board as well as the current piece.
*/
Mario.Board.prototype.draw = function () {
// Clear canvas.
this.context.clearRect(0, 0, Mario.BOARD_WIDTH_PIXELS, Mario.BOARD_HEIGHT_PIXELS);
// Iterate over columns / rows in board data and draw each non-empty block.
for (var x = 0; x < Mario.BOARD_WIDTH; x++) {
for (var y = 0; y < Mario.BOARD_HEIGHT; y++) {
var colorValue = this.getBlockVal(x, y);
if (colorValue != " ") {
if (Mario.VIRUS.indexOf(colorValue) > -1) {
this.drawVirus(x, y, colorValue);
} else {
this.drawBlock(x, y, colorValue);
}
}
}
}
// If there's a falling piece, draw it.
if (this.snapshot !== null && this.snapshot.hasChild("piece")) {
var piece = Mario.Piece.fromSnapshot(this.snapshot.child("piece"));
this.drawPiece(piece);
}
// If this isn't my board, dim it out with a 25% opacity black rectangle.
if (!this.isMyBoard) {
this.context.fillStyle = "rgba(0, 0, 0, 0.25)";
this.context.fillRect(0, 0, Mario.BOARD_WIDTH_PIXELS, Mario.BOARD_HEIGHT_PIXELS);
}
};
/**
* Draw the currently falling piece.
*/
Mario.Board.prototype.drawPiece = function (piece) {
var self = this;
this.forEachBlockOfPiece(piece,
function (x, y, colorValue) {
var left = x * Mario.BLOCK_SIZE_PIXELS;
var top = y * Mario.BLOCK_SIZE_PIXELS;
self.context.fillStyle = Mario.BLOCK_COLORS[colorValue];
self.context.fillRect(left, top, Mario.BLOCK_SIZE_PIXELS, Mario.BLOCK_SIZE_PIXELS);
self.context.lineWidth = 1;
self.context.strokeStyle = Mario.BLOCK_BORDER_COLOR;
self.context.strokeRect(left, top, Mario.BLOCK_SIZE_PIXELS, Mario.BLOCK_SIZE_PIXELS);
});
};
/**
* Draw standard blocks
*/
Mario.Board.prototype.drawBlock = function (x, y, colorValue) {
var self = this;
var left = x * Mario.BLOCK_SIZE_PIXELS;
var top = y * Mario.BLOCK_SIZE_PIXELS;
var radius = Mario.BLOCK_RADIUS_PIXELS;
var side = Mario.BLOCK_SIZE_PIXELS - 2 * radius;
var right = left + Mario.BLOCK_SIZE_PIXELS;
var bottom = top + Mario.BLOCK_SIZE_PIXELS;
/*
self.context.beginPath();
self.moveTo(left + radius, top);
self.lineTo(left + side, top);
self.arcTo(left + side, top, right, top + radius, radius);
self.lineTo(right, top + side);
self.arcTo(right, top + side, right - radius, bottom, radius);
self.lineTo(left + radius, bottom);
self.arcTo(left + radius, bottom, left, top + side, radius);
self.lineTo(left, top + radius);
self.arcTo(left, top + radius, left + radius, top, radius);
*/
self.context.fillStyle = Mario.BLOCK_COLORS[colorValue];
self.context.fillRect(left, top, Mario.BLOCK_SIZE_PIXELS, Mario.BLOCK_SIZE_PIXELS);
self.context.lineWidth = 1;
self.context.strokeStyle = Mario.BLOCK_BORDER_COLOR;
self.context.strokeRect(left, top, Mario.BLOCK_SIZE_PIXELS, Mario.BLOCK_SIZE_PIXELS);
};
/*
* Draw virus blocks
*/
Mario.Board.prototype.drawVirus = function (x, y, colorValue) {
var self = this;
var self = this;
var centerX = (x + 0.5) * Mario.BLOCK_SIZE_PIXELS;
var centerY = (y + 0.5) * Mario.BLOCK_SIZE_PIXELS;
var radius = Mario.BLOCK_SIZE_PIXELS / 2;
self.context.beginPath();
self.context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
self.context.fillStyle = Mario.BLOCK_COLORS[colorValue];
self.context.fill();
self.context.lineWidth = 1;
self.context.strokeStyle = Mario.BLOCK_BORDER_COLOR;
self.context.stroke();
};
/**
* Clear the board contents.
*/
Mario.Board.prototype.clear = function () {
for (var row = 0; row < Mario.BOARD_HEIGHT; row++) {
this.setRow(row, Mario.EMPTY_LINE);
}
};
/**
* Given a Mario.Piece, returns true if it has collided with the board (i.e. its current position
* and rotation causes it to overlap blocks already on the board).
*/
Mario.Board.prototype.checkForPieceCollision = function (piece) {
var collision = false;
var self = this;
this.forEachBlockOfPiece(piece,
function (x, y, colorValue) {
// NOTE: we explicitly allow y < 0 since pieces can be partially visible.
if (x < 0 || x >= Mario.BOARD_WIDTH || y >= Mario.BOARD_HEIGHT) {
collision = true;
}
else if (y >= 0 && self.getBlockVal(x, y) != " ") {
collision = true; // collision with board contents.
}
}, /*includeInvalid=*/ true);
return collision;
};
/**
* Given a Mario.Piece that has landed, add it to the board contents.
*/
Mario.Board.prototype.addLandedPiece = function (piece) {
var self = this;
// We go out of our way to set an entire row at a time just so the rows show up as
// child_added in the graphical debugger, rather than child_changed.
var rowY = -1, rowContents = null;
this.forEachBlockOfPiece(piece,
function (x, y, val) {
if (y != rowY) {
if (rowY !== -1)
self.setRow(rowY, rowContents);
rowContents = self.getRow(y);
rowY = y;
}
rowContents = rowContents.substring(0, x).concat(val).concat(rowContents.substring(x + 1, Mario.BOARD_WIDTH));
});
if (rowY !== -1)
self.setRow(rowY, rowContents);
};
/**
* Given a Mario.Virus, add it to the board contents.
*/
Mario.Board.prototype.addVirus = function (virus) {
//var self = this;
var y = virus.y, x = virus.x, rowContents = null;
rowContents = this.getRow(y);
rowContents = rowContents.substring(0, x).concat(Mario.VIRUS[virus.virusNum]).concat(rowContents.substring(x + 1, Mario.BOARD_WIDTH));
this.virus += 1;
this.setRow(y, rowContents);
};
/**
* Check for any completed sets of 4 same colored blocks in a row or column,
* and removes the matches.
*/
Mario.Board.prototype.removeCompletedPillsHoriz = function () {
// Start at the bottom of the board, work up looking for 4 consecutive blocks
// of the same color in a row.
var row = Mario.BOARD_HEIGHT - 1;
var matches = 0;
while (row >= 0) {
var rowContents = this.getRow(row);
// See if the line is complete (if not, we'll skip it)
var match = rowContents.match(Mario.COMPLETE_SET_PATTERN);
if (match != null) {
var replaceContents = Array(match[0].length + 1).join(" ");
rowContents = rowContents.replace(Mario.COMPLETE_SET_PATTERN, replaceContents);
matches++;
this.setRow(row, rowContents);
}
row--;
}
return matches;
};
/**
* Check for any completed sets of 4 same colored blocks in a row or column,
* and removes the matches.
*/
Mario.Board.prototype.removeCompletedPillsVert = function () {
// Start at the bottom of the board, work up looking for 4 consecutive blocks
// of the same color in a row.
var col = Mario.BOARD_WIDTH - 1;
var matches = 0;
// Iterate over columns, remove matches from each
while (col >= 0) {
var colContents = this.getCol(col);
var match = colContents.match(Mario.COMPLETE_SET_PATTERN);
if (match != null) {
replaceContents = Array(match[0].length + 1).join(" ");
colContents = colContents.replace(Mario.COMPLETE_SET_PATTERN, replaceContents);
matches++;
this.setCol(col, colContents);
}
col--;
}
return matches;
};
/**
* Check for non-Virus pieces that are floating and drop them to the next
* piece on the board.
*/
/*
Mario.Board.prototype.shiftDown = function () {
// Check each piece for island status
// islands = this.getIslands();
// if (islands != null) {
// for (var i = 0; i < islands.length; i++) {
// dropIsland(islands[i]);
// }
// }
};
*/
/*
Mario.Board.prototype.isSupported = function (x, y) {
var below = this.getBlockVal(x, y + 1);
if (below === " ") {
// Not supported below
return false;
} else if (this.isVirus(below)) {
// Supported
return true;
} else {
return this.isSupported(x, y + 1);
};
Mario.Board.prototype.isVirus = function (value) {
return Mario.VIRUS.indexOf(value) > -1;
};
*/
/**
* Generate the specified number of junk rows at the bottom of the board. Return true if the added
* rows overflowed the board (in which case the player loses).
*/
Mario.Board.prototype.addJunkRows = function (numRows) {
var overflow = false;
// First, check if any blocks are going to overflow off the top of the screen.
var topRowContents = this.getRow(numRows - 1);
overflow = topRowContents.match(/[^ ]/);
// Shift rows up to make room for the new rows.
for (var i = 0; i < Mario.BOARD_HEIGHT - numRows; i++) {
var moveLineContents = this.getRow(i + numRows);
this.setRow(i, moveLineContents);
}
// Fill the bottom with junk rows that are full except for a single random gap.
var gap = Math.floor(Math.random() * Mario.FILLED_LINE.length);
var junkRow = Mario.FILLED_LINE.substring(0, gap) + " " + Mario.FILLED_LINE.substring(gap + 1);
for (i = Mario.BOARD_HEIGLP200XHT - numRows; i < Mario.BOARD_HEIGHT; i++) {
this.setRow(i, junkRow);
}
return overflow;
};
/**
* Helper to enumerate the blocks that make up a particular piece. Calls fn() for each block,
* passing the x and y position of the block and the color value. If includeInvalid is true, it
* includes blocks that would fall outside the bounds of the board.
*/
Mario.Board.prototype.forEachBlockOfPiece = function (piece, fn, includeInvalid) {
for (var blockY = 0; blockY < 2; blockY++) {
for (var blockX = 0; blockX < 2; blockX++) {
var colorValue = Mario.PILLS[piece.rotation][blockY][piece.pieceNum].charAt(blockX);
if (colorValue != " ") {
var x = piece.x + blockX, y = piece.y + blockY;
if (includeInvalid || (x >= 0 && x < Mario.BOARD_WIDTH && y >= 0 && y < Mario.BOARD_HEIGHT)) {
fn(x, y, colorValue);
}
}
}
}
};
Mario.Board.prototype.updateVirusCount = function () {
this.virus = this.getVirusCount();
this.playerRef.child("virus").set(this.virus);
if (this.virus === 0) {
this.playerRef.child("win").set(1);
}
}
Mario.Board.prototype.getVirusCount = function () {
var count = 0;
var re = new RegExp("[" + Mario.VIRUS.join("") + "]", "g");
for (var row = 0; row < Mario.BOARD_HEIGHT; row++) {
rowContents = this.getRow(row);
match = rowContents.match(re);
if (match)
count += match.length
}
return count;
};
Mario.Board.prototype.getRow = function (y) {
var row = (y < 10) ? ("0" + y) : ("" + y); // Pad row so they sort nicely in debugger. :-)
var rowContents = this.snapshot === null ? null : this.snapshot.child("board/" + row).val();
return rowContents || Mario.EMPTY_LINE;
};
Mario.Board.prototype.getCol = function (x) {
var col = (x < 10) ? ("0" + x) : ("" + x); // Pad col so they sort nicely in debugger. :-)
colContents = ''; // Column contents from top to bottom
for (var rowY = 0; rowY < Mario.BOARD_HEIGHT; rowY++) {
colContents += this.getRow(rowY).charAt(x);
}
return colContents || Mario.EMPTY_COL;
};
Mario.Board.prototype.getBlockVal = function (x, y) {
return this.getRow(y).charAt(x);
};
Mario.Board.prototype.setRow = function (y, rowContents) {
var row = (y < 10) ? ("0" + y) : ("" + y); // Pad row so they sort nicely in debugger. :-)
if (rowContents === Mario.EMPTY_LINE)
rowContents = null; // delete empty lines so we get remove / added events in debugger. :-)
this.playerRef.child("board").child(row).set(rowContents);
};
Mario.Board.prototype.setCol = function (x, colContents) {
var col = (x < 10) ? ("0" + x): ("" + x); // Pad col for debugger
var curRow = "";
var newRow = "";
var val = null;
// Loop over rows and set correct item in each row
for (var row = 0; row < Mario.BOARD_HEIGHT; row++) {
curRow = this.getRow(row);
val = colContents.charAt(row);
if (curRow.charAt(x) != val) {
newRow = curRow.substring(0, x).concat(val).concat(curRow.substring(x + 1, Mario.BOARD_WIDTH));
this.setRow(row, newRow);
}
}
};
Mario.Board.prototype.setBlockVal = function (x, y, val) {
var rowContents = this.getRow(y);
rowContents = rowContents.substring(0, x) + val + rowContents.substring(x+1);
this.setRow(y, rowContents);
};
/**
* Immutable object representing a falling piece along with its rotation and board position.
* Has helpers for generating mutated Mario.Piece objects (e.g. rotated or dropped).
*/
Mario.Piece = function (pieceNum, x, y, rotation) {
if (arguments.length > 0) {
this.pieceNum = pieceNum;
this.x = x;
this.y = y;
this.rotation = rotation;
} else {
// Initialize new random piece.
this.pieceNum = Math.floor(Math.random() * 6);
this.x = 3; // "center" it.
this.y = -1; // this will make the bottom line of the piece visible.
this.rotation = 0;
}
};
Mario.Virus = function (virusNum, x, y) {
if (arguments.length > 0) {
this.virusNum = virusNum;
this.x = x;
this.y = y;
} else {
// Initialize new random virus.
this.virusNum = Math.floor(Math.random() * 3);
this.x = Math.floor(Math.random() * Mario.BOARD_WIDTH);
this.y = Math.floor(Math.random() * (Mario.BOARD_HEIGHT - 3)) + 3;
}
};
/**
* Create a piece from a Firebase snapshot representing a piece.
*/
Mario.Piece.fromSnapshot = function (snapshot) {
var piece = snapshot.val();
return new Mario.Piece(piece.pieceNum, piece.x, piece.y, piece.rotation);
};
/**
* Writes the current piece data into Firebase.
*/
Mario.Piece.prototype.writeToFirebase = function (pieceRef) {
pieceRef.set({pieceNum: this.pieceNum, x: this.x, y: this.y, rotation: this.rotation});
};
Mario.Piece.prototype.drop = function () {
return new Mario.Piece(this.pieceNum, this.x, this.y + 1, this.rotation);
};
Mario.Piece.prototype.rotate = function (direction) {
return new Mario.Piece(this.pieceNum, this.x, this.y, (this.rotation + direction + 4) % 4);
};
Mario.Piece.prototype.moveLeft = function () {
return new Mario.Piece(this.pieceNum, this.x - 1, this.y, this.rotation);
};
Mario.Piece.prototype.moveRight = function () {
return new Mario.Piece(this.pieceNum, this.x + 1, this.y, this.rotation);
};
/**
* Manages joining the game, responding to keypresses, making the piece drop, etc.
*/
Mario.PlayingState = { Watching: 0, Joining: 1, Playing: 2 };
Mario.Controller = function (marioRef) {
this.marioRef = marioRef;
this.createBoards();
this.playingState = Mario.PlayingState.Watching;
this.waitToJoin();
this.chatRef = marioRef.child("chat");
this.chatRef.push({username: "Controls", text: "Use z and x to rotate block. Space-bar to drop. Arrow keys to move."});
this.chatInput = $("#chat-input");
this.chatHistory = $("#chat-history");
// Clear chat history on firebase when new person joins, begin watching chat
this.chatRef.set(null, this.watchChat());
};
Mario.Controller.prototype.createBoards = function () {
this.boards = [];
for(var i = 0; i <= 1; i++) {
var playerRef = this.marioRef.child("player" + i);
var canvas = $("#canvas" + i).get(0);
this.boards.push(new Mario.Board(canvas, playerRef));
}
};
Mario.Controller.prototype.waitToJoin = function() {
var self = this;
// Listen on "online" location for player0 and player1.
this.marioRef.child("player0/online").on("value", function(onlineSnap) {
if (onlineSnap.val() === null && self.playingState === Mario.PlayingState.Watching) {
self.tryToJoin(0);
}
});
this.marioRef.child("player1/online").on("value", function(onlineSnap) {
if (onlineSnap.val() === null && self.playingState === Mario.PlayingState.Watching) {
self.tryToJoin(1);
}
});
};
/**
* Try to join the game as the specified playerNum.
*/
Mario.Controller.prototype.tryToJoin = function(playerNum) {
// Set ourselves as joining to make sure we don't try to join as both players. :-)
this.playingState = Mario.PlayingState.Joining;
// Use a transaction to make sure we don't conflict with other people trying to join.
var self = this;
this.marioRef.child("player" + playerNum + "/online").transaction(function(onlineVal) {
if (onlineVal === null) {
return true; // Try to set online to true.
} else {
return; // Somebody must have beat us. Abort the transaction.
}
}, function(error, committed) {
if (committed) { // We got in!
self.playingState = Mario.PlayingState.Playing;
self.startPlaying(playerNum);
} else {
self.playingState = Mario.PlayingState.Watching;
}
});
};
/**
* Once we've joined, enable controlling our player.
*/
Mario.Controller.prototype.startPlaying = function (playerNum) {
this.playerNum = playerNum;
this.myPlayerRef = this.marioRef.child("player" + playerNum);
this.opponentPlayerRef = this.marioRef.child("player" + (1 - playerNum));
this.myBoard = this.boards[playerNum];
this.myBoard.isMyBoard = true;
this.myBoard.draw();
// Clear our "online" status when we disconnect so somebody else can join.
this.myPlayerRef.child("online").onDisconnect().remove();
// Clear chat history when player leaves
this.chatRef.onDisconnect().remove();
// Detect when other player pushes rows to our board.
this.watchForExtraRows();
// Detect when game is restarted by other player.
this.watchForRestart();
// Detect when you have won
this.watchForWinner();
// Detect when number of player wins is updated
this.watchWins();
// Detect when number of virus' left updates
this.watchVirus();
$("#gameInProgress").hide();
var self = this;
$("#restartButton").removeAttr("disabled");
$("#restartButton").click(function () {
self.restartGame();
});
var plusDiffBtn = $("#diff" + playerNum + "plus");
plusDiffBtn.removeAttr("disabled");
plusDiffBtn.click(function () {
self.myPlayerRef.child("difficulty").transaction( function(currentDiff) {
return currentDiff += 1;
});
});
var minusDiffBtn = $("#diff" + playerNum + "minus");
minusDiffBtn.removeAttr("disabled");
minusDiffBtn.click(function () {
self.myPlayerRef.child("difficulty").transaction( function(currentDiff) {
return currentDiff -= 1;
});
});
this.updateChat("Joined game!");
this.initializePiece();
this.setDifficulty();
this.enableKeyboard();
this.resetGravity();
this.watchDifficulty();
};
Mario.Controller.prototype.initializePiece = function() {
this.fallingPiece = null;
var pieceRef = this.myPlayerRef.child("piece");
var self = this;
// Watch for changes to the current piece (and initialize it if it's null).
pieceRef.on("value", function(snapshot) {
if (snapshot.val() === null) {
var newPiece = new Mario.Piece();
newPiece.writeToFirebase(pieceRef);
} else {
self.fallingPiece = Mario.Piece.fromSnapshot(snapshot);
}
});
};
Mario.Controller.prototype.initializeVirus = function(numVirus) {
var newVirus = null;
for (var v = 1; v <= numVirus; v++) {
newVirus = new Mario.Virus();
this.myBoard.addVirus(newVirus);
}
this.myBoard.updateVirusCount();
};
Mario.Controller.prototype.setDifficulty = function(difficulty) {
var self = this;
if (arguments.length > 0) {
this.difficulty = difficulty;
} else {
// Use default if not specified.
this.difficulty = Mario.DEFAULT_DIFFICULTY;
}
// Post to firebase
this.myPlayerRef.child("difficulty").set(this.difficulty);
}
/**
* Update chat history on firebase when submitting message.
*/
Mario.Controller.prototype.updateChat = function (msg, name) {
if (msg) {
if (arguments.length < 2)
name = "Player " + String(this.playerNum + 1);
this.chatRef.push({username: name, text: msg});
}
};
/**
* Detect when our opponent pushes new chat message.
*/
Mario.Controller.prototype.watchChat = function () {
var self = this;
this.chatRef.endAt().limitToLast(1).on("child_added", function(snapshot) {
data = snapshot.val()
var newLine = data.username + ": " + data.text + "</b>";
self.chatHistory.append("<li>" + newLine + "</li>");
self.chatHistory.animate( {
scrollTop: $('#chat-history')[0].scrollHeight
}, 1000);
});
};
/**
* Detect when number of virus changes and update display.
*/
Mario.Controller.prototype.watchVirus = function () {
var self = this;
// Watch own board
this.myPlayerRef.child("virus").on("value", function(snapshot) {
$("#virus" + self.playerNum).text(snapshot.val());
});
// Watch opponents board
this.opponentPlayerRef.child("virus").on("value", function(snapshot) {
$("#virus" + (1 - self.playerNum)).text(snapshot.val());
});
};
/**
* Detect when player wins changes and update display.
*/
Mario.Controller.prototype.watchWins = function () {
var self = this;
// Watch own board
this.myPlayerRef.child("wins").set(0);
this.myPlayerRef.child("wins").on("value", function(snapshot) {
$("#wins" + self.playerNum).text(snapshot.val());
});
// Watch opponents board
this.opponentPlayerRef.child("wins").on("value", function(snapshot) {
$("#wins" + (1 - self.playerNum)).text(snapshot.val());
});
};
/**
* Detect when player changes difficulty.
*/
Mario.Controller.prototype.watchDifficulty = function () {
var self = this;
this.myPlayerRef.child("difficulty").on("value", function(snapshot) {
$("#diff" + self.playerNum).text(snapshot.val());
self.difficulty = snapshot.val();
self.restartGame();
});
this.opponentPlayerRef.child("difficulty").on("value", function(snapshot) {
console.log("opp " + (1-self.playerNum) + " diff: " + snapshot.val());
$("#diff" + (1 - self.playerNum)).text(snapshot.val());
});
};
/**
* Sets up handlers for all keyboard commands.
*/
Mario.Controller.prototype.enableKeyboard = function () {
var self = this;
var key = {
space:32, left:37, up:38, right:39, down:40,
rotateLeft:90, rotateRight:88,
enter:13, escape:27
};
this.chatInput.on("keydown", function (evt) {
var keyCode = evt.which;
switch (keyCode) {
case key.enter:
self.updateChat(self.chatInput.val());
self.chatInput.val("");
case key.escape:
document.activeElement.blur();
}
return;
});
$(document).on("keydown", function (evt) {
if (self.fallingPiece === null)
return; // piece isn't initialized yet.
var keyCode = evt.which;
// If Chat Input is active, don't react to keypress here
if ($(document.activeElement).is('input') ||$(document.activeElement).is('textarea'))
return;
var newPiece = null;
switch (keyCode) {
case key.left:
newPiece = self.fallingPiece.moveLeft();
break;
case key.up:
// Removed up control
// newPiece = self.fallingPiece.rotate();
break;
case key.rotateLeft:
newPiece = self.fallingPiece.rotate(1);
break;
case key.rotateRight:
newPiece = self.fallingPiece.rotate(-1);
break;
case key.right:
newPiece = self.fallingPiece.moveRight();
break;
case key.down:
newPiece = self.fallingPiece.drop();
break;
case key.space:
// Drop as far as we can.
var droppedPiece = self.fallingPiece;
do {
newPiece = droppedPiece;
droppedPiece = droppedPiece.drop();
} while (!self.myBoard.checkForPieceCollision(droppedPiece));
break;
}
if (newPiece !== null) {
// If the new piece position / rotation is valid, update self.fallingPiece and firebase.
if (!self.myBoard.checkForPieceCollision(newPiece)) {
// If the keypress moved the piece down, reset gravity.
if (self.fallingPiece.y != newPiece.y) {
self.resetGravity();
}
newPiece.writeToFirebase(self.myPlayerRef.child("piece"));
}
return false; // handled
}
return true;
});
};
/**
* Sets a timer to make the piece repeatedly drop after GRAVITY_DELAY ms.
*/
Mario.Controller.prototype.resetGravity = function () {
// If there's a timer already active, clear it first.
if (this.gravityIntervalId !== null) {
clearInterval(this.gravityIntervalId);
}
var self = this;
this.gravityIntervalId = setInterval(function() {
self.doGravity();
}, Mario.GRAVITY_DELAY);
};
Mario.Controller.prototype.doGravity = function () {
if (this.fallingPiece === null)
return; // piece isn't initialized yet.
var newPiece = this.fallingPiece.drop();
// If we've hit the bottom, add the (pre-drop) piece to the board and create a new piece.
if (this.myBoard.checkForPieceCollision(newPiece)) {
this.myBoard.addLandedPiece(this.fallingPiece);
// Check for completed lines and if appropriate, push extra rows to our opponent.
var completedMatches = this.myBoard.removeCompletedPillsHoriz();
completedMatches += this.myBoard.removeCompletedPillsVert();
// Update virus count if matches were made.
if (completedMatches) {
this.myBoard.updateVirusCount();
}
var rowsToPush = (completedMatches === 2) ? 2 : completedMatches - 1;
if (rowsToPush > 0)
this.opponentPlayerRef.child("extrarows").push(rowsToPush);
// TODO: CHANGE THIS TO BE x RANDOM PIECES ONTO OPPONENTS BOARD
// Create new piece (it'll be initialized to a random piece at the top of the screen).
newPiece = new Mario.Piece();
// Is the board full?
if (this.myBoard.checkForPieceCollision(newPiece)) {
this.gameOver();
// If opponent playing, give them a win
this.opponentPlayerRef.child("wins").transaction( function(priorWins) {
return priorWins += 1;
});
}
}
newPiece.writeToFirebase(this.myPlayerRef.child("piece"));
};
/**
* Detect when our opponent pushes extra rows to us.
*/
Mario.Controller.prototype.watchForExtraRows = function () {
var self = this;
var extraRowsRef = this.myPlayerRef.child("extrarows");
extraRowsRef.on("child_added", function(snapshot) {
var rows = snapshot.val();
extraRowsRef.child(snapshot.key()).remove();
var overflow = self.myBoard.addJunkRows(rows);
if (overflow)
self.gameOver();
// Also move piece up to avoid collisions.
if (self.fallingPiece) {
self.fallingPiece.y -= rows;
self.fallingPiece.writeToFirebase(self.myPlayerRef.child("piece"));
}
});
};
/**
* Detect when our opponent restarts the game.
*/
Mario.Controller.prototype.watchForRestart = function () {
var self = this;
var restartRef = this.myPlayerRef.child("restart");
restartRef.on("value", function(snap) {
if (snap.val() === 1) {
restartRef.set(0);
self.resetMyBoardAndPiece();
}
});
};
/**
* Detect when player wins game.
*/
Mario.Controller.prototype.watchForWinner = function () {
var self = this;
var winRef = this.myPlayerRef.child("win");
var winsRef = this.myPlayerRef.child("wins");
winRef.on("value", function(snapshot) {
if (snapshot.val() === 1) {
winRef.set(0);
// Update firebase score
winsRef.once('value', function (snapshot) {
winsRef.set(snapshot.val() + 1);
});
self.gameOver();
}
});
};
Mario.Controller.prototype.gameOver = function () {
this.restartGame();
};
Mario.Controller.prototype.restartGame = function () {
this.opponentPlayerRef.child("restart").set(1);
this.resetMyBoardAndPiece();
};
Mario.Controller.prototype.resetMyBoardAndPiece = function () {
this.myBoard.clear();
this.initializeVirus(this.difficulty);
var newPiece = new Mario.Piece();
newPiece.writeToFirebase(this.myPlayerRef.child("piece"));
};
start();
});
|
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import { i18n } from 'redux-pagan';
import history from '../libs/History';
import reducers from '../reducers';
const rootReducers = combineReducers({
...reducers,
i18n,
routing: routerReducer
});
const middlewares = [thunk, routerMiddleware(history)];
if (process.env.NODE_ENV !== 'production') {
middlewares.push(createLogger());
}
const store = compose(applyMiddleware(...middlewares))(createStore)(rootReducers);
export default store;
|
var vows = require('vows');
var assert = require('assert');
var suite = vows.describe('pop');
require('../env');
suite.addBatch({
'pop' : {
'topic' : function () {
return CBuffer;
},
'pop items' : function (CBuffer) {
var tmp;
tmp = CBuffer(1, 2, 3);
assert.equal(tmp.pop(), 3);
tmp = CBuffer(1, 2, 3);
tmp.pop();
assert.deepEqual(tmp.toArray(), [1, 2]);
tmp = CBuffer(3);
assert.isUndefined(tmp.pop());
},
'pop properties' : function (CBuffer) {
var tmp;
tmp = CBuffer(1, 2, 3);
tmp.pop();
assert.equal(tmp.end, 1);
assert.equal(tmp.length, 2);
},
'over pop': function(CBuffer) {
var tmp = CBuffer(5);
tmp.push(4, 5, 6, 7, 8, 9, 10);
assert.equal(tmp.pop(), 10);
assert.equal(tmp.end, 0);
assert.equal(tmp.start, 2);
assert.equal(tmp.length, 4);
},
}
});
suite.export(module);
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.6-master-810c4f3
*/
function MdWhiteframeDirective(e){function a(a,m,n){var o=parseInt(n.mdWhiteframe,10)||i;(o>t||r>o)&&(e.warn("md-whiteframe attribute value is invalid. It should be a number between "+r+" and "+t,m[0]),o=i),m.addClass("md-whiteframe-"+o+"dp")}var r=1,t=24,i=4;return{restrict:"A",link:a}}goog.provide("ng.material.components.whiteframe"),goog.require("ng.material.core"),angular.module("material.components.whiteframe",["material.core"]).directive("mdWhiteframe",MdWhiteframeDirective),MdWhiteframeDirective.$inject=["$log"],ng.material.components.whiteframe=angular.module("material.components.whiteframe");
|
var audio = require("audio"),
vec2 = require("vec2"),
vec3 = require("vec3"),
Component = require("./index");
var ComponentPrototype = Component.prototype,
AudioSourcePrototype;
module.exports = AudioSource;
function AudioSource() {
var _this = this;
Component.call(this);
this.offset = vec3.create();
this.audioAsset = null;
this.__source = new audio.Source();
this.__source.on("play", function onPlay() {
_this.emit("play");
});
this.__source.on("pause", function onPause() {
_this.emit("pause");
});
this.__source.on("stop", function onStop() {
_this.emit("stop");
});
this.__source.on("end", function onEnd() {
_this.emit("end");
});
}
Component.extend(AudioSource, "odin.AudioSource");
AudioSourcePrototype = AudioSource.prototype;
AudioSourcePrototype.construct = function(options) {
var audio = options && options.audio;
ComponentPrototype.construct.call(this);
if (audio) {
this.audioAsset = audio;
this.__source.setClip(audio.clip);
this.__source.construct(options);
}
if (options) {
if (options.offset) {
vec2.copy(this.offset, options.offset);
}
}
return this;
};
AudioSourcePrototype.destructor = function() {
ComponentPrototype.destructor.call(this);
this.audioAsset = null;
this.__source.destructor();
return this;
};
AudioSourcePrototype.setOffset = function(value) {
vec3.set(this.offset, value);
return this;
};
AudioSourcePrototype.setClip = function(value) {
this.__source.setClip(value);
return this;
};
AudioSourcePrototype.setPanningModel = function(value) {
this.__source.setPanningModel(value);
return this;
};
AudioSourcePrototype.setDistanceModel = function(value) {
this.__source.setDistanceModel(value);
return this;
};
AudioSourcePrototype.setRefDistance = function(value) {
this.__source.setRefDistance(value);
return this;
};
AudioSourcePrototype.setMaxDistance = function(value) {
this.__source.setMaxDistance(value);
return this;
};
AudioSourcePrototype.setRolloffFactor = function(value) {
this.__source.setRolloffFactor(value);
return this;
};
AudioSourcePrototype.setConeInnerAngle = function(value) {
this.__source.setConeInnerAngle(value);
return this;
};
AudioSourcePrototype.setConeOuterAngle = function(value) {
this.__source.setConeOuterAngle(value);
return this;
};
AudioSourcePrototype.setConeOuterGain = function(value) {
this.__source.setConeOuterGain(value);
return this;
};
AudioSourcePrototype.setAmbient = function(value) {
this.__source.setAmbient(value);
return this;
};
AudioSourcePrototype.setDopplerLevel = function(value) {
this.__source.setDopplerLevel(value);
return this;
};
AudioSourcePrototype.setVolume = function(value) {
this.__source.setVolume(value);
return this;
};
AudioSourcePrototype.setLoop = function(value) {
this.__source.setLoop(value);
return this;
};
AudioSourcePrototype.play = function(delay, offset, duration) {
this.__source.play(delay, offset, duration);
return this;
};
AudioSourcePrototype.pause = function() {
this.__source.pause();
return this;
};
AudioSourcePrototype.stop = function() {
this.__source.stop();
return this;
};
var update_position = vec3.create(),
update_orientation = vec3.create(0.0, 0.0, 1.0),
update_tmp0 = vec3.create();
AudioSourcePrototype.update = function() {
var source = this.__source,
dopplerLevel, entity, scene, camera, transform, transform2d, position, orientation;
ComponentPrototype.update.call(this);
if (source.playing) {
dopplerLevel = source.dopplerLevel;
entity = this.entity;
scene = entity && entity.scene;
camera = scene && scene.hasManager("odin.Camera") && scene.getManager("odin.Camera").getActive();
if (!source.ambient) {
transform = entity.components["odin.Transform"];
transform2d = entity.components["odin.Transform2D"];
position = update_position;
orientation = update_tmp0;
if (transform) {
vec3.copy(position, this.offset);
vec3.transformMat4(position, position, transform.getMatrixWorld());
vec3.transformMat4Rotation(orientation, update_orientation, transform.getMatrixWorld());
} else if (transform2d) {
vec2.copy(position, this.offset);
if (camera && camera.orthographic) {
position[2] = camera.orthographicSize * 0.5;
} else {
position[2] = 0.0;
}
vec2.transformMat4(position, position, transform2d.getMatrixWorld());
vec3.transformMat4Rotation(orientation, update_orientation, transform2d.getMatrixWorld());
}
vec3.normalize(orientation, orientation);
source.setPosition(position);
source.setOrientation(orientation);
}
}
return this;
};
AudioSourcePrototype.toJSON = function(json) {
json = ComponentPrototype.toJSON.call(this, json);
json.offset = vec3.copy(json.offset || [], this.offset);
json.source = this.__source.toJSON(json.source);
return json;
};
AudioSourcePrototype.fromJSON = function(json) {
ComponentPrototype.fromJSON.call(this, json);
vec3.copy(this.offset, json.offset);
this.__source.fromJSON(json.source);
return this;
};
|
var script_create;
script_create = function () {
if ($('.script_form').length) {
$("#script_target_id").imagepicker( {show_label: true} );
}
};
$(document).ready(script_create);
$(document).on('page:load', script_create);
|
var async = require('async');
var colors = require('colors');
var pg = require('pg');
var types = require('pg').types;
types.setTypeParser(1700, 'text', parseFloat);
var _ = require('underscore');
var jwt = require('jsonwebtoken');
var pool = require('../../server.js').pool;
var fs = require("fs");
var dir_1 = "/../../sql/queries/courses/";
var dir_2 = "/../../sql/queries/members/";
var dir_3 = "/../../sql/queries/responsibilities/";
var query_create_course = fs.readFileSync(__dirname + dir_1 + 'create.sql', 'utf8').toString();
var query_get_member = fs.readFileSync(__dirname + dir_2 + 'get.sql', 'utf8').toString();
var query_create_responsibility = fs.readFileSync(__dirname + dir_3 + 'create.sql', 'utf8').toString();
var query_get_responsibilities_by_course = fs.readFileSync(__dirname + dir_3 + 'get_by_course.sql', 'utf8').toString();
// POST
exports.request = function(req, res) {
async.waterfall([
function(callback){
// Connect to database
pool.connect(function(err, client, done) {
if(err) {
callback(err, 500);
} else {
callback(null, client, done);
}
});
},
function(client, done, callback) {
// Authorization
if(req.headers.authorization) {
var token = req.headers.authorization.substring(7);
// Verify token
jwt.verify(token, process.env.JWTSECRET, function(err, decoded) {
if(err){
callback(new Error("Authorization failed"), 401);
} else {
if(decoded.member){
callback(null, client, done);
} else {
callback(new Error("Authorization failed"), 401);
}
}
});
} else {
callback(new Error("Authorization failed"), 401);
}
},
function(client, done, callback) {
// TODO: Add object/schema validation
var object = {
course_name: req.body.course_name,
year: req.body.year,
term: req.body.term,
lecturer: req.body.lecturer,
institute_id: req.body.institute_id
};
var params = _.values(object);
callback(null, client, done, params);
},
function(client, done, params, callback){
// Database query
client.query(query_create_course, params, function(err, result) {
done();
if (err) {
callback(err, 500);
} else {
callback(null, client, done, result.rows[0]);
}
});
},
function(client, done, course, callback){
// Create responsibilities
async.eachOfSeries(req.body.responsibilities, function (responsibility, key, callback) {
// Database query
client.query(query_get_member, [
responsibility.member_id
], function(err, result) {
done();
if (err) {
callback(err, 500);
} else {
// Check if Member exists
if (result.rows.length === 0) {
callback(new Error("Member not found"), 404);
} else {
// Database query
client.query(query_create_responsibility, [
course.course_id,
responsibility.member_id
], function(err, result) {
done();
if (err) {
callback(err, 500);
} else {
callback(null);
}
});
}
}
});
}, function(err){
if(err){
callback(err, 500);
} else {
callback(null, client, done, course);
}
});
},
function(client, done, course, callback){
// Database query
client.query(query_get_responsibilities_by_course, [
course.course_id
], function(err, result) {
done();
if (err) {
callback(err, 500);
} else {
course.responsibilities = result.rows;
callback(null, 201, course);
}
});
}
], function(err, code, result) {
if(err){
console.error(colors.red(err));
res.status(code).send(err.message);
} else {
res.status(code).send(result);
}
});
};
|
import React from 'react';
// Exported from redux-devtools
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
// createDevTools takes a monitor and produces a DevTools component
const DevTools = createDevTools(
// Monitors are individually adjustable with props.
// Consult their repositories to learn about those props.
// Here, we put LogMonitor inside a DockMonitor.
// Note: DockMonitor is visible by default.
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
defaultIsVisible={true}>
<LogMonitor theme='tomorrow' />
</DockMonitor>
);
export default DevTools;
|
// Include Desktop Specific JavaScript files here (or inside of your Desktop Controller, or differentiate based off App.mobile === false)
require(["Filmtrik", "routers/AppRouter", "controllers/DesktopController", "jquery", "backbone", "marionette", "jqueryui", "bootstrap", "backbone.validateAll"],
function (Filmtrik, AppRouter, AppController) {
Filmtrik.appRouter = new AppRouter({
controller:new AppController()
});
// Start Marionette Application in desktop mode (default)
Filmtrik.start();
});
|
var flatten = require('arr-flatten'),
ensureMap = require('ensure-map'),
onFinished = require('on-finished');
module.exports = function(logger) {
return function *(next) {
var ctx = this;
ctx.log = logger;
onFinished(ctx.res, function() {
ctx.log.debug({ res: ctx.res, req: ctx.req }, 'Response finished');
});
try {
yield* next;
} catch (err) {
ctx.log.error({ err: err }, 'Error');
throw err;
}
};
};
module.exports.include = function() {
var included = flatten([].slice.call(arguments));
var map = ensureMap(included);
return function *(next) {
var ctx = this;
if (typeof ctx.log === 'undefined') {
throw new Error('.use(logging(logger)) first');
}
if (included.length) {
var values = {};
included.forEach(function(key) {
var alias = map[key];
values[alias] = ctx[key];
});
ctx.log = ctx.log.child(values, true);
}
yield* next;
};
};
|
// The MIT License (MIT)
// Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.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.
!function($){
"use strict";
var Typed = function(el, options){
// chosen element to manipulate text
this.el = $(el);
// options
this.options = $.extend({}, $.fn.typed.defaults, options);
// text content of element
this.text = this.el.text();
// typing speed
this.typeSpeed = this.options.typeSpeed;
// add a delay before typing starts
this.startDelay = this.options.startDelay;
// backspacing speed
this.backSpeed = this.options.backSpeed;
// amount of time to wait before backspacing
this.backDelay = this.options.backDelay;
// input strings of text
this.strings = this.options.strings;
// character number position of current string
this.strPos = 0;
// current array position
this.arrayPos = 0;
// number to stop backspacing on.
// default 0, can change depending on how many chars
// you want to remove at the time
this.stopNum = 0;
// Looping logic
this.loop = this.options.loop;
this.loopCount = this.options.loopCount;
this.curLoop = 0;
// for stopping
this.stop = false;
// All systems go!
this.build();
};
Typed.prototype = {
constructor: Typed
, init: function(){
// begin the loop w/ first current string (global self.string)
// current string will be passed as an argument each time after this
var self = this;
self.timeout = setTimeout(function() {
// Start typing
self.typewrite(self.strings[self.arrayPos], self.strPos);
}, self.startDelay);
}
, build: function(){
// Insert cursor
this.cursor = $("<span class=\"typed-cursor\">|</span>");
this.el.after(this.cursor);
this.init();
}
// pass current string state to each function, types 1 char per call
, typewrite: function(curString, curStrPos){
// exit when stopped
if(this.stop === true)
return;
// varying values for setTimeout during typing
// can't be global since number changes each time loop is executed
var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed;
var self = this;
// ------------- optional ------------- //
// backpaces a certain string faster
// ------------------------------------ //
if (self.arrayPos == 1){
self.stopNum = 3;
self.backDelay = 10;
}
//every other time, delete the whole typed string
else{
self.stopNum = 0;
self.backDelay = self.options.backDelay;
}
// contain typing function in a timeout humanize'd delay
self.timeout = setTimeout(function() {
// check for an escape character before a pause value
// format: \^\d+ eg: ^1000 should be able to print the ^ too using ^^
// single ^ are removed from string
var charPause = 0;
var substr = curString.substr(curStrPos);
if (substr.charAt(0) === '^') {
var e = 1;
if(substr.match(/^\^\d+/)) {
substr = substr.replace(/^\^(\d+).*/, "$1");
e += substr.length;
charPause = parseInt(substr);
}
// strip out the escape character and pause value so they're not printed
curString = curString.substring(0,curStrPos)+curString.substring(curStrPos+e);
}
// timeout for any pause after a character
self.timeout = setTimeout(function() {
if(curStrPos === curString.length) {
// fires callback function
self.options.onStringTyped(self.arrayPos);
// is this the final string
if(self.arrayPos === self.strings.length-1) {
// animation that occurs on the last typed string
self.options.callback();
self.curLoop++;
// quit if we wont loop back
if(self.loop === false || self.curLoop === self.loopCount)
return;
}
self.timeout = setTimeout(function(){
self.backspace(curString, curStrPos);
}, self.backDelay);
} else {
/* call before functions if applicable */
if(curStrPos === 0)
self.options.preStringTyped(self.arrayPos);
// start typing each new char into existing string
// curString: arg, self.text: original text inside element
self.el.text(self.text + curString.substr(0, curStrPos+1));
// add characters one by one
curStrPos++;
// loop the function
self.typewrite(curString, curStrPos);
}
// end of character pause
}, charPause);
// humanized value for typing
}, humanize);
}
, backspace: function(curString, curStrPos){
// exit when stopped
if (this.stop === true) {
return;
}
// varying values for setTimeout during typing
// can't be global since number changes each time loop is executed
var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed;
var self = this;
self.timeout = setTimeout(function() {
// ----- this part is optional ----- //
// check string array position
// on the first string, only delete one word
// the stopNum actually represents the amount of chars to
// keep in the current string. In my case it's 14.
// if (self.arrayPos == 1){
// self.stopNum = 14;
// }
//every other time, delete the whole typed string
// else{
// self.stopNum = 0;
// }
// ----- continue important stuff ----- //
// replace text with current text + typed characters
self.el.text(self.text + curString.substr(0, curStrPos));
// if the number (id of character in current string) is
// less than the stop number, keep going
if (curStrPos > self.stopNum){
// subtract characters one by one
curStrPos--;
// loop the function
self.backspace(curString, curStrPos);
}
// if the stop number has been reached, increase
// array position to next string
else if (curStrPos <= self.stopNum) {
self.arrayPos++;
if(self.arrayPos === self.strings.length) {
self.arrayPos = 0;
self.init();
} else
self.typewrite(self.strings[self.arrayPos], curStrPos);
}
// humanized value for typing
}, humanize);
}
// Start & Stop currently not working
// , stop: function() {
// var self = this;
// self.stop = true;
// clearInterval(self.timeout);
// }
// , start: function() {
// var self = this;
// if(self.stop === false)
// return;
// this.stop = false;
// this.init();
// }
// Reset and rebuild the element
, reset: function(){
var self = this;
clearInterval(self.timeout);
var id = this.el.attr('id');
this.el.after('<span id="' + id + '"/>')
this.el.remove();
this.cursor.remove();
// Send the callback
self.options.resetCallback();
}
};
$.fn.typed = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('typed')
, options = typeof option == 'object' && option;
if (!data) $this.data('typed', (data = new Typed(this, options)));
if (typeof option == 'string') data[option]();
});
};
$.fn.typed.defaults = {
strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
// typing speed
typeSpeed: 0,
// time before typing starts
startDelay: 0,
// backspacing speed
backSpeed: 0,
// time before backspacing
backDelay: 500,
// loop
loop: false,
// false = infinite
loopCount: false,
// call when done callback function
callback: function() {},
// starting callback function before each string
preStringTyped: function() {},
//callback for every typed string
onStringTyped: function() {},
// callback for reset
resetCallback: function() {}
};
}(window.jQuery);
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { generateUniqueID } from './generateUniqueID';
export var initMetric = function (name, value) {
if (value === void 0) { value = -1; }
return {
name: name,
value: value,
delta: 0,
entries: [],
id: generateUniqueID(),
isFinal: false,
};
};
//# sourceMappingURL=initMetric.js.map
|
/**
* Created by Prem on 11/07/17.
*/
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let messages = new Schema({
from: {
type: String,
required: false,
minLength: 1,
trim: true
},
to: {
type: String,
required: false,
minLength: 1,
trim: true
},
message: {
type: String,
required: true,
minLength: 1,
trim: true
}
}, {_id: false});
let courses = new Schema({
name: {
type: String,
required: true,
minLength: 1,
trim: true
},
announcements: {
type: [String]
},
messages: {
type: [messages]
},
files: {
type: [String]
}
}, {_id: false});
let StudentHome = mongoose.model('StudentHome', {
FullName: {
type: String,
required: true,
minLength: 1,
trim: true
},
Email: {
type: String,
required: true,
minLength: 1,
trim: true
},
Sem: {
type: String,
required: true,
minLength: 1,
trim: true
},
Courses: {
type: [courses],
required: true,
minLength: 1,
trim: true
},
});
module.exports = {StudentHome};
|
// /* global Feature, Scenario */
// Feature('Unregistered user can register using Github Auth')
// Scenario('with unregistered user', (unregisteredUser, homePage) => {
// // TODO: complete after researching redirect issue
// // unregisteredUser.registers('timothy-tolley', 'ideology1')
// // unregisteredUser.clicks(homePage.hamburger)
// // unregisteredUser.sees('Home', homePage.header)
// // unregisteredUser.sees('Profile', homePage.header)
// // unregisteredUser.sees('Log off', homePage.header)
// // unregisteredUser.doesntSee('Register', homePage.header)
// })
|
/*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
// Selectors
$.ui.focusable = function( element, hasTabindex ) {
var map, mapName, img, focusableIfVisible, fieldset,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
}
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally aren't placed inside legends, we skip
// this portion of the check.
fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};
// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
}
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
return $.ui.focusable;
} ) );
|
import React from 'react';
import ReactDOM from 'react-dom';
import * as d3Node from '../d3/d3Node';
export default class Node extends React.Component {
componentDidMount() {
const el = ReactDOM.findDOMNode(this);
d3Node.create(el, {
width: '100%',
height: '300px',
}, this.props.data);
}
render() {
return <div className="Node"></div>;
}
}
Node.propTypes = {
data: React.PropTypes.array,
};
|
"use strict";
var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');
var co = require('co');
var parse = require('./parse');
var dragon = require('./dragon');
var content_type = require('./content_type');
var logger = require('./tool/log');
var Mongo = require('./db/mongodb');
const route_set = new Set(['default', 'query','restful']);
class server {
constructor(config) {
this.config = config;
this.logger = new logger(config);
}
set router(name){
this.route_name = name;
}
init() {
if(!this.route_name){
this.route_name = "default";
}
if(!route_set.has(this.route_name)){
throw Error('route setting error');
}
this.instance = http.createServer(function(request, response) {
response.setTimeout(60000, function() {
this.error_handler(504, response, new Error('timeout error'));
}.bind(this));
var url_info = url.parse(request.url);
var path = url_info.pathname;
var extend = path.lastIndexOf(".") > 0 ? path.substr(path.lastIndexOf(".") + 1) : null;
if(extend && content_type.is_static(extend)){
this.assets(path, extend, response);
} else {
this.worker(request, response);
}
}.bind(this));
}
run() {
this.init();
this.logger.debug('begin server on ' + this.config.port + ' ......');
this.instance.listen(this.config.port);
}
assets(assets_path, extend, response){
var assets_path = path.join(this.config['assets_root'], assets_path);
//this.logger.debug('assets:' + assets_path);
if (!fs.existsSync(assets_path)) {
this.error_handler(404, response);
return false;
}
var _dragon = new dragon();
_dragon.assets(assets_path, extend).then(function(resolve){
this.normal_handler(resolve,response);
}.bind(this)).catch(function(err) {
if(this.config.debug){
this.error_debug(err,response);
}else {
this.error_handler(500,response);
}
return false;
}.bind(this));
}
worker(request, response){
//路由
var route = require(path.join(__dirname,"route",this.route_name));
var destiny = new route().dispatch(request);
if(!destiny){
return this.error_handler(500, response, new Error('route error'));
}
//this.logger.debug('controller:' + destiny.controller);
//this.logger.debug('action:' + destiny.action);
//初始化controller
var controller_path = path.join(this.config['controller_root'], destiny.controller + '.js');
//this.logger.debug('controller_path:' + controller_path);
if (!fs.existsSync(controller_path)) {
return this.error_handler(404, response, new Error('controller no found'));
}
var controller = require(path.join(this.config['controller_root'], destiny.controller));
if (!controller[destiny.action]) {
return this.error_handler(404, response, new Error('action no found'));
}
co(function* (){
var parser = new parse(request);
var params = yield parser.exec();
var _dragon = new dragon(request,destiny,params,this.config);
var result = yield controller[destiny.action](_dragon);
return result;
}.bind(this)).then(function (result) {
this.normal_handler(result,response);
return false;
}.bind(this),function (err) {
this.error_handler(500,response,err);
return false;
}.bind(this));
}
header(_response) {
if (_response) {
//重定向特殊处理
if (_response.type == 'redirect') {
return {
'Location': _response.body,
'connection':'keep-alive'
};
}
var buffer = new Buffer(_response.body);
if (_response.cookie && _response.cookie.length) {
return {
'Content-Type': _response.type,
'Content-Length': buffer.length,
'Set-Cookie': _response.cookie,
'connection':'keep-alive'
};
} else {
return {
'Content-Type': _response.type,
'Content-Length': buffer.length,
'connection':'keep-alive'
};
}
} else {
return {
'Content-Length': 0,
'connection':'keep-alive'
}
}
}
normal_handler(_response,response){
if(!response.finished){
var header = this.header(_response);
response.writeHead(_response.code, header);
response.write(_response.body);
response.end();
}
}
error_handler(code, response, err){
if(response.finished){
return;
}
if(err && this.config.debug){
this.error_debug(code,response,err);
return;
}
switch (code) {
case 404:
if(err && this.config.debug){
this.error_debug(err,response);
}
response.writeHead(404, this.header(null));
break;
case 500:
response.writeHead(500, this.header(null));
break;
case 504:
response.writeHead(504, this.header(null));
break;
default:
}
response.end();
}
error_debug(code, response, err){
this.logger.error('error :' + err.stack);
response.writeHead(code, {
'Content-Type': 'text/plain'
});
if(err instanceof Error){
response.write(err.stack);
} else {
response.write(err);
}
response.end();
}
}
module.exports = server;
|
import React from 'react'
import { render } from 'react-dom'
import App from './end/App'
import './index.css'
render(<App />, document.getElementById('root'))
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var app = {
// Application Constructor
initialize: function() {
if(localStorage.getItem('user_token')){
document.querySelector('#myNavigator').setAttribute('page','page2.html');
}
else{
document.querySelector('#myNavigator').setAttribute('page','login.html');
}
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
this.checkLocalStore();
},
//Check localstorage
checkLocalStorage: function() {
if (typeof(Storage) == "undefined") {
alert('Error: cannot set up local storage');
}
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
}
app.initialize();
document.addEventListener('init', function(event) {
var page = event.target;
//if(localStorage.getItem('user_token')){
// document.querySelector('#myNavigator').pushPage('page2.html', {data: {title: 'Page 2'}, animation: 'none'});
//}
//else{
if (page.id === 'login') {
page.querySelector('#loginButton').onclick = function() {
login();
// document.querySelector('#myNavigator').pushPage('page2.html', {data: {title: 'Page 2'}});
};
} else if (page.id === 'page2') {
//2page.querySelector('ons-toolbar .center').innerHTML = page.data.title;
// page.querySelector('ons-toolbar .center').onclick = function(){
// document.querySelector('#myNavigator').pushPage('login.html',{data: {tittle: 'Login'}});
//}
//document.querySelector('#myNavigator').pushPage('login.html',{data: {tittle: 'Login'}});
// }
}
});
var checkToken = function(){
if(localStorage.getItem('user_token')){
document.querySelector('#myNavigator').setAttribute('page','page2.html');
}
else{
document.querySelector('#myNavigator').setAttribute('page','login.html');
}
}
var login = function() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
$.ajax({
// 'url' : 'http://localhost:3306/api/v1/users/login',
'url' : 'http://blaszku.alwaysdata.net/api/v1/users/login',
'type' : 'POST',
'data' : {
'login' : username,
'password' : password
},
'success': function(data){
if(data.token){
localStorage.setItem('user_token', data.token);
//document.querySelector('#myNavigator').pushPage('page2.html', {data: {title: 'Page 2'}});
document.querySelector('#myNavigator').replacePage('page2.html');
}
else{
ons.notification.alert(data.error);
}
},
'error': function(xhr, status, error){
var json = $.parseJSON(xhr.responseText);
ons.notification.alert(json.error);
}
});
};
var register = function() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
}
|
import React from 'react';
import Settings from 'material-ui/svg-icons/action/settings';
import MenuListItem from './MenuListItem';
import appActions from '../../appActions';
class SettingsMenuItems extends React.Component {
handleThemeChange() {
this.props.dispatch(appActions.themeChanged());
}
handleToggleSettingsClick() {
this.props.dispatch(appActions.toggleSettings());
}
render() {
const menuItems = [
<MenuListItem
key={1}
toggle
toggleText="Light Theme"
toggleValue={this.props.values.lightTheme}
onToggle={this.handleThemeChange.bind(this)}
/>,
];
return (
<div>
<MenuListItem
primaryText="Settings"
leftIcon={<Settings />}
open={this.props.values.settingsShow}
nestedItems={menuItems}
onClick={this.handleToggleSettingsClick.bind(this)}
/>
</div>);
}
}
export default SettingsMenuItems;
|
/*
* Rea
* by stagas
*
* MIT licenced
*/
var router = require('connect/lib/middleware/router')
// modified version of creationix/stack
function Stack() {
var handle = function(req, res, next) { next() }
;[].slice.call(arguments).reverse().forEach(function(layer) {
var child = handle
handle = function (req, res, next) {
layer(req, res, function () {
child(req, res, next)
})
}
})
return handle
}
module.exports = function Rea() {
var rea = function() {
if (!arguments.length) {
var stack = []
rea.routes.forEach(function(route) {
route.handlers.forEach(function(handle) {
stack.push(router(function(app) {
for (var method in handle) {
if (Array.isArray(handle[method]))
app[method].apply(this, [route.route].concat(handle[method]))
else
app[method](route.route, handle[method])
}
}))
})
})
rea.handle = Stack.apply(this, stack)
return rea.router
}
var route = null, handlers = []
for (var i = 0, len = arguments.length; i < len; i++) {
switch (typeof arguments[i]) {
case 'string':
route = arguments[i]
break
case 'function':
handlers.push({ all: arguments[i] })
break
case 'object':
if (arguments[i] instanceof RegExp) {
route = arguments[i]
} else {
handlers.push(arguments[i])
}
break
default:
//
break
}
}
if (route === null) {
var last = rea.routes.length - 1
rea.routes[last].handlers = rea.routes[last].handlers.concat(handlers)
} else {
rea.routes.push({ route: route, handlers: handlers })
}
return rea
}
rea.routes = []
rea.handle = function(req, res, next) { next() }
rea.router = function(req, res, next) {
return rea.handle(req, res, next)
}
return rea
}
|
module.exports = {
OK: 200,
OK_NO_CONTENT: 204,
BAD_REQUEST: 400,
NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500
}
|
import parsePropertyValue from './../src/parse-property-value';
describe('parsePropertyValue', function () {
it('should parse unit-less value', function () {
const expectation = {
unit: '',
value: 100,
output: '100',
original: '100'
};
expect(parsePropertyValue('100')).toEqual(expectation);
});
it('should return property value with unit', function () {
const expectation = {
unit: 'px',
value: 100,
output: '100px',
original: '100px'
};
expect(parsePropertyValue('100px')).toEqual(expectation);
});
it('should return negative property value', function () {
const expectation = {
unit: 'px',
value: -100,
output: '-100px',
original: '-100px'
};
expect(parsePropertyValue('-100px')).toEqual(expectation);
});
it('should return color property value', function () {
const expectation = {
unit: 'rgb',
value: [0, 0, 0],
output: '#000000',
original: 'rgb(0, 0, 0)'
};
expect(parsePropertyValue('rgb(0, 0, 0)')).toEqual(expectation);
});
it('should return zero-value property', function () {
const expectation = {
unit: 'px',
value: 0,
output: '0px',
original: '0px'
};
expect(parsePropertyValue('0px')).toEqual(expectation);
});
it('should return null on `auto` property', function () {
const expectation = {
unit: '',
value: null,
output: 'auto',
original: 'auto'
};
expect(parsePropertyValue('auto')).toEqual(expectation);
});
});
|
'use strict';
var path = require('path');
var webpack = require('webpack');
var _ = require('lodash');
var common = require('./webpack.common.config');
var hot = _.cloneDeep(common);
hot.entry.unshift(
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server'
);
hot.output.publicPath = '//localhost:8080/assets/javascripts';
hot.module.loaders[0].loaders.unshift('react-hot');
hot.devtool = 'cheap-module-eval-source-map';
hot.plugins = [
new webpack.HotModuleReplacementPlugin()
];
hot.devServer = {
contentBase: './public',
publicPath: '/assets/javascripts',
hot: true,
colors: true,
headers: {
'Access-Control-Allow-Origin': '*'
}
};
module.exports = hot;
|
'use strict';
var chai = require('chai');
var expect = chai.expect;
exports.basicSuperAgentRequestSuccess = function basicSuperAgentRequestSuccess(err, res, statusCode) {
expect(err, 'should not have an err').to.not.exist;
expect(res.status, 'should have the expected status').to.eql(statusCode || 200);
expect(res.data).to.not.exist;
expect(res.text, 'response should have text').to.exist;
expect(res.body, 'should have a body').to.exist;
};
exports.assertHeadRequestSuccess = function assertHeadRequestSuccess(err, res) {
expect(err, 'should not have an err object').to.not.exist;
expect(res.status, 'should have a statusCode of 200').to.eql(200);
expect(res.data).to.not.exist;
expect(res.text).to.not.exist;
expect(res.body, 'expect body to exist').to.exist;
};
exports.assertBadSuperAgentRequest = function assertBadSuperAgentRequest(err, res, statusCode) {
expect(err, 'expect err to exist').to.exist;
expect(res, 'expect res to exist').to.exist;
expect(res.status, 'status should equal: ' + statusCode).to.equal(statusCode);
var body = res.body;
expect(body).to.not.be.empty;
expect(body.statusCode).to.equal(statusCode);
expect(body.error).to.not.be.empty;
};
exports.assert404SuperAgentRequest = function assert404SuperAgentRequest(err, res) {
expect(err, 'should have an err object').to.exist;
expect(res, 'should have a res object').to.exist;
expect(res.status).to.equal(404);
};
|
var through = require('through'),
gutil = require('gulp-util'),
File = gutil.File,
PluginError = gutil.PluginError,
crypto = require('crypto');
module.exports = function(data){
var manifest = data;
return through(function(file) {
if(file.isNull()) return;
if(file.isStream()){
return this.emit('error', new PluginError('gulp-sterno-manifest', 'Streams not supported'));
}
var key = '/' + file.path.replace(file.base, '');
manifest[key] = crypto.createHash('md5').update(file.contents).digest('hex');
}, function(){
this.emit('data', new File({
contents: new Buffer(JSON.stringify(manifest, null, 2)), path: './'
}));
this.emit('end');
});
};
|
;(function(undefined) {
'use strict';
/**
* artoo core
* ===========
*
* The main artoo namespace and its vital properties.
*/
// Checking whether a body exists
var body;
if ('document' in this) {
body = document.getElementsByTagName('body')[0];
if (!body) {
body = document.createElement('body');
document.documentElement.appendChild(body);
}
}
// Main object
var artoo = {
// Standard properties
$: {},
jquery: {
applyPlugins: function() {
artoo.jquery.plugins.map(function(p) {
p(artoo.$);
});
},
plugins: []
},
mountNode: body,
stylesheets: {},
templates: {},
// Emitter shim properties
_enabled: true,
_children: [],
_handlers: {},
_handlersAll: []
};
// Non-writable version
Object.defineProperty(artoo, 'version', {
value: '0.3.2'
});
// Exporting to global scope
this.artoo = artoo;
}).call(this);
/**
* artoo node.js shim
* ===================
*
* Make it possible to require artoo through node.
*/
var artoo = this.artoo;
(function() {
'use strict';
/**
* Here is the list of every allowed parameter when using Emitter#on:
* @type {Object}
*/
var __allowedOptions = {
once: 'boolean',
scope: 'object'
};
/**
* The emitter's constructor. It initializes the handlers-per-events store and
* the global handlers store.
*
* Emitters are useful for non-DOM events communication. Read its methods
* documentation for more information about how it works.
*
* @return {Emitter} The fresh new instance.
*/
var Emitter = function() {
this._enabled = true;
this._children = [];
this._handlers = {};
this._handlersAll = [];
};
/**
* This method binds one or more functions to the emitter, handled to one or a
* suite of events. So, these functions will be executed anytime one related
* event is emitted.
*
* It is also possible to bind a function to any emitted event by not
* specifying any event to bind the function to.
*
* Recognized options:
* *******************
* - {?boolean} once If true, the handlers will be unbound after the first
* execution. Default value: false.
* - {?object} scope If a scope is given, then the listeners will be called
* with this scope as "this".
*
* Variant 1:
* **********
* > myEmitter.on('myEvent', function(e) { console.log(e); });
* > // Or:
* > myEmitter.on('myEvent', function(e) { console.log(e); }, { once: true });
*
* @param {string} event The event to listen to.
* @param {function} handler The function to bind.
* @param {?object} options Eventually some options.
* @return {Emitter} Returns this.
*
* Variant 2:
* **********
* > myEmitter.on(
* > ['myEvent1', 'myEvent2'],
* > function(e) { console.log(e); }
* >);
* > // Or:
* > myEmitter.on(
* > ['myEvent1', 'myEvent2'],
* > function(e) { console.log(e); }
* > { once: true }}
* >);
*
* @param {array} events The events to listen to.
* @param {function} handler The function to bind.
* @param {?object} options Eventually some options.
* @return {Emitter} Returns this.
*
* Variant 3:
* **********
* > myEmitter.on({
* > myEvent1: function(e) { console.log(e); },
* > myEvent2: function(e) { console.log(e); }
* > });
* > // Or:
* > myEmitter.on({
* > myEvent1: function(e) { console.log(e); },
* > myEvent2: function(e) { console.log(e); }
* > }, { once: true });
*
* @param {object} bindings An object containing pairs event / function.
* @param {?object} options Eventually some options.
* @return {Emitter} Returns this.
*
* Variant 4:
* **********
* > myEmitter.on(function(e) { console.log(e); });
* > // Or:
* > myEmitter.on(function(e) { console.log(e); }, { once: true});
*
* @param {function} handler The function to bind to every events.
* @param {?object} options Eventually some options.
* @return {Emitter} Returns this.
*/
Emitter.prototype.on = function(a, b, c) {
var i,
l,
k,
event,
eArray,
bindingObject;
// Variant 1 and 2:
if (typeof b === 'function') {
eArray = typeof a === 'string' ?
[a] :
a;
for (i = 0, l = eArray.length; i !== l; i += 1) {
event = eArray[i];
// Check that event is not '':
if (!event)
continue;
if (!this._handlers[event])
this._handlers[event] = [];
bindingObject = {
handler: b
};
for (k in c || {})
if (__allowedOptions[k])
bindingObject[k] = c[k];
else
throw new Error(
'The option "' + k + '" is not recognized by Emmett.'
);
this._handlers[event].push(bindingObject);
}
// Variant 3:
} else if (a && typeof a === 'object' && !Array.isArray(a))
for (event in a)
Emitter.prototype.on.call(this, event, a[event], b);
// Variant 4:
else if (typeof a === 'function') {
bindingObject = {
handler: a
};
for (k in c || {})
if (__allowedOptions[k])
bindingObject[k] = c[k];
else
throw new Error(
'The option "' + k + '" is not recognized by Emmett.'
);
this._handlersAll.push(bindingObject);
}
// No matching variant:
else
throw new Error('Wrong arguments.');
return this;
};
/**
* This method works exactly as the previous #on, but will add an options
* object if none is given, and set the option "once" to true.
*
* The polymorphism works exactly as with the #on method.
*/
Emitter.prototype.once = function(a, b, c) {
// Variant 1 and 2:
if (typeof b === 'function') {
c = c || {};
c.once = true;
this.on(a, b, c);
// Variants 3 and 4:
} else if (
// Variant 3:
(a && typeof a === 'object' && !Array.isArray(a)) ||
// Variant 4:
(typeof a === 'function')
) {
b = b || {};
b.once = true;
this.on(a, b);
// No matching variant:
} else
throw new Error('Wrong arguments.');
return this;
};
/**
* This method unbinds one or more functions from events of the emitter. So,
* these functions will no more be executed when the related events are
* emitted. If the functions were not bound to the events, nothing will
* happen, and no error will be thrown.
*
* Variant 1:
* **********
* > myEmitter.off('myEvent', myHandler);
*
* @param {string} event The event to unbind the handler from.
* @param {function} handler The function to unbind.
* @return {Emitter} Returns this.
*
* Variant 2:
* **********
* > myEmitter.off(['myEvent1', 'myEvent2'], myHandler);
*
* @param {array} events The events to unbind the handler from.
* @param {function} handler The function to unbind.
* @return {Emitter} Returns this.
*
* Variant 3:
* **********
* > myEmitter.off({
* > myEvent1: myHandler1,
* > myEvent2: myHandler2
* > });
*
* @param {object} bindings An object containing pairs event / function.
* @return {Emitter} Returns this.
*
* Variant 4:
* **********
* > myEmitter.off(myHandler);
*
* @param {function} handler The function to unbind from every events.
* @return {Emitter} Returns this.
*/
Emitter.prototype.off = function(events, handler) {
var i,
n,
j,
m,
k,
a,
event,
eArray = typeof events === 'string' ?
[events] :
events;
if (arguments.length === 1 && typeof eArray === 'function') {
handler = arguments[0];
// Handlers bound to events:
for (k in this._handlers) {
a = [];
for (i = 0, n = this._handlers[k].length; i !== n; i += 1)
if (this._handlers[k][i].handler !== handler)
a.push(this._handlers[k][i]);
this._handlers[k] = a;
}
a = [];
for (i = 0, n = this._handlersAll.length; i !== n; i += 1)
if (this._handlersAll[i].handler !== handler)
a.push(this._handlersAll[i]);
this._handlersAll = a;
}
else if (arguments.length === 2) {
for (i = 0, n = eArray.length; i !== n; i += 1) {
event = eArray[i];
if (this._handlers[event]) {
a = [];
for (j = 0, m = this._handlers[event].length; j !== m; j += 1)
if (this._handlers[event][j].handler !== handler)
a.push(this._handlers[event][j]);
this._handlers[event] = a;
}
if (this._handlers[event] && this._handlers[event].length === 0)
delete this._handlers[event];
}
}
return this;
};
/**
* This method unbinds every handlers attached to every or any events. So,
* these functions will no more be executed when the related events are
* emitted. If the functions were not bound to the events, nothing will
* happen, and no error will be thrown.
*
* Usage:
* ******
* > myEmitter.unbindAll();
*
* @return {Emitter} Returns this.
*/
Emitter.prototype.unbindAll = function() {
var k;
this._handlersAll = [];
for (k in this._handlers)
delete this._handlers[k];
return this;
};
/**
* This method emits the specified event(s), and executes every handlers bound
* to the event(s).
*
* Use cases:
* **********
* > myEmitter.emit('myEvent');
* > myEmitter.emit('myEvent', myData);
* > myEmitter.emit(['myEvent1', 'myEvent2']);
* > myEmitter.emit(['myEvent1', 'myEvent2'], myData);
*
* @param {string|array} events The event(s) to emit.
* @param {object?} data The data.
* @return {Emitter} Returns this.
*/
Emitter.prototype.emit = function(events, data) {
var i,
n,
j,
m,
z,
a,
event,
child,
handlers,
eventName,
self = this,
eArray = typeof events === 'string' ?
[events] :
events;
// Check that the emitter is enabled:
if (!this._enabled)
return this;
data = data === undefined ? {} : data;
for (i = 0, n = eArray.length; i !== n; i += 1) {
eventName = eArray[i];
handlers = (this._handlers[eventName] || []).concat(this._handlersAll);
if (handlers.length) {
event = {
type: eventName,
data: data || {},
target: this
};
a = [];
for (j = 0, m = handlers.length; j !== m; j += 1) {
// We have to verify that the handler still exists in the array,
// as it might have been mutated already
if (
(
this._handlers[eventName] &&
this._handlers[eventName].indexOf(handlers[j]) >= 0
) ||
this._handlersAll.indexOf(handlers[j]) >= 0
) {
handlers[j].handler.call(
'scope' in handlers[j] ? handlers[j].scope : this,
event
);
// Since the listener callback can mutate the _handlers,
// we register the handlers we want to remove, not the ones
// we want to keep
if (handlers[j].once)
a.push(handlers[j]);
}
}
// Go through handlers to remove
for (z = 0; z < a.length; z++) {
this._handlers[eventName].splice(a.indexOf(a[z]), 1);
}
}
}
// Events propagation:
for (i = 0, n = this._children.length; i !== n; i += 1) {
child = this._children[i];
child.emit.apply(child, arguments);
}
return this;
};
/**
* This method creates a new instance of Emitter and binds it as a child. Here
* is what children do:
* - When the parent emits an event, the children will emit the same later
* - When a child is killed, it is automatically unreferenced from the parent
* - When the parent is killed, all children will be killed as well
*
* @return {Emitter} Returns the fresh new child.
*/
Emitter.prototype.child = function() {
var self = this,
child = new Emitter();
child.on('emmett:kill', function() {
if (self._children)
for (var i = 0, l = self._children.length; i < l; i++)
if (self._children[i] === child) {
self._children.splice(i, 1);
break;
}
});
this._children.push(child);
return child;
};
/**
* This returns an array of handler functions corresponding to the given
* event or every handler functions if an event were not to be given.
*
* @param {?string} event Name of the event.
* @return {Emitter} Returns this.
*/
function mapHandlers(a) {
var i, l, h = [];
for (i = 0, l = a.length; i < l; i++)
h.push(a[i].handler);
return h;
}
Emitter.prototype.listeners = function(event) {
var handlers = [],
k,
i,
l;
// If no event is passed, we return every handlers
if (!event) {
handlers = mapHandlers(this._handlersAll);
for (k in this._handlers)
handlers = handlers.concat(mapHandlers(this._handlers[k]));
// Retrieving handlers per children
for (i = 0, l = this._children.length; i < l; i++)
handlers = handlers.concat(this._children[i].listeners());
}
// Else we only retrieve the needed handlers
else {
handlers = mapHandlers(this._handlers[event]);
// Retrieving handlers per children
for (i = 0, l = this._children.length; i < l; i++)
handlers = handlers.concat(this._children[i].listeners(event));
}
return handlers;
};
/**
* This method will first dispatch a "emmett:kill" event, and then unbinds all
* listeners and make it impossible to ever rebind any listener to any event.
*/
Emitter.prototype.kill = function() {
this.emit('emmett:kill');
this.unbindAll();
this._handlers = null;
this._handlersAll = null;
this._enabled = false;
if (this._children)
for (var i = 0, l = this._children.length; i < l; i++)
this._children[i].kill();
this._children = null;
};
/**
* This method disabled the emitter, which means its emit method will do
* nothing.
*
* @return {Emitter} Returns this.
*/
Emitter.prototype.disable = function() {
this._enabled = false;
return this;
};
/**
* This method enables the emitter.
*
* @return {Emitter} Returns this.
*/
Emitter.prototype.enable = function() {
this._enabled = true;
return this;
};
/**
* Version:
*/
Emitter.version = '2.1.2';
// Export:
artoo.emitter = Emitter;
}).call(this);
;(function(undefined) {
'use strict';
/**
* artoo Node.js utilities
* ========================
*
* Some useful utilities when using artoo.js within node.
*/
var cheerio = require('cheerio'),
path = require('path');
// Setting initial context
artoo.$ = cheerio.load('');
// Methods
artoo.bootstrap = function(cheerioInstance) {
['scrape', 'scrapeOne', 'scrapeTable'].forEach(function(m) {
cheerioInstance.prototype[m] = function() {
return artoo[m].apply(
artoo, [artoo.$(this)].concat(Array.prototype.slice.call(arguments)));
};
});
};
artoo.bootstrap(cheerio);
artoo.setContext = function($) {
// Fixing context
artoo.$ = $;
};
// Giving paths to alternative lib versions so they can be used afterwards
artoo.paths = {
browser: path.join(__dirname, 'artoo.concat.js'),
chrome: path.join(__dirname, 'artoo.chrome.js'),
phantom: path.join(__dirname, 'artoo.phantom.js')
};
}).call(this);
;(function(undefined) {
'use strict';
/**
* artoo helpers
* ==============
*
* Some useful helpers.
*/
var _root = this;
// Extending Emmett
Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
obj.__proto__ = proto;
return obj;
};
var ee = new artoo.emitter();
Object.setPrototypeOf(artoo, Object.getPrototypeOf(ee));
// Legacy support
// TODO: drop this asap
artoo.hooks = {
trigger: function(name) {
artoo.emit(name);
}
};
/**
* Generic Helpers
* ----------------
*
* Some basic helpers from collection handling to type checking.
*/
// Useless function
function noop() {}
// Recursively extend objects
function extend() {
var i,
k,
res = {},
l = arguments.length;
for (i = l - 1; i >= 0; i--)
for (k in arguments[i])
if (res[k] && isPlainObject(arguments[i][k]))
res[k] = extend(arguments[i][k], res[k]);
else
res[k] = arguments[i][k];
return res;
}
// Is the var an array?
function isArray(v) {
return v instanceof Array;
}
// Is the var an object?
function isObject(v) {
return v instanceof Object;
}
// Is the var a real NaN
function isRealNaN(v) {
return isNaN(v) && (typeof v === 'number');
}
// Is the var a plain object?
function isPlainObject(v) {
return v instanceof Object &&
!(v instanceof Array) &&
!(v instanceof Function);
}
// Is a var non primitive?
function isNonPrimitive(v) {
return isPlainObject(v) || isArray(v);
}
// Is a var primitive?
function isPrimitive(v) {
return !isNonScalar(v);
}
// Get first item of array returning true to given function
function first(a, fn, scope) {
for (var i = 0, l = a.length; i < l; i++) {
if (fn.call(scope || null, a[i]))
return a[i];
}
return;
}
// Get the index of an element in an array by function
function indexOf(a, fn, scope) {
for (var i = 0, l = a.length; i < l; i++) {
if (fn.call(scope || null, a[i]))
return i;
}
return -1;
}
/**
* Document Helpers
* -----------------
*
* Functions to deal with DOM selection and the current document.
*/
// Checking whether a variable is a jQuery selector
function isSelector(v) {
return (artoo.$ && v instanceof artoo.$) ||
(jQuery && v instanceof jQuery) ||
($ && v instanceof $);
}
// Checking whether a variable is a DOM document
function isDocument(v) {
return v instanceof HTMLDocument ||
v instanceof XMLDocument;
}
// Get either string or document and return valid jQuery selection
function jquerify(v) {
var $ = artoo.$;
if (isDocument(v))
return $(v);
return $('<div />').append(v);
}
// Creating an HTML or XML document
function createDocument(root, namespace) {
if (!root)
return document.implementation.createHTMLDocument();
else
return document.implementation.createDocument(
namespace || null,
root,
null
);
}
// Loading an external file the same way the browser would load it from page
function getScript(url, async, cb) {
if (typeof async === 'function') {
cb = async;
async = false;
}
var el = document.createElement('script');
// Script attributes
el.type = 'text/javascript';
el.src = url;
// Should the script be loaded asynchronously?
if (async)
el.async = true;
// Defining callbacks
el.onload = el.onreadystatechange = function() {
if ((!this.readyState ||
this.readyState == 'loaded' ||
this.readyState == 'complete')) {
el.onload = el.onreadystatechange = null;
// Removing element from head
artoo.mountNode.removeChild(el);
if (typeof cb === 'function')
cb();
}
};
// Appending the script to head
artoo.mountNode.appendChild(el);
}
// Loading an external stylesheet
function getStylesheet(data, isUrl, cb) {
var el = document.createElement(isUrl ? 'link' : 'style'),
head = document.getElementsByTagName('head')[0];
el.type = 'text/css';
if (isUrl) {
el.href = data;
el.rel = 'stylesheet';
// Waiting for script to load
el.onload = el.onreadystatechange = function() {
if ((!this.readyState ||
this.readyState == 'loaded' ||
this.readyState == 'complete')) {
el.onload = el.onreadystatechange = null;
if (typeof cb === 'function')
cb();
}
};
}
else {
el.innerHTML = data;
}
// Appending the stylesheet to head
head.appendChild(el);
}
var globalsBlackList = [
'__commandLineAPI',
'applicationCache',
'chrome',
'closed',
'console',
'crypto',
'CSS',
'defaultstatus',
'defaultStatus',
'devicePixelRatio',
'document',
'external',
'frameElement',
'history',
'indexedDB',
'innerHeight',
'innerWidth',
'length',
'localStorage',
'location',
'name',
'offscreenBuffering',
'opener',
'outerHeight',
'outerWidth',
'pageXOffset',
'pageYOffset',
'performance',
'screen',
'screenLeft',
'screenTop',
'screenX',
'screenY',
'scrollX',
'scrollY',
'sessionStorage',
'speechSynthesis',
'status',
'styleMedia'
];
function getGlobalVariables() {
var p = Object.getPrototypeOf(_root),
o = {},
i;
for (i in _root)
if (!~i.indexOf('webkit') &&
!(i in p) &&
_root[i] !== _root &&
!(_root[i] instanceof BarProp) &&
!(_root[i] instanceof Navigator) &&
!~globalsBlackList.indexOf(i))
o[i] = _root[i];
return o;
}
/**
* Async Helpers
* --------------
*
* Some helpful functions to deal with asynchronous matters.
*/
// Waiting for something to happen
function waitFor(check, cb, params) {
params = params || {};
if (typeof cb === 'object') {
params = cb;
cb = params.done;
}
var milliseconds = params.interval || 30,
j = 0;
var i = setInterval(function() {
if (check()) {
clearInterval(i);
cb(null);
}
if (params.timeout && params.timeout - (j * milliseconds) <= 0) {
clearInterval(i);
cb(new Error('timeout'));
}
j++;
}, milliseconds);
}
// Dispatch asynchronous function
function async() {
var args = Array.prototype.slice.call(arguments);
return setTimeout.apply(null, [args[0], 0].concat(args.slice(1)));
}
// Launching tasks in parallel with an optional limit
function parallel(tasks, params, last) {
var onEnd = (typeof params === 'function') ? params : params.done || last,
running = [],
results = [],
d = 0,
t,
l,
i;
if (typeof onEnd !== 'function')
onEnd = noop;
function cleanup() {
running.forEach(function(r) {
clearTimeout(r);
});
}
function onTaskEnd(err, result) {
// Adding results to accumulator
results.push(result);
if (err) {
cleanup();
return onEnd(err, results);
}
if (++d >= tasks.length) {
// Parallel action is finished, returning
return onEnd(null, results);
}
// Adding on stack
t = tasks[i++];
running.push(async(t, onTaskEnd));
}
for (i = 0, l = params.limit || tasks.length; i < l; i++) {
t = tasks[i];
// Dispatching the function asynchronously
running.push(async(t, onTaskEnd));
}
}
/**
* Monkey Patching
* ----------------
*
* Some monkey patching shortcuts. Useful for sniffers and overriding
* native functions.
*/
function before(targetFunction, beforeFunction) {
// Replacing the target function
return function() {
// Applying our function
beforeFunction.apply(this, Array.prototype.slice.call(arguments));
// Applying the original function
return targetFunction.apply(this, Array.prototype.slice.call(arguments));
};
}
/**
* Exportation
* ------------
*/
// Exporting to artoo root
artoo.injectScript = function(url, cb) {
getScript(url, cb);
};
artoo.injectStyle = function(url, cb) {
getStylesheet(url, true, cb);
};
artoo.injectInlineStyle = function(text) {
getStylesheet(text, false);
};
artoo.waitFor = waitFor;
artoo.getGlobalVariables = getGlobalVariables;
// Exporting to artoo helpers
artoo.helpers = {
before: before,
createDocument: createDocument,
extend: extend,
first: first,
indexOf: indexOf,
isArray: isArray,
isDocument: isDocument,
isObject: isObject,
isPlainObject: isPlainObject,
isRealNaN: isRealNaN,
isSelector: isSelector,
isNonPrimitive: isNonPrimitive,
isPrimitive: isPrimitive,
jquerify: jquerify,
noop: noop,
parallel: parallel
};
}).call(this);
;(function(undefined) {
'use strict';
/**
* artoo parsers
* ==============
*
* Compilation of small parsers aim at understanding some popular web
* string formats such as querystrings, headers etc.
*/
function parseQueryString(s) {
var data = {};
s.split('&').forEach(function(item) {
var pair = item.split('=');
data[decodeURIComponent(pair[0])] =
pair[1] ? decodeURIComponent(pair[1]) : true;
});
return data;
}
function parseUrl(url) {
var data = {href: url};
// Searching for a protocol
var ps = url.split('://');
if (ps.length > 1)
data.protocol = ps[0];
url = ps[ps.length > 1 ? 1 : 0];
// Searching for an authentification
var a = url.split('@');
if (a.length > 1) {
var as = a[0].split(':');
if (as.length > 1) {
data.auth = {
user: as[0],
password: as[1]
};
}
else {
data.auth = {
user: as[0]
};
}
url = a[1];
}
// Searching for origin
var m = url.match(/([^\/:]+)(.*)/);
data.host = m[1];
data.hostname = m[1];
if (m[2]) {
var f = m[2].trim();
// Port
if (f.charAt(0) === ':') {
data.port = +f.match(/\d+/)[0];
data.host += ':' + data.port;
}
// Path
data.path = '/' + f.split('/').slice(1).join('/');
data.pathname = data.path.split('?')[0].split('#')[0];
}
// Tld
if (~data.hostname.search('.')) {
var ds = data.hostname.split('.');
// Check for IP
if (!(ds.length === 4 &&
ds.every(function(i) { return !isNaN(+i); }))) {
// Checking TLD-less urls
if (ds.length > 1) {
// TLD
data.tld = ds[ds.length - 1];
// Domain
data.domain = ds[ds.length - 2];
// Subdomains
if (ds.length > 2) {
data.subdomains = [];
for (var i = 0, l = ds.length - 2; i < l; i++)
data.subdomains.unshift(ds[i]);
}
}
else {
// TLD-less url
data.domain = ds[0];
}
}
else {
// This is an IP
data.domain = data.hostname;
}
}
// Hash
var hs = url.split('#');
if (hs.length > 1) {
data.hash = '#' + hs[1];
}
// Querystring
var qs = url.split('?');
if (qs.length > 1) {
data.search = '?' + qs[1];
data.query = parseQueryString(qs[1]);
}
// Extension
var ss = data.pathname.split('/'),
es = ss[ss.length - 1].split('.');
if (es.length > 1)
data.extension = es[es.length - 1];
return data;
}
function parseHeaders(headers) {
var data = {};
headers.split('\n').filter(function(item) {
return item.trim();
}).forEach(function(item) {
if (item) {
var pair = item.split(': ');
data[pair[0]] = pair[1];
}
});
return data;
}
function parseCookie(s) {
var cookie = {
httpOnly: false,
secure: false
};
if (!s.trim())
return;
s.split('; ').forEach(function(item) {
// Path
if (~item.search(/path=/i)) {
cookie.path = item.split('=')[1];
}
else if (~item.search(/expires=/i)) {
cookie.expires = item.split('=')[1];
}
else if (~item.search(/httponly/i) && !~item.search('=')) {
cookie.httpOnly = true;
}
else if (~item.search(/secure/i) && !~item.search('=')) {
cookie.secure = true;
}
else {
var is = item.split('=');
cookie.key = is[0];
cookie.value = decodeURIComponent(is[1]);
}
});
return cookie;
}
function parseCookies(s) {
var cookies = {};
if (!s.trim())
return cookies;
s.split('; ').forEach(function(item) {
var pair = item.split('=');
cookies[pair[0]] = decodeURIComponent(pair[1]);
});
return cookies;
}
/**
* Exporting
*/
artoo.parsers = {
cookie: parseCookie,
cookies: parseCookies,
headers: parseHeaders,
queryString: parseQueryString,
url: parseUrl
};
}).call(this);
;(function(undefined) {
'use strict';
/**
* artoo writers
* ==============
*
* Compilation of writers for popular formats such as CSV or YAML.
*/
// Dependencies
var isPlainObject = artoo.helpers.isPlainObject,
isArray = artoo.helpers.isArray,
isPrimitive = artoo.helpers.isPrimitive,
isNonPrimitive = artoo.helpers.isNonPrimitive,
isRealNaN = artoo.helpers.isRealNaN;
/**
* CSV
* ---
*
* Converts an array of array or array of objects into a correct
* CSV string for exports purposes.
*
* Exposes some handful options such as choice of delimiters or order
* of keys to handle.
*/
// Convert an object into an array of its properties
function objectToArray(o, order) {
order = order || Object.keys(o);
return order.map(function(k) {
return o[k];
});
}
// Retrieve an index of keys present in an array of objects
function keysIndex(a) {
var keys = [],
l,
k,
i;
for (i = 0, l = a.length; i < l; i++)
for (k in a[i])
if (!~keys.indexOf(k))
keys.push(k);
return keys;
}
// Escape a string for a RegEx
function rescape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
// Converting an array of arrays into a CSV string
function toCSVString(data, params) {
params = params || {};
var header = params.headers || [],
plainObject = isPlainObject(data[0]),
keys = plainObject && (params.order || keysIndex(data)),
oData,
i;
// Defaults
var escape = params.escape || '"',
delimiter = params.delimiter || ',';
// Dealing with headers polymorphism
if (!header.length)
if (plainObject && params.headers !== false)
header = keys;
// Should we append headers
oData = (header.length ? [header] : []).concat(
plainObject ?
data.map(function(e) { return objectToArray(e, keys); }) :
data
);
// Converting to string
return oData.map(function(row) {
return row.map(function(item) {
// Wrapping escaping characters
var i = ('' + (typeof item === 'undefined' ? '' : item)).replace(
new RegExp(rescape(escape), 'g'),
escape + escape
);
// Escaping if needed
return ~i.indexOf(delimiter) || ~i.indexOf(escape) || ~i.indexOf('\n') ?
escape + i + escape :
i;
}).join(delimiter);
}).join('\n');
}
/**
* YAML
* ----
*
* Converts JavaScript data into a YAML string for export purposes.
*/
// Characters to escape in YAML
var ymlEscape = /[:#,\-\[\]\{\}&%]|!{1,2}/;
// Creating repeating sequences
function repeatString(string, nb) {
var s = string,
l,
i;
if (nb <= 0)
return '';
for (i = 1, l = nb | 0; i < l; i++)
s += string;
return s;
}
// YAML conversion
var yml = {
string: function(string) {
return (~string.search(ymlEscape)) ?
'\'' + string.replace(/'/g, '\'\'') + '\'' :
string;
},
number: function(nb) {
return '' + nb;
},
array: function(a, lvl) {
lvl = lvl || 0;
if (!a.length)
return '[]';
var string = '',
l,
i;
for (i = 0, l = a.length; i < l; i++) {
string += repeatString(' ', lvl);
if (isPrimitive(a[i])) {
string += '- ' + processYAMLVariable(a[i]) + '\n';
}
else {
if (isPlainObject(a[i]))
string += '-' + processYAMLVariable(a[i], lvl + 1, true);
else
string += processYAMLVariable(a[i], lvl + 1);
}
}
return string;
},
object: function(o, lvl, indent) {
lvl = lvl || 0;
if (!Object.keys(o).length)
return (lvl ? '- ' : '') + '{}';
var string = '',
key,
c = 0,
i;
for (i in o) {
key = yml.string(i);
string += repeatString(' ', lvl);
if (indent && !c)
string = string.slice(0, -1);
string += key + ': ' + (isNonPrimitive(o[i]) ? '\n' : '') +
processYAMLVariable(o[i], lvl + 1) + '\n';
c++;
}
return string;
},
fn: function(fn) {
return yml.string(fn.toString());
},
boolean: function(v) {
return '' + v;
},
nullValue: function(v) {
return '~';
}
};
// Get the correct handler corresponding to variable type
function processYAMLVariable(v, lvl, indent) {
// Scalars
if (typeof v === 'string')
return yml.string(v);
else if (typeof v === 'number')
return yml.number(v);
else if (typeof v === 'boolean')
return yml.boolean(v);
else if (typeof v === 'undefined' || v === null || isRealNaN(v))
return yml.nullValue(v);
// Nonscalars
else if (isPlainObject(v))
return yml.object(v, lvl, indent);
else if (isArray(v))
return yml.array(v, lvl);
else if (typeof v === 'function')
return yml.fn(v);
// Error
else
throw TypeError('artoo.writers.processYAMLVariable: wrong type.');
}
// Converting JavaScript variables to a YAML string
function toYAMLString(data) {
return '---\n' + processYAMLVariable(data);
}
/**
* Web Formats
* ------------
*
* Converts JavaScript data into standard web formats such as querystrings.
*/
function toQueryString(o, fn) {
if (!isPlainObject(o))
throw Error('artoo.writers.queryString: wrong arguments.');
var s = '',
k;
for (k in o) {
s +=
(s ? '&' : '') +
k + '=' +
encodeURIComponent(typeof fn === 'function' ? fn(o[k]) : o[k]);
}
return s;
}
function toCookie(key, value, params) {
params = params || {};
var cookie = key + '=' + encodeURIComponent(value);
if (params.days) {
var date = new Date();
date.setTime(date.getTime() + (params.days * 24 * 60 * 60 * 1000));
cookie += '; expires=' + date.toGMTString();
}
if (params.path)
cookie += '; path=' + params.path;
if (params.domain)
cookie += '; domain=' + params.domain;
if (params.httpOnly)
cookie += '; HttpOnly';
if (params.secure)
cookie += '; Secure';
return cookie;
}
/**
* Exporting
*/
artoo.writers = {
cookie: toCookie,
csv: toCSVString,
queryString: toQueryString,
yaml: toYAMLString
};
}).call(this);
;(function(undefined) {
'use strict';
/**
* artoo helpers
* ==============
*
* Replacing some helpers by their node.js counterparts.
*/
var _root = this;
// False function
artoo.helpers.isDocument = function(v) {
return false;
};
// Is this a cheerio selector?
artoo.helpers.isSelector = function(v) {
return !!(v && v.prototype && v.prototype.cheerio &&
v.prototype.cheerio === '[cheerio object]') ||
!!(v._root && v.options && 'normalizeWhitespace' in v.options);
};
}).call(this);
;(function(undefined) {
'use strict';
/**
* artoo scrape methods
* =====================
*
* Some scraping helpers.
*/
var _root = this,
extend = artoo.helpers.extend;
/**
* Helpers
*/
function step(o, scope) {
var $ = artoo.$,
$sel = o.sel ? $(scope).find(o.sel) : $(scope),
val;
// Polymorphism
if (typeof o === 'function') {
val = o.call(scope, $);
}
else if (typeof o.method === 'function')
val = o.method.call($sel.get(), $);
else if (typeof o === 'string') {
if (typeof $sel[o] === 'function')
val = $sel[o]();
else
val = $sel.attr(o);
}
else {
val = (o.attr !== undefined) ?
$sel.attr(o.attr) :
$sel[o.method || 'text']();
}
// Default value?
if (o.defaultValue && !val)
val = o.defaultValue;
return val;
}
// Scraping function after polymorphism has been taken care of
function scrape(iterator, data, params, cb) {
var $ = artoo.$,
scraped = [],
loneSelector = !!data.attr || !!data.method || data.scrape ||
typeof data === 'string' ||
typeof data === 'function';
params = params || {};
// Transforming to selector
var $iterator;
if (typeof iterator === 'function')
$iterator = $(iterator($));
else
$iterator = $(iterator);
// Iteration
$iterator.each(function(i) {
var item = {},
p;
// TODO: figure iteration scope elsewhere for scrape recursivity
if (loneSelector)
item = (typeof data === 'object' && 'scrape' in data) ?
scrape(
(data.sel ? $(this).find(data.sel) : $(this))
.find(data.scrape.iterator),
data.scrape.data,
data.scrape.params
) :
step(data, this);
else
for (p in data) {
item[p] = (typeof data[p] === 'object' && 'scrape' in data[p]) ?
scrape(
(data[p].sel ? $(this).find(data[p].sel) : $(this))
.find(data[p].scrape.iterator),
data[p].scrape.data,
data[p].scrape.params
) :
step(data[p], this);
}
scraped.push(item);
// Breaking if limit i attained
return !params.limit || i < params.limit - 1;
});
scraped = params.one ? scraped[0] : scraped;
// Triggering callback
if (typeof cb === 'function')
cb(scraped);
// Returning data
return scraped;
}
// Function taking care of harsh polymorphism
function polymorphism(iterator, data, params, cb) {
var h = artoo.helpers,
i, d, p, c;
if (h.isPlainObject(iterator) &&
!h.isSelector(iterator) &&
!h.isDocument(iterator) &&
(iterator.iterator || iterator.data || iterator.params)) {
d = iterator.data;
p = h.isPlainObject(iterator.params) ? iterator.params : {};
i = iterator.iterator;
}
else {
d = data;
p = h.isPlainObject(params) ? params : {};
i = iterator;
}
// Default values
d = d || 'text';
c = typeof cb === 'function' ? cb :
typeof params === 'function' ? params :
p.done;
return [i, d, p, c];
}
/**
* Public interface
*/
artoo.scrape = function(iterator, data, params, cb) {
var args = polymorphism(iterator, data, params, cb);
// Warn if no iterator or no data
if (!args[0] || !args[1])
throw TypeError('artoo.scrape: wrong arguments.');
return scrape.apply(this, args);
};
// Scrape only the first corresponding item
artoo.scrapeOne = function(iterator, data, params, cb) {
var args = polymorphism(iterator, data, params, cb);
// Extending parameters
args[2] = artoo.helpers.extend(args[2], {limit: 1, one: true});
return scrape.apply(this, args);
};
// Scrape a table
// TODO: handle different contexts
// TODO: better header handle
artoo.scrapeTable = function(root, params, cb) {
params = params || {};
var sel = typeof root !== 'string' ? root.selector : root,
headers;
if (!params.headers) {
return artoo.scrape(sel + ' tr:has(td)', {
scrape: {
iterator: 'td',
data: params.data || 'text'
}
}, params, cb);
}
else {
var headerType = params.headers.type ||
params.headers.method && 'first' ||
params.headers,
headerFn = params.headers.method;
if (headerType === 'th') {
headers = artoo.scrape(
sel + ' th', headerFn || 'text'
);
}
else if (headerType === 'first') {
headers = artoo.scrape(
sel + ' tr:has(td):first td',
headerFn || 'text'
);
}
else if (artoo.helpers.isArray(headerType)) {
headers = headerType;
}
else {
throw TypeError('artoo.scrapeTable: wrong headers type.');
}
// Scraping
return artoo.scrape(
sel + ' tr:has(td)' +
(headerType === 'first' ? ':not(:first)' : ''), function() {
var o = {};
headers.forEach(function(h, i) {
o[h] = step(
params.data || 'text',
$(this).find('td:eq(' + i + ')')
);
}, this);
return o;
}, params, cb);
}
};
/**
* jQuery plugin
*/
function _scrape($) {
var methods = ['scrape', 'scrapeOne', 'scrapeTable'];
methods.forEach(function(method) {
$.fn[method] = function() {
return artoo[method].apply(
artoo, [$(this)].concat(Array.prototype.slice.call(arguments)));
};
});
}
// Exporting
artoo.jquery.plugins.push(_scrape);
}).call(this);
/**
* artoo node.js require
* ======================
*
* Simply exporting artoo through a node module.
*/
module.exports = artoo;
|
$(document).ready( function() {
// Setup the datepickers
$('#date_start').datepicker({
dateFormat: 'dd/mm/yy',
minDate: 0,
onSelect: function( selectedDate ) {
$( "#end_date" ).datepicker( 'option', 'minDate', selectedDate );
}
});
$('#end_date').datepicker({
dateFormat: 'dd/mm/yy'
});
// Setup the time pickers
$('.user_event_time').clockpicker({
donetext: 'Done',
autoclose: true,
'default': 'now'
});
$('.user_event_time_end').clockpicker({
donetext: 'Done',
autoclose: true,
'default': 'now'
});
$("#user_event_image").change(readURL);
// If localstorage is available
if(lsTest() === true){
if (localStorage.getItem("wceUser") !== null){
fetchUserDetails();
}
$("#submission-btn").hover(saveUserDetails);
}
});
// Retrieve user details from localstorage
function fetchUserDetails() {
var lsUser = localStorage.getItem('wceUser');
var user = JSON.parse(lsUser);
if (isRealValue(user)){
$('#user_event_first_name').val(user.first);
$('#user_event_last_name').val(user.last);
$('#user_event_user_email').val(user.email);
}
}
// Save user details to localstorage
function saveUserDetails() {
var user = {
'first': $('#user_event_first_name').val(),
'last': $('#user_event_last_name').val(),
'email': $('#user_event_user_email').val()
};
localStorage.setItem('wceUser', JSON.stringify(user));
}
// Check an object for null
function isRealValue(obj){
return obj && obj !== "null" && obj!== "undefined";
}
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
|
// Generated by CoffeeScript 1.12.6
(function() {
'use strict';
module.exports = function(dd) {
var errorHash;
errorHash = dd.helper.requireSafe('lib/code/errors');
return dd.drive([
{
it: "returns false if no errors found",
i: [errorHash, ['title', dd.helper.f, 'name', true]],
e: false
}, {
it: "delegates found errors output to test engine and returns true",
i: [errorHash, ['title', null, 'name', false]],
e: true
}
]);
};
}).call(this);
|
describe("Thermostat", function() {
var thermostat;
beforeEach(function() {
thermostat = new Thermostat();
});
it("starts with a temperature of 20 degrees", function() {
expect(thermostat.getCurrentTemperature()).toEqual(20);
});
it("increases the temperature with the up button", function() {
thermostat.up();
expect(thermostat.getCurrentTemperature()).toEqual(21);
});
it("decreases the temperature with the down button", function() {
thermostat.down();
expect(thermostat.getCurrentTemperature()).toEqual(19);
});
it("has a minimum temperature of 10 degrees", function(){
for (var i = 0; i < 11; i++) {
thermostat.down();
}
expect(thermostat.getCurrentTemperature()).toEqual(10);
});
it("can turn powerSaving off", function() {
thermostat.switchPowerSaving();
expect(thermostat.isPowerSavingOn()).toBe(false);
});
it("can turn powerSaving on", function() {
thermostat.switchPowerSaving();
thermostat.switchPowerSaving();
expect(thermostat.isPowerSavingOn()).toBe(true);
});
it("resets the temperature to 20", function() {
for(var i = 0; i < 6; i++) {
thermostat.up();
}
thermostat.resetTemp();
expect(thermostat.getCurrentTemperature()).toEqual(20);
});
describe("gives the level of energy usage according to temperature", function() {
it("returns medium when the temperature is between 18 to 25", function() {
expect(thermostat.energyUsage()).toEqual("medium");
});
it("returns low when the temperature is 18 or less", function() {
for(var i = 0; i < 3; i--) {
thermostat.down();
}
expect(thermostat.energyUsage()).toEqual("low");
});
it("returns high when the temperature is 25 or more", function() {
for(var i = 0; i < 6; i++) {
thermostat.up();
}
expect(thermostat.energyUsage()).toEqual("high");
});
});
describe("powerSaving off", function() {
beforeEach(function() {
thermostat.switchPowerSaving();
});
it("has a maximum temperature of 32 degrees", function() {
for(var i = 0; i < 13; i++) {
thermostat.up();
}
expect(thermostat.getCurrentTemperature()).toEqual(32);
});
});
describe("powerSaving mode", function() {
it("has a power saving mode on by default", function() {
expect(thermostat.isPowerSavingOn()).toBe(true);
});
it("has a maximum temperature of 25 degrees", function() {
for(var i = 0; i < 6; i++) {
thermostat.up();
}
expect(thermostat.getCurrentTemperature()).toEqual(25);
});
});
});
|
import {Command} from "./Command";
export class MaintainerCommand extends Command {
constructor(instruction) {
super();
this.instruction = instruction;
}
buildInstruction() {
return `MAINTAINER ${this.instruction}`;
}
}
|
var fs = require('fs');
var should = require('should');
var jsdom = require('jsdom').jsdom;
require('jsdom').defaultDocumentFeatures = {
FetchExternalResources: false,
ProcessExternalResources: false
};
var TestUtils = require('./test_utils.js');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var Utils = require('../src/common/utils.js').Utils;
var HighscorePage = require('../src/common/highscore_page.js').HighscorePage;
describe('HighscorePage', function() {
var utils = new Utils(XMLHttpRequest);
var highscorePage = new HighscorePage(utils);
describe('#parse', function() {
beforeEach(function() {
highscorePage = new HighscorePage(utils);
});
it('should not find highscores div', function(done) {
global.document = jsdom('');
highscorePage.parse(function(err) {
err.should.equal('Highscores div not found');
highscorePage.elements.should.eql({});
done();
});
});
it('should not find world', function(done) {
global.document = jsdom('<div id="highscores"></div>');
highscorePage.parse(function(err) {
err.should.equal('No world found');
highscorePage.elements.should.have.keys('highscores_div');
done();
});
});
it('should parse Antica', function(done) {
var data = fs.readFileSync(__dirname + '/files/highscore_page_antica_magic.html', 'utf8');
global.document = jsdom(data);
highscorePage.parse(function(err) {
should.not.exist(err);
highscorePage.list.should.equal('Magic Level');
highscorePage.world.should.equal('Antica');
highscorePage.elements.should.have.keys('highscores_div');
done();
});
});
it('should fetch and parse Aurera', function(done) {
this.timeout(5000);
utils.fetch('http://www.tibia.com/community/?subtopic=highscores&world=Aurera', function(err, data) {
should.not.exist(err);
global.document = jsdom(data);
highscorePage.parse(function(err) {
should.not.exist(err);
highscorePage.list.should.equal('Experience');
highscorePage.world.should.equal('Aurera');
highscorePage.elements.should.have.keys('highscores_div');
done();
});
});
});
it('should fetch and parse Inferna secure', function(done) {
this.timeout(5000);
utils.fetch('http://www.tibia.com/community/?subtopic=highscores&world=Inferna', function(err, data) {
should.not.exist(err);
global.document = jsdom(data);
highscorePage.parse(function(err) {
should.not.exist(err);
highscorePage.list.should.equal('Experience');
highscorePage.world.should.equal('Inferna');
highscorePage.elements.should.have.keys('highscores_div');
done();
});
});
});
});
describe('#update', function() {
beforeEach(function() {
highscorePage = new HighscorePage(utils);
});
it('should update Antica', function(done) {
var data = fs.readFileSync(__dirname + '/files/highscore_page_antica_experience.html', 'utf8');
global.document = jsdom(data);
highscorePage.parse(function(err) {
should.not.exist(err);
highscorePage.list.should.equal('Experience');
highscorePage.world.should.equal('Antica');
highscorePage.elements.should.have.keys('highscores_div');
// Update with first and last player in the list
highscorePage.update({
'Meendel': {
level: 11,
vocation: 'Royal Paladin'
},
'Linglifer': {
level: 427,
vocation: 'Master Sorcerer'
}
});
var meendel_found = false;
var linglifer_found = false;
var links = highscorePage.elements.highscores_div.getElementsByTagName('a');
var link_exp = /https:\/\/secure\.tibia\.com\/community\/\?subtopic=characters&name=.+/;
for (var i = 0, j = links.length; i < j; i++) {
if (link_exp.test(links[i].href)) {
var name = utils.decode(links[i].innerHTML);
var level_column = links[i].parentElement.parentElement.getElementsByTagName('td')[2];
if (name === 'Meendel') {
meendel_found = true;
TestUtils.rgbToHex(links[i].style.color).should.equal(utils.color.green);
level_column.textContent.should.equal('11 (-500)');
} else if (name === 'Linglifer') {
linglifer_found = true;
TestUtils.rgbToHex(links[i].style.color).should.equal(utils.color.green);
level_column.textContent.should.equal('427 (+1)');
} else {
links[i].style.color.should.equal('');
level_column.textContent.should.equal('' + parseInt(level_column.textContent, 10));
}
}
}
meendel_found.should.equal(true);
linglifer_found.should.equal(true);
done();
});
});
});
describe('#toString', function() {
beforeEach(function() {
highscorePage = new HighscorePage(utils);
});
it('should have keys', function() {
var str = highscorePage.toString();
str.should.have.keys('list', 'world', 'elements');
});
});
});
|
// Given two paramaters, an integer(n), a list of Arrays with Objects that conatin a Host_id, Listing_id, Score, City
// Build a function that helps display n amount of objects per page.
// The list of objects are given in order of Score, from High to Low.
// The objects must be displayed in order of highest score first.
// We dont want one host dominating the pages.
// Each page must display any unique hosts that havent displayed yet.
// After each page insert an empty space as a line break escept for the last page
function paginate(num, results) {
}
var test = [ "11, 2, 99, San Francisco",
"6, 3, 96, Los Angeles",
"6, 24, 92, San Francisco",
"3, 56, 90, San Francisco",
"6, 65, 80, Los Angeles",
"1, 29, 76, San Francisco",
"1, 19, 60, San Francisco",
"6, 10, 52, Los Angeles",
"11, 11, 46, San Francisco",
"5, 65, 40, Los Angeles",
"4, 29, 36, San Francisco",
"3, 19, 32, San Francisco",
"2, 10, 28, Los Angeles",
"2, 11, 26, San Francisco",
"5, 19, 20, San Francisco"
];
console.log( paginate( 3, test ) );
|
var path = require('path'),
rootPath = path.normalize(__dirname + '/../..');
module.exports = {
app: {
name: "scape",
url: "https://github.com/arabold/scape/",
title: "Scape",
description: "Responsive email editor based on ZURB's Ink boilerplate"
},
root: rootPath,
port: process.env.PORT || 3000
}
|
export { FunnelBar } from './FunnelBar';
|
define(['js/d3/d3.min.js', 'js/doT/doT.min.js'], function(d3, doT) {
function composite(widthValue, heightValue, selectionValue, xdomain) {
var margin = {top: 10, right: 0, bottom: ((heightValue - 10) || 10), left: 0},
width = (widthValue || 960) - margin.left - margin.right,
height = (heightValue || 90) - margin.top - margin.bottom;
var space = selectionValue;
space.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style({'font-size': '10px', 'font-family': 'sans-serif'});
var vis = space.append("g")
.attr("id","vis")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
var brush = d3.svg.brush();
function chart() {
};
chart.addChart = function(child) {
var top = height + margin.top;
height += child.height();
space.attr("height", height + margin.top + margin.bottom);
var child_space = vis.append("g")
.attr("transform", "translate(" + margin.left + "," + top + ")");
child(child_space, brush, xdomain);
return chart;
}
chart.title = function(value) {
if (!arguments.length) return title;
title = value;
vis.insert("text")
.attr("class", "title")
.attr("x", width / 2)
.attr("y", 5) // - (margin.top / 4))
.attr("text-anchor", "middle")
.attr("stroke", 'Black')
.style({"font-size": "16px", "text-decoration": "underline"})
.text(title);
return chart;
};
return chart;
};
function axisFormatTime(domain) {
var axisFormatMillis = d3.time.format("%H:%M:%S.%L"),
axisFormatSeconds = d3.time.format("%H:%M:%S"),
axisFormatMinutes = d3.time.format("%H:%M"),
axisFormatHours = d3.time.format("%dth %H:%M");
var step = domain[1].getTime() - domain[0];
var format = step < 3e3 ? axisFormatMillis
: step < 6e5 ? axisFormatSeconds
: step < 864e5 ? axisFormatMinutes
: axisFormatHours;
return format;
};
function saveName(name) {
return name.replace(/[^a-zA-Z0-9]/g,'_');
};
// this was inspired by the recomendation for reuseable charts:
// http://bost.ocks.org/mike/chart/
function builder(nameValue, widthValue, heightValue, renderLegendValue, renderAxisValue, hasBrushValue) {
var name = nameValue;
var margin = {top: 20, right: 45, bottom: 20, left: 45};
var width = (widthValue || 960) - margin.left - margin.right;
var height = (heightValue || 100) - margin.top - margin.bottom;
var renderLegend = 'none'; // one of ['none', 'asc', 'desc']
if ([true, 'ascending', 'asc'].indexOf(renderLegendValue) > -1) renderLegend = 'asc';
if (['descending', 'desc'].indexOf(renderLegendValue) > -1) renderLegend = 'desc';
console.log('render legend: ' + renderLegend);
if (arguments.length > 3) renderLegend = renderLegendValue;
var renderAxis = {'x': true, 'y': true, 'x2': true, 'y2': true};
if (arguments.length > 4) renderAxis = renderAxisValue;
var hasBrush = false;
if (arguments.length > 5) hasBrush = hasBrushValue;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var y2 = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var x2Axis = d3.svg.axis().scale(x).orient("bottom")
.tickFormat(d3.time.format(""));
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(height/25);
var y2Axis = d3.svg.axis().scale(y).orient("right").ticks(height/25);
var axisStyle = { 'stroke': 'Black', 'fill': 'none', 'stroke-width': '1px'};
var vis, brush, xdomain, legend;
var xlabel, title;
// var timeoffset = 7200000; // = +0200
var evt = d3.dispatch("change");
function updateExtent(scale, extent) {
var changed;
if (scale.domain()[0] !== extent[0]) { changed = true; }
if (scale.domain()[1] !== extent[1]) { changed = true; }
// if changed, update scale and fire event
if (changed) {
// update scale
scale.domain(extent);
// console.log('extended domain: ' + extent);
// update axes
if (renderAxis['x']) vis.select(".x.axis").call(xAxis);
if (renderAxis['y']) vis.select(".y.axis").call(yAxis);
if (renderAxis['x2']) vis.select(".x2.axis").call(x2Axis);
if (renderAxis['y2']) vis.select(".y2.axis").call(y2Axis);
vis.selectAll('.axis line, .axis path').style(axisStyle);
// fire event
evt.change();
};
};
function path(data, column, axis, path, style) {
function update() {
// console.log('updating ' + column);
vis.select("path#" + saveName(column)).attr("d", path);
};
vis.insert("path", "g.axis")
.data([data])
.attr("id", saveName(column))
.style(style);
if (axis === 2) {
y2Axis.scale(y2);
updateExtent(y2, [0, Math.max(y2.domain()[1], d3.max(data.map(function(d) {
return d[column] * 1.05; })))]);
} else {
updateExtent(y, [0, Math.max(y.domain()[1], d3.max(data.map(function(d) {
return d[column] * 1.05; })))]);
}
update();
// register listener
evt.on("change." + column, update);
if (!hasBrush) {
// use namespace to register multiple event listeners
brush.on("brush." + name + "." + column, function() {
var extent = brush.empty() ? xdomain : brush.extent()
xAxis.tickFormat(axisFormatTime(extent));
updateExtent(x, extent);
});
};
};
function addLegendEntry(color, label) {
if (renderLegend !== 'none') {
var entry;
if (renderLegend == 'asc') entry = legend.insert("g", ".legend");
else entry = legend.append("g");
entry.attr("class", "legend");
entry.append("rect")
.attr("x", width + margin.left - margin.right - 22)
.attr("y", 0)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
entry.append("text")
.attr("x", width + margin.left - margin.right - 28)
.attr("y", 8)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(label);
legend.selectAll(".legend")
.attr("transform", function(d, i) { return "translate(0," + (height - (i+1) * 20) + ")"; });
};
};
function chart(space, brushValue, xdomainValue) { //, xdomainEvent) {
vis = space.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
brush = brushValue;
xdomain = xdomainValue;
xAxis.tickFormat(axisFormatTime(xdomain));
vis.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")");
vis.append("g")
.attr("class", "y axis")
vis.append("g")
.attr("class", "x2 axis")
vis.append("g")
.attr("class", "y2 axis")
.attr("transform", "translate(" + width + ",0)")
if (renderLegend != 'none') legend = vis.append("g").attr("id","legend");
if (hasBrush) {
brush.x(x);
vis.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height + 7)
.style({'stroke': 'Black', 'fill-opacity': .125, 'shape-rendering': 'crispEdges'});
};
// xdomainEvent.on("change.name", function() {updateEvent(x, xdomain)});
updateExtent(x, xdomain);
};
chart.line = function(data, column, color, axis, label) {
var line = d3.svg.line()
//.x(function(d) { return x(d.ms_since_epoch); })
.x(function(d) { return x(d.timestamp); })
.y(function(d) {
if (axis === 2) return y2(d[column]);
else return y(d[column]);
});
var style = {'fill': 'none', 'stroke': color, 'stroke-width': '1.5px'};
path(data, column, axis, line, style);
addLegendEntry(color, label);
return chart;
};
chart.area = function(data, column, color, axis, label) {
var area = d3.svg.area()
//.x(function(d) { return x(d.ms_since_epoch); })
.x(function(d) { return x(d.timestamp); })
.y0(height)
.y1(function(d) {
if (axis === 2) return y2(d[column]);
else return y(d[column]);
});
var style = {'fill': color, 'stroke': color};
path(data, column, axis, area, style);
addLegendEntry(color, label);
return chart;
};
chart.bar = function(data, column, color, barCfgFunc, axis, label) {
var bar = vis.insert("g", "g.axis")
.attr("id", column)
.selectAll(".bar")
.data(data);
function size(selection) {
var n = 0;
selection.each(function() { ++n; });
return n;
};
function update() {
var barCfg = barCfgFunc(width, x.domain());
//bar.attr("x", function(d) { return x(d.ms_since_epoch) + barCfg['barGap']/2; })
bar.attr("x", function(d) { return x(d.timestamp) + barCfg['barGap']/2; })
.attr("y", function(d) { return y(d[column]) - .5; })
.attr("height", function(d) { return height - y(d[column]); })
.attr("width", barCfg['barWidth']);
};
// enter
bar.enter().append("rect")
.attr('class', "bar")
.style({'fill': color, 'stroke': 'Black'});
if (axis === 2) {
y2Axis.scale(y2);
updateExtent(y2, [0, Math.max(y2.domain()[1], d3.max(data.map(function(d) {
return d[column] * 1.05; })))]);
} else {
updateExtent(y, [0, Math.max(y.domain()[1], d3.max(data.map(function(d) {
return d[column] * 1.05; })))]);
}
update();
// register listener
evt.on("change." + column, update);
if (!hasBrush) {
// use namespace to register multiple event listeners
brush.on("brush." + name + "." + column, function() {
var extent = brush.empty() ? xdomain : brush.extent()
xAxis.tickFormat(axisFormatTime(extent));
updateExtent(x, extent);
});
};
addLegendEntry(color, label);
return chart;
};
chart.rMarker = function(data, column, color, axis, label) {
var dot = vis.insert("g", "g.axis")
.attr("id", column)
.selectAll(".dot")
.data(data);
function update() {
dot.attr("r", function(d){ return d[column] * 5; } )
//.attr("cx", function(d){ return x(d.ms_since_epoch); } );
.attr("cx", function(d){ return x(d.timestamp); } );
};
// enter
dot.enter().append("circle")
.attr('class', "dot")
.attr("y", 0)
.attr("cy", function(d){ return height; } )
.style({'fill': color, 'stroke': 'Black'});
update();
// register listener
evt.on("change." + column, update);
if (!hasBrush) {
// use namespace to register multiple event listeners
brush.on("brush." + name + "." + column, function() {
var extent = brush.empty() ? xdomain : brush.extent()
xAxis.tickFormat(axisFormatTime(extent));
updateExtent(x, extent);
});
};
addLegendEntry(color, label);
return chart;
};
chart.title = function(value, helpers) {
// all helper methods have one parameter: brush
if (!arguments.length) return title;
title = value;
var newTitle;
var tpl;
function buildTitle() {
var ctx = {};
for (var key in helpers) {
ctx[key] = helpers[key](brush);
};
return tpl(ctx);
};
if (arguments.length == 2) {
tpl = doT.template(title);
brush.on("brush." + name + ".title", function() {
vis.selectAll("text.title")
.text(buildTitle());
});
newTitle = buildTitle();
} else {
newTitle = title;
};
vis.insert("text")
.attr("class", "title")
.attr("x", 0)
.attr("dx", ".35em")
.attr("y", 0 - (margin.top / 4))
.attr("text-anchor", "left")
.attr("stroke", 'Black')
.style("font-size", "12px")
.text(newTitle);
return chart;
};
chart.xlabel = function(value) {
if (!arguments.length) return xlabel;
xlabel = value;
vis.select(".x.axis")
.append("text")
.attr("y", 0)
.attr("x", width)
.attr("dx", "-.35em")
.attr("dy", "-.35em")
.style("text-anchor", "end")
.text(xlabel);
return chart;
};
chart.ylabel = function(value) {
if (!arguments.length) return ylabel;
ylabel = value;
vis.select(".y.axis")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dx", "-.35em")
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(ylabel);
return chart;
};
chart.y2label = function(value) {
if (!arguments.length) return ylabel;
ylabel = value;
vis.select(".y2.axis")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dx", "-.35em")
.attr("dy", "-1em")
.style("text-anchor", "end")
.text(ylabel);
return chart;
};
chart.height = function(value) {
if (!arguments.length) return height + margin.top + margin.bottom;
height = value - margin.top - margin.bottom;
return chart;
};
chart.yTickFormat = function(formater) {
yAxis.tickFormat(formater);
vis.select(".y.axis").call(yAxis);
return chart;
};
chart.y2TickFormat = function(formater) {
y2Axis.tickFormat(formater);
vis.select(".y2.axis").call(y2Axis);
return chart;
};
return chart;
};
return {chart: builder, composite: composite};
});
|
module.exports = function ({ $lookup }) {
return {
object: function () {
return function (object, $buffer, $start) {
let $i = []
$buffer[$start++] = object.nudge & 0xff
for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) {
$buffer[$start++] = object.array[$i[0]] & 0xff
}
for (;;) {
if ($i[0] == 16) {
break
}
$buffer[$start++] = 0xd
$i[0]++
if ($i[0] == 16) {
break
}
$buffer[$start++] = 0xa
$i[0]++
}
$buffer[$start++] = object.sentry & 0xff
return { start: $start, serialize: null }
}
} ()
}
}
|
goog.provide('API.Client.FreeStyleProjectactions');
/**
* @record
*/
API.Client.FreeStyleProjectactions = function() {}
/**
* @type {!string}
* @export
*/
API.Client.FreeStyleProjectactions.prototype._class;
|
import fs from 'fs';
// var storePath = path.join(path.dirname(fs.realpathSync(__filename)), 'store');
function nodeModules(storePath){
let files = [];
const webpackModules = function(path){ return require(storePath+"/"+path) }
webpackModules.keys = () => files
webpackModules.set = function(storeName,actionFileName){
files.push(`./${storeName}/${actionFileName}`);
return files;
}
fs.readdirSync(storePath,{withFileTypes:true}).forEach(dirent => {
if(dirent.isDirectory()){
fs.readdirSync(storePath+"/"+dirent.name).forEach(actionName => {
if('_' !== actionName[0]){
webpackModules.set(dirent.name,actionName)
}
})
}
})
return webpackModules
}
export default nodeModules
|
import React from 'react';
import classnames from 'classnames';
import styles from './styles.css';
export default () => (
<span>
<span className={styles.dot}>.</span>
<span className={classnames(styles.dot, styles.dotTwo)}>.</span>
<span className={classnames(styles.dot, styles.dotThree)}>.</span>
</span>
);
|
function SolverState(repulsion, wholeNumber, attraction, limit) {
this.REPULSION = repulsion;
this.WHOLENUMBER = wholeNumber;
this.ATTRACTION = attraction;
this.LIMIT = limit;
}
|
/**
* Created by Dzianis on 25/08/2016.
*/
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
class Cell extends Component {
static propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
ball: PropTypes.any,
onClick: PropTypes.func.isRequired
};
static mapStateToProps ({ activeBall }) {
return { activeBall };
}
render () {
let css = "m5-cell-content ";
let color = {};
if (this.props.ball) {
css += "m5-ball ";
color = {
backgroundColor: this.props.ball.color,
};
if(this.props.activeBall &&
this.props.activeBall.x === this.props.x &&
this.props.activeBall.y === this.props.y) {
css += "m5-active-ball";
}
}
return <div className={css}
onClick={() => this.props.onClick(this.props.x, this.props.y)}
style={color}></div>
}
}
export default connect(Cell.mapStateToProps, null)(Cell);
|
const assign = require('object-assign');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const baseConfig = require('./webpack.base.config.js');
const config = Object.assign(baseConfig, {});
Object.assign = assign;
// No hot reload, just straight compiling.
// Keep this in sync with webpack.config.js and .babelrc
config.module.rules.push({
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['latest', 'react'],
plugins: ['transform-decorators-legacy'],
},
});
// Extract all the sass and scss into a separate file.
config.plugins.push(new ExtractTextPlugin('styles.css'));
config.module.rules.push({
test: /(\.scss|\.css)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
'sass-loader',
],
}),
});
module.exports = config;
|
describe('bsdate', function() {
beforeEach(function() {
browser().navigateTo(mainUrl);
});
it('should show editor and submit new value', function() {
var s = '[ng-controller="DevBsdateCtrl"] ';
expect(element(s+'a#minMax').css('display')).not().toBe('none');
expect(element(s+'a#minMax').text()).toMatch('15/05/1984');
element(s+'a#minMax').click();
element(s+'form .input-group-btn button[type="button"]').click();
expect(element(s+'a#minMax').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="text"]:visible').count()).toBe(1);
expect(element(s+'form input[type="text"]').val()).toBe('15-May-1984');
expect(element(s+'form .editable-buttons button[type="submit"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="button"]:visible').count()).toBe(1);
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form table button.btn-info span').text()).toMatch('15');
//set 01 May
element(s+'form table > tbody > tr:eq(0) > td:eq(3) > button').click();
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(0);
expect(element(s+'form input[type="text"]').val()).toBe('01-May-1984');
//submit
element(s+'form button[type="submit"]').click();
expect(element(s+'a#minMax').css('display')).not().toBe('none');
expect(element(s+'a#minMax').text()).toMatch('01/05/1984');
expect(element(s+'form').count()).toBe(0);
});
it('should show editor and not submit new value when new value is outside of date range', function() {
var s = '[ng-controller="DevBsdateCtrl"] ';
expect(element(s+'a#minMax').css('display')).not().toBe('none');
expect(element(s+'a#minMax').text()).toMatch('15/05/1984');
element(s+'a#minMax').click();
element(s+'form .input-group-btn button[type="button"]').click();
expect(element(s+'a#minMax').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="text"]:visible').count()).toBe(1);
expect(element(s+'form input[type="text"]').val()).toBe('15-May-1984');
expect(element(s+'form .editable-buttons button[type="submit"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="button"]:visible').count()).toBe(1);
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form table button.btn-info span').text()).toMatch('15');
//set 29 april
element(s+'form table > tbody > tr:eq(0) > td:eq(1) > button').click();
expect(element(s+'form table > tbody > tr:eq(0) > td:eq(1) > button').attr('disabled')).toBe("disabled");
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form input[type="text"]').val()).toBe('15-May-1984');
//submit
element(s+'form button[type="submit"]').click();
expect(element(s+'a#minMax').css('display')).not().toBe('none');
expect(element(s+'a#minMax').text()).toMatch('');
expect(element(s+'form').count()).toBe(0);
});
it('should show editor with selected date set to the current date', function() {
var s = '[ng-controller="DevBsdateCtrl"] ';
expect(element(s+'a#initDate').css('display')).not().toBe('none');
expect(element(s+'a#initDate').text()).toMatch('empty');
element(s+'a#initDate').click();
element(s+'form .input-group-btn button[type="button"]').click();
expect(element(s+'a#initDate').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="text"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="submit"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="button"]:visible').count()).toBe(1);
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form table button.btn-sm span').text()).toMatch(new Date().getDate());
});
it('should show editor and submit new value and input field is read only', function() {
var s = '[ng-controller="DevBsdateCtrl"] ';
expect(element(s+'a#readOnly').css('display')).not().toBe('none');
expect(element(s+'a#readOnly').text()).toMatch('15/05/2006');
element(s+'a#readOnly').click();
element(s+'form .input-group-btn button[type="button"]').click();
expect(element(s+'a#readOnly').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="text"]:visible').count()).toBe(1);
expect(element(s+'form input[type="text"]').attr('readonly')).toBe("readonly");
expect(element(s+'form input[type="text"]').val()).toBe('15-May-2006');
expect(element(s+'form .editable-buttons button[type="submit"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="button"]:visible').count()).toBe(1);
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form table button.btn-info span').text()).toMatch('15');
//set 01 May
element(s+'form table > tbody > tr:eq(0) > td:eq(3) > button').click();
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(0);
expect(element(s+'form input[type="text"]').val()).toBe('02-May-2006');
//submit
element(s+'form button[type="submit"]').click();
expect(element(s+'a#readOnly').css('display')).not().toBe('none');
expect(element(s+'a#readOnly').text()).toMatch('02/05/2006');
expect(element(s+'form').count()).toBe(0);
});
it('should show editor and submit new value and on change event is called', function() {
var s = '[ng-controller="DevBsdateCtrl"] ';
expect(element(s+'a#onChangeDate').css('display')).not().toBe('none');
expect(element(s+'a#onChangeDate').text()).toMatch('15/05/1984');
element(s+'a#onChangeDate').click();
element(s+'form .input-group-btn button[type="button"]').click();
expect(element(s+'a#onChangeDate').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="text"]:visible').count()).toBe(1);
expect(element(s+'form input[type="text"]').val()).toBe('15-May-1984');
expect(element(s+'form .editable-buttons button[type="submit"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="button"]:visible').count()).toBe(1);
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form table button.btn-info span').text()).toMatch('15');
//set 29 april
element(s+'form table > tbody > tr:eq(0) > td:eq(1) > button').click();
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(0);
expect(element(s+'form input[type="text"]').val()).toBe('29-April-1984');
//submit
element(s+'form button[type="submit"]').click();
expect(element(s+'a#onChangeDate').css('display')).not().toBe('none');
expect(element(s+'a#onChangeDate').text()).toMatch('29/04/1984');
expect(element(s+'form').count()).toBe(0);
});
it('should show input without calendar button and open calendar popup on click of input field', function() {
var s = '[ng-controller="DevBsdateCtrl"] ';
expect(element(s+'a#hideCalendarButton').css('display')).not().toBe('none');
expect(element(s+'a#hideCalendarButton').text()).toMatch('15/05/1984');
element(s+'a#hideCalendarButton').click();
expect(element(s+'form .input-group-btn button[type="button"]').count()).toBe(0);
element(s+'form input[type="text"]').click();
expect(element(s+'a#hideCalendarButton').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="text"]:visible').count()).toBe(1);
expect(element(s+'form input[type="text"]').val()).toBe('15-May-1984');
expect(element(s+'form .editable-buttons button[type="submit"]:visible').count()).toBe(1);
expect(element(s+'form .editable-buttons button[type="button"]:visible').count()).toBe(1);
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(1);
expect(element(s+'form table button.btn-info span').text()).toMatch('15');
//set 29 april
element(s+'form table > tbody > tr:eq(0) > td:eq(1) > button').click();
expect(element(s+'ul.dropdown-menu:visible').count()).toBe(0);
expect(element(s+'form input[type="text"]').val()).toBe('29-April-1984');
//submit
element(s+'form button[type="submit"]').click();
expect(element(s+'a#hideCalendarButton').css('display')).not().toBe('none');
expect(element(s+'a#hideCalendarButton').text()).toMatch('29/04/1984');
expect(element(s+'form').count()).toBe(0);
});
});
|
var test = require('test');
var pass = false;
try {
require('b');
} catch (exception) {
pass = true;
}
test.assert(pass, 'require does not fall back to relative modules when absolutes are not available.')
|
var through = require('through2');
var gutil = require('gulp-util');
var request = require('request');
var path = require('path');
var fs = require('fs');
var PluginError = gutil.PluginError;
var green = gutil.colors.green;
const PLUGIN_NAME = "gulp-file-upload";
function fileUpload(options) {
var options = options;
if (!options.destDir)
options.destDir = 'dest';
return through.obj(function (file, env, cb) {
var file_path = file.path;
var proj_name = options.proj_name;
var domain = options.domain;
var regexp = new RegExp("[\\s\\S]*" + options.destDir + "[\\/]?");
var rel_path = path.dirname(file_path.replace(/\\+/g, '\/')).replace(regexp, '') + '/';
var destPath = options.to + proj_name + '/' + rel_path;
gutil.log(green(domain + options.to.replace('/data/wapstatic/', '') + proj_name + '/' + rel_path + path.basename(file_path)));
request.post({
url: options.url,
formData: {
to: destPath,
file: fs.createReadStream(file_path)
}
}, function (err, resp, body) {
if (err) {
throw new PluginError(PLUGIN_NAME, "upload file fail: ", err);
}
gutil.log(green("from => ", file.path, ", to => ", destPath, ", SUCCESS!"));
cb(null);
});
});
}
module.exports = fileUpload;
|
module.exports = function (grunt) {
grunt.initConfig({
// Builds Sass
sass: {
dev: {
options: {
style: 'expanded',
sourcemap: true,
includePaths: [
'govuk_modules/govuk_template/assets/stylesheets',
'govuk_modules/govuk_frontend_toolkit/stylesheets',
'govuk_modules/govuk-elements-sass/'
],
outputStyle: 'expanded'
},
files: [{
expand: true,
cwd: 'app/assets/sass',
src: ['*.scss'],
dest: 'public/stylesheets/',
ext: '.css'
}]
}
},
// Copies templates and assets from external modules and dirs
sync: {
assets: {
files: [{
expand: true,
cwd: 'app/assets/',
src: ['**/*', '!sass/**'],
dest: 'public/'
}],
ignoreInDest: '**/stylesheets/**',
updateAndDelete: true
},
govuk: {
files: [{
cwd: 'node_modules/govuk_frontend_toolkit/',
src: '**',
dest: 'govuk_modules/govuk_frontend_toolkit/'
},
{
cwd: 'node_modules/govuk_template_jinja/assets/',
src: '**',
dest: 'govuk_modules/govuk_template/assets/'
},
{
cwd: 'node_modules/govuk_template_jinja/views/layouts/',
src: '**',
dest: 'govuk_modules/govuk_template/views/layouts/'
},
{
cwd: 'node_modules/govuk-elements-sass/public/sass/',
src: ['**', '!node_modules', '!elements-page.scss', '!elements-page-ie6.scss', '!elements-page-ie7.scss', '!elements-page-ie8.scss', '!main.scss', '!main-ie6.scss', '!main-ie7.scss', '!main-ie8.scss', '!prism.scss'],
dest: 'govuk_modules/govuk-elements-sass/'
}]
},
govuk_template_jinja: {
files: [{
cwd: 'govuk_modules/govuk_template/views/layouts/',
src: '**',
dest: 'lib/'
}]
},
tachyons: {
files: [{
cwd: 'node_modules/tachyons/css/',
src: '**',
dest: 'public/stylesheets/'
}]
}
},
// Watches assets and sass for changes
watch: {
css: {
files: ['app/assets/sass/**/*.scss'],
tasks: ['sass'],
options: {
spawn: false
}
},
assets: {
files: ['app/assets/**/*', '!app/assets/sass/**'],
tasks: ['sync:assets'],
options: {
spawn: false
}
}
},
// nodemon watches for changes and restarts app
nodemon: {
dev: {
script: 'server.js',
options: {
ext: 'js, json',
ignore: ['node_modules/**', 'app/assets/**', 'app/components/**', 'app/lib/**', 'public/**'],
args: grunt.option.flags()
}
}
},
concurrent: {
target: {
tasks: ['watch', 'nodemon'],
options: {
logConcurrentOutput: true
}
}
}
})
;[
'grunt-sync',
'grunt-contrib-watch',
'grunt-sass',
'grunt-nodemon',
'grunt-concurrent'
].forEach(function (task) {
grunt.loadNpmTasks(task)
})
grunt.registerTask('generate-assets', [
'sync',
'sass'
])
grunt.registerTask('default', [
'generate-assets',
'concurrent:target'
])
grunt.registerTask(
'test',
'default',
function () {
grunt.log.writeln('Test that the app runs')
}
)
}
|
console.log('Problem 4. Number of elements');
/*Write a function to count the number of div elements on the web page*/
function numberOfElements(){
var count = document.getElementsByTagName('div').length;
console.log('There are ' + count + ' DIVs. in the HTML page');
}
numberOfElements();
|
/**
* Socket.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
description: {
type: 'string',
required: false,
defaultsTo: ''
},
physicalSocket: {
type: 'string',
required: false,
defaultsTo: ''
},
timerMode: {
type: 'boolean',
required: false,
defaultsTo: false
},
switchedOn: {
type: 'boolean', // True: the socket is on. Else it's off
required: false,
defaultsTo: false
},
requestedSwitchedOn: {
type: 'boolean', // True: the socket is expected to be on
required: false,
defaultsTo: false
},
realPower: {
type: 'number',
defaultsTo: 0,
required: false
},
reactivePower: {
type: 'number',
defaultsTo: 0,
required: false
},
voltage: {
type: 'number',
defaultsTo: 0,
required: false
},
frequency: {
type: 'number',
defaultsTo: 0,
required: false
},
startTime: { // when the socket gets switched on (in minutes after midnight)
type: 'number',
defaultsTo: 0,
required: false
},
stopTime: { // when the socket gets switched off (in minutes after midnight)
type: 'number',
defaultsTo: 24*60,
required: false
},
random: {
type: 'boolean',
required: false,
defaultsTo: true
},
randomBreaks: {
type: 'boolean',
required: false,
defaultsTo: true
},
lastMessageReceived: {
type: 'string',
columnType: 'bigint',
required: false
}
}
};
|
/*!
* Bootstrap collapse.js v5.0.0-alpha1 (https://getbootstrap.com/)
* Copyright 2011-2020 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./dom/data.js'), require('./dom/event-handler.js'), require('./dom/manipulator.js'), require('./dom/selector-engine.js')) :
typeof define === 'function' && define.amd ? define(['./dom/data.js', './dom/event-handler.js', './dom/manipulator.js', './dom/selector-engine.js'], factory) :
(global = global || self, global.Collapse = factory(global.Data, global.EventHandler, global.Manipulator, global.SelectorEngine));
}(this, (function (Data, EventHandler, Manipulator, SelectorEngine) { 'use strict';
Data = Data && Object.prototype.hasOwnProperty.call(Data, 'default') ? Data['default'] : Data;
EventHandler = EventHandler && Object.prototype.hasOwnProperty.call(EventHandler, 'default') ? EventHandler['default'] : EventHandler;
Manipulator = Manipulator && Object.prototype.hasOwnProperty.call(Manipulator, 'default') ? Manipulator['default'] : Manipulator;
SelectorEngine = SelectorEngine && Object.prototype.hasOwnProperty.call(SelectorEngine, 'default') ? SelectorEngine['default'] : SelectorEngine;
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
/**
* --------------------------------------------------------------------------
* Bootstrap (v5.0.0-alpha1): util/index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var MILLISECONDS_MULTIPLIER = 1000;
var TRANSITION_END = 'transitionend'; // Shoutout AngusCroll (https://goo.gl/pxwQGp)
var toType = function toType(obj) {
if (obj === null || obj === undefined) {
return "" + obj;
}
return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
};
var getSelector = function getSelector(element) {
var selector = element.getAttribute('data-target');
if (!selector || selector === '#') {
var hrefAttr = element.getAttribute('href');
selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null;
}
return selector;
};
var getSelectorFromElement = function getSelectorFromElement(element) {
var selector = getSelector(element);
if (selector) {
return document.querySelector(selector) ? selector : null;
}
return null;
};
var getElementFromSelector = function getElementFromSelector(element) {
var selector = getSelector(element);
return selector ? document.querySelector(selector) : null;
};
var getTransitionDurationFromElement = function getTransitionDurationFromElement(element) {
if (!element) {
return 0;
} // Get transition-duration of the element
var _window$getComputedSt = window.getComputedStyle(element),
transitionDuration = _window$getComputedSt.transitionDuration,
transitionDelay = _window$getComputedSt.transitionDelay;
var floatTransitionDuration = parseFloat(transitionDuration);
var floatTransitionDelay = parseFloat(transitionDelay); // Return 0 if element or transition duration is not found
if (!floatTransitionDuration && !floatTransitionDelay) {
return 0;
} // If multiple durations are defined, take the first
transitionDuration = transitionDuration.split(',')[0];
transitionDelay = transitionDelay.split(',')[0];
return (parseFloat(transitionDuration) + parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
};
var triggerTransitionEnd = function triggerTransitionEnd(element) {
element.dispatchEvent(new Event(TRANSITION_END));
};
var isElement = function isElement(obj) {
return (obj[0] || obj).nodeType;
};
var emulateTransitionEnd = function emulateTransitionEnd(element, duration) {
var called = false;
var durationPadding = 5;
var emulatedDuration = duration + durationPadding;
function listener() {
called = true;
element.removeEventListener(TRANSITION_END, listener);
}
element.addEventListener(TRANSITION_END, listener);
setTimeout(function () {
if (!called) {
triggerTransitionEnd(element);
}
}, emulatedDuration);
};
var typeCheckConfig = function typeCheckConfig(componentName, config, configTypes) {
Object.keys(configTypes).forEach(function (property) {
var expectedTypes = configTypes[property];
var value = config[property];
var valueType = value && isElement(value) ? 'element' : toType(value);
if (!new RegExp(expectedTypes).test(valueType)) {
throw new Error(componentName.toUpperCase() + ": " + ("Option \"" + property + "\" provided type \"" + valueType + "\" ") + ("but expected type \"" + expectedTypes + "\"."));
}
});
};
var reflow = function reflow(element) {
return element.offsetHeight;
};
var getjQuery = function getjQuery() {
var _window = window,
jQuery = _window.jQuery;
if (jQuery && !document.body.hasAttribute('data-no-jquery')) {
return jQuery;
}
return null;
};
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'collapse';
var VERSION = '5.0.0-alpha1';
var DATA_KEY = 'bs.collapse';
var EVENT_KEY = "." + DATA_KEY;
var DATA_API_KEY = '.data-api';
var Default = {
toggle: true,
parent: ''
};
var DefaultType = {
toggle: 'boolean',
parent: '(string|element)'
};
var EVENT_SHOW = "show" + EVENT_KEY;
var EVENT_SHOWN = "shown" + EVENT_KEY;
var EVENT_HIDE = "hide" + EVENT_KEY;
var EVENT_HIDDEN = "hidden" + EVENT_KEY;
var EVENT_CLICK_DATA_API = "click" + EVENT_KEY + DATA_API_KEY;
var CLASS_NAME_SHOW = 'show';
var CLASS_NAME_COLLAPSE = 'collapse';
var CLASS_NAME_COLLAPSING = 'collapsing';
var CLASS_NAME_COLLAPSED = 'collapsed';
var WIDTH = 'width';
var HEIGHT = 'height';
var SELECTOR_ACTIVES = '.show, .collapsing';
var SELECTOR_DATA_TOGGLE = '[data-toggle="collapse"]';
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Collapse = /*#__PURE__*/function () {
function Collapse(element, config) {
this._isTransitioning = false;
this._element = element;
this._config = this._getConfig(config);
this._triggerArray = SelectorEngine.find(SELECTOR_DATA_TOGGLE + "[href=\"#" + element.id + "\"]," + (SELECTOR_DATA_TOGGLE + "[data-target=\"#" + element.id + "\"]"));
var toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE);
for (var i = 0, len = toggleList.length; i < len; i++) {
var elem = toggleList[i];
var selector = getSelectorFromElement(elem);
var filterElement = SelectorEngine.find(selector).filter(function (foundElem) {
return foundElem === element;
});
if (selector !== null && filterElement.length) {
this._selector = selector;
this._triggerArray.push(elem);
}
}
this._parent = this._config.parent ? this._getParent() : null;
if (!this._config.parent) {
this._addAriaAndCollapsedClass(this._element, this._triggerArray);
}
if (this._config.toggle) {
this.toggle();
}
Data.setData(element, DATA_KEY, this);
} // Getters
var _proto = Collapse.prototype;
// Public
_proto.toggle = function toggle() {
if (this._element.classList.contains(CLASS_NAME_SHOW)) {
this.hide();
} else {
this.show();
}
};
_proto.show = function show() {
var _this = this;
if (this._isTransitioning || this._element.classList.contains(CLASS_NAME_SHOW)) {
return;
}
var actives;
var activesData;
if (this._parent) {
actives = SelectorEngine.find(SELECTOR_ACTIVES, this._parent).filter(function (elem) {
if (typeof _this._config.parent === 'string') {
return elem.getAttribute('data-parent') === _this._config.parent;
}
return elem.classList.contains(CLASS_NAME_COLLAPSE);
});
if (actives.length === 0) {
actives = null;
}
}
var container = SelectorEngine.findOne(this._selector);
if (actives) {
var tempActiveData = actives.filter(function (elem) {
return container !== elem;
});
activesData = tempActiveData[0] ? Data.getData(tempActiveData[0], DATA_KEY) : null;
if (activesData && activesData._isTransitioning) {
return;
}
}
var startEvent = EventHandler.trigger(this._element, EVENT_SHOW);
if (startEvent.defaultPrevented) {
return;
}
if (actives) {
actives.forEach(function (elemActive) {
if (container !== elemActive) {
Collapse.collapseInterface(elemActive, 'hide');
}
if (!activesData) {
Data.setData(elemActive, DATA_KEY, null);
}
});
}
var dimension = this._getDimension();
this._element.classList.remove(CLASS_NAME_COLLAPSE);
this._element.classList.add(CLASS_NAME_COLLAPSING);
this._element.style[dimension] = 0;
if (this._triggerArray.length) {
this._triggerArray.forEach(function (element) {
element.classList.remove(CLASS_NAME_COLLAPSED);
element.setAttribute('aria-expanded', true);
});
}
this.setTransitioning(true);
var complete = function complete() {
_this._element.classList.remove(CLASS_NAME_COLLAPSING);
_this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW);
_this._element.style[dimension] = '';
_this.setTransitioning(false);
EventHandler.trigger(_this._element, EVENT_SHOWN);
};
var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
var scrollSize = "scroll" + capitalizedDimension;
var transitionDuration = getTransitionDurationFromElement(this._element);
EventHandler.one(this._element, TRANSITION_END, complete);
emulateTransitionEnd(this._element, transitionDuration);
this._element.style[dimension] = this._element[scrollSize] + "px";
};
_proto.hide = function hide() {
var _this2 = this;
if (this._isTransitioning || !this._element.classList.contains(CLASS_NAME_SHOW)) {
return;
}
var startEvent = EventHandler.trigger(this._element, EVENT_HIDE);
if (startEvent.defaultPrevented) {
return;
}
var dimension = this._getDimension();
this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px";
reflow(this._element);
this._element.classList.add(CLASS_NAME_COLLAPSING);
this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW);
var triggerArrayLength = this._triggerArray.length;
if (triggerArrayLength > 0) {
for (var i = 0; i < triggerArrayLength; i++) {
var trigger = this._triggerArray[i];
var elem = getElementFromSelector(trigger);
if (elem && !elem.classList.contains(CLASS_NAME_SHOW)) {
trigger.classList.add(CLASS_NAME_COLLAPSED);
trigger.setAttribute('aria-expanded', false);
}
}
}
this.setTransitioning(true);
var complete = function complete() {
_this2.setTransitioning(false);
_this2._element.classList.remove(CLASS_NAME_COLLAPSING);
_this2._element.classList.add(CLASS_NAME_COLLAPSE);
EventHandler.trigger(_this2._element, EVENT_HIDDEN);
};
this._element.style[dimension] = '';
var transitionDuration = getTransitionDurationFromElement(this._element);
EventHandler.one(this._element, TRANSITION_END, complete);
emulateTransitionEnd(this._element, transitionDuration);
};
_proto.setTransitioning = function setTransitioning(isTransitioning) {
this._isTransitioning = isTransitioning;
};
_proto.dispose = function dispose() {
Data.removeData(this._element, DATA_KEY);
this._config = null;
this._parent = null;
this._element = null;
this._triggerArray = null;
this._isTransitioning = null;
} // Private
;
_proto._getConfig = function _getConfig(config) {
config = _objectSpread2(_objectSpread2({}, Default), config);
config.toggle = Boolean(config.toggle); // Coerce string values
typeCheckConfig(NAME, config, DefaultType);
return config;
};
_proto._getDimension = function _getDimension() {
var hasWidth = this._element.classList.contains(WIDTH);
return hasWidth ? WIDTH : HEIGHT;
};
_proto._getParent = function _getParent() {
var _this3 = this;
var parent = this._config.parent;
if (isElement(parent)) {
// it's a jQuery object
if (typeof parent.jquery !== 'undefined' || typeof parent[0] !== 'undefined') {
parent = parent[0];
}
} else {
parent = SelectorEngine.findOne(parent);
}
var selector = SELECTOR_DATA_TOGGLE + "[data-parent=\"" + parent + "\"]";
SelectorEngine.find(selector, parent).forEach(function (element) {
var selected = getElementFromSelector(element);
_this3._addAriaAndCollapsedClass(selected, [element]);
});
return parent;
};
_proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
if (element) {
var isOpen = element.classList.contains(CLASS_NAME_SHOW);
if (triggerArray.length) {
triggerArray.forEach(function (elem) {
if (isOpen) {
elem.classList.remove(CLASS_NAME_COLLAPSED);
} else {
elem.classList.add(CLASS_NAME_COLLAPSED);
}
elem.setAttribute('aria-expanded', isOpen);
});
}
}
} // Static
;
Collapse.collapseInterface = function collapseInterface(element, config) {
var data = Data.getData(element, DATA_KEY);
var _config = _objectSpread2(_objectSpread2(_objectSpread2({}, Default), Manipulator.getDataAttributes(element)), typeof config === 'object' && config ? config : {});
if (!data && _config.toggle && typeof config === 'string' && /show|hide/.test(config)) {
_config.toggle = false;
}
if (!data) {
data = new Collapse(element, _config);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
};
Collapse.jQueryInterface = function jQueryInterface(config) {
return this.each(function () {
Collapse.collapseInterface(this, config);
});
};
Collapse.getInstance = function getInstance(element) {
return Data.getData(element, DATA_KEY);
};
_createClass(Collapse, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Collapse;
}();
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
// preventDefault only for <a> elements (which change the URL) not inside the collapsible element
if (event.target.tagName === 'A') {
event.preventDefault();
}
var triggerData = Manipulator.getDataAttributes(this);
var selector = getSelectorFromElement(this);
var selectorElements = SelectorEngine.find(selector);
selectorElements.forEach(function (element) {
var data = Data.getData(element, DATA_KEY);
var config;
if (data) {
// update parent attribute
if (data._parent === null && typeof triggerData.parent === 'string') {
data._config.parent = triggerData.parent;
data._parent = data._getParent();
}
config = 'toggle';
} else {
config = triggerData;
}
Collapse.collapseInterface(element, config);
});
});
var $ = getjQuery();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
* add .collapse to jQuery only if jQuery is present
*/
/* istanbul ignore if */
if ($) {
var JQUERY_NO_CONFLICT = $.fn[NAME];
$.fn[NAME] = Collapse.jQueryInterface;
$.fn[NAME].Constructor = Collapse;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Collapse.jQueryInterface;
};
}
return Collapse;
})));
//# sourceMappingURL=collapse.js.map
|
class SockJS {
constructor(url, whitelist, options, mockOptions) {
this.nextLoginState = true;
this.url = url;
this.whitelist = whitelist;
this.options = options;
SockJS.mockInstances.push(this);
SockJS.currentMockInstance = this;
let fn = () => {
if (typeof this.onopen === 'function') {
this.onopen();
}
};
if (mockOptions != null && mockOptions.timeout) {
window.setTimeout(fn, mockOptions.timeout);
} else {
window.setTimeout(fn, 1);
}
}
log(...args) {
var log = window.console;
if (SockJS.currentMockInstance && SockJS.currentMockInstance.$log) {
log = SockJS.currentMockInstance.$log;
}
log.debug(...args);
}
close(mockOptions) {
this.log("[MOCK] SockJS.close()");
let fn = () => {
if (typeof this.onclose === 'function') {
this.onclose();
}
};
if (mockOptions && mockOptions.timeout) {
window.setTimeout(fn, mockOptions.timeout);
} else {
fn();
}
}
send(event) {
let message = this._unwrapFromEvent(event);
if (message.type !== 'send') {
return;
}
this.log(`[MOCK] SockJS.send(${event})`);
if (message.replyAddress) {
this.log(`[MOCK] Sending reply to ${message.replyAddress}`);
var mockReply = message.body.mockReply || {data: 'reply'};
var reply = this._wrapToEvent(message.replyAddress, mockReply, undefined, mockReply.type);
this.onmessage(reply);
}
}
_unwrapFromEvent(event) {
return JSON.parse(event);
}
_wrapToEvent(address, body, replyAddress, type) {
return {
data : JSON.stringify({
type: type,
address : address,
message : body,
replyAddress : replyAddress
})
};
}
_buildLoginReplyAsSuccess(username, password) {
this.sessionId = "SESSION" + (Math.round(1000000 * Math.random()));
return {
status : 'ok',
sessionID : this.sessionId
};
}
_buildLoginReplyAsFail(username, password) {
return {
status : 'fail'
};
}
onmessage() {
console.warn('No SockJS.onmessage() defined!');
}
}
SockJS.mockInstances = [];
SockJS.currentMockInstance = null;
module.exports = SockJS;
|
import { connect } from "react-redux";
import LastUpdateInfo from "../components/lastUpdateInfo.js";
function mapStateToProps(state) {
const { selectedSubreddit, postsBySubreddit } = state;
const { lastUpdated } = postsBySubreddit[selectedSubreddit] || {};
return {
lastUpdated
};
}
export default connect(mapStateToProps)(LastUpdateInfo);
|
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var createMesh = require('gl-mesh3d');
var parseColorScale = require('../../lib/gl_format_color').parseColorScale;
var str2RgbaArray = require('../../lib/str2rgbarray');
var extractOpts = require('../../components/colorscale').extractOpts;
var zip3 = require('../../plots/gl3d/zip3');
var findNearestOnAxis = require('../isosurface/convert').findNearestOnAxis;
var generateIsoMeshes = require('../isosurface/convert').generateIsoMeshes;
function VolumeTrace(scene, mesh, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = mesh;
this.name = '';
this.data = null;
this.showContour = false;
}
var proto = VolumeTrace.prototype;
proto.handlePick = function(selection) {
if(selection.object === this.mesh) {
var rawId = selection.data.index;
var x = this.data._meshX[rawId];
var y = this.data._meshY[rawId];
var z = this.data._meshZ[rawId];
var height = this.data._Ys.length;
var depth = this.data._Zs.length;
var i = findNearestOnAxis(x, this.data._Xs).id;
var j = findNearestOnAxis(y, this.data._Ys).id;
var k = findNearestOnAxis(z, this.data._Zs).id;
var selectIndex = selection.index = k + depth * j + depth * height * i;
selection.traceCoordinate = [
this.data._meshX[selectIndex],
this.data._meshY[selectIndex],
this.data._meshZ[selectIndex],
this.data._value[selectIndex]
];
var text = this.data.hovertext || this.data.text;
if(Array.isArray(text) && text[selectIndex] !== undefined) {
selection.textLabel = text[selectIndex];
} else if(text) {
selection.textLabel = text;
}
return true;
}
};
proto.update = function(data) {
var scene = this.scene;
var layout = scene.fullSceneLayout;
this.data = generateIsoMeshes(data);
// Unpack position data
function toDataCoords(axis, coord, scale, calendar) {
return coord.map(function(x) {
return axis.d2l(x, 0, calendar) * scale;
});
}
var positions = zip3(
toDataCoords(layout.xaxis, data._meshX, scene.dataScale[0], data.xcalendar),
toDataCoords(layout.yaxis, data._meshY, scene.dataScale[1], data.ycalendar),
toDataCoords(layout.zaxis, data._meshZ, scene.dataScale[2], data.zcalendar));
var cells = zip3(data._meshI, data._meshJ, data._meshK);
var config = {
positions: positions,
cells: cells,
lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
ambient: data.lighting.ambient,
diffuse: data.lighting.diffuse,
specular: data.lighting.specular,
roughness: data.lighting.roughness,
fresnel: data.lighting.fresnel,
vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
faceNormalsEpsilon: data.lighting.facenormalsepsilon,
opacity: data.opacity,
opacityscale: data.opacityscale,
contourEnable: data.contour.show,
contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
contourWidth: data.contour.width,
useFacetNormals: data.flatshading
};
var cOpts = extractOpts(data);
config.vertexIntensity = data._meshIntensity;
config.vertexIntensityBounds = [cOpts.min, cOpts.max];
config.colormap = parseColorScale(data);
// Update mesh
this.mesh.update(config);
};
proto.dispose = function() {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
function createVolumeTrace(scene, data) {
var gl = scene.glplot.gl;
var mesh = createMesh({gl: gl});
var result = new VolumeTrace(scene, mesh, data.uid);
mesh._trace = result;
result.update(data);
scene.glplot.add(mesh);
return result;
}
module.exports = createVolumeTrace;
|
'use strict';
var S = require('..');
var eq = require('./internal/eq');
test('eitherToMaybe', function() {
eq(typeof S.eitherToMaybe, 'function');
eq(S.eitherToMaybe.length, 1);
eq(S.eitherToMaybe.toString(), 'eitherToMaybe :: Either a b -> Maybe b');
eq(S.eitherToMaybe(S.Left('Cannot divide by zero')), S.Nothing);
eq(S.eitherToMaybe(S.Right(42)), S.Just(42));
});
|
"use strict";
/* tslint:disable */
var load_themed_styles_1 = require("@microsoft/load-themed-styles");
var styles = {
pickerText: 'pickerText_56a98698',
inputFocused: 'inputFocused_56a98698',
pickerInput: 'pickerInput_56a98698',
};
load_themed_styles_1.loadStyles([{ "rawString": ".pickerText_56a98698{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;box-sizing:border-box;border:1px solid " }, { "theme": "neutralLight", "defaultValue": "#eaeaea" }, { "rawString": ";min-width:180px;padding:1px;min-height:32px}.pickerText_56a98698:hover{border-color:" }, { "theme": "themeLight", "defaultValue": "#c7e0f4" }, { "rawString": "}.pickerText_56a98698.inputFocused_56a98698{border-color:" }, { "theme": "themePrimary", "defaultValue": "#0078d7" }, { "rawString": "}.pickerInput_56a98698{height:26px;border:none;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;outline:0;padding:0 6px 0;margin:1px}" }]);
module.exports = styles;
/* tslint:enable */
//# sourceMappingURL=BasePicker.scss.js.map
|
import './field_group';
import '../dom';
frappe.provide('frappe.ui');
window.cur_dialog = null;
frappe.ui.open_dialogs = [];
frappe.ui.Dialog = class Dialog extends frappe.ui.FieldGroup {
constructor(opts) {
this.display = false;
this.is_dialog = true;
$.extend(this, { animate: true, size: null }, opts);
super();
this.make();
}
make() {
this.$wrapper = frappe.get_modal("", "");
this.wrapper = this.$wrapper.find('.modal-dialog')
.get(0);
if ( this.size == "small" )
$(this.wrapper).addClass("modal-sm");
else if ( this.size == "large" )
$(this.wrapper).addClass("modal-lg");
this.make_head();
this.modal_body = this.$wrapper.find(".modal-body");
this.$body = $('<div></div>').appendTo(this.modal_body);
this.body = this.$body.get(0);
this.$message = $('<div class="hide modal-message"></div>').appendTo(this.modal_body);
this.header = this.$wrapper.find(".modal-header");
// make fields (if any)
super.make();
// show footer
this.action = this.action || { primary: { }, secondary: { } };
if(this.primary_action || (this.action.primary && this.action.primary.onsubmit)) {
this.set_primary_action(this.primary_action_label || this.action.primary.label || __("Submit"),
this.primary_action || this.action.primary.onsubmit);
}
if(this.secondary_action) {
this.set_secondary_action(this.secondary_action);
}
if (this.secondary_action_label || (this.action.secondary && this.action.secondary.label)) {
this.get_close_btn().html(this.secondary_action_label || this.action.secondary.label);
}
var me = this;
this.$wrapper
.on("hide.bs.modal", function() {
me.display = false;
me.secondary_action && me.secondary_action();
if(frappe.ui.open_dialogs[frappe.ui.open_dialogs.length-1]===me) {
frappe.ui.open_dialogs.pop();
if(frappe.ui.open_dialogs.length) {
window.cur_dialog = frappe.ui.open_dialogs[frappe.ui.open_dialogs.length-1];
} else {
window.cur_dialog = null;
}
}
me.onhide && me.onhide();
me.on_hide && me.on_hide();
})
.on("shown.bs.modal", function() {
// focus on first input
me.display = true;
window.cur_dialog = me;
frappe.ui.open_dialogs.push(me);
me.focus_on_first_input();
me.on_page_show && me.on_page_show();
})
.on('scroll', function() {
var $input = $('input:focus');
if($input.length && ['Date', 'Datetime',
'Time'].includes($input.attr('data-fieldtype'))) {
$input.blur();
}
});
}
get_primary_btn() {
return this.$wrapper.find(".modal-header .btn-primary");
}
set_message(text) {
this.$message.removeClass('hide');
this.$body.addClass('hide');
this.$message.text(text);
}
clear_message() {
this.$message.addClass('hide');
this.$body.removeClass('hide');
}
set_primary_action(label, click) {
this.has_primary_action = true;
var me = this;
return this.get_primary_btn()
.removeClass("hide")
.html(label)
.click(function() {
me.primary_action_fulfilled = true;
// get values and send it
// as first parameter to click callback
// if no values then return
var values = me.get_values();
if(!values) return;
click && click.apply(me, [values]);
});
}
set_secondary_action(click) {
this.get_close_btn().on('click', click);
}
disable_primary_action() {
this.get_primary_btn().addClass('disabled');
}
enable_primary_action() {
this.get_primary_btn().removeClass('disabled');
}
make_head() {
this.set_title(this.title);
}
set_title(t) {
this.$wrapper.find(".modal-title").html(t);
}
show() {
// show it
if ( this.animate ) {
this.$wrapper.addClass('fade');
} else {
this.$wrapper.removeClass('fade');
}
this.$wrapper.modal("show");
this.primary_action_fulfilled = false;
this.is_visible = true;
}
hide() {
this.$wrapper.modal("hide");
this.is_visible = false;
}
get_close_btn() {
return this.$wrapper.find(".btn-modal-close");
}
no_cancel() {
this.get_close_btn().toggle(false);
}
cancel() {
this.get_close_btn().trigger("click");
}
};
|
import React, { Component } from 'react';
class Page extends Component {
render() {
//console.log(this.props.entry) // logs the current state and the text entry
//console.log(this.props.updateEntry) //logs the function itself
return (
<div className="Page">
<div className="Welcome">
<br></br>
<h1>Welcome to Dear Diary, {this.props.user}</h1>
<h4>Entry for the Date: {this.props.logTime}</h4>
<h3>Title: <input type="text" className="currTitle" value={this.props.title} onChange={this.props.updateTitle} /> </h3>
<div>
<textarea className="Entry" placeholder="Start Writing..." cols="70" wrap="soft" rows="30"
onChange={this.props.updateEntry} value={this.props.entry}>
</textarea>
</div>
<div className="log">
<div><input type="submit" className="button" value="Log" onClick={this.props.postToDB}/> </div>
</div>
<div className="log">
<input type="text" id="searchField" />
<input type="submit" className="button" value="Get Past Entries" onClick={this.props.getFromDB}/>
</div>
</div>
</div>
);
}
}
export default Page;
|
"use strict"
import Queue from "./queue"
import PromiseSet from "./promise-set"
export default function QueueConsumer(queue){
this.__queue = queue
this.__doing = new PromiseSet()
this.__done = ()=>{}
}
Object.assign(QueueConsumer.prototype, {
start: function(consumer, concurrency=1){
for (let i=0; i<concurrency; i++){
this.__queue.pop()
.then(x => this.__doing.add(consumer(x)))
.then(()=> {
this.__done()
this.start(consumer)
})
}
},
end: function(){
let p = new Promise(resolve => {this.__done = ()=>{
if (this.__queue.size() === 0 && this.__doing.size() === 0) resolve()
}})
this.__done()
return p
},
})
|
'use strict';
module.exports = require('./driver.js');
|
var _; //globals
/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
"Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
It's the tie to go along with jQuery's tux."
*/
describe("About Higher Order Functions", function () {
it("should use filter to return array items that meet a criteria", function () {
var numbers = [1,2,3];
var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });
expect(odd).toEqual([1,3]);
expect(odd.length).toBe(2);
expect(numbers.length).toBe(3);
});
it("should use 'map' to transform each element", function () {
var numbers = [1, 2, 3];
var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });
expect(numbersPlus1).toEqual([2,3,4]);
expect(numbers).toEqual([1,2,3]);
});
it("should use 'reduce' to update the same result on each iteration", function () {
var numbers = [1, 2, 3];
var reduction = _(numbers).reduce(
function(memo, x) {
//note: memo is the result from last call, and x is the current number
return memo + x;
},
/* initial */ 0
);
expect(reduction).toBe(6);
expect(numbers).toEqual([1,2,3]);
});
it("should use 'forEach' for simple iteration", function () {
var numbers = [1,2,3];
var msg = "";
var isEven = function (item) {
msg += (item % 2) === 0;
};
_(numbers).forEach(isEven);
expect(msg).toEqual(false true false);
expect(numbers).toEqual([1,2,3]);
});
it("should use 'all' to test whether all items pass condition", function () {
var onlyEven = [2,4,6];
var mixedBag = [2,4,5,6];
var isEven = function(x) { return x % 2 === 0 };
expect(_(onlyEven).all(isEven)).toBe(true);
expect(_(mixedBag).all(isEven)).toBe(false);
});
it("should use 'any' to test if any items passes condition" , function () {
var onlyEven = [2,4,6];
var mixedBag = [2,4,5,6];
var isEven = function(x) { return x % 2 === 0 };
expect(_(onlyEven).any(isEven)).toBe(true);
expect(_(mixedBag).any(isEven)).toBe(true);
});
it("should use range to generate an array", function() {
expect(_.range(3)).toEqual([0,1,2]);
expect(_.range(1, 4)).toEqual([1,2,3]);
expect(_.range(0, -4, -1)).toEqual([0,-1,-2,-3]);
});
it("should use flatten to make nested arrays easy to work with", function() {
expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual([1,2,3,4]);
});
it("should use chain() ... .value() to use multiple higher order functions", function() {
var result = _([ [0, 1], 2 ]).chain()
.flatten()
.map(function(x) { return x+1 } )
.reduce(function (sum, x) { return sum + x })
.value();
expect(result).toEqual(6);
});
});
|
import angular from 'angular';
import homeComponent from './home-component';
import homeConfig from './home-config';
import characterSelection from './directives/character-selection/index';
import queryBar from './directives/query-bar/index';
import characterDisplay from './directives/character-display/index';
require('./home.scss');
angular.module('home', [])
.directive('characterDisplay', characterDisplay)
.directive('characterSelection', characterSelection)
.directive('queryBar', queryBar)
.component('home', homeComponent)
.config(homeConfig);
|
"use strict";
const Collection = require("../util/Collection");
const GuildChannel = require("./GuildChannel");
const Member = require("./Member");
/**
* Represents a guild voice channel. See GuildChannel for more properties and methods.
* @extends GuildChannel
* @prop {Number?} bitrate The bitrate of the channel
* @prop {String?} rtcRegion The RTC region ID of the channel (automatic when `null`)
* @prop {Number} type The type of the channel
* @prop {Number?} userLimit The max number of users that can join the channel
* @prop {Number?} videoQualityMode The camera video quality mode of the voice channel. `1` is auto, `2` is 720p
* @prop {Collection<Member>} voiceMembers Collection of Members in this channel
*/
class VoiceChannel extends GuildChannel {
constructor(data, client) {
super(data, client);
this.voiceMembers = new Collection(Member);
this.update(data);
}
update(data) {
super.update(data);
if(data.bitrate !== undefined) {
this.bitrate = data.bitrate;
}
if(data.rtc_region !== undefined) {
this.rtcRegion = data.rtc_region;
}
if(data.user_limit !== undefined) {
this.userLimit = data.user_limit;
}
if(data.video_quality_mode !== undefined) {
this.videoQualityMode = data.video_quality_mode;
}
}
/**
* Create an invite for the channel
* @arg {Object} [options] Invite generation options
* @arg {Number} [options.maxAge] How long the invite should last in seconds
* @arg {Number} [options.maxUses] How many uses the invite should last for
* @arg {Boolean} [options.temporary] Whether the invite grants temporary membership or not
* @arg {Boolean} [options.unique] Whether the invite is unique or not
* @arg {String} [reason] The reason to be displayed in audit logs
* @returns {Promise<Invite>}
*/
createInvite(options, reason) {
return this.client.createChannelInvite.call(this.client, this.id, options, reason);
}
/**
* Get all invites in the channel
* @returns {Promise<Array<Invite>>}
*/
getInvites() {
return this.client.getChannelInvites.call(this.client, this.id);
}
/**
* Joins the channel.
* @arg {Object} [options] VoiceConnection constructor options
* @arg {Object} [options.opusOnly] Skip opus encoder initialization. You should not enable this unless you know what you are doing
* @arg {Object} [options.shared] Whether the VoiceConnection will be part of a SharedStream or not
* @arg {Boolean} [options.selfMute] Whether the bot joins the channel muted or not
* @arg {Boolean} [options.selfDeaf] Whether the bot joins the channel deafened or not
* @returns {Promise<VoiceConnection>} Resolves with a VoiceConnection
*/
join(options) {
return this.client.joinVoiceChannel.call(this.client, this.id, options);
}
/**
* Leaves the channel.
*/
leave() {
return this.client.leaveVoiceChannel.call(this.client, this.id);
}
toJSON(props = []) {
return super.toJSON([
"bitrate",
"rtcRegion",
"userLimit",
"videoQualityMode",
"voiceMembers",
...props
]);
}
}
module.exports = VoiceChannel;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92-1.31-2.92-2.92-2.92z" />
, 'ShareSharp');
|
const EventEmitter = require('events');
const Grid = require('../../../gamelib/grid/Grid.js');
const BaseCell = require('../../../gamelib/grid/BaseCell.js');
const Wall = require('./Wall.js');
const Mouse = require('./Mouse.js');
const Cat = require('./Cat.js');
const House = require('./House.js');
const Trap = require('./Trap.js');
const LAYER_V_WALL = 2;
const LAYER_H_WALL = 1;
class Game extends EventEmitter {
static create() {
return new this();
}
constructor() {
super();
this.board = Grid.create({
rows: 12,
cols: 9,
layerCount: 3
});
}
load(data) {
this.data = data;
this.cats = [];
this.mouses = [];
data.wall.forEach(p => this.addWall(p[0], p[1], p[2]));
data.mouse.forEach(p => this.addMouse(p[0], p[1], p[2]));
data.cat.forEach(p => this.addCat(p[0], p[1], p[2]));
}
start() {
this.runningMouse = this.mouses.length;
this.mouses.forEach((item) => {
item.state = 'run';
});
this.cats.forEach((item) => {
item.state = 'run';
});
}
reset() {
this.emit('reset');
this.load(this.data);
}
win() {
this.emit('win');
}
lost() {
this.emit('lost');
}
addWall(i, j, dir) {
var layer = (dir === 0) ? LAYER_H_WALL : LAYER_V_WALL;
var wall = this.board.createCell({
i, j, dir, layer
}, BaseCell);
this.emit('addWall', wall);
return wall;
}
removeWall(i, j, dir) {
if (dir === 0) {
layer = LAYER_H_WALL;
} else {
layer = LAYER_V_WALL;
}
var cell = this.board.layers[layer][i][j];
if (cell) {
cell.destroy();
this.board.destroyCell(cell);
}
}
addHouse(i, j) {
var house = this.board.createCell({
i, j, dir, layer: 0
}, House);
this.emit('addHouse', house);
return house;
}
removeHouse(i, j) {
var house = this.board.layers[0][i][j];
if (house) {
this.board.destroyCell(house);
}
}
addTrap(i, j) {
var trap = this.board.createCell({
i, j, dir, layer: 0
}, Trap);
this.emit('addTrap', trap);
return trap;
}
removeTrap(i, j) {
var trap = this.board.layers[0][i][j];
if (trap) {
this.board.destroyCell(trap);
}
}
addCat(i, j, dir) {
var cat = Cat.create(this, {
i, j, dir
});
this.cats.push(cat);
this.emit('addCat', cat);
return cat;
}
removeCat(cat) {
cat.destroy();
var p = this.cats.indexOf(cat);
if (p >= 0) {
this.cats.splice(p, 1);
}
}
addMouse(i, j, dir) {
var mouse = Mouse.create(this, {
i, j, dir
});
this.mouses.push(mouse);
this.emit('addMouse', mouse);
return mouse;
}
removeMouse(mouse) {
mouse.destroy();
var p = this.mouses.indexOf(mouse);
if (p >= 0) {
this.mouses.splice(p, 1);
}
}
isWall(i, j, dir) {
if (dir === 0) {
if (j <= 0) {
return true;
} else {
return !!this.board.layers[LAYER_V_WALL][i][j - 1];
}
} else if (dir === 1) {
if (i >= this.board.rows - 1) {
return true;
} else {
return !!this.board.layers[LAYER_H_WALL][i][j];
}
} else if (dir === 2) {
if (j >= this.board.cols - 1) {
return true;
} else {
return !!this.board.layers[LAYER_V_WALL][i][j];
}
} else if (dir === 3) {
if (i <= 0) {
return true;
} else {
return !!this.board.layers[LAYER_H_WALL][i - 1][j];
}
}
return true;
}
test(cat, mouse) {
var dx = cat.x - mouse.x;
var dy = cat.y - mouse.y;
var dist = Math.sqrt(dx * dx + dy * dy);
return dist < 0.1;
}
update(dt) {
//this.board.update(dt);
this.mouses.forEach(item => item.update(dt));
this.cats.forEach(item => item.update(dt));
}
}
module.exports = Game;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const bignumber_js_1 = require("bignumber.js");
const json2typescript_1 = require("json2typescript");
const DataConverter_1 = require("./DataConverter");
let WithdrawalData = class WithdrawalData {
constructor() {
this.PaymentUuid = undefined;
this.Currency = undefined;
this.Amount = undefined;
this.Opened = undefined;
this.Authorized = undefined;
this.PendingPayment = undefined;
this.TxCost = undefined;
this.TxId = undefined;
this.Canceled = undefined;
this.InvalidAddress = undefined;
}
};
tslib_1.__decorate([
json2typescript_1.JsonProperty('PaymentUuid', undefined, true),
tslib_1.__metadata("design:type", String)
], WithdrawalData.prototype, "PaymentUuid", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty(),
tslib_1.__metadata("design:type", String)
], WithdrawalData.prototype, "Currency", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty('Amount', DataConverter_1.BigNumberConverter, false),
tslib_1.__metadata("design:type", bignumber_js_1.default)
], WithdrawalData.prototype, "Amount", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty('Opened', DataConverter_1.DateConverter, false),
tslib_1.__metadata("design:type", Date)
], WithdrawalData.prototype, "Opened", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty(),
tslib_1.__metadata("design:type", Boolean)
], WithdrawalData.prototype, "Authorized", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty(),
tslib_1.__metadata("design:type", Boolean)
], WithdrawalData.prototype, "PendingPayment", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty('TxCost', DataConverter_1.BigNumberConverter, false),
tslib_1.__metadata("design:type", bignumber_js_1.default)
], WithdrawalData.prototype, "TxCost", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty(),
tslib_1.__metadata("design:type", String)
], WithdrawalData.prototype, "TxId", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty(),
tslib_1.__metadata("design:type", Boolean)
], WithdrawalData.prototype, "Canceled", void 0);
tslib_1.__decorate([
json2typescript_1.JsonProperty(),
tslib_1.__metadata("design:type", Boolean)
], WithdrawalData.prototype, "InvalidAddress", void 0);
WithdrawalData = tslib_1.__decorate([
json2typescript_1.JsonObject
], WithdrawalData);
exports.WithdrawalData = WithdrawalData;
//# sourceMappingURL=WithdrawalData.js.map
|
export default {
type: 'document',
name: 'documentActionsTest',
title: 'Document actions',
fields: [
{
type: 'string',
name: 'title',
title: 'Title',
},
],
}
|
"use strict";
const middleware = require("../index");
const httpMocks = require("node-mocks-http");
const sinon = require("sinon");
const assert = require("chai").assert;
const req = httpMocks.createRequest({
headers: {
Authorization: `Basic ${Buffer.from("username:password").toString(
"base64"
)}`
}
});
describe("basicauth-middleware", function() {
describe("With plain username and password", function() {
it("should call next if user is authentified", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware("username", "password")(req, res, next);
assert.isTrue(next.called);
});
it("should not call next if user is not authentified", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware("userNotAuthetified", "userNotAuthetified")(req, res, next);
assert.isFalse(next.called);
});
it("should respond with 401 if user is not authentified", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware("userNotAuthetified", "userNotAuthetified")(req, res, next);
assert.equal(res.statusCode, 401);
});
it("should respond with default realm", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware("no", "no")(req, res, next);
assert.equal(
res.getHeader("WWW-Authenticate"),
"Basic realm=Authorization Required"
);
});
it("should respond with custom realm if configured", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware("no", "no", "Secret Garden")(req, res, next);
assert.equal(
res.getHeader("WWW-Authenticate"),
"Basic realm=Secret Garden"
);
});
});
describe("With an array of usernames and passwords", function() {
it("should call next if user is authentified", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware([
["username", "password"],
["username2", "password2"]
])(req, res, next);
assert.isTrue(next.called);
});
it("should not call next if user is not authentified", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware([
["wrong user", "password"],
["username2", "password2"]
])(req, res, next);
assert.isFalse(next.called);
});
it("should respond with 401 if user is not authentified", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware([
["wrong user", "password"],
["username2", "password2"]
])(req, res, next);
assert.equal(res.statusCode, 401);
});
it("should respond with default realm", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware([
["wrong user", "password"],
["username2", "password2"]
])(req, res, next);
assert.equal(
res.getHeader("WWW-Authenticate"),
"Basic realm=Authorization Required"
);
});
});
describe("With sync checkFn", function() {
it("should call next if checkFn return true", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function() {
return true;
})(req, res, next);
assert.isTrue(next.called);
});
it("should not call next if checkFn return false", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function() {
return false;
})(req, res, next);
assert.isFalse(next.called);
});
it("should respond with 401 if checkFn return false", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function() {
return false;
})(req, res, next);
assert.equal(res.statusCode, 401);
});
it("should call next with error if an uncaught error occurs here", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
const err = new Error("Test error");
middleware(function() {
throw err;
})(req, res, next);
assert.isTrue(next.calledWith(err));
});
});
describe("With async checkFn", function() {
it("should call next if checkFn call checkCb with true", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function(username, password, checkCb) {
checkCb(null, true);
})(req, res, next);
assert.isTrue(next.called);
});
it("should call next with error checkFn call return an error", function() {
const error = new Error("test error");
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function(username, password, checkCb) {
checkCb(error);
})(req, res, next);
assert.isTrue(next.calledWith(error));
});
it("should not call next if checkFn call checkCb with false", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function(username, password, checkCb) {
checkCb(null, false);
})(req, res, next);
assert.isFalse(next.called);
});
it("should respond 401 if checkFn call checkCb with false", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function(username, password, checkCb) {
checkCb(null, false);
})(req, res, next);
assert.equal(res.statusCode, 401);
});
it("should not call next if checkFn dont call checkCb", function() {
const res = httpMocks.createResponse();
const next = sinon.spy();
middleware(function(username, password, checkCb) {})(req, res, next);
assert.isFalse(next.called);
});
});
describe("With promise", function() {
it("call next with an autorized user", function(done) {
const res = httpMocks.createResponse();
middleware(function(username, password) {
return Promise.resolve(true);
})(req, res, function() {
done();
});
});
it("should call next with error with promise error", function(done) {
const res = httpMocks.createResponse();
middleware(function(username, password) {
return Promise.reject(new Error("test"));
})(req, res, function(err) {
assert.instanceOf(err, Error);
done();
});
});
it("should send 401 with an unauthorized user", function(done) {
const res = httpMocks.createResponse({
eventEmitter: require("events").EventEmitter
});
var next = sinon.spy();
middleware(function(username, password) {
return Promise.resolve(false);
})(req, res, next);
res.on("end", function() {
assert.isFalse(next.called);
assert.equal(res.statusCode, 401);
done();
});
});
it("should send 401 with the correct realm to an unauthorized user", function(done) {
const res = httpMocks.createResponse({
eventEmitter: require("events").EventEmitter
});
var next = sinon.spy();
middleware(function(username, password) {
return Promise.resolve(false);
}, "Secret Garden")(req, res, next);
res.on("end", function() {
assert.isFalse(next.called);
assert.equal(res.statusCode, 401);
assert.equal(
res.getHeader("WWW-Authenticate"),
"Basic realm=Secret Garden"
);
done();
});
});
});
});
|
'use strict';
module.exports = {
port: 443,
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/tekeisushi',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.min.js',
'public/lib/angular-animate/angular-animate.min.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'https://localhost:443/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { Table, Alert } from 'react-bootstrap';
import Card from './card';
import Loader from '../ui/loader';
const ProfileCards = (props) => {
const renderCards = (cards) => {
if (cards) {
return Object.keys(cards).map(key =>
(
<Card
card={cards[key]}
key={cards[key].id}
deleteCard={props.deleteCard}
setCardDefault={props.setCardDefault}
/>
)
);
}
return [];
};
const renderMessage = () => {
const { message } = props;
return (message && message.type === 'card') &&
(
<div>
<Alert
bsStyle={message.status === 'success' ? 'success' : 'error'}
onDismiss={() => { props.clearMessage(); }}
>
<p>{ message.message }</p>
</Alert>
</div>
);
};
return (
<div>
{ renderMessage() }
{
(
props.loading &&
(<h3 className="text-center">Loading</h3>)
)
}
{
(
!props.loading && (renderCards(props.creditCards).length === 0) &&
(<h3 className="text-center">You not have credit cards</h3>)
)
}
{
(
!props.loading && (renderCards(props.creditCards).length > 0) &&
(
<div>
<Loader
show={props.loadingUserActions}
type="rect"
/>
<Table condensed responsive bordered className="text-center">
<tbody>
{ renderCards(props.creditCards) }
</tbody>
</Table>
</div>
)
)
}
</div>
);
};
ProfileCards.defaultProps = {
creditCards: undefined,
loadingUserActions: false
};
ProfileCards.propTypes = {
clearMessage: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired,
creditCards: PropTypes.objectOf(
PropTypes.shape({
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
last_four: PropTypes.string,
exp_year: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
}
)).isRequired,
loadingUserActions: PropTypes.bool
};
export default ProfileCards;
|
'use strict';
const setup = require('./include/setup');
const sinon = require('sinon');
var git, sandbox;
exports.setUp = function (done) {
setup.restore();
sandbox = sinon.sandbox.create();
done();
};
exports.tearDown = function (done) {
setup.restore();
sandbox.restore();
done();
};
exports.log = {
setUp: function (done) {
git = setup.Instance();
done();
},
'picks out the latest item': function (test) {
git.log(function (err, result) {
test.equals(null, err, 'not an error');
test.same('ca931e641eb2929cf86093893e9a467e90bf4c9b', result.latest.hash, 'knows which is latest');
test.same(4, result.total, 'picked out all items');
test.done();
});
setup.closeWith([
'ca931e641eb2929cf86093893e9a467e90bf4c9b;2016-01-04 18:54:56 +0100;Fix log.latest. (HEAD, stmbgr-master);stmbgr;stmbgr@gmail.com',
'8655cb1cf2a3d6b83f4e6f7ff50ee0569758e805;2016-01-03 16:02:22 +0000;Release 1.20.0 (origin/master, origin/HEAD, master);Steve King;steve@mydev.co',
'd4bdd0c823584519ddd70f8eceb8ff06c0d72324;2016-01-03 16:02:04 +0000;Support for any parameters to `git log` by supplying `options` as an array (tag: 1.20.0);Steve King;ste',
'207601debebc170830f2921acf2b6b27034c3b1f;2016-01-03 15:50:58 +0000;Release 1.19.0;Steve King;steve@mydev.co'
].join('\n'))
},
'uses custom splitter': function (test) {
git.log({splitter: "::"}, function (err, result) {
test.equals(null, err, 'not an error');
test.same(["log", "--pretty=format:%H::%ai::%s%d::%aN::%ae"], setup.theCommandRun());
test.same('ca931e641eb2929cf86093893e9a467e90bf4c9b', result.latest.hash, 'knows which is latest');
test.same(4, result.total, 'picked out all items');
test.done();
});
setup.closeWith([
'ca931e641eb2929cf86093893e9a467e90bf4c9b::2016-01-04 18:54:56 +0100::Fix log.latest. (HEAD, stmbgr-master)::stmbgr::stmbgr@gmail.com',
'8655cb1cf2a3d6b83f4e6f7ff50ee0569758e805::2016-01-03 16:02:22 +0000::Release 1.20.0 (origin/master, origin/HEAD, master)::Steve King::steve@mydev.co',
'd4bdd0c823584519ddd70f8eceb8ff06c0d72324::2016-01-03 16:02:04 +0000::Support for any parameters to `git log` by supplying `options` as an array (tag: 1.20.0)::Steve King::ste',
'207601debebc170830f2921acf2b6b27034c3b1f::2016-01-03 15:50:58 +0000::Release 1.19.0::Steve King::steve@mydev.co'
].join('\n'))
},
'with explicit from and to': function (test) {
git.log('from', 'to', function (err, result) {
test.equals(null, err, 'not an error');
test.same(["log", "--pretty=format:%H;%ai;%s%d;%aN;%ae", "from...to"], setup.theCommandRun());
test.done();
});
setup.closeWith('17df9a7421dd86920cd20afd1d6b6be527a89b88;2015-11-24 11:55:47 +0100;add reset command;Mark Oswald;markoswald123@googlemail.com\n\
4e0d08e0653101fb4d8da3ea3420f5c490401e9e;2015-11-19 22:03:49 +0000;Release 1.12.0 (origin/master, origin/HEAD);Steve King;steve@mydev.co\n\
83f3f60d5899116fe4d38b9109c9d925963856da;2015-11-19 13:54:28 +0000;Merge pull request #51 from ebaioni/patch-1 (tag: 1.12.0);Steve King;steve@mydev.co\n\
c515d3f28f587312d816e14ef04db399b7e0adcd;2015-11-19 15:55:41 +1100;updates command to customBinary;Enrico Baioni;baio88@gmail.com\n\
570223e86f0999fd3b39280ad33081e5155d1003;2015-10-12 22:01:05 +0100;Release 1.11.0;Steve King;steve@mydev.co\
');
},
'with options array': function (test) {
git.log(['--some=thing'], function (err, result) {
test.equals(null, err, 'not an error');
test.same(["log", "--pretty=format:%H;%ai;%s%d;%aN;%ae", "--some=thing"], setup.theCommandRun());
test.done();
});
setup.closeWith('17df9a7421dd86920cd20afd1d6b6be527a89b88;2015-11-24 11:55:47 +0100;add reset command;Mark Oswald;markoswald123@googlemail.com\n\
4e0d08e0653101fb4d8da3ea3420f5c490401e9e;2015-11-19 22:03:49 +0000;Release 1.12.0 (origin/master, origin/HEAD);Steve King;steve@mydev.co\n\
83f3f60d5899116fe4d38b9109c9d925963856da;2015-11-19 13:54:28 +0000;Merge pull request #51 from ebaioni/patch-1 (tag: 1.12.0);Steve King;steve@mydev.co\n\
c515d3f28f587312d816e14ef04db399b7e0adcd;2015-11-19 15:55:41 +1100;updates command to customBinary;Enrico Baioni;baio88@gmail.com\n\
570223e86f0999fd3b39280ad33081e5155d1003;2015-10-12 22:01:05 +0100;Release 1.11.0;Steve King;steve@mydev.co\
');
},
'with max count shorthand property': function (test) {
git.log({n: 5}, function (err, result) {
test.equals(null, err, 'not an error');
test.same(["log", "--pretty=format:%H;%ai;%s%d;%aN;%ae", "--max-count=5"], setup.theCommandRun());
test.done();
});
setup.closeWith('17df9a7421dd86920cd20afd1d6b6be527a89b88;2015-11-24 11:55:47 +0100;add reset command;Mark Oswald;markoswald123@googlemail.com\n\
4e0d08e0653101fb4d8da3ea3420f5c490401e9e;2015-11-19 22:03:49 +0000;Release 1.12.0 (origin/master, origin/HEAD);Steve King;steve@mydev.co\n\
83f3f60d5899116fe4d38b9109c9d925963856da;2015-11-19 13:54:28 +0000;Merge pull request #51 from ebaioni/patch-1 (tag: 1.12.0);Steve King;steve@mydev.co\n\
c515d3f28f587312d816e14ef04db399b7e0adcd;2015-11-19 15:55:41 +1100;updates command to customBinary;Enrico Baioni;baio88@gmail.com\n\
570223e86f0999fd3b39280ad33081e5155d1003;2015-10-12 22:01:05 +0100;Release 1.11.0;Steve King;steve@mydev.co\
');
},
'with max count longhand property': function (test) {
git.log({n: 5}, function (err, result) {
test.equals(null, err, 'not an error');
test.same(["log", "--pretty=format:%H;%ai;%s%d;%aN;%ae", "--max-count=5"], setup.theCommandRun());
test.done();
});
setup.closeWith('17df9a7421dd86920cd20afd1d6b6be527a89b88;2015-11-24 11:55:47 +0100;add reset command;Mark Oswald;markoswald123@googlemail.com\n\
4e0d08e0653101fb4d8da3ea3420f5c490401e9e;2015-11-19 22:03:49 +0000;Release 1.12.0 (origin/master, origin/HEAD);Steve King;steve@mydev.co\n\
83f3f60d5899116fe4d38b9109c9d925963856da;2015-11-19 13:54:28 +0000;Merge pull request #51 from ebaioni/patch-1 (tag: 1.12.0);Steve King;steve@mydev.co\n\
c515d3f28f587312d816e14ef04db399b7e0adcd;2015-11-19 15:55:41 +1100;updates command to customBinary;Enrico Baioni;baio88@gmail.com\n\
570223e86f0999fd3b39280ad33081e5155d1003;2015-10-12 22:01:05 +0100;Release 1.11.0;Steve King;steve@mydev.co\
');
},
'with custom options': function (test) {
git.log({n: 5, '--custom': null, '--custom-with-value': '123'}, function (err, result) {
test.equals(null, err, 'not an error');
test.same([
"log",
"--pretty=format:%H;%ai;%s%d;%aN;%ae",
"--max-count=5",
"--custom",
"--custom-with-value=123"
], setup.theCommandRun());
test.done();
});
setup.closeWith('');
},
'with custom format option': function (test) {
git.log({
format: {
'myhash': '%H',
'message': '%s',
'refs': '%D'
}
}, function (err, result) {
test.equals(null, err, 'not an error');
test.same([
"log",
"--pretty=format:%H;%s;%D"
], setup.theCommandRun());
test.same('ca931e641eb2929cf86093893e9a467e90bf4c9b', result.latest.myhash, 'custom field name');
test.same('Fix log.latest.', result.latest.message);
test.same('HEAD, stmbgr-master', result.latest.refs);
test.done();
});
setup.closeWith([
'ca931e641eb2929cf86093893e9a467e90bf4c9b;Fix log.latest.;HEAD, stmbgr-master',
'8655cb1cf2a3d6b83f4e6f7ff50ee0569758e805;Release 1.20.0;origin/master, origin/HEAD, master',
'd4bdd0c823584519ddd70f8eceb8ff06c0d72324;Support for any parameters to `git log` by supplying `options` as an array;tag: 1.20.0',
'207601debebc170830f2921acf2b6b27034c3b1f;Release 1.19.0;'
].join('\n'))
}
};
|
import {Inferno, Component} from './infernowrapper';
import {classNames} from './utils';
import {CharCounter} from './stateless/charcounter';
export default class extends Component {
constructor(props) {
super(props);
this.state = {
editing: false,
inputLen: 0
};
// Privates
this._valueLen = 0;
// Bindings
this._onFocus = this._onFocus.bind(this);
this._onBlur = this._onBlur.bind(this);
this._onInput = this._onInput.bind(this);
}
//
// Private
//
_onFocus() {
this.setState({
editing: true
});
}
_onBlur() {
this.setState({
editing: false
});
}
_onInput(event, value) {
this.setState({
inputLen: value.length
});
}
//
// Public
//
render() {
const value = this.props.value,
inputLen = this.state.inputLen,
placeholder = this.props.placeholder,
floatLabel = !!value || inputLen > 0 || this.props.floatingLabel === true || (placeholder && this.props.label),
label = this.props.label,
isDisabled = this.props.disabled,
type = this.props.type || 'text',
maxLength = this.props.maxLength,
errorMessage = this.props.errorMessage;
let valueLen = 0,
labelLen = 0,
placeholderLen = 0;
if (value) {
valueLen = value.length;
}
if (label) {
labelLen = label.length;
}
if (placeholder) {
placeholderLen = placeholder.length;
}
this._valueLen = Math.max(inputLen, valueLen);
const minSize = Math.max(this._valueLen, labelLen, placeholderLen, 10),
className = classNames(
'igear-input' ,{
'edit':this.state.editing === true,
'disabled':isDisabled,
'error':errorMessage
}),
spanClassName = classNames(
'igear-input-label', {
'float':floatLabel
});
return (
<div class={className}>
<input placeholder={placeholder} size={minSize} type={type} maxlength={maxLength} disabled={isDisabled} onFocus={this._onFocus} onBlur={this._onBlur} onInput={this._onInput} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} class="igear-input-field" value={value} />
<span class={spanClassName}>{label}</span>
<span class="igear-input-underline"></span>
{this.props.charCounter === true ? <CharCounter value={this._valueLen} maxvalue={this.props.maxLength} /> : null}
{errorMessage ? <div class="igear-errormsg">{errorMessage}</div> : null}
</div>
)
}
}
|
Template.userDiaryDetails.helpers({
joinWithDiaries: function() {
var userDiary = this;
var diary = Diaries.findOne({_id: userDiary.diary_id});
return _.extend(userDiary, _.omit(diary, '_id'));
},
countDays: function() {
var userDiary = this;
var diary = UserDiaries.findOne({user_id : userDiary.user_id});
var diaryDate = new Date(diary.createdAt);
var today = new Date();
function makeDate(dmy) {
var montharray = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var yr = dmy.getYear();
if ((navigator.appName == "Microsoft Internet Explorer") && (yr < 2000))
yr = "19" + yr;
if (navigator.appName == "Netscape")
yr = 1900 + yr;
var m = dmy.getMonth();
var d = dmy.getDate();
myDate = montharray[m]+" "+d+", "+yr;
return myDate;
}
countDays = (Math.round((Date.parse(makeDate(today))-Date.parse(makeDate(diaryDate)))/86400000)+1);
return countDays;
},
txtToday : function() {
var userDiary = this;
var diary = UserDiaries.findOne({user_id : userDiary.user_id});
txtT = Diaries.findOne( { _id : diary.diary_id},
{ days: { $elemMatch: { day: countDays } } } );
return txtT.days[countDays - 1].text;
}
});
Template.userDiaryDetails.events({
'click #btn-diary-delete' : function() {
//e.preventDefault();
if (confirm("Удалить дневник?")) {
var currentDiaryId = this._id;
UserDiaries.remove(currentDiaryId);
toastr.success('Дневник удален!', 'Ваш дневник');
Router.go('diaries');
}
}
});
|
function Toggle(id)
{
var e = document.getElementById(id).style;
e.display = ( e.display != 'block' ) ? 'block' : 'none';
}
function buttonToggle(where, showLabel, hideLabel, disp) {
if(typeof(disp)==='undefined') disp = 'block';
where.value = (where.value == showLabel) ? hideLabel : showLabel;
var e = document.getElementById(where.attributes.rel.value);
e.style.display = (e.style.display == disp) ? 'none' : disp;
}
$(document).keydown(function(e) {
var keycode = e.which || e.keyCode;
var key = String.fromCharCode(keycode).toLowerCase()
if ( keycode == 27 ) // escape
{
e.preventDefault();
var elem = document.getElementById("page-controls").style;
elem.display = ( elem.display != 'none' ) ? 'none' : 'block';
}
if ( e.ctrlKey && key == 's' )
{
e.preventDefault();
var elem = document.getElementById("page-controls").style;
// elem.display = 'block';
elem.width = '10em';
$('button[name="submit"]').focus();
}
});
/*
$(document).ready(function() {
$('.toggler').val( function( index, val ) {
return val + ' ▸'; // ◂
});
$('.toggler').click(function () {
$(this).parent().next('.togglee').toggle();
var v1 = $(this).val().slice(0, -1);
var v2 = $(this).val().slice(-1);
v2 = ( v2 == '▸' ) ? '◂' : '▸'
$(this).val(v1 + v2);
});
});
*/
$(document).ready(function($) {
var upChar = '\u25b3';
var dnChar = '\u25bd';
$('#controls ul').toggle();
$('#controls h2').text(dnChar);
$('#controls h2').on('click', function() {
$('#controls ul').toggle();
$(this).toggleClass('active');
nwChar = ( $(this).text() == dnChar ) ? upChar : dnChar;
$(this).text(nwChar)
});
});
// FindFocus
$(document).ready(function($) {
var bFound = false;
for ( var f = 0; f < document.forms.length; f++ )
{
for ( var i = 0; i < document.forms[f].length; i++ )
{
if ( document.forms[f][i].type != "hidden" && document.forms[f][i].disabled != true )
{
document.forms[f][i].focus();
bFound = true;
}
if ( bFound == true ) break;
}
if ( bFound == true ) break;
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:f6ad6d10b0d40075605ea2654b1c7897564f87bc9d310012369843bee9c5c814
size 1486
|
// Calculate the start and end values and store them into the TweenTarget objects
var LoadValues = function (tweenData)
{
var targets = this.targets;
var prop = tweenData.key;
// console.log('--> LoadValues', prop);
// Targets array:
// 0:
// ref: GameObject,
// keys: {
// x: {
// start,
// current,
// end,
// startCache,
// endCache
// },
// y: {
// start,
// current,
// end,
// startCache,
// endCache
// }
// }
for (var i = 0; i < this.totalTargets; i++)
{
var keys = targets[i].keys;
var entry = keys[prop];
var gameObject = targets[i].ref;
if (entry.startCache === null)
{
entry.start = gameObject[prop];
entry.current = entry.start;
entry.end = tweenData.value(entry.start);
// Cache the start and end values so we only do this once (needed?)
entry.startCache = entry.start;
entry.endCache = entry.end;
}
else
{
entry.start = entry.startCache;
entry.current = entry.start;
entry.end = entry.endCache;
gameObject[prop] = entry.start;
}
// console.log('target', gameObject.name, 'key', prop, 'start', entry.start, 'end', entry.end);
}
};
module.exports = LoadValues;
|
console.log('main')
|
'use strict';
const gulp = require('gulp');
const spawn = require('child_process').spawn;
const del = require('del');
const plugins = require('gulp-load-plugins')();
const babelConfig = {
'retainLines': true,
plugins: ['transform-decorators-legacy']
};
gulp.task('clean', function () {
return del(['dist/**']);
});
gulp.task('lint', function () {
return gulp.src(['./src/**/*.js', 'gulpfile.js'])
.pipe(plugins.eslint())
.pipe(plugins.eslint.format())
.pipe(plugins.eslint.failAfterError());
});
gulp.task('build', ['lint', 'clean'], (done) => {
gulp.src('src/**/*.js')
.pipe(plugins.sourcemaps.init())
.pipe(plugins.babel(babelConfig))
.on('error', (e) => {
console.error(e.stack);
this.emit('end');
})
.pipe(plugins.sourcemaps.write('.'))
.pipe(gulp.dest('dist'))
.on('end', done);
});
// BEGIN watch stuff
let server;
gulp.task('serve', ['build'], () => {
if (server) {
server.kill();
}
server = spawn('node', ['--inspect=0.0.0.0:5858', '--nolazy', 'app.js'], {
stdio: 'inherit',
cwd: 'dist',
env: process.env
});
server.on('close', (code) => {
if (code > 0) {
console.error('Error detected, waiting for changes...'); // eslint-disable-line no-console
}
});
});
process.on('exit', () => {
if (server) {
server.kill();
}
});
gulp.task('watch', ['serve'], function () {
gulp.watch('src/**/*.js', {interval: 1000, mode: 'poll'}, ['serve']); // run tests on file save
gulp.watch('/.ravelrc.json', {interval: 1000, mode: 'poll'}, ['serve']);
});
// END watch stuff
gulp.task('default', ['watch']);
|
// A reference configuration file.
exports.config = {
// ----- How to setup Selenium -----
//
// There are three ways to specify how to use Selenium. Specify one of the
// following:
//
// 1. seleniumServerJar - to start Selenium Standalone locally.
// 2. seleniumAddress - to connect to a Selenium server which is already
// running.
// 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.
//
// If the chromeOnly option is specified, no Selenium server will be started,
// and chromeDriver will be used directly (from the location specified in
// chromeDriver)
// The location of the selenium standalone server .jar file.
seleniumServerJar: '../node_modules/protractor/selenium/selenium-server-standalone-2.42.0.jar',
// The port to start the selenium server on, or null if the server should
// find its own unused port.
seleniumPort: null,
// Chromedriver location is used to help the selenium standalone server
// find chromedriver. This will be passed to the selenium jar as
// the system property webdriver.chrome.driver. If null, selenium will
// attempt to find chromedriver using PATH.
chromeDriver: '../node_modules/protractor/selenium/chromedriver',
// If true, only chromedriver will be started, not a standalone selenium.
// Tests for browsers other than chrome will not run.
chromeOnly: false,
// Additional command line options to pass to selenium. For example,
// if you need to change the browser timeout, use
// seleniumArgs: ['-browserTimeout=60'],
seleniumArgs: [],
// If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
// The tests will be run remotely using SauceLabs.
sauceUser: null,
sauceKey: null,
// The address of a running selenium server. If specified, Protractor will
// connect to an already running instance of selenium. This usually looks like
// seleniumAddress: 'http://localhost:4444/wd/hub'
//seleniumAddress: 'http://localhost:4444/wd/hub',
// The timeout for each script run on the browser. This should be longer
// than the maximum time your application needs to stabilize between tasks.
allScriptsTimeout: 11000,
// ----- What tests to run -----
//
// Spec patterns are relative to the location of this config.
specs: [
'e2e/*.js',
],
// ----- Capabilities to be passed to the webdriver instance ----
//
// For a full list of available capabilities, see
// https://code.google.com/p/selenium/wiki/DesiredCapabilities
// and
// https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js
capabilities: {
'browserName': 'chrome'
},
// ----- More information for your tests ----
//
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
baseUrl: 'http://localhost:9999/examples/',
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
// A callback function called once protractor is ready and available, and
// before the specs are executed
// You can specify a file containing code to run by setting onPrepare to
// the filename string.
onPrepare: function() {
// At this point, global 'protractor' object will be set up, and jasmine
// will be available. For example, you can add a Jasmine reporter with:
// jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter(
// 'outputdir/', true, true));
},
// The params object will be passed directly to the protractor instance,
// and can be accessed from your test. It is an arbitrary object and can
// contain anything you my need in your test.
// This can be changed via the command line as:
// --params.login.user 'Joe'
params: {
login: {
user: 'Jane',
password: '1234'
}
},
// ----- Options to be passed to minijasminenode -----
//
// See the full list at https://github.com/juliemr/minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: true,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 30000
}
};
|
'use strict';
describe('sector-component', function () {
var controller, scope, backEndServer;
beforeEach(function () {
this.addMatchers({
toEqualData: function (expected) {
return angular.equals(this.actual, expected);
}
});
});
beforeEach(module('testSPA.sectorComponent'));
beforeEach(inject(function ($rootScope, $controller) {
backEndServer = {
data: {}, done: false, isDone: function () { return backEndServer.done; },
getSectors: jasmine.createSpy().andCallFake(function (params) {
return {
then: function (fn) {
setTimeout(function () { fn(backEndServer.data); backEndServer.done = true; }, 10);
}
};
})
};
scope = $rootScope.$new();
scope.search = { name: '', json: function () { return { name: scope.search.name }; } };
controller = $controller('SectorComponentCtrl', { $scope: scope, backEndServer: backEndServer });
}));
it('should initialise and load full sector list', function () {
runs(function () {
backEndServer.data = [{ name: 'sector-1' }];
expect(scope.sectors).toBeUndefined();
scope.$digest();
});
waitsFor(backEndServer.isDone, "Server call should be complete", 20);
runs(function () {
expect(scope.sectors).toEqualData([{ name: 'sector-1' }]);
});
});
it('should query filtered sector list when search changes', function (done) {
runs(function () {
backEndServer.data = [{ name: 'filtered-1' }];
expect(scope.sectors).toBeUndefined();
scope.search.name = 'test-filter';
scope.$digest();
});
waitsFor(backEndServer.isDone, "Server call should be complete", 20);
runs(function () {
expect(backEndServer.getSectors).toHaveBeenCalledWith({ name: 'test-filter' });
expect(scope.sectors).toEqualData([{ name: 'filtered-1' }]);
});
});
});
|
'use strict';
var helpers = require('opent2t-testcase-helpers');
var uuidRegExMatch = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
function runTranslatorTests(settings) {
helpers.updateSettings(settings);
var test = settings.test;
var opent2t = settings.opent2t;
var SchemaName = settings.schemaName;
var deviceId = settings.deviceId;
var translator;
test.before(() => {
return opent2t.createTranslatorAsync(settings.translatorPath, 'thingTranslator', settings.getDeviceInfo()).then(trans => {
translator = trans;
return opent2t.invokeMethodAsync(translator, SchemaName, 'get', []).then((response) => {
if(deviceId === undefined) {
deviceId = response.entities[0].di;
}
});
});
});
test.serial('Valid Translator', t => {
t.is(typeof translator, 'object') && t.truthy(translator);
});
/**
* Verify that the ouput from GetPlatform includes all of the required properties
*/
test.serial('GetPlatform', t => {
return helpers.runTest(settings, t, () => {
return opent2t.invokeMethodAsync(translator, SchemaName, 'get', []).then((response) => {
// Verify required platform properties are present.
// This is helpful for new translators that do not have a snapshot yet.
t.truthy(response.availability, `Platform requires platform availability (availability)`);
t.truthy(response.pi, `Platform requires an id (pi)`);
t.truthy(response.pi.match(uuidRegExMatch), `Platform id must be a UUID (pi)`);
t.truthy(response.mnmn, `Platform requires a manufacturer name (mnmn)`);
t.truthy(response.mnmo, `Platform requires a model name (mnmo)`);
t.truthy(response.n, `Platform requires a friendly name (n)`);
// Verify that the platform includes the correct opent2t schema
t.not(response.rt.indexOf(SchemaName), -1, `Platform must include '${SchemaName}' in resources (rt)`);
// Verify each entity has the required properties
for(var i = 0; i < response.entities.length; i++) {
let entity = response.entities[i];
t.truthy(entity.icv, `Entity ${i} requires a core version (icv)`);
t.truthy(entity.dmv, `Entity ${i} requires a device model version (dmv)`);
t.truthy(entity.n, `Entity ${i} requires a friendly name (n)`);
t.truthy(entity.di, `Entity ${i} requires an id (di)`);
t.truthy(entity.di.match(uuidRegExMatch), `Entity ${i} id must be a UUID (di)`);
for(var j = 0; j < entity.resources.length; j++) {
let resource = entity.resources[j];
t.truthy(resource.href, `Resource ${i},${j} requires an href (href)`);
t.truthy(resource.rt, `Resource ${i},${j} requires an array of schemas (rt)`);
t.true(Array.isArray(resource.rt), `Resource ${i},${j} requires an array of schemas (rt)`);
t.true(resource.rt.length > 0, `Resource ${i},${j} requires an array of schemas (rt)`);
t.truthy(resource.if, `Resource ${i},${j} requires an array of interfaces (if)`);
t.true(Array.isArray(resource.if), `Resource ${i},${j} requires an array of interfaces (if)`);
t.true(resource.if.length > 0, `Resource ${i},${j} requires an array of interfaces (if)`);
// Check for oic.if.a XOR oic.if.s
t.true(
(resource.if.indexOf('oic.if.a') > -1) != (resource.if.indexOf('oic.if.s') > -1),
`Resource ${i},${j} requires an interface be either an actuator or a sensor (if)`
);
// And it needs oic.r.baseline too
t.true(resource.if.indexOf('oic.if.baseline') > -1, `Resource ${i},${j} requires an interface to include 'oic.r.baseline' (if)`);
}
}
t.snapshot(response);
});
});
});
test.serial('GetPlatformExpanded', t => {
return helpers.runTest(settings, t, () => {
return opent2t.invokeMethodAsync(translator, SchemaName, 'get', [true])
.then((response) => {
// GetPlatform covers the required properties, so just verify a snapshot here.
t.snapshot(response);
});
});
});
test.skip.serial('GetSubscribe', t => {
t.fail("Not Implemented");
});
test.skip.serial('PostSubscribe', t => {
t.fail("Not Implemented");
});
test.skip.serial('DeleteSubscribe', t => {
t.fail("Not Implemented");
});
}
module.exports = runTranslatorTests;
|
var requirejs = require('requirejs');
requirejs.config({
nodeRequire: require
});
requirejs(["i18n/Localizer"], function (Localizer) {
var localizer = new Localizer();
localizer.validateLiterals();
console.log(localizer.get("hello_world"));
localizer.setLocale("ca");
console.log(localizer.get("hello_world"));
localizer.setLocale("es");
console.log(localizer.get("hello_world"));
});
|
import _ from 'lodash'
import m from 'mithril'
import Templates from '../templates/index.js'
export default class Home {
constructor () {
this.links = [
{
href: 'https://mithril.js.org/',
text: 'Mithril Docs'
},
{
href: 'https://github.com/jocodev1/mithril-cli',
text: 'CLI Docs'
},
{
href: 'http://milligram.io/',
text: 'Milligram'
}
]
}
view () {
return Templates.default([
m('h3', 'Welcome to your new Mithril app!'),
m('p', 'By default, this project contains a webpack configuration to help bundle Mithril js files & SCSS for both development & production environments.'),
m('h5', 'Links'),
_.map(this.links, function (link) {
return m('a', { href: link.href, target: '_blank' }, link.text)
})
])
}
}
|
import {inject, renderCss, space, face} from '../lib';
inject({
styles: {
heading: {
phone: {
family: 'serif',
fontWeight: 600,
fontSize: 22,
lineHeight: 30,
fontSmoothing: 'antialiased',
letterSpacing: '0.5px'
},
default: {
family: 'serif',
fontWeight: 600,
fontSize: 20,
lineHeight: 24,
fontSmoothing: 'antialiased',
letterSpacing: '0.5px'
}
},
paragraph: {
phone: {
family: 'sans',
fontWeight: 400,
fontSize: 17,
lineHeight: 21
},
default: {
family: 'sans',
fontWeight: 400,
fontSize: 15,
lineHeight: 18
}
}
},
spaces: {
small: {
phone: 13,
default: 10
}
},
contexts: {
phone: '@media only screen and (min-device-width: 320px) and (max-device-width: 568px) and (-webkit-min-device-pixel-ratio: 2)'
},
families: {
serif: {
fontStack: 'Georgia, serif',
baselineDiscrepency: .15,
caplineDiscrepency: .15
},
sans: {
fontStack: 'Helvetica, sans-serif',
baselineDiscrepency: .13,
caplineDiscrepency: .12
}
}
});
renderCss();
// type.face('heading', {fontStyle: 'italic', fontWeight: 'bold', marginBottom: 'small'});
// type.space('heading', {marginTop: 20, marginBottom: 20});
|
Ext.define('App.view.security.Profile', {
extend: 'Ext.window.Window',
alias: 'widget.profile',
// height: 260,
// width: 550,
requires: [
'App.util.Util',
'App.view.security.formProfile'
],
layout: {
align: 'stretch',
type: 'vbox'
},
title: 'User',
items: [{ xtype: 'formprofile'} ],
});
|
var MongoClient = require('mongodb').MongoClient;
var moment = require("moment");
var async = require("async");
var logger = require("winston");
var db = null;
var queryAggregationCount = 0;
var progressNotifier = null;
exports.setDatabase = function(database)
{
db = database;
};
exports.getDatabase = function()
{
return db;
};
exports.setProgressNotifier = function(cb)
{
progressNotifier = cb;
};
exports.sendProgress = function(data)
{
if (progressNotifier)
progressNotifier(data);
};
exports.persistDataPoint = function(type, data, client_id, created, cb)
{
var dp = {
type: type,
data: parseFloat(data, 10),
created: new Date(created),
client_id: client_id
};
db.collection('datapoints').insertOne(dp, function(err, result)
{
return cb(err, dp);
});
};
exports.dailySummary = function(client_id, cb)
{
var aggregationpoints = db.collection('aggregationpoints');
var start = moment().subtract(24, 'hours').startOf('hour');
var end = moment().startOf('hour');
aggregationpoints.aggregate
([
{
$match: {
from: { $gte: start.toDate() },
to: { $lte: end.toDate() },
client_id: client_id
}
},
{
$group:
{
_id: '$type',
avg: {$avg: '$avg'}
}
}
]).toArray(function(err, docs)
{
logger.info("cached aggregation for period " + start + " to " + end + " with " + docs.length + " docs");
var text = [];
docs.forEach(function(d)
{
var type = d["_id"];
var value = parseFloat(d["avg"]).toFixed(2);
text.push(type + ": " + value);
});
var msg = "Last 24h overview for " + client_id + ":\n" + text.join(", ");
return cb(err, msg);
});
};
exports.getDataPoints = function(type, client_id, cb)
{
var coll = db.collection('datapoints');
coll.find({ type: type, client_id: client_id }, { sort: [['created', -1]], limit : 30 }).toArray(function(err, docs)
{
if (err)
{
return cb("Error retrieving data: " + err);
}
return cb(null, docs);
});
};
exports.aggregate = function(start, end, types, client_id, skipCache, cb)
{
var timeSpan = { from: start, to: end};
// --------------------------------------------------
var liveAggregate = function(cb)
{
var coll = db.collection('datapoints');
coll.aggregate
([
{
$match: {
created: { $gte: start, $lt: end },
client_id: client_id
}
},
{
$group:
{
_id: '$type',
avg: {$avg: '$data'}
}
}
]).toArray(function(err, docs)
{
//logger.info("live aggregation for period " + start + " to " + end + " with " + docs.length + " docs");
++queryAggregationCount;
exports.sendProgress(queryAggregationCount);
return cb(err, timeSpan, docs);
});
};
// --------------------------------------------------
var cachedAggregate = function(cb)
{
var aggregationpoints = db.collection('aggregationpoints');
aggregationpoints.aggregate
([
{
$match: {
from: { $gte: start },
to: { $lte: end },
client_id: client_id
}
},
{
$group:
{
_id: '$type',
avg: {$avg: '$avg'}
}
}
]).toArray(function(err, docs)
{
logger.info("cached aggregation for period " + start + " to " + end + " with " + docs.length + " docs");
++queryAggregationCount;
exports.sendProgress(queryAggregationCount);
return cb(err, timeSpan, docs);
});
};
// --------------------------------------------------
var interferesWithCurrentHour = function()
{
var now = moment();
//if the current date is within the range of start to end, we need to fetch the data live
return start < now && end > now;
};
// --------------------------------------------------
if (skipCache)
{
logger.info("skipping cache");
liveAggregate(cb);
}
else if (interferesWithCurrentHour())
{
logger.info("skipping cache: interferes with current hour");
liveAggregate(cb);
}
else
{
logger.info("using cache");
cachedAggregate(cb);
}
};
exports.dateDiff = function(from, to)
{
from = moment(from);
to = moment(to);
var diffToStart = to.diff(from, "seconds");
//logger.info("diff to start from " + from.format("HH:mm:ss") + " to " + to.format("HH:mm:ss") + " : ", diffToStart)
return diffToStart;
};
exports.aggregation = function(start, end, interval, capabilities, client_id, skipCache, progressCb, cb)
{
exports.setProgressNotifier(progressCb);
var dataPointsTemplate = {};
var types = [];
capabilities.forEach(function(cap)
{
types.push(cap.name);
});
types.forEach(function(type)
{
dataPointsTemplate[type] = [];
});
while (start < end)
{
var startDate = moment(start).toDate();
start.add(interval[0], interval[1]);
//if the start point of the timespan is less than 15 seconds in the past, we
//skip it. It is very likely that there is no datapoint yet
var diff = exports.dateDiff(startDate, moment());
if (diff < 15)
{
continue;
}
types.forEach(function(type)
{
dataPointsTemplate[type].push({
data: null,
from: startDate,
to: moment(start).toDate()
});
});
}
return exports.aggregateWrapper(dataPointsTemplate, client_id, skipCache, cb);
};
exports.aggregateWrapper = function(dps, client_id, skipCache, cb)
{
queryAggregationCount = 0;
var aggregations = [];
var types = Object.keys(dps);
var dates = types.length === 0 ? [] : dps[types[0]];
//logger.info("dpTemplate", dps);
dates.forEach(function(o)
{
aggregations.push(function(cb)
{
exports.aggregate(o.from, o.to, types, client_id, skipCache, cb);
});
});
async.parallel(aggregations, function(err, data)
{
if (err) throw err;
var i = -1;
data.forEach(function(d)
{
i++;
var datapoints = d[1];
datapoints.forEach(function(e)
{
//logger.info("got back datapoints", e);
var type = e["type"] || e["_id"];
if (!dps[type])
{
logger.error("unexpected data type", type);
return;
}
dps[type][i].data = e["avg"];
});
});
logger.info("full data returned");
return cb(null, dps);
});
};
exports.getLastCount = function(client_id, cb)
{
var coll = db.collection('datapoints');
var count = coll.find({
client_id: client_id,
created: { $gte: moment().subtract(10, "minutes").toDate() }
}, {}).count(function(err, count)
{
return cb(err, count);
});
};
exports.logEntry = function(loglevel, message, scope)
{
var coll = db.collection('systemlog');
var isGlobalScope = (scope === true);
var isClientScope = (typeof scope == "string");
var logEntry = {
loglevel: loglevel,
message: message,
created: (new Date),
globalscope: isGlobalScope,
clientname: (isClientScope ? scope : null)
};
coll.insertOne(logEntry, function(err, result)
{
if (err)
{
logger.error("could not store log entry", logEntry, err);
}
});
};
exports.savePushToken = function(clientName, token, client, cb)
{
if (!token)
{
return cb("no token");
}
var coll = db.collection('pushtokens');
coll.createIndex( { token: 1 }, { unique: true }, function(err, res)
{
if (err)
return cb("pushtoken creating unique index" + err);
logger.info("created unique index");
var entry = {
token: token,
created: (new Date),
client: clientName
};
coll.insertOne(entry, function(err, result)
{
if (err && err.toString().indexOf("duplicate key") !== -1)
{
return cb(null, "token already present");
}
return cb(err, result);
});
});
};
exports.getPushTokens = function(client, cb)
{
var coll = db.collection('pushtokens');
coll.find({ client: client }).toArray(function(err, docs)
{
return cb(err, docs);
});
};
exports.removePushTokens = function(tokens, cb)
{
var coll = db.collection('pushtokens');
coll.deleteMany
({
token:
{
'$in': tokens
}
}, function(err, res)
{
if (err)
{
return cb("delete token error: " + err);
}
return cb(null, "deleted " + res.result.n + " push tokens");
});
};
exports.fullAggregation = function(cb)
{
//--------------------------------------------------
var startTime = new Date();
var coll = db.collection('datapoints');
var agg = db.collection('aggregationpoints');
//don't aggregate anything that is within the current hour
var overallEnd = moment().startOf("hour");
//delete all the items with "aggregated: true", that are older than 1h
//we need this to keep the data points of the last hour for the "2 minutes in last hour" interval query
var deleteOlderThan = moment().subtract(1, "hour");
//--------------------------------------------------
//temp vars that will be set by fetchFirst
var start = null;
var end = null;
//--------------------------------------------------
logger.info("fullAggregation");
logger.info("##################################################");
logger.info("##################################################");
logger.info("##################################################");
var start = function()
{
logger.info("##################################################");
logger.info("processing items until " + overallEnd.format("DD.MM.YYYY HH:mm"));
agg.createIndex( { from: 1, to: 1, type: 1, client_id: 1 }, { unique: true }, function(err, res)
{
if (err)
return cb("aggregation creating unique index" + err);
logger.info("created unique index");
logger.info("--------------------------------------------------");
fetchFirst();
});
};
//--------------------------------------------------
var fetchFirst = function()
{
logger.info("fetching first item");
coll.find({ aggregated: null }, { sort: [['created', 1]], limit : 1 }).toArray(function(err, firstDoc)
{
if (!firstDoc || !firstDoc[0] || !firstDoc[0].created)
{
return cb("Full aggregation: No or invalid item found in timespan!" + firstDoc);
}
if (err)
{
return cb("full aggregation fetch first: " + err);
}
var first = moment(firstDoc[0].created);
logger.info("first doc:", firstDoc);
logger.info("first date: " + first.format("DD.MM.YYYY HH:mm"));
start = first.startOf("hour");
end = moment(first).add(1, "hour");
if (overallEnd < end)
{
return cb(null, "stopping aggregation, because the first element + 1h >= end " + overallEnd.format("DD.MM.YYYY HH:mm"));
}
else
{
logger.info("--------------------------------------------------");
removeOld();
}
});
};
//--------------------------------------------------
var removeOld = function()
{
logger.info("deleting already aggregated items");
coll.deleteMany({
aggregated: true,
created: {$lt: deleteOlderThan.toDate()},
}, function(err, res)
{
if (err)
{
return cb("delete aggregation: " + err);
}
var log = "deleted " + res.result.n + " too old aggregated datapoints";
exports.logEntry("info", log, true);
logger.info(log);
logger.info("--------------------------------------------------");
aggregateHour();
});
};
//--------------------------------------------------
var aggregateHour = function()
{
logger.info("aggregation for hour " + moment(start).format("DD.MM.YYYY HH:mm") + " to " + moment(end).format("DD.MM.YYYY HH:mm"));
coll.aggregate
([
{
$match: {
created: { $gte: start.toDate(), $lt: end.toDate() },
aggregated: null
}
},
{
$group:
{
_id: {
type: '$type',
client_id: '$client_id'
},
avg: {$avg: '$data'}
}
}
]).toArray(function(err, docs)
{
if (err)
{
return cb("full aggregation agg: " + err);
}
//process aggregation
var aggregatedDatapoints = [];
docs.forEach(function(d)
{
aggregatedDatapoints.push({
type: d["_id"].type,
avg: d["avg"],
client_id: d["_id"].client_id,
created: (new Date),
from: start.toDate(),
to: end.toDate()
});
});
exports.logEntry("info", "Aggregation success: " + aggregatedDatapoints.length + " datapoints", true);
logger.info("aggregation results: " + aggregatedDatapoints.length + " datapoints");
logger.info("--------------------------------------------------");
storeAggregation(aggregatedDatapoints, function()
{
flagAggregatedPoints();
});
});
};
//--------------------------------------------------
var storeAggregation = function(aggregatedDatapoints, next)
{
logger.info("storing aggregation for " + aggregatedDatapoints.length + " datapoints");
agg.insertMany(aggregatedDatapoints, function(err, res)
{
if (err && err.toString().indexOf("duplicate key") === -1)
{
return cb("full aggregation storage: " + err);
}
logger.info("stored in aggregationpoints: " + aggregatedDatapoints.length + " datapoints");
logger.info("--------------------------------------------------");
next();
});
};
//--------------------------------------------------
var flagAggregatedPoints = function()
{
coll.update({
created: {
$gte: start.toDate(),
$lt: end.toDate()
}}, {
$set: { aggregated: true }
}, {
w:1, multi: true
}, function(err, res)
{
if (err)
{
return cb("flagged aggregation: " + err);
}
var log = "flagged " + res.result.nModified + " datapoints for deletion in next round";
logger.info(log);
exports.logEntry("info", log, true);
logger.info("--------------------------------------------------");
roundDone();
});
};
//--------------------------------------------------
var roundDone = function()
{
var timeSpend = ((new Date).getTime() - startTime.getTime()) / 1000;
var log = "aggregation round done in " + timeSpend + " seconds";
logger.info(log);
exports.logEntry("success", log, true);
logger.info("next round");
logger.info("##################################################");
exports.fullAggregation(cb);
};
start();
};
exports.oldAggregation = function(cb)
{
var AGGREGATION_LEVEL = 1;
var coll = db.collection('aggregationpoints');
var overallEnd = moment().subtract(7, "days").startOf("day");
var startTime = new Date(); //performance measurement
//--------------------------------------------------
logger.info("oldAggregation");
logger.info("##################################################");
logger.info("##################################################");
logger.info("##################################################");
var start = function()
{
logger.info("##################################################");
logger.info("processing items until " + overallEnd.format("DD.MM.YYYY HH:mm"));
logger.info("fetching first item");
coll.find({ $or: [ {
aggregationlevel: null
}, {
aggregationlevel: { $lt: AGGREGATION_LEVEL }
}]}, { sort: [['from', 1]], limit : 1 }).toArray(function(err, firstDoc)
{
if (!firstDoc || !firstDoc[0] || !firstDoc[0].from)
{
return cb("Old Aggregation: No or invalid item found in timespan!" + firstDoc);
}
if (err)
{
return cb("full aggregation fetch first: " + err);
}
var first = moment(firstDoc[0].from);
logger.info("first doc:", firstDoc);
logger.info("first date: " + first.format("DD.MM.YYYY HH:mm"));
var start = first.startOf("day");
var end = moment(start).add(1, "day").startOf("day");
if (overallEnd < end)
{
return cb(null, "stopping aggregation, because the first element >= end " + overallEnd.format("DD.MM.YYYY HH:mm"));
}
logger.info("--------------------------------------------------");
aggregateTimespan(start, end);
});
};
//--------------------------------------------------
var aggregateTimespan = function(start, end)
{
logger.info("=> aggregation span: " + start.format("DD.MM.YYYY HH:mm") + " to " + end.format("DD.MM.YYYY HH:mm"));
coll.aggregate
([
{
$match: {
from: { $gte: start.toDate() },
to: { $lte: end.toDate() },
$or: [ {
aggregationlevel: null
}, {
aggregationlevel: { $lt: AGGREGATION_LEVEL }
}]
}
},
{
$group:
{
_id: {
type: '$type',
client_id: '$client_id'
},
avg: {$avg: '$avg'}
}
}
]).toArray(function(err, docs)
{
if (err)
{
return cb("full aggregation agg: " + err);
}
//process aggregation
var aggregatedDatapoints = [];
docs.forEach(function(d)
{
aggregatedDatapoints.push({
type: d["_id"].type,
avg: d["avg"],
client_id: d["_id"].client_id,
created: (new Date),
from: start.toDate(),
to: end.toDate(),
aggregationlevel: AGGREGATION_LEVEL
});
});
exports.logEntry("info", "Aggregation success: " + aggregatedDatapoints.length + " datapoints", true);
logger.info("aggregation results: " + aggregatedDatapoints.length + " datapoints");
logger.info("--------------------------------------------------");
storeAggregation(aggregatedDatapoints, start, end);
});
};
//--------------------------------------------------
var storeAggregation = function(aggregatedDatapoints, start, end)
{
logger.info("storing aggregation for " + aggregatedDatapoints.length + " datapoints");
if (aggregatedDatapoints.length === 0)
{
return removeOld(start, end);
}
coll.insertMany(aggregatedDatapoints, function(err, res)
{
if (err && err.toString().indexOf("duplicate key") === -1)
{
return cb("full aggregation storage: " + err);
}
logger.info("stored in aggregationpoints: " + aggregatedDatapoints.length + " datapoints");
logger.info("--------------------------------------------------");
return removeOld(start, end);
});
};
//--------------------------------------------------
var removeOld = function(start, end)
{
logger.info("deleting already aggregated items");
coll.deleteMany({
from: { $gte: start.toDate() },
to: { $lte: end.toDate() },
$or: [ {
aggregationlevel: null
}, {
aggregationlevel: { $lt: AGGREGATION_LEVEL }
}]
}, function(err, res)
{
if (err)
{
return cb("delete aggregation: " + err);
}
var log = "deleted " + res.result.n + " too old aggregated datapoints";
exports.logEntry("info", log, true);
logger.info(log);
logger.info("--------------------------------------------------");
roundDone();
});
};
//--------------------------------------------------
var roundDone = function()
{
var timeSpend = ((new Date).getTime() - startTime.getTime()) / 1000;
var log = "aggregation round done in " + timeSpend + " seconds";
logger.info(log);
exports.logEntry("success", log, true);
logger.info("next round");
logger.info("##################################################");
exports.oldAggregation(cb);
};
start();
};
exports.deleteOldLogs = function(cb)
{
var coll = db.collection('systemlog');
var deleteOlderThan = moment().subtract(5, "days").startOf("day");
coll.deleteMany({
created: {$lt: deleteOlderThan.toDate()},
}, function(err, res)
{
if (err)
{
return cb("delete old logs: " + err);
}
var log = "deleted " + res.result.n + " too old log entries";
exports.logEntry("info", log, true);
logger.info(log);
logger.info("--------------------------------------------------");
cb(null, log);
});
};
|
//defining the searched words
var searchWord1 = 'seksuaaliset vähemmistöt';
var searchWord2 = 'lhbt';
$(function () {
// getting the pictures using finna api
function getPictures(pictureSearch1, pictureSearch2) {
console.log('getPictures');
$.ajax({
'url':
'https://api.finna.fi/v1/search?lookfor=' + pictureSearch1 + '+OR+'
+ pictureSearch2 + '&filter[]=online_boolean:"1"&filter[]=format:"0/Image/',
'dataType': 'json',
'success': onGetPictures
});
}
//getting the url:s and adding the pictures to html
function onGetPictures(obj) {
if (obj) {
var records = obj.records;
var pictureAddress = records.map(
function (rec) {
return rec.images;
}
);
console.log(pictureUrl);
} else {
console.log('Not found!');
}
//This function should be in two parts but I did not know how to do it....
var firstPictureUrl = 'https://api.finna.fi' + pictureAddress[0];
$('#carousel').append('<div class="item active" id="item"><img src="'
+ firstPictureUrl + '" alt="pic"></div>');
for (var i = 1; i < pictureAddress.length; i++) {
var pictureUrl = 'https://api.finna.fi' + pictureAddress[i];
console.log(pictureUrl);
$('#carousel').append('<div class="item"><img src="' + pictureUrl
+ '" alt="pic"></div>');
}
}
getPictures(searchWord1, searchWord2);
/*function getBooks(searchBook) {
console.log('getPictures');
$.ajax({
'url': 'https://api.finna.fi/v1/search?lookfor=' + searchBook + '&filter[]=online_boolean:"1"&filter[]=format:"0/Book/',
'dataType': 'json',
'success': onGetBooks
});
}
function onGetBooks(obj) {
if (obj) {
var bookRecords = obj.records;
var bookNames = bookRecords.map(
function(rec) {
return rec.title;
}
);
//$('#result').append(bookNames.join(', ') + '<br>');
console.log(bookNames);
} else {
console.log('Not found!');
}
for (var i=0; i<bookNames.length; i++){
var singleBook = bookNames[i];
$('#result').append('<li>' + singleBook + '</li>');
}
}
$('#searchButton').click(function () {
$('#result').empty();
var searchValue = $('#searchInput').val();
console.log(searchValue);
getBooks(searchValue);
});*/
});
|
import React from 'react';
export default function TotalResults(props) {
const number = props.number;
function format(num) {
let n = num.toString(), p = n.indexOf('.');
return n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g, function ($0, i) {
return p < 0 || i < p ? ($0 + ',') : $0;
});
}
return (
<p className="number-of-results">
<small>About {format(number)} results.</small>
</p>
);
}
|
Ext.define('OppUI.view.loadtestDashboard.loadtestsummary.groupreportfilter.LoadTestGroupReportFilter', {
extend: 'Ext.form.FieldContainer',
alias: 'widget.groupreportfilter',
requires: [
'OppUI.view.loadtestDashboard.loadtestsummary.groupreportfilter.LoadTestGroupReportFilterController',
'OppUI.view.loadtestDashboard.loadtestsummary.groupreportfilter.LoadTestGroupReportFilterModel'
],
controller: 'loadtestgroupreportfilter',
viewModel: {
type: 'loadtestgroupreportfilter'
},
layout: {
type: 'hbox',
align: 'middle' // Child items are stretched to full width
},
fieldDefaults: {
padding: 5
},
items: [{
xtype: 'combobox',
itemId: 'filterCombobox',
store: {
type: 'array',
fields: ['column_name'],
data: [
['appUnderTest'],
['appUnderTestVersion'],
['comments'],
['description'],
['environment'],
['startTime'],
['testName'],
['testSubName'],
['testTool'],
['testToolVersion'],
['vuserCount'],
['slaGroupId']
]
},
displayField: 'column_name',
fieldLabel: 'Filter',
labelWidth: 35,
anchor: '0',
queryMode: 'local',
selectOnTab: false,
name: 'columnName'
}, {
xtype: 'textfield',
itemId: 'filterField',
name: 'criteria',
width: 200
}, {
xtype: 'button',
text: 'Add more',
itemId: 'btnGroupedFilterFieldAdd',
padding: 5,
handler: function(button) {
button.hide();
button.up('panel').add({ xtype: 'groupreportfilter' });
button.up('fieldcontainer').down('#deleteFieldContainerBtn').show();
}
}, {
xtype: 'button',
itemId: 'deleteFieldContainerBtn',
text: 'X',
padding: 5,
hidden: true,
handler: function() {
this.up('panel').remove(this.up('fieldcontainer'), true);
}
}]
});
|
(function($) {
// Initilize tooltipster tooltips
$('.tooltipster').tooltipster({
animation: 'fade',
delay: 0,
theme: 'tooltipster-donnie-dark',
touchDevices: false,
trigger: 'hover'
});
// Add tooltip for topright corner avatar
$('#top-user-image').tooltipster({
content: $('<span>'+donnie_dark_blog_description+'</span>'),
delay: 0,
theme: 'tooltipster-donnie-dark'
});
// Highlight current page on header, if any
$("#donnie-dark-header-content ul.top-navigation-list > li").each(function(index) {
//console.log( index + ": " + $( this ).children("a").attr("id") );
var curItemName = $(this).children("a").attr("id");
if (curItemName != null && curItemName != "") {
var pathname = window.location.pathname;
pathname = pathname.replace(/\//g, "");
curItemName = curItemName.replace("nav-item-", "");
if (pathname == curItemName) {
$(this).children("a").addClass("nav-item-selected");
}
}
});
}(jQuery));
// Make navigator smaller when scrolling page out of top
$(window).scroll( function() {
var scrolled_val = $(document).scrollTop().valueOf();
var maxVal = 20;
if (scrolled_val > maxVal) {
$("div#donnie-dark-top-area").addClass("navScrolled");
$("div#top-user-image").addClass("topImgScrolled");
}
else if (scrolled_val == maxVal || scrolled_val < maxVal) {
$("div#donnie-dark-top-area").removeClass("navScrolled");
$("div#top-user-image").removeClass("topImgScrolled");
}
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return(
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
)
});
}
render() {
return(
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">Add a post</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{ this.renderPosts() }
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return {
posts: state.posts
}
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
|
/**
* flowplayer.playlist 3.0.7. Flowplayer JavaScript plugin.
*
* This file is part of Flowplayer, http://flowplayer.org
*
* Author: Tero Piirainen, <info@flowplayer.org>
* Copyright (c) 2008 Flowplayer Ltd
*
* Dual licensed under MIT and GPL 2+ licenses
* SEE: http://www.opensource.org/licenses
*
* Date: 2009-09-03 09:44:40 +0000 (Thu, 03 Sep 2009)
* Revision: 2090
*/
(function($) {
$f.addPlugin("playlist", function(wrap, options) {
// self points to current Player instance
var self = this;
var opts = {
playingClass: 'playing',
pausedClass: 'paused',
progressClass:'progress',
template: '<a href="${url}">${title}</a>',
loop: false,
playOnClick: true,
manual: false
};
$.extend(opts, options);
wrap = $(wrap);
var manual = self.getPlaylist().length <= 1 || opts.manual;
var els = null;
//{{{ "private" functions
function toString(clip) {
var el = template;
$.each(clip, function(key, val) {
if (!$.isFunction(val)) {
el = el.replace("$\{" +key+ "\}", val).replace("$%7B" +key+ "%7D", val);
}
});
return el;
}
// assign onClick event for each clip
function bindClicks() {
els = wrap.children().unbind("click.playlist").bind("click.playlist", function() {
return play($(this), els.index(this));
});
}
function buildPlaylist() {
wrap.empty();
$.each(self.getPlaylist(), function() {
wrap.append(toString(this));
});
bindClicks();
}
function play(el, clip) {
if (el.hasClass(opts.playingClass) || el.hasClass(opts.pausedClass)) {
self.toggle();
} else {
el.addClass(opts.progressClass);
self.play(clip);
}
return false;
}
function clearCSS() {
if (manual) { els = wrap.children(); }
els.removeClass(opts.playingClass);
els.removeClass(opts.pausedClass);
els.removeClass(opts.progressClass);
}
function getEl(clip) {
return (manual) ? els.filter("[href=" + clip.originalUrl + "]") : els.eq(clip.index);
}
//}}}
/* setup playlists with onClick handlers */
// internal playlist
if (!manual) {
var template = wrap.is(":empty") ? opts.template : wrap.html();
buildPlaylist();
// manual playlist
} else {
els = wrap.children();
// allows dynamic addition of elements
if ($.isFunction(els.live)) {
$(wrap.selector + "> *").live("click", function() {
var el = $(this);
return play(el, el.attr("href"));
});
} else {
els.click(function() {
var el = $(this);
return play(el, el.attr("href"));
});
}
// setup player to play first clip
var clip = self.getClip(0);
if (!clip.url && opts.playOnClick) {
clip.update({url: els.eq(0).attr("href")});
}
}
// onBegin
self.onBegin(function(clip) {
clearCSS();
getEl(clip).addClass(opts.playingClass);
});
// onPause
self.onPause(function(clip) {
getEl(clip).removeClass(opts.playingClass).addClass(opts.pausedClass);
});
// onResume
self.onResume(function(clip) {
getEl(clip).removeClass(opts.pausedClass).addClass(opts.playingClass);
});
// what happens when clip ends ?
if (!opts.loop && !manual) {
// stop the playback exept on the last clip, which is stopped by default
self.onBeforeFinish(function(clip) {
if (!clip.isInStream && clip.index < els.length -1) {
return false;
}
});
}
// on manual setups perform looping here
if (manual && opts.loop) {
self.onBeforeFinish(function(clip) {
var el = getEl(clip);
if (el.next().length) {
el.next().click();
} else {
els.eq(0).click();
}
return false;
});
}
// onUnload
self.onUnload(function() {
clearCSS();
});
// onPlaylistReplace
if (!manual) {
self.onPlaylistReplace(function() {
buildPlaylist();
});
}
// onClipAdd
self.onClipAdd(function(clip, index) {
els.eq(index).before(toString(clip));
bindClicks();
});
return self;
});
})(jQuery);
|
var fs = require('mz/fs');
var readFiles = require('read-files-promise');
var path = require('path');
var config = require('../config/config');
var util = require('../util');
var documentation = require('documentation');
var RSVP = require('rsvp');
/**
* Takes a block of text and wraps URL into a Markdown link.
* For example: this text "Search using http://google.com"
* is turned into "Search using [http://google.com](http://google.com)"
* An optional linkText can be display text for the URL
* The above example would be: "Search using [Google](http://google.com)"
* @param {string} paragraph Block of text to be searched into for URLs
* @param {string} [linkText=""] Text to be displayed for the URL. If this is missing, the URL is used as text.
* @return {string} Block of text with all URLs turned into Markdown links.
*/
function markdownLinks(paragraph, linkText) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return paragraph.replace(urlRegex, function (url) {
if (!linkText) {
linkText = url;
}
return "[" + linkText + "](" + url + ")";
})
}
/**
* Extract Description from Schema and correctly markdown URLs in it.
* @param {object} schema The schema who's name and description will be extracted.
* @returns {string} Schema description with URLs markdowned.
*/
function getSchemaDescription(schema) {
for (var prop in schema) {
if (prop === "description" && typeof (schema[prop]) == "string") {
return markdownLinks(schema[prop], "source");
}
}
}
/**
* Collect descriptions of all schemas.
* @returns {object} Promise. The resolve function has no parameters.
*/
function collectDescriptions() {
return new RSVP.Promise(function (resolve, reject) {
var schemasWithDesc = "";
var schemaFiles = util.getAllFilesFromFolder(config.schemasFolder);
// Get path of schema file
var schemas = schemaFiles.map(function (sf) {
return path.basename(sf, ".json");
});
// Read schema file
readFiles(schemaFiles, { encoding: 'utf8' }).then(function (contentsBuffers) {
var contents = contentsBuffers.map(function (buffer) { return buffer.toString(); });
contents.forEach(function (schemaFileContent, index) {
var schema = JSON.parse(schemaFileContent);
var schemaDesc = getSchemaDescription(schema);
schemasWithDesc += "* **" + schemas[index] + "**: " + schemaDesc + " \n";
});
// Write to file
fs.writeFile(path.resolve(__dirname, '..', config.docFolder + "/" + config.schemasDocFile), schemasWithDesc).then(function () {
resolve();
});
});
});
}
/**
* Generate documentation for code files. It reads the JSDoc comments and generate markdown files for them. One markdown file is generated for each code file.
* @returns {object} Promise. The resolve function has no parameters.
*/
function generateCodeDocs() {
return new RSVP.Promise(function (resolve, reject) {
var promises = config.codeFiles.map(function (jsFile) {
return path.resolve(__dirname, '..', jsFile);
})
.map(function (jsFile) {
return new RSVP.Promise(function (resolve, reject) {
var jf = [jsFile];
documentation(jf, { shallow: true }, function (err, result) {
documentation.formats.md(result, {}, function (err, md) {
// Write to file
fs.writeFile(path.resolve(__dirname, '..', config.docFolder + "/" + jsFile.replace(/^.*[\\\/]/, '') + ".md"), md).then(resolve);
});
});
});
});
RSVP.all(promises).then(resolve);
});
}
module.exports = {
collectDescriptions: collectDescriptions,
generateCodeDocs: generateCodeDocs
};
|
import React, { Component, PropTypes as pt } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { asyncConnect } from 'redux-async-connect';
import Helmet from 'react-helmet';
import last from 'lodash/last';
import { mapStateToProps } from './ArchiveSelectors';
import { loadRemaining } from 'redux/modules/tumblr';
import {
OUTER_STYLE,
HEADER_STYLE,
MONTH_STYLE,
} from './Archive.styles';
import { Picture } from 'components';
import { CENTER_STYLE } from '../Home/Home.styles';
const MONTH_MAP = {
0: 'January',
1: 'February',
2: 'March',
3: 'April',
4: 'May',
5: 'June',
6: 'July',
7: 'August',
8: 'September',
9: 'October',
10: 'November',
11: 'December',
};
@asyncConnect([{
promise: ({ store: { dispatch } }) => dispatch(loadRemaining()),
}])
@connect(mapStateToProps, {})
export default class Archive extends Component {
static propTypes = {
posts: pt.array.isRequired,
postsByTag: pt.object.isRequired,
postsById: pt.object.isRequired,
postsByMonth: pt.object.isRequired,
tags: pt.array.isRequired,
params: pt.object.isRequired,
children: pt.any,
browserWidth: pt.number.isRequired
}
renderPosts = (posts) => {
const {
props: {
params: { id: tagParam },
browserWidth,
posts: allPosts,
}
} = this;
const link = tagParam
? `/archive/tag/${tagParam}/gallery/`
: '/archive/gallery/';
const remainder = (browserWidth - 1) % 76;
const rowAmount = Math.floor((browserWidth - 1) / 76);
const imageSize = 76 + remainder / rowAmount;
return (
<div
style={{
display: 'flex',
width: browserWidth,
flexWrap: 'wrap',
borderLeft: '1px solid white'
}}
>
{posts.map((post, index) =>
post.photos && post.photos.map((photo, photoIndex) =>
<Link
key={`${index}-${photoIndex}`}
to={`${link}${post.id}`}
>
<div
style={{
width: imageSize,
fontSize: 0,
lineHeight: 0,
borderRight: '1px solid white',
borderBottom: '1px solid white'
}}
>
<Picture
src={last(photo.alt_sizes).url}
ratio={1}
/>
</div>
</Link>
)
)}
</div>
);
}
render() {
const {
params: {
id: tagParam
},
posts,
postsByMonth,
postsByTag,
postsById,
children
} = this.props;
const galleryPosts = tagParam
? postsByTag[tagParam].map(postId => postsById[postId])
: posts;
return (
<div
style={OUTER_STYLE}
id="outer-container"
>
<main
id="page-wrap"
style={{
width: '100%'
}}
>
<Helmet title="Archive" />
{tagParam
? <div>
<h1 style={CENTER_STYLE}>
{tagParam}
</h1>
{this.renderPosts(galleryPosts)}
</div>
: Object.keys(postsByMonth).reverse().map((monthKey) => (
<div key={monthKey} style={MONTH_STYLE}>
<h1 style={HEADER_STYLE}>{MONTH_MAP[monthKey]}</h1>
{this.renderPosts(postsByMonth[monthKey])}
</div>
))
}
{children && React.cloneElement(children, {
slides: galleryPosts
.filter(post => post.type === 'photo')
.map(post => ({
url: post.photos[0].original_size.url,
ratio: post.photos[0].original_size.height / post.photos[0].original_size.width,
id: post.id,
summary: post.summary
})
)
})}
</main>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.